text
stringlengths
54
60.6k
<commit_before>#include <iostream> #include <type_traits> struct A {}; struct B : A {}; struct C : B {}; struct D {}; int main(void) { std::cout << "is_const:" << std::endl; std::cout << "int: " << std::is_const<int>::value << std::endl; std::cout << "const int: " << std::is_const<const int>::value << std::endl; std::cout << "const int&: " << std::is_const<const int&>::value << std::endl; std::cout << "const int*: " << std::is_const<const int*>::value << std::endl; std::cout << "int* const: " << std::is_const<int* const>::value << std::endl; using DoublePointer = double*; std::cout << std::endl << "is_pointer:" << std::endl; std::cout << "int: " << std::is_pointer<int>::value << std::endl; std::cout << "int*: " << std::is_pointer<int*>::value << std::endl; std::cout << "double*: " << std::is_pointer<DoublePointer>::value << std::endl; std::cout << std::endl << "is_same:" << std::endl; std::cout << "<int, int>: " << std::is_same<int, int>::value << std::endl; std::cout << "<int, const int>: " << std::is_same<int, const int>::value << std::endl; std::cout << "<int*, int*>: " << std::is_same<int*, int*>::value << std::endl; std::cout << "<double*, double*>: " << std::is_same<DoublePointer, DoublePointer>::value << std::endl; std::cout << std::endl << "is_base_of:" << std::endl; std::cout << "<A, B>: " << std::is_base_of<A, B>::value << std::endl; std::cout << "<B, C>: " << std::is_base_of<B, C>::value << std::endl; std::cout << "<A, C>: " << std::is_base_of<A, C>::value << std::endl; std::cout << "<B, A>: " << std::is_base_of<B, A>::value << std::endl; std::cout << "<C, B>: " << std::is_base_of<C, B>::value << std::endl; std::cout << "<C, A>: " << std::is_base_of<C, A>::value << std::endl; std::cout << "<A, D>: " << std::is_base_of<A, D>::value << std::endl; std::cout << "<B, D>: " << std::is_base_of<B, D>::value << std::endl; std::cout << "<C, D>: " << std::is_base_of<C, D>::value << std::endl; std::cout << std::endl << "is_base_of:" << std::endl; std::cout << "<A*, B*>: " << std::is_convertible<A*, B*>::value << std::endl; std::cout << "<B*, C*>: " << std::is_convertible<B*, C*>::value << std::endl; std::cout << "<A*, C*>: " << std::is_convertible<A*, C*>::value << std::endl; std::cout << "<B*, A*>: " << std::is_convertible<B*, A*>::value << std::endl; std::cout << "<C*, B*>: " << std::is_convertible<C*, B*>::value << std::endl; std::cout << "<C*, A*>: " << std::is_convertible<C*, A*>::value << std::endl; return 0; } <commit_msg>modify on languages/program_on_cpp/In_Depth_C++_11/chapter3-type_traits/basic_traits.cpp<commit_after>#include <iostream> #include <type_traits> struct A {}; struct B : A {}; struct C : B {}; struct D {}; int main(void) { // basic trait judgement; std::cout << "is_const:" << std::endl; std::cout << "int: " << std::is_const<int>::value << std::endl; std::cout << "const int: " << std::is_const<const int>::value << std::endl; std::cout << "const int&: " << std::is_const<const int&>::value << std::endl; std::cout << "const int*: " << std::is_const<const int*>::value << std::endl; std::cout << "int* const: " << std::is_const<int* const>::value << std::endl; using DoublePointer = double*; std::cout << std::endl << "is_pointer:" << std::endl; std::cout << "int: " << std::is_pointer<int>::value << std::endl; std::cout << "int*: " << std::is_pointer<int*>::value << std::endl; std::cout << "double*: " << std::is_pointer<DoublePointer>::value << std::endl; // is_same trait; std::cout << std::endl << "is_same:" << std::endl; std::cout << "<int, int>: " << std::is_same<int, int>::value << std::endl; std::cout << "<int, const int>: " << std::is_same<int, const int>::value << std::endl; std::cout << "<int*, int*>: " << std::is_same<int*, int*>::value << std::endl; std::cout << "<double*, double*>: " << std::is_same<DoublePointer, DoublePointer>::value << std::endl; // is_base_of trait; std::cout << std::endl << "is_base_of:" << std::endl; std::cout << "<A, B>: " << std::is_base_of<A, B>::value << std::endl; std::cout << "<B, C>: " << std::is_base_of<B, C>::value << std::endl; std::cout << "<A, C>: " << std::is_base_of<A, C>::value << std::endl; std::cout << "<B, A>: " << std::is_base_of<B, A>::value << std::endl; std::cout << "<C, B>: " << std::is_base_of<C, B>::value << std::endl; std::cout << "<C, A>: " << std::is_base_of<C, A>::value << std::endl; std::cout << "<A, D>: " << std::is_base_of<A, D>::value << std::endl; std::cout << "<B, D>: " << std::is_base_of<B, D>::value << std::endl; std::cout << "<C, D>: " << std::is_base_of<C, D>::value << std::endl; // is_convertible trait; std::cout << std::endl << "is_convertible:" << std::endl; std::cout << "<A*, B*>: " << std::is_convertible<A*, B*>::value << std::endl; std::cout << "<B*, C*>: " << std::is_convertible<B*, C*>::value << std::endl; std::cout << "<A*, C*>: " << std::is_convertible<A*, C*>::value << std::endl; std::cout << "<B*, A*>: " << std::is_convertible<B*, A*>::value << std::endl; std::cout << "<C*, B*>: " << std::is_convertible<C*, B*>::value << std::endl; std::cout << "<C*, A*>: " << std::is_convertible<C*, A*>::value << std::endl; // convert traits; std::cout << std::endl << "trait convert:" << std::endl; std::cout << "<const int, add const to int>: " << std::is_same<const int, std::add_const<int>::type>::value << std::endl; std::cout << "<int, remove const from const int>: " << std::is_same<int, std::remove_const<const int>::type>::value << std::endl; std::cout << "<int*, add pointer to int>: " << std::is_same<int*, std::add_pointer<int>::type>::value << std::endl; std::cout << "<int, remove pointer from int*>: " << std::is_same<int, std::remove_pointer<int*>::type>::value << std::endl; std::cout << "<int&, add lvalue from int>: " << std::is_same<int&, std::add_lvalue_reference<int>::type>::value << std::endl; std::cout << "<int&&, add rvalue from int>: " << std::is_same<int&&, std::add_rvalue_reference<int>::type>::value << std::endl; std::cout << "<int, remove reference from int&>: " << std::is_same<int, std::remove_reference<int&>::type>::value << std::endl; std::cout << "<int, remove reference from int&&>: " << std::is_same<int, std::remove_reference<int&&>::type>::value << std::endl; std::cout << "<int, remove extent from int[]>: " << std::is_same<int, std::remove_extent<int[]>::type>::value << std::endl; std::cout << "<int[2], remove extent from int[][2]>: " << std::is_same<int[2], std::remove_extent<int[][2]>::type>::value << std::endl; std::cout << "<int[2][3], remove extent from int[][2][3]>: " << std::is_same<int[2][3], std::remove_extent<int[][2][3]>::type>::value << std::endl; std::cout << "<int, remove all extent from int[][2]>: " << std::is_same<int, std::remove_all_extents<int[][2]>::type>::value << std::endl; return 0; } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "AudioOutput.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "routing/VoiceNavigationModel.h" #include <QtCore/QDirIterator> #include <phonon/MediaObject> #include <phonon/MediaSource> #include <phonon/AudioOutput> namespace Marble { class AudioOutputPrivate { public: AudioOutput *q; Phonon::MediaObject *m_output; bool m_muted; VoiceNavigationModel m_voiceNavigation; AudioOutputPrivate( AudioOutput* parent ); void audioOutputFinished(); void setupAudio(); void reset(); void playInstructions(); }; AudioOutputPrivate::AudioOutputPrivate( AudioOutput* parent ) : q( parent ), m_output( 0 ), m_muted( false ) { QObject::connect( &m_voiceNavigation, SIGNAL(instructionChanged()), q, SLOT(playInstructions()) ); } void AudioOutputPrivate::audioOutputFinished() { m_output->setCurrentSource( QString() ); m_output->clearQueue(); } void AudioOutputPrivate::setupAudio() { if ( !m_output ) { m_output = new Phonon::MediaObject( q ); Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput( Phonon::VideoCategory, q ); Phonon::createPath( m_output, audioOutput ); q->connect( m_output, SIGNAL(finished()), q, SLOT(audioOutputFinished()) ); } } void AudioOutputPrivate::reset() { if ( m_output ) { m_output->stop(); m_output->setCurrentSource( QString() ); m_output->clearQueue(); } m_voiceNavigation.reset(); } void AudioOutputPrivate::playInstructions() { setupAudio(); if ( m_output ) { m_output->enqueue( m_voiceNavigation.instruction() ); m_output->play(); } } AudioOutput::AudioOutput( QObject* parent ) : QObject( parent ), d( new AudioOutputPrivate( this ) ) { setSoundEnabled( false ); } AudioOutput::~AudioOutput() { delete d; } void AudioOutput::update(const Route &route, qreal distanceManeuver, qreal distanceTarget, bool deviated ) { d->m_voiceNavigation.update( route, distanceManeuver, distanceTarget, deviated ); } void AudioOutput::setMuted( bool muted ) { d->m_muted = muted; } bool AudioOutput::isMuted() const { return d->m_muted; } void AudioOutput::setSpeaker( const QString &speaker ) { d->m_voiceNavigation.setSpeaker( speaker ); } QString AudioOutput::speaker() const { return d->m_voiceNavigation.speaker(); } void AudioOutput::setSoundEnabled( bool enabled ) { d->m_voiceNavigation.setSpeakerEnabled( !enabled ); } bool AudioOutput::isSoundEnabled() const { return d->m_voiceNavigation.isSpeakerEnabled(); } } #include "AudioOutput.moc" <commit_msg>fix speaker enabled toggling between starts of Marble<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "AudioOutput.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "routing/VoiceNavigationModel.h" #include <QtCore/QDirIterator> #include <phonon/MediaObject> #include <phonon/MediaSource> #include <phonon/AudioOutput> namespace Marble { class AudioOutputPrivate { public: AudioOutput *q; Phonon::MediaObject *m_output; bool m_muted; VoiceNavigationModel m_voiceNavigation; AudioOutputPrivate( AudioOutput* parent ); void audioOutputFinished(); void setupAudio(); void reset(); void playInstructions(); }; AudioOutputPrivate::AudioOutputPrivate( AudioOutput* parent ) : q( parent ), m_output( 0 ), m_muted( false ) { QObject::connect( &m_voiceNavigation, SIGNAL(instructionChanged()), q, SLOT(playInstructions()) ); } void AudioOutputPrivate::audioOutputFinished() { m_output->setCurrentSource( QString() ); m_output->clearQueue(); } void AudioOutputPrivate::setupAudio() { if ( !m_output ) { m_output = new Phonon::MediaObject( q ); Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput( Phonon::VideoCategory, q ); Phonon::createPath( m_output, audioOutput ); q->connect( m_output, SIGNAL(finished()), q, SLOT(audioOutputFinished()) ); } } void AudioOutputPrivate::reset() { if ( m_output ) { m_output->stop(); m_output->setCurrentSource( QString() ); m_output->clearQueue(); } m_voiceNavigation.reset(); } void AudioOutputPrivate::playInstructions() { setupAudio(); if ( m_output ) { m_output->enqueue( m_voiceNavigation.instruction() ); m_output->play(); } } AudioOutput::AudioOutput( QObject* parent ) : QObject( parent ), d( new AudioOutputPrivate( this ) ) { setSoundEnabled( false ); } AudioOutput::~AudioOutput() { delete d; } void AudioOutput::update(const Route &route, qreal distanceManeuver, qreal distanceTarget, bool deviated ) { d->m_voiceNavigation.update( route, distanceManeuver, distanceTarget, deviated ); } void AudioOutput::setMuted( bool muted ) { d->m_muted = muted; } bool AudioOutput::isMuted() const { return d->m_muted; } void AudioOutput::setSpeaker( const QString &speaker ) { d->m_voiceNavigation.setSpeaker( speaker ); } QString AudioOutput::speaker() const { return d->m_voiceNavigation.speaker(); } void AudioOutput::setSoundEnabled( bool enabled ) { d->m_voiceNavigation.setSpeakerEnabled( !enabled ); } bool AudioOutput::isSoundEnabled() const { return !d->m_voiceNavigation.isSpeakerEnabled(); } } #include "AudioOutput.moc" <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "CompileConfig.h" #include "Label.h" #include "Engine.h" #include "Renderer.h" #include "Layer.h" #include "Camera.h" #include "BMFont.h" #include "Cache.h" namespace ouzel { std::shared_ptr<Label> Label::create(const std::string& font, const std::string& text, const Vector2& textAnchor) { std::shared_ptr<Label> result = std::make_shared<Label>(); if (!result->init(font, text, textAnchor)) { result.reset(); } return result; } Label::Label() { _shader = Engine::getInstance()->getCache()->getShader(SHADER_TEXTURE); #ifdef OUZEL_PLATFORM_WINDOWS _uniModelViewProj = 0; #else _uniModelViewProj = _shader->getVertexShaderConstantId("modelViewProj"); #endif } Label::~Label() { } bool Label::init(const std::string& font, const std::string& text, const Vector2& textAnchor) { _font.loadFont(font); _textAnchor = textAnchor; _texture = _font.getTexture(); if (!_texture) { return false; } setText(text); return true; } void Label::draw() { Widget::draw(); LayerPtr layer = _layer.lock(); if (_shader && _texture && layer && _meshBuffer) { Engine::getInstance()->getRenderer()->activateTexture(_texture, 0); Engine::getInstance()->getRenderer()->activateShader(_shader); Matrix4 modelViewProj = layer->getCamera()->getViewProjection() * _transform; _shader->setVertexShaderConstant(_uniModelViewProj, { modelViewProj }); Engine::getInstance()->getRenderer()->drawMeshBuffer(_meshBuffer); } } void Label::setText(const std::string& text) { _text = text; if (_text.empty()) { _meshBuffer.reset(); } else { _meshBuffer = _font.createMeshBuffer(_text, _color, _textAnchor); } } void Label::setColor(const Color& color) { _meshBuffer = _font.createMeshBuffer(_text, _color, _textAnchor); } } <commit_msg>Fix label color setter<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "CompileConfig.h" #include "Label.h" #include "Engine.h" #include "Renderer.h" #include "Layer.h" #include "Camera.h" #include "BMFont.h" #include "Cache.h" namespace ouzel { std::shared_ptr<Label> Label::create(const std::string& font, const std::string& text, const Vector2& textAnchor) { std::shared_ptr<Label> result = std::make_shared<Label>(); if (!result->init(font, text, textAnchor)) { result.reset(); } return result; } Label::Label() { _shader = Engine::getInstance()->getCache()->getShader(SHADER_TEXTURE); #ifdef OUZEL_PLATFORM_WINDOWS _uniModelViewProj = 0; #else _uniModelViewProj = _shader->getVertexShaderConstantId("modelViewProj"); #endif } Label::~Label() { } bool Label::init(const std::string& font, const std::string& text, const Vector2& textAnchor) { _font.loadFont(font); _textAnchor = textAnchor; _texture = _font.getTexture(); if (!_texture) { return false; } setText(text); return true; } void Label::draw() { Widget::draw(); LayerPtr layer = _layer.lock(); if (_shader && _texture && layer && _meshBuffer) { Engine::getInstance()->getRenderer()->activateTexture(_texture, 0); Engine::getInstance()->getRenderer()->activateShader(_shader); Matrix4 modelViewProj = layer->getCamera()->getViewProjection() * _transform; _shader->setVertexShaderConstant(_uniModelViewProj, { modelViewProj }); Engine::getInstance()->getRenderer()->drawMeshBuffer(_meshBuffer); } } void Label::setText(const std::string& text) { _text = text; if (_text.empty()) { _meshBuffer.reset(); } else { _meshBuffer = _font.createMeshBuffer(_text, _color, _textAnchor); } } void Label::setColor(const Color& color) { _color = color; _meshBuffer = _font.createMeshBuffer(_text, _color, _textAnchor); } } <|endoftext|>
<commit_before>#include "browser/views/inspectable_web_contents_view_views.h" #include "browser/inspectable_web_contents_delegate.h" #include "browser/inspectable_web_contents_impl.h" #include "browser/inspectable_web_contents_view_delegate.h" #include "base/strings/utf_string_conversions.h" #include "ui/views/controls/label.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/window/client_view.h" namespace brightray { namespace { class DevToolsWindowDelegate : public views::ClientView, public views::WidgetDelegate { public: DevToolsWindowDelegate(InspectableWebContentsViewViews* shell, views::View* view, views::Widget* widget) : views::ClientView(widget, view), shell_(shell), view_(view), widget_(widget), title_(base::ASCIIToUTF16("Developer Tools")) { // A WidgetDelegate should be deleted on DeleteDelegate. set_owned_by_client(); if (shell->GetDelegate()) icon_ = shell->GetDelegate()->GetDevToolsWindowIcon(); } virtual ~DevToolsWindowDelegate() {} void SetWindowTitle(const base::string16& title) { title_ = title; } // views::WidgetDelegate: void DeleteDelegate() override { delete this; } views::View* GetInitiallyFocusedView() override { return view_; } bool CanResize() const override { return true; } bool CanMaximize() const override { return true; } bool CanMinimize() const override { return true; } base::string16 GetWindowTitle() const override { return title_; } gfx::ImageSkia GetWindowAppIcon() override { return GetWindowIcon(); } gfx::ImageSkia GetWindowIcon() override { return icon_; } views::Widget* GetWidget() override { return widget_; } const views::Widget* GetWidget() const override { return widget_; } views::View* GetContentsView() override { return view_; } views::ClientView* CreateClientView(views::Widget* widget) override { return this; } // views::ClientView: bool CanClose() override { shell_->inspectable_web_contents()->CloseDevTools(); return false; } private: InspectableWebContentsViewViews* shell_; views::View* view_; views::Widget* widget_; base::string16 title_; gfx::ImageSkia icon_; DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate); }; } // namespace InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContentsImpl* inspectable_web_contents) { return new InspectableWebContentsViewViews(inspectable_web_contents); } InspectableWebContentsViewViews::InspectableWebContentsViewViews( InspectableWebContentsImpl* inspectable_web_contents) : inspectable_web_contents_(inspectable_web_contents), devtools_window_web_view_(nullptr), contents_web_view_(nullptr), devtools_web_view_(new views::WebView(nullptr)), devtools_visible_(false), devtools_window_delegate_(nullptr) { set_owned_by_client(); if (inspectable_web_contents_->GetWebContents()->GetNativeView()) { views::WebView* contents_web_view = new views::WebView(nullptr); contents_web_view->SetWebContents(inspectable_web_contents_->GetWebContents()); contents_web_view_ = contents_web_view; } else { contents_web_view_ = new views::Label(L"No content under offscreen mode"); } devtools_web_view_->SetVisible(false); AddChildView(devtools_web_view_); AddChildView(contents_web_view_); } InspectableWebContentsViewViews::~InspectableWebContentsViewViews() { if (devtools_window_) inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen()); } views::View* InspectableWebContentsViewViews::GetView() { return this; } views::View* InspectableWebContentsViewViews::GetWebView() { return contents_web_view_; } void InspectableWebContentsViewViews::ShowDevTools() { if (devtools_visible_) return; devtools_visible_ = true; if (devtools_window_) { devtools_window_web_view_->SetWebContents( inspectable_web_contents_->GetDevToolsWebContents()); devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds()); devtools_window_->Show(); } else { devtools_web_view_->SetVisible(true); devtools_web_view_->SetWebContents( inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_view_->RequestFocus(); Layout(); } } void InspectableWebContentsViewViews::CloseDevTools() { if (!devtools_visible_) return; devtools_visible_ = false; if (devtools_window_) { inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen()); devtools_window_.reset(); devtools_window_web_view_ = nullptr; devtools_window_delegate_ = nullptr; } else { devtools_web_view_->SetVisible(false); devtools_web_view_->SetWebContents(NULL); Layout(); } } bool InspectableWebContentsViewViews::IsDevToolsViewShowing() { return devtools_visible_; } bool InspectableWebContentsViewViews::IsDevToolsViewFocused() { if (devtools_window_web_view_) return devtools_window_web_view_->HasFocus(); else if (devtools_web_view_) return devtools_web_view_->HasFocus(); else return false; } void InspectableWebContentsViewViews::SetIsDocked(bool docked) { CloseDevTools(); if (!docked) { devtools_window_.reset(new views::Widget); devtools_window_web_view_ = new views::WebView(NULL); devtools_window_delegate_ = new DevToolsWindowDelegate(this, devtools_window_web_view_, devtools_window_.get()); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.delegate = GetDevToolsWindowDelegate(); params.bounds = inspectable_web_contents()->GetDevToolsBounds(); #if defined(USE_X11) params.wm_role_name = "devtools"; if (GetDelegate()) GetDelegate()->GetDevToolsWindowWMClass(&params.wm_class_name, &params.wm_class_class); #endif devtools_window_->Init(params); devtools_window_->UpdateWindowIcon(); } ShowDevTools(); } void InspectableWebContentsViewViews::SetContentsResizingStrategy( const DevToolsContentsResizingStrategy& strategy) { strategy_.CopyFrom(strategy); Layout(); } void InspectableWebContentsViewViews::SetTitle(const base::string16& title) { if (devtools_window_) { GetDevToolsWindowDelegate()->SetWindowTitle(title); devtools_window_->UpdateWindowTitle(); } } void InspectableWebContentsViewViews::Layout() { if (!devtools_web_view_->visible()) { contents_web_view_->SetBoundsRect(GetContentsBounds()); return; } gfx::Size container_size(width(), height()); gfx::Rect new_devtools_bounds; gfx::Rect new_contents_bounds; ApplyDevToolsContentsResizingStrategy(strategy_, container_size, &new_devtools_bounds, &new_contents_bounds); // DevTools cares about the specific position, so we have to compensate RTL // layout here. new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds)); new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds)); devtools_web_view_->SetBoundsRect(new_devtools_bounds); contents_web_view_->SetBoundsRect(new_contents_bounds); } } // namespace brightray <commit_msg>Fix building under linux<commit_after>#include "browser/views/inspectable_web_contents_view_views.h" #include "browser/inspectable_web_contents_delegate.h" #include "browser/inspectable_web_contents_impl.h" #include "browser/inspectable_web_contents_view_delegate.h" #include "base/strings/utf_string_conversions.h" #include "ui/views/controls/label.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/window/client_view.h" namespace brightray { namespace { class DevToolsWindowDelegate : public views::ClientView, public views::WidgetDelegate { public: DevToolsWindowDelegate(InspectableWebContentsViewViews* shell, views::View* view, views::Widget* widget) : views::ClientView(widget, view), shell_(shell), view_(view), widget_(widget), title_(base::ASCIIToUTF16("Developer Tools")) { // A WidgetDelegate should be deleted on DeleteDelegate. set_owned_by_client(); if (shell->GetDelegate()) icon_ = shell->GetDelegate()->GetDevToolsWindowIcon(); } virtual ~DevToolsWindowDelegate() {} void SetWindowTitle(const base::string16& title) { title_ = title; } // views::WidgetDelegate: void DeleteDelegate() override { delete this; } views::View* GetInitiallyFocusedView() override { return view_; } bool CanResize() const override { return true; } bool CanMaximize() const override { return true; } bool CanMinimize() const override { return true; } base::string16 GetWindowTitle() const override { return title_; } gfx::ImageSkia GetWindowAppIcon() override { return GetWindowIcon(); } gfx::ImageSkia GetWindowIcon() override { return icon_; } views::Widget* GetWidget() override { return widget_; } const views::Widget* GetWidget() const override { return widget_; } views::View* GetContentsView() override { return view_; } views::ClientView* CreateClientView(views::Widget* widget) override { return this; } // views::ClientView: bool CanClose() override { shell_->inspectable_web_contents()->CloseDevTools(); return false; } private: InspectableWebContentsViewViews* shell_; views::View* view_; views::Widget* widget_; base::string16 title_; gfx::ImageSkia icon_; DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate); }; } // namespace InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContentsImpl* inspectable_web_contents) { return new InspectableWebContentsViewViews(inspectable_web_contents); } InspectableWebContentsViewViews::InspectableWebContentsViewViews( InspectableWebContentsImpl* inspectable_web_contents) : inspectable_web_contents_(inspectable_web_contents), devtools_window_web_view_(nullptr), contents_web_view_(nullptr), devtools_web_view_(new views::WebView(nullptr)), devtools_visible_(false), devtools_window_delegate_(nullptr) { set_owned_by_client(); if (inspectable_web_contents_->GetWebContents()->GetNativeView()) { views::WebView* contents_web_view = new views::WebView(nullptr); contents_web_view->SetWebContents(inspectable_web_contents_->GetWebContents()); contents_web_view_ = contents_web_view; } else { contents_web_view_ = new views::Label(base::ASCIIToUTF16("No content under offscreen mode")); } devtools_web_view_->SetVisible(false); AddChildView(devtools_web_view_); AddChildView(contents_web_view_); } InspectableWebContentsViewViews::~InspectableWebContentsViewViews() { if (devtools_window_) inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen()); } views::View* InspectableWebContentsViewViews::GetView() { return this; } views::View* InspectableWebContentsViewViews::GetWebView() { return contents_web_view_; } void InspectableWebContentsViewViews::ShowDevTools() { if (devtools_visible_) return; devtools_visible_ = true; if (devtools_window_) { devtools_window_web_view_->SetWebContents( inspectable_web_contents_->GetDevToolsWebContents()); devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds()); devtools_window_->Show(); } else { devtools_web_view_->SetVisible(true); devtools_web_view_->SetWebContents( inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_view_->RequestFocus(); Layout(); } } void InspectableWebContentsViewViews::CloseDevTools() { if (!devtools_visible_) return; devtools_visible_ = false; if (devtools_window_) { inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen()); devtools_window_.reset(); devtools_window_web_view_ = nullptr; devtools_window_delegate_ = nullptr; } else { devtools_web_view_->SetVisible(false); devtools_web_view_->SetWebContents(NULL); Layout(); } } bool InspectableWebContentsViewViews::IsDevToolsViewShowing() { return devtools_visible_; } bool InspectableWebContentsViewViews::IsDevToolsViewFocused() { if (devtools_window_web_view_) return devtools_window_web_view_->HasFocus(); else if (devtools_web_view_) return devtools_web_view_->HasFocus(); else return false; } void InspectableWebContentsViewViews::SetIsDocked(bool docked) { CloseDevTools(); if (!docked) { devtools_window_.reset(new views::Widget); devtools_window_web_view_ = new views::WebView(NULL); devtools_window_delegate_ = new DevToolsWindowDelegate(this, devtools_window_web_view_, devtools_window_.get()); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.delegate = GetDevToolsWindowDelegate(); params.bounds = inspectable_web_contents()->GetDevToolsBounds(); #if defined(USE_X11) params.wm_role_name = "devtools"; if (GetDelegate()) GetDelegate()->GetDevToolsWindowWMClass(&params.wm_class_name, &params.wm_class_class); #endif devtools_window_->Init(params); devtools_window_->UpdateWindowIcon(); } ShowDevTools(); } void InspectableWebContentsViewViews::SetContentsResizingStrategy( const DevToolsContentsResizingStrategy& strategy) { strategy_.CopyFrom(strategy); Layout(); } void InspectableWebContentsViewViews::SetTitle(const base::string16& title) { if (devtools_window_) { GetDevToolsWindowDelegate()->SetWindowTitle(title); devtools_window_->UpdateWindowTitle(); } } void InspectableWebContentsViewViews::Layout() { if (!devtools_web_view_->visible()) { contents_web_view_->SetBoundsRect(GetContentsBounds()); return; } gfx::Size container_size(width(), height()); gfx::Rect new_devtools_bounds; gfx::Rect new_contents_bounds; ApplyDevToolsContentsResizingStrategy(strategy_, container_size, &new_devtools_bounds, &new_contents_bounds); // DevTools cares about the specific position, so we have to compensate RTL // layout here. new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds)); new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds)); devtools_web_view_->SetBoundsRect(new_devtools_bounds); contents_web_view_->SetBoundsRect(new_contents_bounds); } } // namespace brightray <|endoftext|>
<commit_before>#include "chacha20.h" static Nan::Persistent<v8::FunctionTemplate> chacha20_constructor; ChaCha20::ChaCha20() {} ChaCha20::~ChaCha20() {} void ChaCha20::Init(v8::Local<v8::Object> &target) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(ChaCha20::New); chacha20_constructor.Reset(tpl); tpl->SetClassName(Nan::New("ChaCha20").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "init", ChaCha20::Init); Nan::SetPrototypeMethod(tpl, "initIV", ChaCha20::InitIV); Nan::SetPrototypeMethod(tpl, "initKey", ChaCha20::InitKey); Nan::SetPrototypeMethod(tpl, "encrypt", ChaCha20::Encrypt); Nan::SetPrototypeMethod(tpl, "setCounter", ChaCha20::SetCounter); Nan::SetPrototypeMethod(tpl, "getCounter", ChaCha20::GetCounter); v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(chacha20_constructor); target->Set(Nan::New("ChaCha20").ToLocalChecked(), ctor->GetFunction()); } NAN_METHOD(ChaCha20::New) { ChaCha20* chacha = new ChaCha20(); chacha->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_METHOD(ChaCha20::Init) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.init() requires arguments."); v8::Local<v8::Object> key = info[0].As<v8::Object>(); if (!key->IsNull() && !key->IsUndefined()) chacha->InitKey(key); if (info.Length() > 1) { v8::Local<v8::Object> iv = info[1].As<v8::Object>(); if (!iv->IsNull() && !iv->IsUndefined()) { v8::Local<v8::Value> num = Nan::New<v8::Number>(0); if (info.Length() > 2 && info[2]->IsNumber()) num = v8::Local<v8::Value>::Cast(info[2]); chacha->InitIV(iv, num); } } } void ChaCha20::InitKey(v8::Local<v8::Object> &key) { Nan::HandleScope scope; if (!node::Buffer::HasInstance(key)) return Nan::ThrowTypeError("First argument must be a Buffer."); const uint8_t *data = (uint8_t *)node::Buffer::Data(key); size_t len = node::Buffer::Length(key); if (len != 32) return Nan::ThrowError("Invalid key size."); chacha20_keysetup(&ctx, data, 32); } void ChaCha20::InitIV(v8::Local<v8::Object> &iv, v8::Local<v8::Value> &num) { Nan::HandleScope scope; if (!node::Buffer::HasInstance(iv)) return Nan::ThrowTypeError("First argument must be a Buffer."); uint32_t ctr = 0; if (num->IsNumber()) ctr = v8::Local<v8::Integer>::Cast(num)->Value(); const uint8_t *data = (uint8_t *)node::Buffer::Data(iv); size_t len = node::Buffer::Length(iv); if (len != 8 && len != 12) return Nan::ThrowError("Invalid IV size."); chacha20_ivsetup(&ctx, (uint8_t *)data, (uint8_t)len); chacha20_counter_set(&ctx, ctr); } NAN_METHOD(ChaCha20::InitIV) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.init() requires arguments."); v8::Local<v8::Object> buf = info[0].As<v8::Object>(); v8::Local<v8::Value> num = Nan::New<v8::Number>(0); if (info.Length() > 1) num = v8::Local<v8::Value>::Cast(info[1]); chacha->InitIV(buf, num); } NAN_METHOD(ChaCha20::InitKey) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.init() requires arguments."); v8::Local<v8::Object> buf = info[0].As<v8::Object>(); if (!node::Buffer::HasInstance(buf)) return Nan::ThrowTypeError("First argument must be a Buffer."); chacha->InitKey(buf); } NAN_METHOD(ChaCha20::Encrypt) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.update() requires arguments."); v8::Local<v8::Object> buf = info[0].As<v8::Object>(); if (!node::Buffer::HasInstance(buf)) return Nan::ThrowTypeError("First argument must be a Buffer."); const uint8_t *data = (uint8_t *)node::Buffer::Data(buf); size_t len = node::Buffer::Length(buf); chacha20_encrypt(&chacha->ctx, (uint8_t *)data, (uint8_t *)data, len); info.GetReturnValue().Set(buf); } NAN_METHOD(ChaCha20::SetCounter) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.setCounter() requires arguments."); v8::Local<v8::Object> num = info[0].As<v8::Object>(); if (!num->IsNumber()) return Nan::ThrowError("First argument must be a number."); uint64_t ctr = v8::Local<v8::Integer>::Cast(num)->Value(); chacha20_counter_set(&chacha->ctx, ctr); } NAN_METHOD(ChaCha20::GetCounter) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); info.GetReturnValue().Set( Nan::New<v8::Number>((double)chacha20_counter_get(&chacha->ctx))); } <commit_msg>chacha20: fix 64 bit counters.<commit_after>#include "chacha20.h" static Nan::Persistent<v8::FunctionTemplate> chacha20_constructor; ChaCha20::ChaCha20() {} ChaCha20::~ChaCha20() {} void ChaCha20::Init(v8::Local<v8::Object> &target) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(ChaCha20::New); chacha20_constructor.Reset(tpl); tpl->SetClassName(Nan::New("ChaCha20").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "init", ChaCha20::Init); Nan::SetPrototypeMethod(tpl, "initIV", ChaCha20::InitIV); Nan::SetPrototypeMethod(tpl, "initKey", ChaCha20::InitKey); Nan::SetPrototypeMethod(tpl, "encrypt", ChaCha20::Encrypt); Nan::SetPrototypeMethod(tpl, "setCounter", ChaCha20::SetCounter); Nan::SetPrototypeMethod(tpl, "getCounter", ChaCha20::GetCounter); v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(chacha20_constructor); target->Set(Nan::New("ChaCha20").ToLocalChecked(), ctor->GetFunction()); } NAN_METHOD(ChaCha20::New) { ChaCha20* chacha = new ChaCha20(); chacha->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_METHOD(ChaCha20::Init) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.init() requires arguments."); v8::Local<v8::Object> key = info[0].As<v8::Object>(); if (!key->IsNull() && !key->IsUndefined()) chacha->InitKey(key); if (info.Length() > 1) { v8::Local<v8::Object> iv = info[1].As<v8::Object>(); if (!iv->IsNull() && !iv->IsUndefined()) { v8::Local<v8::Value> num = Nan::New<v8::Number>(0); if (info.Length() > 2 && info[2]->IsNumber()) num = v8::Local<v8::Value>::Cast(info[2]); chacha->InitIV(iv, num); } } } void ChaCha20::InitKey(v8::Local<v8::Object> &key) { Nan::HandleScope scope; if (!node::Buffer::HasInstance(key)) return Nan::ThrowTypeError("First argument must be a Buffer."); const uint8_t *data = (uint8_t *)node::Buffer::Data(key); size_t len = node::Buffer::Length(key); if (len != 32) return Nan::ThrowError("Invalid key size."); chacha20_keysetup(&ctx, data, 32); } void ChaCha20::InitIV(v8::Local<v8::Object> &iv, v8::Local<v8::Value> &num) { Nan::HandleScope scope; if (!node::Buffer::HasInstance(iv)) return Nan::ThrowTypeError("First argument must be a Buffer."); const uint8_t *data = (uint8_t *)node::Buffer::Data(iv); size_t len = node::Buffer::Length(iv); if (len != 8 && len != 12) return Nan::ThrowError("Invalid IV size."); uint64_t ctr = 0; if (num->IsNumber()) ctr = (uint64_t)v8::Local<v8::Integer>::Cast(num)->Value(); chacha20_ivsetup(&ctx, (uint8_t *)data, (uint8_t)len); chacha20_counter_set(&ctx, ctr); } NAN_METHOD(ChaCha20::InitIV) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.init() requires arguments."); v8::Local<v8::Object> buf = info[0].As<v8::Object>(); v8::Local<v8::Value> num = Nan::New<v8::Number>(0); if (info.Length() > 1) num = v8::Local<v8::Value>::Cast(info[1]); chacha->InitIV(buf, num); } NAN_METHOD(ChaCha20::InitKey) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.init() requires arguments."); v8::Local<v8::Object> buf = info[0].As<v8::Object>(); if (!node::Buffer::HasInstance(buf)) return Nan::ThrowTypeError("First argument must be a Buffer."); chacha->InitKey(buf); } NAN_METHOD(ChaCha20::Encrypt) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.update() requires arguments."); v8::Local<v8::Object> buf = info[0].As<v8::Object>(); if (!node::Buffer::HasInstance(buf)) return Nan::ThrowTypeError("First argument must be a Buffer."); const uint8_t *data = (uint8_t *)node::Buffer::Data(buf); size_t len = node::Buffer::Length(buf); chacha20_encrypt(&chacha->ctx, (uint8_t *)data, (uint8_t *)data, len); info.GetReturnValue().Set(buf); } NAN_METHOD(ChaCha20::SetCounter) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); if (info.Length() < 1) return Nan::ThrowError("chacha20.setCounter() requires arguments."); v8::Local<v8::Object> num = info[0].As<v8::Object>(); if (!num->IsNumber()) return Nan::ThrowError("First argument must be a number."); uint64_t ctr = v8::Local<v8::Integer>::Cast(num)->Value(); chacha20_counter_set(&chacha->ctx, ctr); } NAN_METHOD(ChaCha20::GetCounter) { ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder()); info.GetReturnValue().Set( Nan::New<v8::Number>((double)chacha20_counter_get(&chacha->ctx))); } <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS # define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1 #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1 #endif #define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING // This one has to come first (includes the config.h)! #include <dune/stuff/test/main.hxx> #include <vector> #include <string> #include <map> #if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # include <dune/pymor/parameters/base.hh> # include <dune/hdd/linearelliptic/testcases/OS2014.hh> # include <dune/hdd/linearelliptic/testcases/spe10.hh> # include "linearelliptic-block-swipdg.hh" # include "linearelliptic-block-swipdg-expectations.hh" using namespace Dune; using namespace HDD; typedef ALUGrid< 2, 2, simplex, conforming > GridType; typedef LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridType > SmoothTestCaseType; typedef LinearElliptic::Tests::BlockSWIPDGStudy< SmoothTestCaseType > SmoothStudyType; typedef LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridType > MultiscaleTestCaseType; typedef LinearElliptic::Tests::BlockSWIPDGStudy< MultiscaleTestCaseType > MultiscaleStudyType; template< class TestCaseType > void print_parameter_information(const TestCaseType& test_case) { const auto& parameters = test_case.parameters(); const auto& problem = test_case.problem(); for (auto parameter : parameters) EXPECT_EQ(parameter.second.type(), problem.parameter_type()) << " id: " << parameter.first << ", parameter: " << parameter.second; const auto& diffusion_factor = *problem.diffusion_factor(); const auto& diffusion_tensor = *problem.diffusion_tensor(); const auto& force = *problem.force(); const auto& dirichlet = *problem.dirichlet(); const auto& neumann = *problem.neumann(); EXPECT_TRUE(diffusion_factor.parametric()); EXPECT_FALSE(diffusion_tensor.parametric()); EXPECT_FALSE(force.parametric()); EXPECT_FALSE(dirichlet.parametric()); EXPECT_FALSE(neumann.parametric()); DSC_LOG_INFO << "| mu = " << parameters.at("mu") << "\n" << "| mu_bar = " << parameters.at("mu_bar") << "\n" << "| mu_hat = " << parameters.at("mu_hat") << "\n" << "| mu_minimizing = " << parameters.at("mu_minimizing") << "\n"; const double alpha = diffusion_factor.alpha(parameters.at("mu"), parameters.at("mu_hat")); const double gamma = diffusion_factor.gamma(parameters.at("mu"), parameters.at("mu_hat")); DSC_LOG_INFO << "| alpha(mu, mu_hat)^-1/2 = " << std::setprecision(2) << std::scientific << 1.0/std::sqrt(alpha) << "\n" << "| gamma_tilde(mu, mu_hat)^2 = " << std::setprecision(2) << std::scientific << std::max(std::sqrt(gamma), 1.0/std::sqrt(alpha)) << "\n" << "+\n"; } // ... print_parameter_information(...) template< class TestCaseType, class StudyType > void run_eoc_study(const std::string partitioning, const std::vector< std::string >& only_these_norms, const std::map< std::string, Pymor::Parameter >& parameters, const bool print_header, const std::string visualization) { const TestCaseType test_case(parameters, partitioning); if (print_header) test_case.print_header(DSC_LOG_INFO); print_parameter_information(test_case); StudyType study(test_case, only_these_norms, {}, visualization); Stuff::Test::check_eoc_study_for_success(study, study.run_eoc(DSC_LOG_INFO)); } // ... run_eoc_study(...) TEST(OS2014_parametric_convergence_study, eta_DF_comparison) { const std::string partitioning = "[4 4 1]"; const std::vector< std::string > only_these_norms = {"eta_DF_OS2014", "eta_DF_OS2014_*", "eta_OS2014", "eta_OS2014_*", "eff_OS2014_mu", "eff_OS2014_*_mu"}; const std::string visualization_prefix = ""; //"OS2014_parametric_block_convergence_study_eta_DF_comparison"; bool print_header = true; for (auto mu_hat_value : {0.1/*, 0.5*/, 1.0}) { const auto mu_hat = Pymor::Parameter("mu", mu_hat_value); for (auto mu_value : {0.1/*, 0.3, 0.5, 0.75*/, 1.0}) { const auto mu = Pymor::Parameter("mu", mu_value); const auto mu_bar = mu; run_eoc_study< SmoothTestCaseType, SmoothStudyType >(partitioning, only_these_norms, {{"mu_hat", mu_hat}, {"mu_bar", mu_bar}, {"mu", mu}, {"mu_minimizing", Pymor::Parameter("mu", 0.1)}}, print_header, visualization_prefix); if (print_header) print_header = false; } } } // TEST(OS2014_parametric_convergence_study, eta_DF_comparison) TEST(OS2014_parametric_convergence_study, multiscale) { const std::string partitioning = "[20 4 1]"; const std::vector< std::string > only_these_norms = {"energy_mu", "eta_OS2014", "eta_OS2014_*"}; const std::string visualization_prefix = ""; //"OS2014_parametric_block_convergence_study_spe10_model1"; bool print_header = true; for (auto mu_hat_value : {0.1/*, 0.5*/, 1.0}) { const auto mu_hat = Pymor::Parameter("mu", mu_hat_value); for (auto mu_value : {0.1/*, 0.3, 0.5, 0.75*/, 1.0}) { const auto mu = Pymor::Parameter("mu", mu_value); const auto mu_bar = mu; run_eoc_study< MultiscaleTestCaseType, MultiscaleStudyType >(partitioning, only_these_norms, {{"mu_hat", mu_hat}, {"mu_bar", mu_bar}, {"mu", mu}, {"mu_minimizing", Pymor::Parameter("mu", 0.1)}}, print_header, visualization_prefix); if (print_header) print_header = false; } } } // TEST(OS2014_parametric_convergence_study, multiscale) extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< SmoothTestCaseType >; extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< MultiscaleTestCaseType >; #else // HAVE_ALUGRID TEST(DISABLED_OS2014_parametric_convergence_study, eta_DF_comparison) {} TEST(DISABLED_OS2014_parametric_convergence_study, multiscale) {} #endif // HAVE_ALUGRID <commit_msg>[test.OS2014...] drop mu_minimizing<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS # define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1 #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1 #endif #define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING // This one has to come first (includes the config.h)! #include <dune/stuff/test/main.hxx> #include <vector> #include <string> #include <map> #if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # include <dune/pymor/parameters/base.hh> # include <dune/hdd/linearelliptic/testcases/OS2014.hh> # include <dune/hdd/linearelliptic/testcases/spe10.hh> # include "linearelliptic-block-swipdg.hh" # include "linearelliptic-block-swipdg-expectations.hh" using namespace Dune; using namespace HDD; typedef ALUGrid< 2, 2, simplex, conforming > GridType; typedef LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridType > SmoothTestCaseType; typedef LinearElliptic::Tests::BlockSWIPDGStudy< SmoothTestCaseType > SmoothStudyType; typedef LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridType > MultiscaleTestCaseType; typedef LinearElliptic::Tests::BlockSWIPDGStudy< MultiscaleTestCaseType > MultiscaleStudyType; template< class TestCaseType > void print_parameter_information(const TestCaseType& test_case) { const auto& parameters = test_case.parameters(); const auto& problem = test_case.problem(); for (auto parameter : parameters) EXPECT_EQ(parameter.second.type(), problem.parameter_type()) << " id: " << parameter.first << ", parameter: " << parameter.second; const auto& diffusion_factor = *problem.diffusion_factor(); const auto& diffusion_tensor = *problem.diffusion_tensor(); const auto& force = *problem.force(); const auto& dirichlet = *problem.dirichlet(); const auto& neumann = *problem.neumann(); EXPECT_TRUE(diffusion_factor.parametric()); EXPECT_FALSE(diffusion_tensor.parametric()); EXPECT_FALSE(force.parametric()); EXPECT_FALSE(dirichlet.parametric()); EXPECT_FALSE(neumann.parametric()); DSC_LOG_INFO << "| mu = " << parameters.at("mu") << "\n" << "| mu_bar = " << parameters.at("mu_bar") << "\n" << "| mu_hat = " << parameters.at("mu_hat") << "\n"; const double alpha = diffusion_factor.alpha(parameters.at("mu"), parameters.at("mu_hat")); const double gamma = diffusion_factor.gamma(parameters.at("mu"), parameters.at("mu_hat")); DSC_LOG_INFO << "| alpha(mu, mu_hat)^-1/2 = " << std::setprecision(2) << std::scientific << 1.0/std::sqrt(alpha) << "\n" << "| gamma_tilde(mu, mu_hat)^2 = " << std::setprecision(2) << std::scientific << std::max(std::sqrt(gamma), 1.0/std::sqrt(alpha)) << "\n" << "+\n"; } // ... print_parameter_information(...) template< class TestCaseType, class StudyType > void run_eoc_study(const std::string partitioning, const std::vector< std::string >& only_these_norms, const std::map< std::string, Pymor::Parameter >& parameters, const bool print_header, const std::string visualization) { const TestCaseType test_case(parameters, partitioning); if (print_header) test_case.print_header(DSC_LOG_INFO); print_parameter_information(test_case); StudyType study(test_case, only_these_norms, {}, visualization); Stuff::Test::check_eoc_study_for_success(study, study.run_eoc(DSC_LOG_INFO)); } // ... run_eoc_study(...) TEST(OS2014_parametric_convergence_study, eta_DF_comparison) { const std::string partitioning = "[4 4 1]"; const std::vector< std::string > only_these_norms = {"eta_DF_OS2014", "eta_DF_OS2014_*", "eta_OS2014", "eta_OS2014_*", "eff_OS2014_mu", "eff_OS2014_*_mu"}; const std::string visualization_prefix = ""; //"OS2014_parametric_block_convergence_study_eta_DF_comparison"; bool print_header = true; for (auto mu_hat_value : {0.1/*, 0.5*/, 1.0}) { const auto mu_hat = Pymor::Parameter("mu", mu_hat_value); for (auto mu_value : {0.1/*, 0.3, 0.5, 0.75*/, 1.0}) { const auto mu = Pymor::Parameter("mu", mu_value); const auto mu_bar = mu; run_eoc_study< SmoothTestCaseType, SmoothStudyType >(partitioning, only_these_norms, {{"mu_hat", mu_hat}, {"mu_bar", mu_bar}, {"mu", mu}}, print_header, visualization_prefix); if (print_header) print_header = false; } } } // TEST(OS2014_parametric_convergence_study, eta_DF_comparison) TEST(OS2014_parametric_convergence_study, multiscale) { const std::string partitioning = "[20 4 1]"; const std::vector< std::string > only_these_norms = {"energy_mu", "eta_OS2014", "eta_OS2014_*"}; const std::string visualization_prefix = ""; //"OS2014_parametric_block_convergence_study_spe10_model1"; bool print_header = true; for (auto mu_hat_value : {0.1/*, 0.5*/, 1.0}) { const auto mu_hat = Pymor::Parameter("mu", mu_hat_value); for (auto mu_value : {0.1/*, 0.3, 0.5, 0.75*/, 1.0}) { const auto mu = Pymor::Parameter("mu", mu_value); const auto mu_bar = mu; run_eoc_study< MultiscaleTestCaseType, MultiscaleStudyType >(partitioning, only_these_norms, {{"mu_hat", mu_hat}, {"mu_bar", mu_bar}, {"mu", mu}}, print_header, visualization_prefix); if (print_header) print_header = false; } } } // TEST(OS2014_parametric_convergence_study, multiscale) extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< SmoothTestCaseType >; extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< MultiscaleTestCaseType >; #else // HAVE_ALUGRID TEST(DISABLED_OS2014_parametric_convergence_study, eta_DF_comparison) {} TEST(DISABLED_OS2014_parametric_convergence_study, multiscale) {} #endif // HAVE_ALUGRID <|endoftext|>
<commit_before><commit_msg>fixed vs2017 compile error<commit_after><|endoftext|>
<commit_before><commit_msg>Fix per-application DPI scaling. Make DPI scaling dropdown box require Windows Vista or above.<commit_after><|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <GLES2/gl2.h> #include <GLES2/gl2chromium.h> #include <GLES2/gl2ext.h> #include <GLES2/gl2extchromium.h> #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/process/process_handle.h" #include "gpu/command_buffer/client/gles2_implementation.h" #include "gpu/command_buffer/service/command_buffer_service.h" #include "gpu/command_buffer/service/image_manager.h" #include "gpu/command_buffer/tests/gl_manager.h" #include "gpu/command_buffer/tests/gl_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gl/gl_image.h" using testing::_; using testing::IgnoreResult; using testing::InvokeWithoutArgs; using testing::Invoke; using testing::Return; using testing::SetArgPointee; using testing::StrictMock; namespace gpu { namespace gles2 { static const int kImageWidth = 32; static const int kImageHeight = 32; class GpuMemoryBufferTest : public testing::TestWithParam<gfx::GpuMemoryBuffer::Format> { protected: void SetUp() override { gl_.Initialize(GLManager::Options()); gl_.MakeCurrent(); glGenTextures(2, texture_ids_); glBindTexture(GL_TEXTURE_2D, texture_ids_[1]); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glGenFramebuffers(1, &framebuffer_id_); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id_); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_ids_[1], 0); } void TearDown() override { glDeleteTextures(2, texture_ids_); glDeleteFramebuffers(1, &framebuffer_id_); gl_.Destroy(); } GLManager gl_; GLuint texture_ids_[2]; GLuint framebuffer_id_; }; namespace { std::vector<uint8> GetTexturePixel(const gfx::GpuMemoryBuffer::Format format) { std::vector<uint8> pixel; switch (format) { case gfx::GpuMemoryBuffer::RGBA_8888: pixel.push_back(255u); pixel.push_back(0u); pixel.push_back(0u); pixel.push_back(255u); return pixel; case gfx::GpuMemoryBuffer::BGRA_8888: pixel.push_back(0u); pixel.push_back(0u); pixel.push_back(255u); pixel.push_back(255u); return pixel; case gfx::GpuMemoryBuffer::ATC: case gfx::GpuMemoryBuffer::ATCIA: case gfx::GpuMemoryBuffer::DXT1: case gfx::GpuMemoryBuffer::DXT5: case gfx::GpuMemoryBuffer::ETC1: case gfx::GpuMemoryBuffer::RGBX_8888: NOTREACHED(); return std::vector<uint8>(); } NOTREACHED(); return std::vector<uint8>(); } std::vector<uint8> GetFramebufferPixel( const gfx::GpuMemoryBuffer::Format format) { std::vector<uint8> pixel; switch (format) { case gfx::GpuMemoryBuffer::RGBA_8888: case gfx::GpuMemoryBuffer::BGRA_8888: pixel.push_back(255u); pixel.push_back(0u); pixel.push_back(0u); pixel.push_back(255u); return pixel; case gfx::GpuMemoryBuffer::ATC: case gfx::GpuMemoryBuffer::ATCIA: case gfx::GpuMemoryBuffer::DXT1: case gfx::GpuMemoryBuffer::DXT5: case gfx::GpuMemoryBuffer::ETC1: case gfx::GpuMemoryBuffer::RGBX_8888: NOTREACHED(); return std::vector<uint8>(); } NOTREACHED(); return std::vector<uint8>(); } GLenum InternalFormat(gfx::GpuMemoryBuffer::Format format) { switch (format) { case gfx::GpuMemoryBuffer::RGBA_8888: return GL_RGBA; case gfx::GpuMemoryBuffer::BGRA_8888: return GL_BGRA_EXT; case gfx::GpuMemoryBuffer::ATC: case gfx::GpuMemoryBuffer::ATCIA: case gfx::GpuMemoryBuffer::DXT1: case gfx::GpuMemoryBuffer::DXT5: case gfx::GpuMemoryBuffer::ETC1: case gfx::GpuMemoryBuffer::RGBX_8888: NOTREACHED(); return 0; } NOTREACHED(); return 0; } } // namespace // An end to end test that tests the whole GpuMemoryBuffer lifecycle. TEST_P(GpuMemoryBufferTest, Lifecycle) { scoped_ptr<gfx::GpuMemoryBuffer> buffer(gl_.CreateGpuMemoryBuffer( gfx::Size(kImageWidth, kImageHeight), GetParam())); // Map buffer for writing. void* data; bool rv = buffer->Map(&data); DCHECK(rv); uint8* mapped_buffer = static_cast<uint8*>(data); ASSERT_TRUE(mapped_buffer != NULL); // Assign a value to each pixel. uint32 stride = 0; buffer->GetStride(&stride); ASSERT_NE(stride, 0u); std::vector<uint8> pixel = GetTexturePixel(GetParam()); for (int y = 0; y < kImageHeight; ++y) { for (int x = 0; x < kImageWidth; ++x) { std::copy(pixel.begin(), pixel.end(), mapped_buffer + y * stride + x * pixel.size()); } } // Unmap the buffer. buffer->Unmap(); // Create the image. This should add the image ID to the ImageManager. GLuint image_id = glCreateImageCHROMIUM(buffer->AsClientBuffer(), kImageWidth, kImageHeight, InternalFormat(GetParam())); EXPECT_NE(0u, image_id); EXPECT_TRUE(gl_.decoder()->GetImageManager()->LookupImage(image_id) != NULL); // Bind the texture and the image. glBindTexture(GL_TEXTURE_2D, texture_ids_[0]); glBindTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id); // Copy texture so we can verify result using CheckPixels. glCopyTextureCHROMIUM(GL_TEXTURE_2D, texture_ids_[0], texture_ids_[1], InternalFormat(GetParam()), GL_UNSIGNED_BYTE); EXPECT_TRUE(glGetError() == GL_NO_ERROR); // Check if pixels match the values that were assigned to the mapped buffer. GLTestHelper::CheckPixels(0, 0, kImageWidth, kImageHeight, 0, &GetFramebufferPixel(GetParam()).front()); EXPECT_TRUE(GL_NO_ERROR == glGetError()); // Release the image. glReleaseTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id); // Destroy the image. glDestroyImageCHROMIUM(image_id); } INSTANTIATE_TEST_CASE_P(GpuMemoryBufferTests, GpuMemoryBufferTest, ::testing::Values(gfx::GpuMemoryBuffer::RGBA_8888, gfx::GpuMemoryBuffer::BGRA_8888)); } // namespace gles2 } // namespace gpu <commit_msg>Test gpu memory buffers drawing directly to the backbuffer.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <GLES2/gl2.h> #include <GLES2/gl2chromium.h> #include <GLES2/gl2ext.h> #include <GLES2/gl2extchromium.h> #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/process/process_handle.h" #include "gpu/command_buffer/client/gles2_implementation.h" #include "gpu/command_buffer/service/command_buffer_service.h" #include "gpu/command_buffer/service/image_manager.h" #include "gpu/command_buffer/tests/gl_manager.h" #include "gpu/command_buffer/tests/gl_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gl/gl_image.h" using testing::_; using testing::IgnoreResult; using testing::InvokeWithoutArgs; using testing::Invoke; using testing::Return; using testing::SetArgPointee; using testing::StrictMock; namespace gpu { namespace gles2 { static const int kImageWidth = 32; static const int kImageHeight = 32; class GpuMemoryBufferTest : public testing::TestWithParam<gfx::GpuMemoryBuffer::Format> { protected: void SetUp() override { GLManager::Options options; options.size = gfx::Size(kImageWidth, kImageHeight); gl_.Initialize(options); gl_.MakeCurrent(); } void TearDown() override { gl_.Destroy(); } GLManager gl_; }; namespace { #define SHADER(Src) #Src // clang-format off const char kVertexShader[] = SHADER( attribute vec4 a_position; varying vec2 v_texCoord; void main() { gl_Position = a_position; v_texCoord = vec2((a_position.x + 1.0) * 0.5, (a_position.y + 1.0) * 0.5); } ); const char* kFragmentShader = SHADER( precision mediump float; uniform sampler2D a_texture; varying vec2 v_texCoord; void main() { gl_FragColor = texture2D(a_texture, v_texCoord); } ); // clang-format on std::vector<uint8> GetTexturePixel(const gfx::GpuMemoryBuffer::Format format) { std::vector<uint8> pixel; switch (format) { case gfx::GpuMemoryBuffer::RGBA_8888: pixel.push_back(255u); pixel.push_back(0u); pixel.push_back(0u); pixel.push_back(255u); return pixel; case gfx::GpuMemoryBuffer::BGRA_8888: pixel.push_back(0u); pixel.push_back(0u); pixel.push_back(255u); pixel.push_back(255u); return pixel; case gfx::GpuMemoryBuffer::ATC: case gfx::GpuMemoryBuffer::ATCIA: case gfx::GpuMemoryBuffer::DXT1: case gfx::GpuMemoryBuffer::DXT5: case gfx::GpuMemoryBuffer::ETC1: case gfx::GpuMemoryBuffer::RGBX_8888: NOTREACHED(); return std::vector<uint8>(); } NOTREACHED(); return std::vector<uint8>(); } std::vector<uint8> GetFramebufferPixel( const gfx::GpuMemoryBuffer::Format format) { std::vector<uint8> pixel; switch (format) { case gfx::GpuMemoryBuffer::RGBA_8888: case gfx::GpuMemoryBuffer::BGRA_8888: pixel.push_back(255u); pixel.push_back(0u); pixel.push_back(0u); pixel.push_back(255u); return pixel; case gfx::GpuMemoryBuffer::ATC: case gfx::GpuMemoryBuffer::ATCIA: case gfx::GpuMemoryBuffer::DXT1: case gfx::GpuMemoryBuffer::DXT5: case gfx::GpuMemoryBuffer::ETC1: case gfx::GpuMemoryBuffer::RGBX_8888: NOTREACHED(); return std::vector<uint8>(); } NOTREACHED(); return std::vector<uint8>(); } GLenum InternalFormat(gfx::GpuMemoryBuffer::Format format) { switch (format) { case gfx::GpuMemoryBuffer::RGBA_8888: return GL_RGBA; case gfx::GpuMemoryBuffer::BGRA_8888: return GL_BGRA_EXT; case gfx::GpuMemoryBuffer::ATC: case gfx::GpuMemoryBuffer::ATCIA: case gfx::GpuMemoryBuffer::DXT1: case gfx::GpuMemoryBuffer::DXT5: case gfx::GpuMemoryBuffer::ETC1: case gfx::GpuMemoryBuffer::RGBX_8888: NOTREACHED(); return 0; } NOTREACHED(); return 0; } } // namespace // An end to end test that tests the whole GpuMemoryBuffer lifecycle. TEST_P(GpuMemoryBufferTest, Lifecycle) { GLuint texture_id = 0; glGenTextures(1, &texture_id); ASSERT_NE(0u, texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // Create the gpu memory buffer. scoped_ptr<gfx::GpuMemoryBuffer> buffer(gl_.CreateGpuMemoryBuffer( gfx::Size(kImageWidth, kImageHeight), GetParam())); // Map buffer for writing. void* data; bool rv = buffer->Map(&data); DCHECK(rv); uint8* mapped_buffer = static_cast<uint8*>(data); ASSERT_TRUE(mapped_buffer != NULL); // Assign a value to each pixel. uint32 stride = 0; buffer->GetStride(&stride); ASSERT_NE(stride, 0u); std::vector<uint8> pixel = GetTexturePixel(GetParam()); for (int y = 0; y < kImageHeight; ++y) { for (int x = 0; x < kImageWidth; ++x) { std::copy(pixel.begin(), pixel.end(), mapped_buffer + y * stride + x * pixel.size()); } } // Unmap the buffer. buffer->Unmap(); // Create the image. This should add the image ID to the ImageManager. GLuint image_id = glCreateImageCHROMIUM(buffer->AsClientBuffer(), kImageWidth, kImageHeight, InternalFormat(GetParam())); ASSERT_NE(0u, image_id); ASSERT_TRUE(gl_.decoder()->GetImageManager()->LookupImage(image_id) != NULL); // Bind the image. glBindTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id); // Build program, buffers and draw the texture. GLuint vertex_shader = GLTestHelper::LoadShader(GL_VERTEX_SHADER, kVertexShader); GLuint fragment_shader = GLTestHelper::LoadShader(GL_FRAGMENT_SHADER, kFragmentShader); GLuint program = GLTestHelper::SetupProgram(vertex_shader, fragment_shader); ASSERT_NE(0u, program); glUseProgram(program); GLint sampler_location = glGetUniformLocation(program, "a_texture"); ASSERT_NE(-1, sampler_location); glUniform1i(sampler_location, 0); GLuint vbo = GLTestHelper::SetupUnitQuad(glGetAttribLocation(program, "a_position")); ASSERT_NE(0u, vbo); glViewport(0, 0, kImageWidth, kImageHeight); glDrawArrays(GL_TRIANGLES, 0, 6); ASSERT_TRUE(glGetError() == GL_NO_ERROR); // Check if pixels match the values that were assigned to the mapped buffer. GLTestHelper::CheckPixels(0, 0, kImageWidth, kImageHeight, 0, &GetFramebufferPixel(GetParam()).front()); EXPECT_TRUE(GL_NO_ERROR == glGetError()); // Release the image. glReleaseTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id); // Clean up. glDeleteProgram(program); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteBuffers(1, &vbo); glDestroyImageCHROMIUM(image_id); glDeleteTextures(1, &texture_id); } INSTANTIATE_TEST_CASE_P(GpuMemoryBufferTests, GpuMemoryBufferTest, ::testing::Values(gfx::GpuMemoryBuffer::RGBA_8888, gfx::GpuMemoryBuffer::BGRA_8888)); } // namespace gles2 } // namespace gpu <|endoftext|>
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */ #include <granary.h> using namespace granary; GRANARY_DEFINE_bool(count_execs, false, "Count the number of times each block is executed. This option is only " "meaningful for dynamic instrumentation. By default, `count_bbs` does not " "count the number of executions of each basic block.", "count_bbs"); // Records the static number of basic blocks. This could be an underestimation // of the total number of basic blocks in the instrumented binary, but an // overestimate of the total number of *distinct* basic blocks instrumented // (because of race conditions when two threads simultaneously instrument the // same basic block). std::atomic<uint64_t> NUM_BBS(ATOMIC_VAR_INIT(0)); namespace { // Runtime block execution counter. class BlockCounter : public MutableMetaData<BlockCounter> { public: BlockCounter(void) : count(0) {} uint64_t count; }; // Simple tool for static and dynamic basic block counting. class BBCount : public InstrumentationTool { public: virtual void Init(InitReason) { if (FLAG_count_execs) { RegisterMetaData<BlockCounter>(); } } virtual ~BBCount(void) = default; virtual void InstrumentBlock(DecodedBasicBlock *bb) { NUM_BBS.fetch_add(1); if (!FLAG_count_execs) { return; } Instruction *insert_instr = bb->FirstInstruction(); // Try to find a good place to insert this instruction such that the // placement is before an instruction that kills the flags (but doesn't // read them). for (auto instr : bb->ReversedAppInstructions()) { if (!IsA<ControlFlowInstruction *>(instr) && instr->WritesConditionCodes() && !instr->ReadsConditionCodes()) { insert_instr = instr; } } // Now that we have an insertion spot (either first instruction, or before // and instruction that kills the flags), go and insert the increment to // the block-specific execution counter. auto meta = GetMetaData<BlockCounter>(bb); MemoryOperand counter_addr(&(meta->count)); lir::InlineAssembly asm_({&counter_addr}); asm_.InlineBefore(insert_instr, "INC m64 %0;"_x86_64); } }; } // namespace // Initialize the `count_bbs` tool. GRANARY_CLIENT_INIT({ RegisterInstrumentationTool<BBCount>("count_bbs"); }) <commit_msg>Minor improvement to the count_bbs tool. Still don't have it report on dynamic execution counters though.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */ #include <granary.h> using namespace granary; GRANARY_DEFINE_bool(count_execs, false, "Count the number of times each block is executed. This option is only " "meaningful for dynamic instrumentation. By default, `count_bbs` does not " "count the number of executions of each basic block.", "count_bbs"); // Records the static number of basic blocks. This could be an underestimation // of the total number of basic blocks in the instrumented binary, but an // overestimate of the total number of *distinct* basic blocks instrumented // (because of race conditions when two threads simultaneously instrument the // same basic block). std::atomic<uint64_t> NUM_BBS(ATOMIC_VAR_INIT(0)); namespace { // Runtime block execution counter. class BlockCounter : public MutableMetaData<BlockCounter> { public: BlockCounter(void) : count(0) {} uint64_t count; }; // Simple tool for static and dynamic basic block counting. class BBCount : public InstrumentationTool { public: virtual void Init(InitReason) { if (FLAG_count_execs) { RegisterMetaData<BlockCounter>(); } } virtual void Exit(ExitReason) { os::Log(os::LogOutput, "%lu blocks were translated.\n", NUM_BBS.load()); } virtual ~BBCount(void) = default; virtual void InstrumentBlock(DecodedBasicBlock *bb) { NUM_BBS.fetch_add(1); if (!FLAG_count_execs) { return; } Instruction *insert_instr = bb->FirstInstruction(); // Try to find a good place to insert this instruction such that the // placement is before an instruction that kills the flags (but doesn't // read them). for (auto instr : bb->ReversedAppInstructions()) { if (!IsA<ControlFlowInstruction *>(instr) && instr->WritesConditionCodes() && !instr->ReadsConditionCodes()) { insert_instr = instr; } } // Now that we have an insertion spot (either first instruction, or before // and instruction that kills the flags), go and insert the increment to // the block-specific execution counter. auto meta = GetMetaData<BlockCounter>(bb); MemoryOperand counter_addr(&(meta->count)); lir::InlineAssembly asm_({&counter_addr}); asm_.InlineBefore(insert_instr, "INC m64 %0;"_x86_64); } }; } // namespace // Initialize the `count_bbs` tool. GRANARY_CLIENT_INIT({ RegisterInstrumentationTool<BBCount>("count_bbs"); }) <|endoftext|>
<commit_before><commit_msg>Remove white spaces.<commit_after><|endoftext|>
<commit_before>#include "control.hpp" #include "math.hpp" #include "model.hpp" #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <GL/glu.h> #include <SOIL/SOIL.h> #include <chrono> #include <cmath> #include <iostream> #include <memory> #include <sstream> #include <thread> #include "omp.h" namespace Control { void control::deadzone(float &x, float &y) { float r = sqrt(x*x + y*y), theta = atan2(y, x); if(r < r_dead) { x = y = 0; } else { x = (x/r - r_dead) / (1-r_dead); y = (y/r - r_dead) / (1-r_dead); } } bool control::init(std::atomic_bool &alive) { //using namespace Util; // Task 1: view before model (splash) using namespace View; glfwSetInputMode(viewer.win, GLFW_STICKY_KEYS, 1); glfwMakeContextCurrent(viewer.win); glGenBuffers(1, &viewer.ids[view::e_id_vbuf]); glBindBuffer(GL_ARRAY_BUFFER, viewer.ids[view::e_id_vbuf]); glBufferData(GL_ARRAY_BUFFER, model.floats.size() * sizeof(float), (void*) &model.floats[0], GL_STATIC_DRAW); glGenBuffers(1, &viewer.ids[view::e_id_fbuf]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, viewer.ids[view::e_id_fbuf]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.ints.size() * sizeof(int), (void*) &model.ints[0], GL_STATIC_DRAW); viewer.nTriangles = model.ints.size()/3; return alive; //return viewer.init(alive); } bool control::poll(std::atomic_bool &alive) { std::ostringstream oss; if(alive) viewer.poll(alive); if(alive) { if(glfwGetKey(viewer.win, GLFW_KEY_ESCAPE) == GLFW_PRESS) alive = false; int nButtons; const uint8_t *buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &nButtons); for(int i = 0; i < nButtons; i++) { if(buttons[i] == GLFW_PRESS) { if(i == 8) alive = false; else if(i == 7) viewer.x = viewer.y = viewer.z = 0; else if(i == 4) viewer.y -= .1; else if(i == 5) viewer.y += .1; } } int nAxes; const GLfloat *axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &nAxes); if(nAxes >= 2) { float x = axes[0], y = axes[1]; deadzone(x, y); viewer.x -= x/20; viewer.z -= y/20; } if(nAxes >= 5) { float theta = axes[3], phi = axes[4]; viewer.theta = theta*M_PI; viewer.phi = phi*M_PI; } } return alive; } bool control::run(std::atomic_bool &alive) { auto delay = 150; int frame = 0, dFrames = 0, fps = 0; auto kill = [&alive] {alive = false;}; double t1 = glfwGetTime(), t2; while(true) { if(poll(alive)) viewer.run(alive); if(delay > 1) { std::this_thread::sleep_for( std::chrono::milliseconds(delay)); } else { delay = 1; } t2 = glfwGetTime() - t1; frame++; dFrames++; if(t2 > 1.0) { delay *= dFrames / t2 / 60; std::cout << "FPS: " << int(dFrames/t2) << std::endl; t1 += t2; dFrames = 0; } if(!alive) break; } return alive; } control::control(std::atomic_bool &alive, const Model::model &model, View::view &view): task(), model(model), viewer(view) {} } <commit_msg>Removed buffer generation (expected in view)<commit_after>#include "control.hpp" #include "math.hpp" #include "model.hpp" #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <GL/glu.h> #include <SOIL/SOIL.h> #include <chrono> #include <cmath> #include <iostream> #include <memory> #include <sstream> #include <thread> #include "omp.h" namespace Control { void control::deadzone(float &x, float &y) { float r = sqrt(x*x + y*y), theta = atan2(y, x); if(r < r_dead) { x = y = 0; } else { x = (x/r - r_dead) / (1-r_dead); y = (y/r - r_dead) / (1-r_dead); } } bool control::init(std::atomic_bool &alive) { //using namespace Util; // Task 1: view before model (splash) using namespace View; glfwSetInputMode(viewer.win, GLFW_STICKY_KEYS, 1); glfwMakeContextCurrent(viewer.win); glBindBuffer(GL_ARRAY_BUFFER, viewer.ids[view::e_id_vbuf]); glBufferData(GL_ARRAY_BUFFER, model.floats.size() * sizeof(float), (void*) &model.floats[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, viewer.ids[view::e_id_fbuf]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.ints.size() * sizeof(int), (void*) &model.ints[0], GL_STATIC_DRAW); viewer.nTriangles = model.ints.size()/3; return alive; //return viewer.init(alive); } bool control::poll(std::atomic_bool &alive) { std::ostringstream oss; if(alive) viewer.poll(alive); if(alive) { if(glfwGetKey(viewer.win, GLFW_KEY_ESCAPE) == GLFW_PRESS) alive = false; int nButtons; const uint8_t *buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &nButtons); for(int i = 0; i < nButtons; i++) { if(buttons[i] == GLFW_PRESS) { if(i == 8) alive = false; else if(i == 7) viewer.x = viewer.y = viewer.z = 0; else if(i == 4) viewer.y -= .1; else if(i == 5) viewer.y += .1; } } int nAxes; const GLfloat *axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &nAxes); if(nAxes >= 2) { float x = axes[0], y = axes[1]; deadzone(x, y); viewer.x -= x/20; viewer.z -= y/20; } if(nAxes >= 5) { float theta = axes[3], phi = axes[4]; viewer.theta = theta*M_PI; viewer.phi = phi*M_PI; } } return alive; } bool control::run(std::atomic_bool &alive) { auto delay = 150; int frame = 0, dFrames = 0, fps = 0; auto kill = [&alive] {alive = false;}; double t1 = glfwGetTime(), t2; while(true) { if(poll(alive)) viewer.run(alive); if(delay > 1) { std::this_thread::sleep_for( std::chrono::milliseconds(delay)); } else { delay = 1; } t2 = glfwGetTime() - t1; frame++; dFrames++; if(t2 > 1.0) { delay *= dFrames / t2 / 60; std::cout << "FPS: " << int(dFrames/t2) << std::endl; t1 += t2; dFrames = 0; } if(!alive) break; } return alive; } control::control(std::atomic_bool &alive, const Model::model &model, View::view &view): task(), model(model), viewer(view) {} } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_MAC_PLATFORM_PTHREAD_HPP #define IOX_HOOFS_MAC_PLATFORM_PTHREAD_HPP #include <pthread.h> #define PTHREAD_MUTEX_STALLED 1 #define PTHREAD_MUTEX_ROBUST 2 using iox_pthread_t = pthread_t; using iox_pthread_attr_t = pthread_attr_t; int iox_pthread_setname_np(iox_pthread_t, const char*); int iox_pthread_getname_np(iox_pthread_t thread, char* name, size_t len); int iox_pthread_create(iox_pthread_t* thread, const iox_pthread_attr_t* attr, void* (*start_routine)(void*), void* arg); int iox_pthread_join(iox_pthread_t thread, void** retval); iox_pthread_t iox_pthread_self(); int pthread_mutexattr_setrobust(pthread_mutexattr_t*, int); #endif // IOX_HOOFS_MAC_PLATFORM_PTHREAD_HPP <commit_msg>iox-#1036 Add pthread_mutex_consistent to mac os platform<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_MAC_PLATFORM_PTHREAD_HPP #define IOX_HOOFS_MAC_PLATFORM_PTHREAD_HPP #include <pthread.h> #define PTHREAD_MUTEX_STALLED 1 #define PTHREAD_MUTEX_ROBUST 2 using iox_pthread_t = pthread_t; using iox_pthread_attr_t = pthread_attr_t; int iox_pthread_setname_np(iox_pthread_t, const char*); int iox_pthread_getname_np(iox_pthread_t thread, char* name, size_t len); int iox_pthread_create(iox_pthread_t* thread, const iox_pthread_attr_t* attr, void* (*start_routine)(void*), void* arg); int iox_pthread_join(iox_pthread_t thread, void** retval); iox_pthread_t iox_pthread_self(); int pthread_mutexattr_setrobust(pthread_mutexattr_t*, int); inline int pthread_mutex_consistent(pthread_mutex_t*) { return 0; } #endif // IOX_HOOFS_MAC_PLATFORM_PTHREAD_HPP <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file linear_observation_model.hpp * \date October 2014 * \author Jan Issac (jan.issac@gmail.com) */ #ifndef FL__MODELS_PROCESS_MODELS_LINEAR_GAUSSIAN_OBSERVATION_MODEL_HPP #define FL__MODELS_PROCESS_MODELS_LINEAR_GAUSSIAN_OBSERVATION_MODEL_HPP #include <fl/util/traits.hpp> #include <fl/distribution/gaussian.hpp> namespace fl { // Forward declarations template <typename Obsrv, typename State> class LinearGaussianObservationModel; template <typename Observation_, typename State_> struct Traits< LinearGaussianObservationModel<Observation_, State_>> { typedef State_ State; typedef Observation_ Observation; typedef Gaussian<Observation_> GaussianBase; typedef typename Traits<GaussianBase>::Scalar Scalar; typedef typename Traits<GaussianBase>::SecondMoment SecondMoment; typedef typename Traits<GaussianBase>::StandardVariate Noise; typedef Eigen::Matrix<Scalar, Observation::SizeAtCompileTime, State::SizeAtCompileTime> SensorMatrix; }; /** * \ingroup observation_models */ template <typename Observation_,typename State_> class LinearGaussianObservationModel : public Traits< LinearGaussianObservationModel<Observation_, State_> >::GaussianBase { public: typedef LinearGaussianObservationModel<Observation_, State_> This; typedef typename Traits<This>::State State; typedef typename Traits<This>::Observation Observation; typedef typename Traits<This>::Noise Noise; typedef typename Traits<This>::Scalar Scalar; typedef typename Traits<This>::SecondMoment SecondMoment; typedef typename Traits<This>::SensorMatrix SensorMatrix; using Traits<This>::GaussianBase::mean; using Traits<This>::GaussianBase::covariance; using Traits<This>::GaussianBase::dimension; public: LinearGaussianObservationModel( const SecondMoment& noise_covariance, const size_t observation_dimension = Observation::SizeAtCompileTime, const size_t state_dimension = State::SizeAtCompileTime): Traits<This>::GaussianBase(observation_dimension), state_dimension_(state_dimension == Eigen::Dynamic? 0 : state_dimension), H_(SensorMatrix::Zero(dimension(), StateDimension())) { covariance(noise_covariance); } ~LinearGaussianObservationModel() { } virtual void condition(const State& x) { mean(H_ * x); } virtual const SensorMatrix& H() const { return H_; } virtual void H(const SensorMatrix& sensor_matrix) { H_ = sensor_matrix; } virtual size_t StateDimension() const { return state_dimension_; } protected: size_t state_dimension_; SensorMatrix H_; }; // Forward declarations template <typename Observation_, typename State_a_, typename State_b_> class FactorizedLinearGaussianObservationModel; template <typename Observation_, typename State_a_, typename State_b_> struct Traits<FactorizedLinearGaussianObservationModel<Observation_, State_a_, State_b_>> { typedef Observation_ Observation; typedef State_a_ State_a; typedef State_b_ State_b; typedef Gaussian<Observation_> GaussianBase; typedef typename Traits<GaussianBase>::Scalar Scalar; typedef typename Traits<GaussianBase>::SecondMoment SecondMoment; typedef typename Traits<GaussianBase>::StandardVariate Noise; typedef Eigen::Matrix<Scalar, Observation::SizeAtCompileTime, State_a::SizeAtCompileTime> SensorMatrix_a; typedef Eigen::Matrix<Scalar, Observation::SizeAtCompileTime, State_b::SizeAtCompileTime> SensorMatrix_b; }; template <typename Observation_,typename State_a_, typename State_b_> class FactorizedLinearGaussianObservationModel: public Traits< FactorizedLinearGaussianObservationModel< Observation_, State_a_, State_b_>>::GaussianBase { public: typedef FactorizedLinearGaussianObservationModel< Observation_, State_a_, State_b_ > This; typedef typename Traits<This>::Noise Noise; typedef typename Traits<This>::Scalar Scalar; typedef typename Traits<This>::SecondMoment SecondMoment; typedef typename Traits<This>::Observation Observation; typedef typename Traits<This>::State_a State_a; typedef typename Traits<This>::State_b State_b; typedef typename Traits<This>::SensorMatrix_a SensorMatrix_a; typedef typename Traits<This>::SensorMatrix_b SensorMatrix_b; using Traits<This>::GaussianBase::mean; using Traits<This>::GaussianBase::covariance; using Traits<This>::GaussianBase::dimension; public: FactorizedLinearGaussianObservationModel( const SecondMoment& noise_covariance, const size_t observation_dimension = Observation::SizeAtCompileTime, const size_t state_a_dimension = State_a::SizeAtCompileTime, const size_t state_b_dimension = State_b::SizeAtCompileTime): Traits<This>::GaussianBase(observation_dimension), state_a_dimension_(state_a_dimension), state_b_dimension_(state_b_dimension), H_a_(SensorMatrix_a::Zero(dimension(), State_a_dimension())), H_b_(SensorMatrix_b::Zero(dimension(), State_b_dimension())) { covariance(noise_covariance); } ~FactorizedLinearGaussianObservationModel() { } virtual Observation Predict(const Noise& noise) const { return map_standard_normal(noise); } virtual void condition(const State_a& state_a, const State_b& state_b, size_t state_index, size_t pixel_index) { mean(H_a_ * state_a + H_b_ * state_b); } virtual const SensorMatrix_a& H_a() const { return H_a_; } virtual const SensorMatrix_b& H_b() const { return H_b_; } virtual void H_a(const SensorMatrix_a& sensor_matrix_a) { H_a_ = sensor_matrix_a; } virtual void H_b(const SensorMatrix_b& sensor_matrix_b) { H_b_ = sensor_matrix_b; } virtual size_t State_a_dimension() const { return state_a_dimension_; } virtual size_t State_b_dimension() const { return state_b_dimension_; } protected: size_t state_a_dimension_; size_t state_b_dimension_; SensorMatrix_a H_a_; SensorMatrix_b H_b_; }; //template <typename Observation_,typename State_a_, typename State_b_> //class FactorizedLinearGaussianOservationModel2; //template <typename Observation_, typename State_a_, typename State_b_> //struct Traits<FactorizedLinearGaussianOservationModel2<Observation_, // State_a_, // State_b_>> //{ // typedef Observation_ Observation; // typedef Gaussian<Observation_> GaussianBase; // typedef typename Traits<GaussianBase>::Scalar Scalar; // typedef typename Traits<GaussianBase>::SecondMoment SecondMoment; // typedef typename Traits<GaussianBase>::Noise Noise; // typedef State_a_ State_a; // typedef State_b_ State_b; // enum // { // Dim_ab = (State_a::SizeAtCompileTime == Eigen::Dynamic || // State_b::SizeAtCompileTime == Eigen::Dynamic) // ? Eigen::Dynamic // : State_a::SizeAtCompileTime + State_b::SizeAtCompileTime // }; // typedef Eigen::Matrix<Scalar, Dim_ab, 1> State_ab; // typedef Eigen::Matrix<Scalar, Dim_ab, Dim_ab> SensorMatrix_ab; // typedef Eigen::Matrix<Scalar, // Observation::SizeAtCompileTime, // State_a::SizeAtCompileTime> SensorMatrix_a; // typedef Eigen::Matrix<Scalar, // Observation::SizeAtCompileTime, // State_b::SizeAtCompileTime> SensorMatrix_b; // typedef LinearGaussianOservationModel<Observation, State_ab> Base; //}; //template <typename Observation_,typename State_a_, typename State_b_> //class FactorizedLinearGaussianOservationModel2: // public Traits<FactorizedLinearGaussianOservationModel2< // Observation_, State_a_, State_b_>>::Base //{ //public: // typedef FactorizedLinearGaussianOservationModel2<Observation_, State_a_, State_b_> Traits; // typedef typename Traits<This>::State_a State_a; // typedef typename Traits<This>::State_b State_b; // typedef typename Traits<This>::Observation Observation; // typedef typename Traits<This>::Noise Noise; // typedef typename Traits<This>::Scalar Scalar; // typedef typename Traits<This>::SecondMoment SecondMoment; // typedef typename Traits<This>::SensorMatrix_a SensorMatrix_a; // typedef typename Traits<This>::SensorMatrix_b SensorMatrix_b; // using Traits<This>::GaussianBase::Mean; // using Traits<This>::GaussianBase::Covariance; // using Traits<This>::GaussianBase::Dimension; // using Traits<This>::Base::map_standard_normal; // using Traits<This>::Base::H; // using Traits<This>::Base::StateDimension; //public: // FactorizedLinearGaussianOservationModel2( // const SecondMoment& noise_covariance, // const size_t observation_dimension = Observation::SizeAtCompileTime, // const size_t state_a_dimension = State_a::SizeAtCompileTime, // const size_t state_b_dimension = State_b::SizeAtCompileTime): // Traits<This>::GaussianBase(observation_dimension), // state_a_dimension_(State_a::SizeAtCompileTime), // state_b_dimension_(State_b::SizeAtCompileTime), // H_a_(SensorMatrix_a::Zero(dimension(), State_a_dimension())), // H_b_(SensorMatrix_b::Zero(dimension(), State_b_dimension())), // Traits<This>::Base(noise_covariance, ) // { // covariance(noise_covariance); // } //protected: // virtual void condition(const State_a& state_a, // const State_b& state_b, // size_t state_index, // size_t pixel_index) // { // // delta_time_ = delta_time; // mean(H_a_ * state_a + H_b_ * state_b); // } // virtual const SensorMatrix_a& H_a() const // { // return H_a_; // } // virtual const SensorMatrix_b& H_b() const // { // return H_b_; // } // virtual void H_a(const SensorMatrix_a& sensor_matrix_a) // { // H_a_ = sensor_matrix_a; // } // virtual void H_b(const SensorMatrix_b& sensor_matrix_b) // { // H_b_ = sensor_matrix_b; // } // virtual size_t State_a_dimension() const // { // return state_a_dimension_; // } // virtual size_t State_b_dimension() const // { // return state_b_dimension_; // } //protected: // size_t state_a_dimension_; // size_t state_b_dimension_; // SensorMatrix_a H_a_; // SensorMatrix_b H_b_; //}; } #endif <commit_msg>Implemented linear model using the observation interface<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file linear_observation_model.hpp * \date October 2014 * \author Jan Issac (jan.issac@gmail.com) */ #ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP #define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP #include <fl/util/traits.hpp> #include <fl/distribution/gaussian.hpp> #include <fl/model/observation/observation_model_interface.hpp> namespace fl { // Forward declarations template < typename Observation, typename State > class LinearGaussianObservationModel; /** * Linear Gaussian observation model traits. This trait definition contains all * types used internally within the model. Additionally, it provides the types * needed externally to use the linear Gaussian model. */ template < typename Observation_, typename State_ > struct Traits< LinearGaussianObservationModel<Observation_, State_> > { typedef State_ State; typedef Observation_ Observation; typedef Gaussian<Observation> GaussianBase; typedef typename Traits<GaussianBase>::Scalar Scalar; typedef typename Traits<GaussianBase>::SecondMoment SecondMoment; typedef typename Traits<GaussianBase>::StandardVariate Noise; typedef Eigen::Matrix< Scalar, Observation::SizeAtCompileTime, State::SizeAtCompileTime > SensorMatrix; typedef ObservationModelInterface< Observation, State, Noise > ObservationModelBase; }; /** * \ingroup observation_models */ template <typename Observation,typename State> class LinearGaussianObservationModel : public Traits< LinearGaussianObservationModel<Observation, State> >::ObservationModelBase, public Traits< LinearGaussianObservationModel<Observation, State> >::GaussianBase { public: typedef LinearGaussianObservationModel<Observation, State> This; typedef typename Traits<This>::Noise Noise; typedef typename Traits<This>::Scalar Scalar; typedef typename Traits<This>::SecondMoment SecondMoment; typedef typename Traits<This>::SensorMatrix SensorMatrix; using Traits<This>::GaussianBase::mean; using Traits<This>::GaussianBase::covariance; using Traits<This>::GaussianBase::dimension; public: LinearGaussianObservationModel( const SecondMoment& noise_covariance, const size_t observation_dim = DimensionOf<Observation>(), const size_t state_dim = DimensionOf<State>()) : Traits<This>::GaussianBase(observation_dim), state_dimension_(state_dim), H_(SensorMatrix::Zero(observation_dimension(), state_dimension())) { covariance(noise_covariance); } ~LinearGaussianObservationModel() { } virtual void condition(const State& x) { mean(H_ * x); } virtual const SensorMatrix& H() const { return H_; } virtual void H(const SensorMatrix& sensor_matrix) { H_ = sensor_matrix; } virtual Observation predict_observation(const State& state, const Noise& noise, double delta_time) { condition(state); return Traits<This>::GaussianBase::map_standard_normal(noise); } virtual size_t observation_dimension() const { return Traits<This>::GaussianBase::dimension(); } virtual size_t noise_dimension() const { return Traits<This>::GaussianBase::standard_variate_dimension(); } virtual size_t state_dimension() const { return state_dimension_; } protected: size_t state_dimension_; SensorMatrix H_; }; //// Forward declarations //template <typename Observation_, typename State_a_, typename State_b_> //class FactorizedLinearGaussianObservationModel; //template <typename Observation_, typename State_a_, typename State_b_> //struct Traits<FactorizedLinearGaussianObservationModel<Observation_, // State_a_, // State_b_>> //{ // typedef Observation_ Observation; // typedef State_a_ State_a; // typedef State_b_ State_b; // typedef Gaussian<Observation_> GaussianBase; // typedef typename Traits<GaussianBase>::Scalar Scalar; // typedef typename Traits<GaussianBase>::SecondMoment SecondMoment; // typedef typename Traits<GaussianBase>::StandardVariate Noise; // typedef Eigen::Matrix<Scalar, // Observation::SizeAtCompileTime, // State_a::SizeAtCompileTime> SensorMatrix_a; // typedef Eigen::Matrix<Scalar, // Observation::SizeAtCompileTime, // State_b::SizeAtCompileTime> SensorMatrix_b; //}; //template <typename Observation_,typename State_a_, typename State_b_> //class FactorizedLinearGaussianObservationModel: // public Traits< // FactorizedLinearGaussianObservationModel< // Observation_, State_a_, State_b_>>::GaussianBase //{ //public: // typedef FactorizedLinearGaussianObservationModel< // Observation_, // State_a_, // State_b_ // > This; // typedef typename Traits<This>::Noise Noise; // typedef typename Traits<This>::Scalar Scalar; // typedef typename Traits<This>::SecondMoment SecondMoment; // typedef typename Traits<This>::Observation Observation; // typedef typename Traits<This>::State_a State_a; // typedef typename Traits<This>::State_b State_b; // typedef typename Traits<This>::SensorMatrix_a SensorMatrix_a; // typedef typename Traits<This>::SensorMatrix_b SensorMatrix_b; // using Traits<This>::GaussianBase::mean; // using Traits<This>::GaussianBase::covariance; // using Traits<This>::GaussianBase::dimension; //public: // FactorizedLinearGaussianObservationModel( // const SecondMoment& noise_covariance, // const size_t observation_dimension = Observation::SizeAtCompileTime, // const size_t state_a_dimension = State_a::SizeAtCompileTime, // const size_t state_b_dimension = State_b::SizeAtCompileTime): // Traits<This>::GaussianBase(observation_dimension), // state_a_dimension_(state_a_dimension), // state_b_dimension_(state_b_dimension), // H_a_(SensorMatrix_a::Zero(dimension(), State_a_dimension())), // H_b_(SensorMatrix_b::Zero(dimension(), State_b_dimension())) // { // covariance(noise_covariance); // } // ~FactorizedLinearGaussianObservationModel() { } // virtual Observation Predict(const Noise& noise) const // { // return map_standard_normal(noise); // } // virtual void condition(const State_a& state_a, // const State_b& state_b, // size_t state_index, // size_t pixel_index) // { // mean(H_a_ * state_a + H_b_ * state_b); // } // virtual const SensorMatrix_a& H_a() const // { // return H_a_; // } // virtual const SensorMatrix_b& H_b() const // { // return H_b_; // } // virtual void H_a(const SensorMatrix_a& sensor_matrix_a) // { // H_a_ = sensor_matrix_a; // } // virtual void H_b(const SensorMatrix_b& sensor_matrix_b) // { // H_b_ = sensor_matrix_b; // } // virtual size_t State_a_dimension() const // { // return state_a_dimension_; // } // virtual size_t State_b_dimension() const // { // return state_b_dimension_; // } //protected: // size_t state_a_dimension_; // size_t state_b_dimension_; // SensorMatrix_a H_a_; // SensorMatrix_b H_b_; //}; //template <typename Observation_,typename State_a_, typename State_b_> //class FactorizedLinearGaussianOservationModel2; //template <typename Observation_, typename State_a_, typename State_b_> //struct Traits<FactorizedLinearGaussianOservationModel2<Observation_, // State_a_, // State_b_>> //{ // typedef Observation_ Observation; // typedef Gaussian<Observation_> GaussianBase; // typedef typename Traits<GaussianBase>::Scalar Scalar; // typedef typename Traits<GaussianBase>::SecondMoment SecondMoment; // typedef typename Traits<GaussianBase>::Noise Noise; // typedef State_a_ State_a; // typedef State_b_ State_b; // enum // { // Dim_ab = (State_a::SizeAtCompileTime == Eigen::Dynamic || // State_b::SizeAtCompileTime == Eigen::Dynamic) // ? Eigen::Dynamic // : State_a::SizeAtCompileTime + State_b::SizeAtCompileTime // }; // typedef Eigen::Matrix<Scalar, Dim_ab, 1> State_ab; // typedef Eigen::Matrix<Scalar, Dim_ab, Dim_ab> SensorMatrix_ab; // typedef Eigen::Matrix<Scalar, // Observation::SizeAtCompileTime, // State_a::SizeAtCompileTime> SensorMatrix_a; // typedef Eigen::Matrix<Scalar, // Observation::SizeAtCompileTime, // State_b::SizeAtCompileTime> SensorMatrix_b; // typedef LinearGaussianOservationModel<Observation, State_ab> Base; //}; //template <typename Observation_,typename State_a_, typename State_b_> //class FactorizedLinearGaussianOservationModel2: // public Traits<FactorizedLinearGaussianOservationModel2< // Observation_, State_a_, State_b_>>::Base //{ //public: // typedef FactorizedLinearGaussianOservationModel2<Observation_, State_a_, State_b_> Traits; // typedef typename Traits<This>::State_a State_a; // typedef typename Traits<This>::State_b State_b; // typedef typename Traits<This>::Observation Observation; // typedef typename Traits<This>::Noise Noise; // typedef typename Traits<This>::Scalar Scalar; // typedef typename Traits<This>::SecondMoment SecondMoment; // typedef typename Traits<This>::SensorMatrix_a SensorMatrix_a; // typedef typename Traits<This>::SensorMatrix_b SensorMatrix_b; // using Traits<This>::GaussianBase::Mean; // using Traits<This>::GaussianBase::Covariance; // using Traits<This>::GaussianBase::Dimension; // using Traits<This>::Base::map_standard_normal; // using Traits<This>::Base::H; // using Traits<This>::Base::StateDimension; //public: // FactorizedLinearGaussianOservationModel2( // const SecondMoment& noise_covariance, // const size_t observation_dimension = Observation::SizeAtCompileTime, // const size_t state_a_dimension = State_a::SizeAtCompileTime, // const size_t state_b_dimension = State_b::SizeAtCompileTime): // Traits<This>::GaussianBase(observation_dimension), // state_a_dimension_(State_a::SizeAtCompileTime), // state_b_dimension_(State_b::SizeAtCompileTime), // H_a_(SensorMatrix_a::Zero(dimension(), State_a_dimension())), // H_b_(SensorMatrix_b::Zero(dimension(), State_b_dimension())), // Traits<This>::Base(noise_covariance, ) // { // covariance(noise_covariance); // } //protected: // virtual void condition(const State_a& state_a, // const State_b& state_b, // size_t state_index, // size_t pixel_index) // { // // delta_time_ = delta_time; // mean(H_a_ * state_a + H_b_ * state_b); // } // virtual const SensorMatrix_a& H_a() const // { // return H_a_; // } // virtual const SensorMatrix_b& H_b() const // { // return H_b_; // } // virtual void H_a(const SensorMatrix_a& sensor_matrix_a) // { // H_a_ = sensor_matrix_a; // } // virtual void H_b(const SensorMatrix_b& sensor_matrix_b) // { // H_b_ = sensor_matrix_b; // } // virtual size_t State_a_dimension() const // { // return state_a_dimension_; // } // virtual size_t State_b_dimension() const // { // return state_b_dimension_; // } //protected: // size_t state_a_dimension_; // size_t state_b_dimension_; // SensorMatrix_a H_a_; // SensorMatrix_b H_b_; //}; } #endif <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "nearest_neighbor_recommender.hpp" #include <string> #include <utility> #include <vector> #include "jubatus/util/data/serialization.h" #include "../common/exception.hpp" namespace jubatus { namespace core { namespace recommender { nearest_neighbor_recommender::nearest_neighbor_recommender( jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base> nearest_neighbor_engine) : nearest_neighbor_engine_(nearest_neighbor_engine) { } void nearest_neighbor_recommender::similar_row( const common::sfv_t& query, std::vector<std::pair<std::string, float> >& ids, size_t ret_num) const { nearest_neighbor_engine_->similar_row(query, ids, ret_num); } void nearest_neighbor_recommender::neighbor_row( const common::sfv_t& query, std::vector<std::pair<std::string, float> >& ids, size_t ret_num) const { nearest_neighbor_engine_->neighbor_row(query, ids, ret_num); } void nearest_neighbor_recommender::clear() { orig_.clear(); nearest_neighbor_engine_->clear(); } void nearest_neighbor_recommender::clear_row(const std::string& id) { throw JUBATUS_EXCEPTION(common::unsupported_method(__func__)); } void nearest_neighbor_recommender::update_row( const std::string& id, const common::sfv_t& diff) { orig_.set_row(id, diff); common::sfv_t row; orig_.get_row(id, row); nearest_neighbor_engine_->set_row(id, row); } void nearest_neighbor_recommender::get_all_row_ids( std::vector<std::string>& ids) const { nearest_neighbor_engine_->get_all_row_ids(ids); } std::string nearest_neighbor_recommender::type() const { return "nearest_neighbor_recommender:" + nearest_neighbor_engine_->type(); } framework::mixable* nearest_neighbor_recommender::get_mixable() const { // TODO: implement //return nearest_neighbor_engine_->get_mixable(); return 0; } void nearest_neighbor_recommender::pack(framework::packer& packer) const { // TODO: implement } void nearest_neighbor_recommender::unpack(msgpack::object o) { // TODO: implement } } // namespace recommender } // namespace core } // namespace jubatus <commit_msg>Implement pack/unpack/get_mixable methods in nearest_neighbor_recommender<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "nearest_neighbor_recommender.hpp" #include <string> #include <utility> #include <vector> #include "jubatus/util/data/serialization.h" #include "../common/exception.hpp" namespace jubatus { namespace core { namespace recommender { nearest_neighbor_recommender::nearest_neighbor_recommender( jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base> nearest_neighbor_engine) : nearest_neighbor_engine_(nearest_neighbor_engine) { } void nearest_neighbor_recommender::similar_row( const common::sfv_t& query, std::vector<std::pair<std::string, float> >& ids, size_t ret_num) const { nearest_neighbor_engine_->similar_row(query, ids, ret_num); } void nearest_neighbor_recommender::neighbor_row( const common::sfv_t& query, std::vector<std::pair<std::string, float> >& ids, size_t ret_num) const { nearest_neighbor_engine_->neighbor_row(query, ids, ret_num); } void nearest_neighbor_recommender::clear() { orig_.clear(); nearest_neighbor_engine_->clear(); } void nearest_neighbor_recommender::clear_row(const std::string& id) { throw JUBATUS_EXCEPTION(common::unsupported_method(__func__)); } void nearest_neighbor_recommender::update_row( const std::string& id, const common::sfv_t& diff) { orig_.set_row(id, diff); common::sfv_t row; orig_.get_row(id, row); nearest_neighbor_engine_->set_row(id, row); } void nearest_neighbor_recommender::get_all_row_ids( std::vector<std::string>& ids) const { nearest_neighbor_engine_->get_all_row_ids(ids); } std::string nearest_neighbor_recommender::type() const { return "nearest_neighbor_recommender:" + nearest_neighbor_engine_->type(); } framework::mixable* nearest_neighbor_recommender::get_mixable() const { return nearest_neighbor_engine_->get_mixable(); } void nearest_neighbor_recommender::pack(framework::packer& packer) const { packer.pack_array(2); orig_.pack(packer); nearest_neighbor_engine_->pack(packer); } void nearest_neighbor_recommender::unpack(msgpack::object o) { if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) { throw msgpack::type_error(); } orig_.unpack(o.via.array.ptr[0]); nearest_neighbor_engine_->unpack(o.via.array.ptr[1]); } } // namespace recommender } // namespace core } // namespace jubatus <|endoftext|>
<commit_before>#include <cstdlib> #include <sqlite3.h> #include <nan.h> #include "macros.h" #include "database.h" namespace NODE_SQLITE3_PLUS_DATABASE { int WRITE_MODE = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; int READ_MODE = SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX; v8::PropertyAttribute FROZEN = static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly); bool CONSTRUCTING_STATEMENT = false; enum STATE {CONNECTING, READY, DONE}; class Database : public Nan::ObjectWrap { public: Database(char*); ~Database(); static NAN_MODULE_INIT(Init); friend class OpenWorker; friend class CloseWorker; private: static CONSTRUCTOR(constructor); static NAN_METHOD(New); static NAN_GETTER(OpenGetter); static NAN_METHOD(Close); static NAN_METHOD(Prepare); char* filename; sqlite3* readHandle; sqlite3* writeHandle; STATE state; }; class Statement : public Nan::ObjectWrap { public: Statement(); ~Statement(); static void Init(); friend class Database; private: static CONSTRUCTOR(constructor); static NAN_METHOD(New); sqlite3_stmt* handle; bool dead; }; class OpenWorker : public Nan::AsyncWorker { public: OpenWorker(Database*); ~OpenWorker(); void Execute(); void HandleOKCallback(); void HandleErrorCallback(); private: Database* db; }; class CloseWorker : public Nan::AsyncWorker { public: CloseWorker(Database*, bool); ~CloseWorker(); void Execute(); void HandleOKCallback(); void HandleErrorCallback(); private: Database* db; bool doNothing; }; Database::Database(char* filename) : Nan::ObjectWrap(), filename(filename), readHandle(NULL), writeHandle(NULL), state(CONNECTING) {} Database::~Database() { state = DONE; sqlite3_close(readHandle); sqlite3_close(writeHandle); readHandle = NULL; writeHandle = NULL; free(filename); filename = NULL; } NAN_MODULE_INIT(Database::Init) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(Nan::New("Database").ToLocalChecked()); Nan::SetPrototypeMethod(t, "disconnect", Close); Nan::SetPrototypeMethod(t, "prepare", Prepare); Nan::SetAccessor(t->InstanceTemplate(), Nan::New("connected").ToLocalChecked(), OpenGetter); constructor.Reset(Nan::GetFunction(t).ToLocalChecked()); Nan::Set(target, Nan::New("Database").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked()); } CONSTRUCTOR(Database::constructor); NAN_METHOD(Database::New) { REQUIRE_ARGUMENTS(1); if (!info.IsConstructCall()) { v8::Local<v8::Value> args[1] = {info[0]}; v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor); info.GetReturnValue().Set(cons->NewInstance(1, args)); } else { REQUIRE_ARGUMENT_STRING(0, filename); Database* db = new Database(RAW_STRING(filename)); db->Wrap(info.This()); db->Ref(); AsyncQueueWorker(new OpenWorker(db)); info.GetReturnValue().Set(info.This()); } } NAN_GETTER(Database::OpenGetter) { Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); info.GetReturnValue().Set(db->state == READY); } NAN_METHOD(Database::Close) { Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); if (db->state != DONE) { db->Ref(); // -- // This should wait in queue for all pending transactions to finish. (writes AND reads). // This should be invoked right away if there are no pending transactions (which will) // always be the case if it's still connecting. db->state == DONE simply means that it // was READY when Close was invoked, and therefore should be treated equally, as shown // below. AsyncQueueWorker(new CloseWorker(db, db->state == CONNECTING)); // -- db->state = DONE; } info.GetReturnValue().Set(info.This()); } NAN_METHOD(Database::Prepare) { REQUIRE_ARGUMENT_STRING(0, source); v8::Local<v8::Function> cons = Nan::New<v8::Function>(Statement::constructor); CONSTRUCTING_STATEMENT = true; v8::Local<v8::Object> statement = cons->NewInstance(0, NULL); CONSTRUCTING_STATEMENT = false; Nan::ForceSet(statement, Nan::New("database").ToLocalChecked(), info.This(), FROZEN); Nan::ForceSet(statement, Nan::New("source").ToLocalChecked(), source, FROZEN); info.GetReturnValue().Set(statement); } Statement::Statement() : Nan::ObjectWrap(), handle(NULL), dead(false) {} Statement::~Statement() { dead = true; sqlite3_finalize(handle); handle = NULL; } void Statement::Init() { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(Nan::New("Statement").ToLocalChecked()); constructor.Reset(Nan::GetFunction(t).ToLocalChecked()); } CONSTRUCTOR(Statement::constructor); NAN_METHOD(Statement::New) { if (!CONSTRUCTING_STATEMENT) { return Nan::ThrowSyntaxError("Statements can only be constructed by the db.prepare() method."); } Statement* stmt = new Statement(); stmt->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } OpenWorker::OpenWorker(Database* db) : Nan::AsyncWorker(NULL), db(db) {} OpenWorker::~OpenWorker() {} void OpenWorker::Execute() { int status; status = sqlite3_open_v2(db->filename, &db->writeHandle, WRITE_MODE, NULL); if (status != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->writeHandle)); sqlite3_close(db->writeHandle); db->writeHandle = NULL; return; } status = sqlite3_open_v2(db->filename, &db->readHandle, READ_MODE, NULL); if (status != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->readHandle)); sqlite3_close(db->writeHandle); sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; return; } sqlite3_busy_timeout(db->writeHandle, 30000); sqlite3_busy_timeout(db->readHandle, 30000); } void OpenWorker::HandleOKCallback() { Nan::HandleScope scope; if (db->state == DONE) { sqlite3_close(db->writeHandle); sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; } else { db->state = READY; v8::Local<v8::Value> args[1] = {Nan::New("connect").ToLocalChecked()}; EMIT_EVENT(db->handle(), 1, args); } db->Unref(); } void OpenWorker::HandleErrorCallback() { Nan::HandleScope scope; if (db->state != DONE) { db->state = DONE; v8::Local<v8::Value> args[2] = { Nan::New("disconnect").ToLocalChecked(), v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; EMIT_EVENT(db->handle(), 2, args); } db->Unref(); } CloseWorker::CloseWorker(Database* db, bool doNothing) : Nan::AsyncWorker(NULL), db(db), doNothing(doNothing) {} CloseWorker::~CloseWorker() {} void CloseWorker::Execute() { if (!doNothing) { int status1 = sqlite3_close(db->writeHandle); int status2 = sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; if (status1 != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->writeHandle)); } else if (status2 != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->readHandle)); } } } void CloseWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> args[2] = {Nan::New("disconnect").ToLocalChecked(), Nan::Null()}; EMIT_EVENT(db->handle(), 2, args); db->Unref(); } void CloseWorker::HandleErrorCallback() { Nan::HandleScope scope; v8::Local<v8::Value> args[2] = { Nan::New("disconnect").ToLocalChecked(), v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; EMIT_EVENT(db->handle(), 2, args); db->Unref(); } NAN_MODULE_INIT(InitDatabase) { Database::Init(target); Statement::Init(); } } <commit_msg>minor change<commit_after>#include <cstdlib> #include <sqlite3.h> #include <nan.h> #include "macros.h" #include "database.h" namespace NODE_SQLITE3_PLUS_DATABASE { int WRITE_MODE = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; int READ_MODE = SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX; v8::PropertyAttribute FROZEN = static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly); enum STATE {CONNECTING, READY, DONE}; bool CONSTRUCTING_STATEMENT = false; class Database : public Nan::ObjectWrap { public: Database(char*); ~Database(); static NAN_MODULE_INIT(Init); friend class OpenWorker; friend class CloseWorker; private: static CONSTRUCTOR(constructor); static NAN_METHOD(New); static NAN_GETTER(OpenGetter); static NAN_METHOD(Close); static NAN_METHOD(Prepare); char* filename; sqlite3* readHandle; sqlite3* writeHandle; STATE state; }; class Statement : public Nan::ObjectWrap { public: Statement(); ~Statement(); static void Init(); friend class Database; private: static CONSTRUCTOR(constructor); static NAN_METHOD(New); sqlite3_stmt* handle; bool dead; }; class OpenWorker : public Nan::AsyncWorker { public: OpenWorker(Database*); ~OpenWorker(); void Execute(); void HandleOKCallback(); void HandleErrorCallback(); private: Database* db; }; class CloseWorker : public Nan::AsyncWorker { public: CloseWorker(Database*, bool); ~CloseWorker(); void Execute(); void HandleOKCallback(); void HandleErrorCallback(); private: Database* db; bool doNothing; }; Database::Database(char* filename) : Nan::ObjectWrap(), filename(filename), readHandle(NULL), writeHandle(NULL), state(CONNECTING) {} Database::~Database() { state = DONE; sqlite3_close(readHandle); sqlite3_close(writeHandle); readHandle = NULL; writeHandle = NULL; free(filename); filename = NULL; } NAN_MODULE_INIT(Database::Init) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(Nan::New("Database").ToLocalChecked()); Nan::SetPrototypeMethod(t, "disconnect", Close); Nan::SetPrototypeMethod(t, "prepare", Prepare); Nan::SetAccessor(t->InstanceTemplate(), Nan::New("connected").ToLocalChecked(), OpenGetter); constructor.Reset(Nan::GetFunction(t).ToLocalChecked()); Nan::Set(target, Nan::New("Database").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked()); } CONSTRUCTOR(Database::constructor); NAN_METHOD(Database::New) { REQUIRE_ARGUMENTS(1); if (!info.IsConstructCall()) { v8::Local<v8::Value> args[1] = {info[0]}; v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor); info.GetReturnValue().Set(cons->NewInstance(1, args)); } else { REQUIRE_ARGUMENT_STRING(0, filename); Database* db = new Database(RAW_STRING(filename)); db->Wrap(info.This()); db->Ref(); AsyncQueueWorker(new OpenWorker(db)); info.GetReturnValue().Set(info.This()); } } NAN_GETTER(Database::OpenGetter) { Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); info.GetReturnValue().Set(db->state == READY); } NAN_METHOD(Database::Close) { Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); if (db->state != DONE) { db->Ref(); // -- // This should wait in queue for all pending transactions to finish. (writes AND reads). // This should be invoked right away if there are no pending transactions (which will) // always be the case if it's still connecting. db->state == DONE simply means that it // was READY when Close was invoked, and therefore should be treated equally, as shown // below. AsyncQueueWorker(new CloseWorker(db, db->state == CONNECTING)); // -- db->state = DONE; } info.GetReturnValue().Set(info.This()); } NAN_METHOD(Database::Prepare) { REQUIRE_ARGUMENT_STRING(0, source); v8::Local<v8::Function> cons = Nan::New<v8::Function>(Statement::constructor); CONSTRUCTING_STATEMENT = true; v8::Local<v8::Object> statement = cons->NewInstance(0, NULL); CONSTRUCTING_STATEMENT = false; Nan::ForceSet(statement, Nan::New("database").ToLocalChecked(), info.This(), FROZEN); Nan::ForceSet(statement, Nan::New("source").ToLocalChecked(), source, FROZEN); info.GetReturnValue().Set(statement); } Statement::Statement() : Nan::ObjectWrap(), handle(NULL), dead(false) {} Statement::~Statement() { dead = true; sqlite3_finalize(handle); handle = NULL; } void Statement::Init() { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(Nan::New("Statement").ToLocalChecked()); constructor.Reset(Nan::GetFunction(t).ToLocalChecked()); } CONSTRUCTOR(Statement::constructor); NAN_METHOD(Statement::New) { if (!CONSTRUCTING_STATEMENT) { return Nan::ThrowSyntaxError("Statements can only be constructed by the db.prepare() method."); } Statement* stmt = new Statement(); stmt->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } OpenWorker::OpenWorker(Database* db) : Nan::AsyncWorker(NULL), db(db) {} OpenWorker::~OpenWorker() {} void OpenWorker::Execute() { int status; status = sqlite3_open_v2(db->filename, &db->writeHandle, WRITE_MODE, NULL); if (status != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->writeHandle)); sqlite3_close(db->writeHandle); db->writeHandle = NULL; return; } status = sqlite3_open_v2(db->filename, &db->readHandle, READ_MODE, NULL); if (status != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->readHandle)); sqlite3_close(db->writeHandle); sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; return; } sqlite3_busy_timeout(db->writeHandle, 30000); sqlite3_busy_timeout(db->readHandle, 30000); } void OpenWorker::HandleOKCallback() { Nan::HandleScope scope; if (db->state == DONE) { sqlite3_close(db->writeHandle); sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; } else { db->state = READY; v8::Local<v8::Value> args[1] = {Nan::New("connect").ToLocalChecked()}; EMIT_EVENT(db->handle(), 1, args); } db->Unref(); } void OpenWorker::HandleErrorCallback() { Nan::HandleScope scope; if (db->state != DONE) { db->state = DONE; v8::Local<v8::Value> args[2] = { Nan::New("disconnect").ToLocalChecked(), v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; EMIT_EVENT(db->handle(), 2, args); } db->Unref(); } CloseWorker::CloseWorker(Database* db, bool doNothing) : Nan::AsyncWorker(NULL), db(db), doNothing(doNothing) {} CloseWorker::~CloseWorker() {} void CloseWorker::Execute() { if (!doNothing) { int status1 = sqlite3_close(db->writeHandle); int status2 = sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; if (status1 != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->writeHandle)); } else if (status2 != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->readHandle)); } } } void CloseWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> args[2] = {Nan::New("disconnect").ToLocalChecked(), Nan::Null()}; EMIT_EVENT(db->handle(), 2, args); db->Unref(); } void CloseWorker::HandleErrorCallback() { Nan::HandleScope scope; v8::Local<v8::Value> args[2] = { Nan::New("disconnect").ToLocalChecked(), v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; EMIT_EVENT(db->handle(), 2, args); db->Unref(); } NAN_MODULE_INIT(InitDatabase) { Database::Init(target); Statement::Init(); } } <|endoftext|>
<commit_before>#include "debugger.h" #include "gameboy.h" #include "cpu/cpu.h" #include "util/log.h" #include "util/string.h" #include <iostream> Debugger::Debugger(Gameboy& inGameboy, bool should_debug) : gameboy(inGameboy), enabled(should_debug) { } void Debugger::cycle() { if (!enabled) return; steps++; if (breakpoint_addr != 0 && !debugger_enabled) { if (gameboy.cpu.pc.value() != breakpoint_addr) { return; } debugger_enabled = true; } if (!debugger_enabled) { return; } if (counter > 0) { counter--; return; } while (true) { Command cmd = get_command(); bool should_continue = execute(cmd); if (should_continue) break; } } bool Debugger::execute(Command command) { switch (command.type) { case CommandType::Step: /* Note: 'Step' allows the program to break * out of the debugger loop so the boolean * return value of this function is returned */ return command_step(command.args); case CommandType::Run: debugger_enabled = false; return true; case CommandType::BreakAddr: command_breakaddr(command.args); break; case CommandType::Registers: command_registers(command.args); break; case CommandType::Flags: command_flags(command.args); break; case CommandType::Memory: command_memory(command.args); break; case CommandType::MemoryCell: command_memory_cell(command.args); break; case CommandType::Steps: command_steps(command.args); break; case CommandType::Log: command_log(command.args); break; case CommandType::Exit: command_exit(command.args); break; case CommandType::Help: command_help(command.args); break; case CommandType::Unknown: printf("Unknown command\n"); break; } return false; } bool Debugger::command_step(Args args) { switch (args.size()) { case 0: return true; case 1: /* TODO: Clean this up * Try/catch should be moved somewhere (could use optional?) * Should be able to avoid subtracting 1 */ try { int nsteps = std::stoi(args[0]); if (nsteps == 0) { log_error("Cannot step zero times"); return false; } if (nsteps < 0) { log_error("Cannot step a negative number of times"); return false; } counter = static_cast<uint>(nsteps - 1); } catch (std::invalid_argument&) { log_error("Invalid number of steps: %s", args[0].c_str()); /* If an invalid argument was encountered, the program * should not step at all, thus false is returned */ return false; } return true; default: log_error("Invalid arguments to 'step'"); return false; } } void Debugger::command_registers(Args args) { unused(args); /* printf("A: %02X | B: %02X | C: %02X | D: %02X | E: %02X | F: %02X\n", */ /* gameboy.cpu.a.value(), */ /* gameboy.cpu.b.value(), */ /* gameboy.cpu.c.value(), */ /* gameboy.cpu.d.value(), */ /* gameboy.cpu.e.value(), */ /* gameboy.cpu.f.value()); */ printf("AF: %04X\n", gameboy.cpu.af.value()); printf("BC: %04X\n", gameboy.cpu.bc.value()); printf("DE: %04X\n", gameboy.cpu.de.value()); printf("HL: %04X\n", gameboy.cpu.hl.value()); printf("SP: %04X\n", gameboy.cpu.sp.value()); printf("PC: %04X\n", gameboy.cpu.pc.value()); } void Debugger::command_flags(Args args) { unused(args); printf("Zero: %d\n", gameboy.cpu.f.flag_zero_value()); printf("Subtract: %d\n", gameboy.cpu.f.flag_subtract_value()); printf("Half Carry: %d\n", gameboy.cpu.f.flag_half_carry_value()); printf("Carry: %d\n", gameboy.cpu.f.flag_carry_value()); } void Debugger::command_memory(Args args) { if (args.size() > 3) { log_error("Invalid arguments to command"); return; } /* TODO: Error handling for mis-parsed arguments */ u16 memory_location = static_cast<u16>(std::stoul(args[0], nullptr, 16)); uint lines = 10; if (args.size() >= 2) { lines = static_cast<uint>(std::stoi(args[1])); } uint line_length = 16; if (args.size() == 3) { line_length = static_cast<uint>(std::stoul(args[2])); } for (uint i = 0; i < lines; i++) { Address addr = static_cast<u16>(memory_location + i * line_length); printf("0x%04X | ", addr.value()); for (uint cell = 0; cell < line_length; cell++) { Address cell_addr = static_cast<u16>(addr.value() + cell); printf("%02X ", gameboy.mmu.read(cell_addr)); } printf("\n"); } } void Debugger::command_memory_cell(Args args) { if (args.size() != 1) { log_error("Invalid arguments to command"); return; } u16 memory_location = static_cast<u16>(std::stoul(args[0], nullptr, 16)); printf("0x%02X\n", gameboy.mmu.read(memory_location)); return; } void Debugger::command_breakaddr(Args args) { if (args.size() != 1) { log_error("Invalid arguments to command"); return; } u16 addr = static_cast<u16>(std::stoul(args[0], nullptr, 16)); breakpoint_addr = addr; log_info("Breakpoint set for address 0x%04X", breakpoint_addr); } void Debugger::command_steps(Args args) { unused(args); printf("Steps: %d\n", steps); } void Debugger::command_log(Args args) { if (args.size() != 1) { log_error("Invalid arguments to command"); return; } std::string desired_log_level = args[0]; std::transform(desired_log_level.begin(), desired_log_level.end(), desired_log_level.begin(), ::tolower); if (desired_log_level == "none") { log_set_level(LogLevel::Error); printf("Log level: Error\n"); } else if (desired_log_level == "error") { log_set_level(LogLevel::Error); printf("Log level: Error\n"); } else if (desired_log_level == "debug") { log_set_level(LogLevel::Debug); printf("Log level: Debug\n"); } else if (desired_log_level == "trace") { log_set_level(LogLevel::Trace); printf("Log level: Trace\n"); } else { log_error("Invalid log level"); } } void Debugger::command_exit(Args args) { unused(args); log_error("Exiting"); exit(1); } void Debugger::command_help(Args args) { unused(args); printf("\n"); printf("= Flow Control\n"); printf("step $steps=1 Run $steps cycles\n"); printf("run Run until the next breakpoint\n"); printf("breakaddr $addr Set a breakpoint at $addr\n"); printf("\n"); printf("= Debug Information\n"); printf("registers Print a dump of the CPU registers\n"); printf("flags Print a dump of the CPU flags\n"); printf("memory $start $lines Print a dump of memory from $start to $end\n"); printf("memorycell $addr Print the value of the memory at $addr\n"); printf("\n"); printf("= Other\n"); printf("steps Print the number of steps so far\n"); printf("help Print this help page\n"); printf("exit Exit the emulator\n"); printf("\n"); } Command Debugger::get_command() const { printf("%s", PROMPT); std::string input_line; std::getline(std::cin, input_line); return parse(input_line); } Command Debugger::parse(std::string input) const { using std::string; using std::vector; vector<string> elems = split(input); /* If nothing was entered, step */ /* TODO: This could repeat the last command, similar to GDB */ if (elems.size() < 1) return { CommandType::Step, vector<string>() }; string cmd = elems[0]; CommandType cmd_type = parse_command(cmd); vector<string> args(elems.begin() + 1, elems.end()); return { cmd_type, args }; } CommandType Debugger::parse_command(std::string cmd) const { std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower); if (cmd == "step") return CommandType::Step; if (cmd == "run") return CommandType::Run; if (cmd == "breakaddr") return CommandType::BreakAddr; if (cmd == "regs") return CommandType::Registers; if (cmd == "flags") return CommandType::Flags; if (cmd == "mem") return CommandType::Memory; if (cmd == "memcell") return CommandType::MemoryCell; if (cmd == "steps") return CommandType::Steps; if (cmd == "log") return CommandType::Log; if (cmd == "exit") return CommandType::Exit; if (cmd == "help") return CommandType::Help; return CommandType::Unknown; } <commit_msg>Permit 's' and 'r' as aliases for 'step' and 'run'<commit_after>#include "debugger.h" #include "gameboy.h" #include "cpu/cpu.h" #include "util/log.h" #include "util/string.h" #include <iostream> Debugger::Debugger(Gameboy& inGameboy, bool should_debug) : gameboy(inGameboy), enabled(should_debug) { } void Debugger::cycle() { if (!enabled) return; steps++; if (breakpoint_addr != 0 && !debugger_enabled) { if (gameboy.cpu.pc.value() != breakpoint_addr) { return; } debugger_enabled = true; } if (!debugger_enabled) { return; } if (counter > 0) { counter--; return; } while (true) { Command cmd = get_command(); bool should_continue = execute(cmd); if (should_continue) break; } } bool Debugger::execute(Command command) { switch (command.type) { case CommandType::Step: /* Note: 'Step' allows the program to break * out of the debugger loop so the boolean * return value of this function is returned */ return command_step(command.args); case CommandType::Run: debugger_enabled = false; return true; case CommandType::BreakAddr: command_breakaddr(command.args); break; case CommandType::Registers: command_registers(command.args); break; case CommandType::Flags: command_flags(command.args); break; case CommandType::Memory: command_memory(command.args); break; case CommandType::MemoryCell: command_memory_cell(command.args); break; case CommandType::Steps: command_steps(command.args); break; case CommandType::Log: command_log(command.args); break; case CommandType::Exit: command_exit(command.args); break; case CommandType::Help: command_help(command.args); break; case CommandType::Unknown: printf("Unknown command\n"); break; } return false; } bool Debugger::command_step(Args args) { switch (args.size()) { case 0: return true; case 1: /* TODO: Clean this up * Try/catch should be moved somewhere (could use optional?) * Should be able to avoid subtracting 1 */ try { int nsteps = std::stoi(args[0]); if (nsteps == 0) { log_error("Cannot step zero times"); return false; } if (nsteps < 0) { log_error("Cannot step a negative number of times"); return false; } counter = static_cast<uint>(nsteps - 1); } catch (std::invalid_argument&) { log_error("Invalid number of steps: %s", args[0].c_str()); /* If an invalid argument was encountered, the program * should not step at all, thus false is returned */ return false; } return true; default: log_error("Invalid arguments to 'step'"); return false; } } void Debugger::command_registers(Args args) { unused(args); /* printf("A: %02X | B: %02X | C: %02X | D: %02X | E: %02X | F: %02X\n", */ /* gameboy.cpu.a.value(), */ /* gameboy.cpu.b.value(), */ /* gameboy.cpu.c.value(), */ /* gameboy.cpu.d.value(), */ /* gameboy.cpu.e.value(), */ /* gameboy.cpu.f.value()); */ printf("AF: %04X\n", gameboy.cpu.af.value()); printf("BC: %04X\n", gameboy.cpu.bc.value()); printf("DE: %04X\n", gameboy.cpu.de.value()); printf("HL: %04X\n", gameboy.cpu.hl.value()); printf("SP: %04X\n", gameboy.cpu.sp.value()); printf("PC: %04X\n", gameboy.cpu.pc.value()); } void Debugger::command_flags(Args args) { unused(args); printf("Zero: %d\n", gameboy.cpu.f.flag_zero_value()); printf("Subtract: %d\n", gameboy.cpu.f.flag_subtract_value()); printf("Half Carry: %d\n", gameboy.cpu.f.flag_half_carry_value()); printf("Carry: %d\n", gameboy.cpu.f.flag_carry_value()); } void Debugger::command_memory(Args args) { if (args.size() > 3) { log_error("Invalid arguments to command"); return; } /* TODO: Error handling for mis-parsed arguments */ u16 memory_location = static_cast<u16>(std::stoul(args[0], nullptr, 16)); uint lines = 10; if (args.size() >= 2) { lines = static_cast<uint>(std::stoi(args[1])); } uint line_length = 16; if (args.size() == 3) { line_length = static_cast<uint>(std::stoul(args[2])); } for (uint i = 0; i < lines; i++) { Address addr = static_cast<u16>(memory_location + i * line_length); printf("0x%04X | ", addr.value()); for (uint cell = 0; cell < line_length; cell++) { Address cell_addr = static_cast<u16>(addr.value() + cell); printf("%02X ", gameboy.mmu.read(cell_addr)); } printf("\n"); } } void Debugger::command_memory_cell(Args args) { if (args.size() != 1) { log_error("Invalid arguments to command"); return; } u16 memory_location = static_cast<u16>(std::stoul(args[0], nullptr, 16)); printf("0x%02X\n", gameboy.mmu.read(memory_location)); return; } void Debugger::command_breakaddr(Args args) { if (args.size() != 1) { log_error("Invalid arguments to command"); return; } u16 addr = static_cast<u16>(std::stoul(args[0], nullptr, 16)); breakpoint_addr = addr; log_info("Breakpoint set for address 0x%04X", breakpoint_addr); } void Debugger::command_steps(Args args) { unused(args); printf("Steps: %d\n", steps); } void Debugger::command_log(Args args) { if (args.size() != 1) { log_error("Invalid arguments to command"); return; } std::string desired_log_level = args[0]; std::transform(desired_log_level.begin(), desired_log_level.end(), desired_log_level.begin(), ::tolower); if (desired_log_level == "none") { log_set_level(LogLevel::Error); printf("Log level: Error\n"); } else if (desired_log_level == "error") { log_set_level(LogLevel::Error); printf("Log level: Error\n"); } else if (desired_log_level == "debug") { log_set_level(LogLevel::Debug); printf("Log level: Debug\n"); } else if (desired_log_level == "trace") { log_set_level(LogLevel::Trace); printf("Log level: Trace\n"); } else { log_error("Invalid log level"); } } void Debugger::command_exit(Args args) { unused(args); log_error("Exiting"); exit(1); } void Debugger::command_help(Args args) { unused(args); printf("\n"); printf("= Flow Control\n"); printf("step $steps=1 Run $steps cycles\n"); printf("run Run until the next breakpoint\n"); printf("breakaddr $addr Set a breakpoint at $addr\n"); printf("\n"); printf("= Debug Information\n"); printf("registers Print a dump of the CPU registers\n"); printf("flags Print a dump of the CPU flags\n"); printf("memory $start $lines Print a dump of memory from $start to $end\n"); printf("memorycell $addr Print the value of the memory at $addr\n"); printf("\n"); printf("= Other\n"); printf("steps Print the number of steps so far\n"); printf("help Print this help page\n"); printf("exit Exit the emulator\n"); printf("\n"); } Command Debugger::get_command() const { printf("%s", PROMPT); std::string input_line; std::getline(std::cin, input_line); return parse(input_line); } Command Debugger::parse(std::string input) const { using std::string; using std::vector; vector<string> elems = split(input); /* If nothing was entered, step */ /* TODO: This could repeat the last command, similar to GDB */ if (elems.size() < 1) return { CommandType::Step, vector<string>() }; string cmd = elems[0]; CommandType cmd_type = parse_command(cmd); vector<string> args(elems.begin() + 1, elems.end()); return { cmd_type, args }; } CommandType Debugger::parse_command(std::string cmd) const { std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower); if (cmd == "step" || cmd == "s") return CommandType::Step; if (cmd == "run" || cmd == "r") return CommandType::Run; if (cmd == "breakaddr") return CommandType::BreakAddr; if (cmd == "regs") return CommandType::Registers; if (cmd == "flags") return CommandType::Flags; if (cmd == "mem") return CommandType::Memory; if (cmd == "memcell") return CommandType::MemoryCell; if (cmd == "steps") return CommandType::Steps; if (cmd == "log") return CommandType::Log; if (cmd == "exit") return CommandType::Exit; if (cmd == "help") return CommandType::Help; return CommandType::Unknown; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstddef> #include <cstring> #include <string> #include <iostream> #include <system_error> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <pwd.h> #include "control-cmds.h" #include "service-constants.h" #include "cpbuffer.h" // dinitctl: utility to control the Dinit daemon, including starting and stopping of services. // This utility communicates with the dinit daemon via a unix socket (/dev/initctl). using handle_t = uint32_t; class ReadCPException { public: int errcode; ReadCPException(int err) : errcode(err) { } }; static void fillBufferTo(CPBuffer *buf, int fd, int rlength) { int r = buf->fillTo(fd, rlength); if (r == -1) { throw ReadCPException(errno); } else if (r == 0) { throw ReadCPException(0); } } static const char * describeState(bool stopped) { return stopped ? "stopped" : "started"; } static const char * describeVerb(bool stop) { return stop ? "stop" : "start"; } // Wait for a reply packet, skipping over any information packets // that are received in the meantime. static void wait_for_reply(CPBuffer &rbuffer, int fd) { fillBufferTo(&rbuffer, fd, 1); while (rbuffer[0] >= 100) { // Information packet; discard. fillBufferTo(&rbuffer, fd, 1); int pktlen = (unsigned char) rbuffer[1]; fillBufferTo(&rbuffer, fd, pktlen); rbuffer.consume(pktlen); } } // Write *all* the requested buffer and re-try if necessary until // the buffer is written or an unrecoverable error occurs. static int write_all(int fd, const void *buf, size_t count) { const char *cbuf = static_cast<const char *>(buf); int w = 0; while (count > 0) { int r = write(fd, cbuf, count); if (r == -1) { if (errno == EINTR) continue; return r; } w += r; cbuf += r; count -= r; } return w; } int main(int argc, char **argv) { using namespace std; bool do_stop = false; bool show_help = argc < 2; char *service_name = nullptr; std::string control_socket_str; const char * control_socket_path = nullptr; bool verbose = true; bool sys_dinit = false; // communicate with system daemon bool wait_for_service = true; int command = 0; constexpr int START_SERVICE = 1; constexpr int STOP_SERVICE = 2; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (strcmp(argv[i], "--help") == 0) { show_help = true; break; } else if (strcmp(argv[i], "--no-wait") == 0) { wait_for_service = false; } else if (strcmp(argv[i], "--quiet") == 0) { verbose = false; } else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) { sys_dinit = true; } else { cerr << "Unrecognized command-line parameter: " << argv[i] << endl; return 1; } } else if (command == 0) { if (strcmp(argv[i], "start") == 0) { command = START_SERVICE; } else if (strcmp(argv[i], "stop") == 0) { command = STOP_SERVICE; } else { show_help = true; break; } } else { // service name service_name = argv[i]; // TODO support multiple services (or at least give error if multiple // services supplied) } } if (service_name == nullptr || command == 0) { show_help = true; } if (show_help) { cout << "dinit-start: start a dinit service" << endl; cout << " --help : show this help" << endl; cout << " --no-wait : don't wait for service startup/shutdown to complete" << endl; cout << " --quiet : suppress output (except errors)" << endl; cout << " -s, --system : control system daemon instead of user daemon" << endl; cout << " <service-name> : start the named service" << endl; return 1; } do_stop = (command == STOP_SERVICE); control_socket_path = "/dev/dinitctl"; if (! sys_dinit) { char * userhome = getenv("HOME"); if (userhome == nullptr) { struct passwd * pwuid_p = getpwuid(getuid()); if (pwuid_p != nullptr) { userhome = pwuid_p->pw_dir; } } if (userhome != nullptr) { control_socket_str = userhome; control_socket_str += "/.dinitctl"; control_socket_path = control_socket_str.c_str(); } else { cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl; return 1; } } int socknum = socket(AF_UNIX, SOCK_STREAM, 0); if (socknum == -1) { perror("socket"); return 1; } struct sockaddr_un * name; uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1; name = (struct sockaddr_un *) malloc(sockaddr_size); if (name == nullptr) { cerr << "dinit-start: out of memory" << endl; return 1; } name->sun_family = AF_UNIX; strcpy(name->sun_path, control_socket_path); int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size); if (connr == -1) { perror("connect"); return 1; } // TODO should start by querying protocol version // Build buffer; uint16_t sname_len = strlen(service_name); int bufsize = 3 + sname_len; char * buf = new char[bufsize]; buf[0] = DINIT_CP_LOADSERVICE; memcpy(buf + 1, &sname_len, 2); memcpy(buf + 3, service_name, sname_len); int r = write_all(socknum, buf, bufsize); delete [] buf; if (r == -1) { perror("write"); return 1; } // Now we expect a reply: // NOTE: should skip over information packets. try { CPBuffer rbuffer; wait_for_reply(rbuffer, socknum); ServiceState state; ServiceState target_state; handle_t handle; if (rbuffer[0] == DINIT_RP_SERVICERECORD) { fillBufferTo(&rbuffer, socknum, 2 + sizeof(handle)); rbuffer.extract((char *) &handle, 2, sizeof(handle)); state = static_cast<ServiceState>(rbuffer[1]); target_state = static_cast<ServiceState>(rbuffer[2 + sizeof(handle)]); rbuffer.consume(3 + sizeof(handle)); } else if (rbuffer[0] == DINIT_RP_NOSERVICE) { cerr << "Failed to find/load service." << endl; return 1; } else { cerr << "Protocol error." << endl; return 1; } ServiceState wanted_state = do_stop ? ServiceState::STOPPED : ServiceState::STARTED; int command = do_stop ? DINIT_CP_STOPSERVICE : DINIT_CP_STARTSERVICE; // Need to issue STOPSERVICE/STARTSERVICE if (target_state != wanted_state) { buf = new char[2 + sizeof(handle)]; buf[0] = command; buf[1] = 0; // don't pin memcpy(buf + 2, &handle, sizeof(handle)); r = write_all(socknum, buf, 2 + sizeof(handle)); delete buf; if (r == -1) { perror("write"); return 1; } wait_for_reply(rbuffer, socknum); if (rbuffer[0] != DINIT_RP_ACK) { cerr << "Protocol error." << endl; return 1; } rbuffer.consume(1); } if (state == wanted_state) { if (verbose) { cout << "Service already " << describeState(do_stop) << "." << endl; } return 0; // success! } if (! wait_for_service) { return 0; } ServiceEvent completionEvent; ServiceEvent cancelledEvent; if (do_stop) { completionEvent = ServiceEvent::STOPPED; cancelledEvent = ServiceEvent::STOPCANCELLED; } else { completionEvent = ServiceEvent::STARTED; cancelledEvent = ServiceEvent::STARTCANCELLED; } // Wait until service started: r = rbuffer.fillTo(socknum, 2); while (r > 0) { if (rbuffer[0] >= 100) { int pktlen = (unsigned char) rbuffer[1]; fillBufferTo(&rbuffer, socknum, pktlen); if (rbuffer[0] == DINIT_IP_SERVICEEVENT) { handle_t ev_handle; rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle)); ServiceEvent event = static_cast<ServiceEvent>(rbuffer[2 + sizeof(ev_handle)]); if (ev_handle == handle) { if (event == completionEvent) { if (verbose) { cout << "Service " << describeState(do_stop) << "." << endl; } return 0; } else if (event == cancelledEvent) { if (verbose) { cout << "Service " << describeVerb(do_stop) << " cancelled." << endl; } return 1; } else if (! do_stop && event == ServiceEvent::FAILEDSTART) { if (verbose) { cout << "Service failed to start." << endl; } return 1; } } } rbuffer.consume(pktlen); r = rbuffer.fillTo(socknum, 2); } else { // Not an information packet? cerr << "protocol error" << endl; return 1; } } if (r == -1) { perror("read"); } else { cerr << "protocol error (connection closed by server)" << endl; } return 1; } catch (ReadCPException &exc) { cerr << "control socket read failure or protocol error" << endl; return 1; } catch (std::bad_alloc &exc) { cerr << "out of memory" << endl; return 1; } return 0; } <commit_msg>Fix "skip to reply packet" method.<commit_after>#include <cstdio> #include <cstddef> #include <cstring> #include <string> #include <iostream> #include <system_error> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <pwd.h> #include "control-cmds.h" #include "service-constants.h" #include "cpbuffer.h" // dinitctl: utility to control the Dinit daemon, including starting and stopping of services. // This utility communicates with the dinit daemon via a unix socket (/dev/initctl). using handle_t = uint32_t; class ReadCPException { public: int errcode; ReadCPException(int err) : errcode(err) { } }; static void fillBufferTo(CPBuffer *buf, int fd, int rlength) { int r = buf->fillTo(fd, rlength); if (r == -1) { throw ReadCPException(errno); } else if (r == 0) { throw ReadCPException(0); } } static const char * describeState(bool stopped) { return stopped ? "stopped" : "started"; } static const char * describeVerb(bool stop) { return stop ? "stop" : "start"; } // Wait for a reply packet, skipping over any information packets // that are received in the meantime. static void wait_for_reply(CPBuffer &rbuffer, int fd) { fillBufferTo(&rbuffer, fd, 1); while (rbuffer[0] >= 100) { // Information packet; discard. fillBufferTo(&rbuffer, fd, 1); int pktlen = (unsigned char) rbuffer[1]; rbuffer.consume(1); // Consume one byte so we'll read one byte of the next packet fillBufferTo(&rbuffer, fd, pktlen); rbuffer.consume(pktlen - 1); } } // Write *all* the requested buffer and re-try if necessary until // the buffer is written or an unrecoverable error occurs. static int write_all(int fd, const void *buf, size_t count) { const char *cbuf = static_cast<const char *>(buf); int w = 0; while (count > 0) { int r = write(fd, cbuf, count); if (r == -1) { if (errno == EINTR) continue; return r; } w += r; cbuf += r; count -= r; } return w; } int main(int argc, char **argv) { using namespace std; bool do_stop = false; bool show_help = argc < 2; char *service_name = nullptr; std::string control_socket_str; const char * control_socket_path = nullptr; bool verbose = true; bool sys_dinit = false; // communicate with system daemon bool wait_for_service = true; int command = 0; constexpr int START_SERVICE = 1; constexpr int STOP_SERVICE = 2; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (strcmp(argv[i], "--help") == 0) { show_help = true; break; } else if (strcmp(argv[i], "--no-wait") == 0) { wait_for_service = false; } else if (strcmp(argv[i], "--quiet") == 0) { verbose = false; } else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) { sys_dinit = true; } else { cerr << "Unrecognized command-line parameter: " << argv[i] << endl; return 1; } } else if (command == 0) { if (strcmp(argv[i], "start") == 0) { command = START_SERVICE; } else if (strcmp(argv[i], "stop") == 0) { command = STOP_SERVICE; } else { show_help = true; break; } } else { // service name service_name = argv[i]; // TODO support multiple services (or at least give error if multiple // services supplied) } } if (service_name == nullptr || command == 0) { show_help = true; } if (show_help) { cout << "dinit-start: start a dinit service" << endl; cout << " --help : show this help" << endl; cout << " --no-wait : don't wait for service startup/shutdown to complete" << endl; cout << " --quiet : suppress output (except errors)" << endl; cout << " -s, --system : control system daemon instead of user daemon" << endl; cout << " <service-name> : start the named service" << endl; return 1; } do_stop = (command == STOP_SERVICE); control_socket_path = "/dev/dinitctl"; if (! sys_dinit) { char * userhome = getenv("HOME"); if (userhome == nullptr) { struct passwd * pwuid_p = getpwuid(getuid()); if (pwuid_p != nullptr) { userhome = pwuid_p->pw_dir; } } if (userhome != nullptr) { control_socket_str = userhome; control_socket_str += "/.dinitctl"; control_socket_path = control_socket_str.c_str(); } else { cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl; return 1; } } int socknum = socket(AF_UNIX, SOCK_STREAM, 0); if (socknum == -1) { perror("socket"); return 1; } struct sockaddr_un * name; uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1; name = (struct sockaddr_un *) malloc(sockaddr_size); if (name == nullptr) { cerr << "dinit-start: out of memory" << endl; return 1; } name->sun_family = AF_UNIX; strcpy(name->sun_path, control_socket_path); int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size); if (connr == -1) { perror("connect"); return 1; } // TODO should start by querying protocol version // Build buffer; uint16_t sname_len = strlen(service_name); int bufsize = 3 + sname_len; char * buf = new char[bufsize]; buf[0] = DINIT_CP_LOADSERVICE; memcpy(buf + 1, &sname_len, 2); memcpy(buf + 3, service_name, sname_len); int r = write_all(socknum, buf, bufsize); delete [] buf; if (r == -1) { perror("write"); return 1; } // Now we expect a reply: // NOTE: should skip over information packets. try { CPBuffer rbuffer; wait_for_reply(rbuffer, socknum); ServiceState state; ServiceState target_state; handle_t handle; if (rbuffer[0] == DINIT_RP_SERVICERECORD) { fillBufferTo(&rbuffer, socknum, 2 + sizeof(handle)); rbuffer.extract((char *) &handle, 2, sizeof(handle)); state = static_cast<ServiceState>(rbuffer[1]); target_state = static_cast<ServiceState>(rbuffer[2 + sizeof(handle)]); rbuffer.consume(3 + sizeof(handle)); } else if (rbuffer[0] == DINIT_RP_NOSERVICE) { cerr << "Failed to find/load service." << endl; return 1; } else { cerr << "Protocol error." << endl; return 1; } ServiceState wanted_state = do_stop ? ServiceState::STOPPED : ServiceState::STARTED; int command = do_stop ? DINIT_CP_STOPSERVICE : DINIT_CP_STARTSERVICE; // Need to issue STOPSERVICE/STARTSERVICE if (target_state != wanted_state) { buf = new char[2 + sizeof(handle)]; buf[0] = command; buf[1] = 0; // don't pin memcpy(buf + 2, &handle, sizeof(handle)); r = write_all(socknum, buf, 2 + sizeof(handle)); delete buf; if (r == -1) { perror("write"); return 1; } wait_for_reply(rbuffer, socknum); if (rbuffer[0] != DINIT_RP_ACK) { cerr << "Protocol error." << endl; return 1; } rbuffer.consume(1); } if (state == wanted_state) { if (verbose) { cout << "Service already " << describeState(do_stop) << "." << endl; } return 0; // success! } if (! wait_for_service) { return 0; } ServiceEvent completionEvent; ServiceEvent cancelledEvent; if (do_stop) { completionEvent = ServiceEvent::STOPPED; cancelledEvent = ServiceEvent::STOPCANCELLED; } else { completionEvent = ServiceEvent::STARTED; cancelledEvent = ServiceEvent::STARTCANCELLED; } // Wait until service started: r = rbuffer.fillTo(socknum, 2); while (r > 0) { if (rbuffer[0] >= 100) { int pktlen = (unsigned char) rbuffer[1]; fillBufferTo(&rbuffer, socknum, pktlen); if (rbuffer[0] == DINIT_IP_SERVICEEVENT) { handle_t ev_handle; rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle)); ServiceEvent event = static_cast<ServiceEvent>(rbuffer[2 + sizeof(ev_handle)]); if (ev_handle == handle) { if (event == completionEvent) { if (verbose) { cout << "Service " << describeState(do_stop) << "." << endl; } return 0; } else if (event == cancelledEvent) { if (verbose) { cout << "Service " << describeVerb(do_stop) << " cancelled." << endl; } return 1; } else if (! do_stop && event == ServiceEvent::FAILEDSTART) { if (verbose) { cout << "Service failed to start." << endl; } return 1; } } } rbuffer.consume(pktlen); r = rbuffer.fillTo(socknum, 2); } else { // Not an information packet? cerr << "protocol error" << endl; return 1; } } if (r == -1) { perror("read"); } else { cerr << "protocol error (connection closed by server)" << endl; } return 1; } catch (ReadCPException &exc) { cerr << "control socket read failure or protocol error" << endl; return 1; } catch (std::bad_alloc &exc) { cerr << "out of memory" << endl; return 1; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012-2015 Dano Pernis // See LICENSE for details #include <gtk/gtk.h> #include <glib.h> #include <fstream> #include <iostream> #include <stdexcept> #include <cassert> #include "CPU.h" namespace hcc { struct ROM : public IROM { unsigned short *data; static const unsigned int size = 0x8000; ROM() { data = new unsigned short[size]; } virtual ~ROM() { delete[] data; } bool load(const char *filename) { std::ifstream input(filename); std::string line; unsigned int counter = 0; while (input.good() && counter < size) { getline(input, line); if (line.size() == 0) continue; if (line.size() != 16) return false; unsigned int instruction = 0; for (unsigned int i = 0; i<16; ++i) { instruction <<= 1; switch (line[i]) { case '0': break; case '1': instruction |= 1; break; default: return false; } } data[counter++] = instruction; } // clear the rest while (counter < size) { data[counter++] = 0; } return true; } virtual unsigned short get(unsigned int address) const { if (address < size) { return data[address]; } else { std::cerr << "requested memory at " << address << '\n'; throw std::runtime_error("Memory::get"); } } }; } // end namespace struct GUIEmulatorRAM : public hcc::IRAM { static const unsigned int CHANNELS = 3; static const unsigned int SCREEN_WIDTH = 512; static const unsigned int SCREEN_HEIGHT = 256; static const unsigned int size = 0x6001; unsigned short *data; unsigned char *vram; GdkPixbuf *pixbuf; GtkWidget *screen; void putpixel(unsigned short x, unsigned short y, bool black) { unsigned int offset = CHANNELS*(SCREEN_WIDTH*y + x); for (unsigned int channel = 0; channel<CHANNELS; ++channel) { vram[offset++] = black ? 0x00 : 0xff; } } public: GUIEmulatorRAM() { data = new unsigned short[size]; vram = new unsigned char[CHANNELS*SCREEN_WIDTH*SCREEN_HEIGHT]; pixbuf = gdk_pixbuf_new_from_data(vram, GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT, CHANNELS*SCREEN_WIDTH, NULL, NULL); screen = gtk_image_new_from_pixbuf(pixbuf); } virtual ~GUIEmulatorRAM() { delete[] data; delete[] vram; } void keyboard(unsigned short value) { data[0x6000] = value; } GtkWidget* getScreenWidget() { return screen; } virtual void set(unsigned int address, unsigned short value) { if (address >= size) { throw std::runtime_error("RAM::set"); } data[address] = value; // check if we are writing to video RAM if (0x4000 <= address && address <0x6000) { address -= 0x4000; unsigned short y = address / 32; unsigned short x = 16*(address % 32); for (int bit = 0; bit<16; ++bit) { putpixel(x + bit, y, value & 1); value = value >> 1; } gdk_threads_enter(); gtk_widget_queue_draw(screen); gdk_threads_leave(); } } virtual unsigned short get(unsigned int address) const { if (address >= size) { throw std::runtime_error("RAM::get"); } return data[address]; } }; struct emulator { emulator(); void load_clicked(); void run_clicked(); void pause_clicked(); gboolean keyboard_callback(GdkEventKey* event); void run_thread(); GtkToolItem* create_button(const gchar* stock_id, const gchar* text, GCallback callback); hcc::ROM rom; GUIEmulatorRAM ram; hcc::CPU cpu; bool running = false; GtkWidget* window; GtkWidget* load_dialog; GtkWidget* error_dialog; GtkToolItem* button_load; GtkToolItem* button_run; GtkToolItem* button_pause; }; gboolean c_keyboard_callback(GtkWidget*, GdkEventKey *event, gpointer user_data) { return reinterpret_cast<emulator*>(user_data)->keyboard_callback(event); } void c_load_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->load_clicked(); } void c_run_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->run_clicked(); } void c_pause_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->pause_clicked(); } gpointer c_run_thread(gpointer user_data) { reinterpret_cast<emulator*>(user_data)->run_thread(); return NULL; } // Translate special keys. See Figure 5.6 in TECS book. unsigned short translate(guint keyval) { switch (keyval) { case GDK_KEY_Return: return 128; case GDK_KEY_BackSpace: return 129; case GDK_KEY_Left: return 130; case GDK_KEY_Up: return 131; case GDK_KEY_Right: return 132; case GDK_KEY_Down: return 133; case GDK_KEY_Home: return 134; case GDK_KEY_End: return 135; case GDK_KEY_Page_Up: return 136; case GDK_KEY_Page_Down: return 137; case GDK_KEY_Insert: return 138; case GDK_KEY_Delete: return 139; case GDK_KEY_Escape: return 140; case GDK_KEY_F1: return 141; case GDK_KEY_F2: return 142; case GDK_KEY_F3: return 143; case GDK_KEY_F4: return 144; case GDK_KEY_F5: return 145; case GDK_KEY_F6: return 146; case GDK_KEY_F7: return 147; case GDK_KEY_F8: return 148; case GDK_KEY_F9: return 149; case GDK_KEY_F10: return 150; case GDK_KEY_F11: return 151; case GDK_KEY_F12: return 152; } return keyval; } emulator::emulator() { /* toolbar buttons */ button_load = create_button("document-open", "Load...", G_CALLBACK(c_load_clicked)); button_run = create_button("media-playback-start", "Run", G_CALLBACK(c_run_clicked)); button_pause = create_button("media-playback-pause", "Pause", G_CALLBACK(c_pause_clicked)); GtkToolItem *separator1 = gtk_separator_tool_item_new(); gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE); /* toolbar itself */ GtkWidget *toolbar = gtk_toolbar_new(); gtk_widget_set_hexpand(toolbar, TRUE); gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1); /* keyboard */ GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus"); gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); g_signal_connect(keyboard, "key-press-event", G_CALLBACK(c_keyboard_callback), this); g_signal_connect(keyboard, "key-release-event", G_CALLBACK(c_keyboard_callback), this); /* main layout */ GtkWidget *grid = gtk_grid_new(); gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1); gtk_grid_attach(GTK_GRID(grid), ram.getScreenWidget(), 0, 1, 1, 1); gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1); /* main window */ window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "HACK emulator"); gtk_window_set_resizable(GTK_WINDOW(window), FALSE); gtk_window_set_focus(GTK_WINDOW(window), NULL); g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL); gtk_container_add(GTK_CONTAINER(window), grid); gtk_widget_show_all(window); gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE); load_dialog = gtk_file_chooser_dialog_new( "Load ROM", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN, "gtk-cancel", GTK_RESPONSE_CANCEL, "gtk-open", GTK_RESPONSE_ACCEPT, NULL); error_dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "Error loading program"); } GtkToolItem* emulator::create_button(const gchar* stock_id, const gchar* text, GCallback callback) { GtkToolItem *button = gtk_tool_button_new(NULL, text); gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id); gtk_tool_item_set_tooltip_text(button, text); g_signal_connect(button, "clicked", callback, this); return button; } void emulator::load_clicked() { const gint result = gtk_dialog_run(GTK_DIALOG(load_dialog)); gtk_widget_hide(load_dialog); if (result != GTK_RESPONSE_ACCEPT) { return; } char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(load_dialog)); const bool loaded = rom.load(filename); g_free(filename); if (!loaded) { gtk_dialog_run(GTK_DIALOG(error_dialog)); gtk_widget_hide(error_dialog); return; } cpu.reset(); gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE); } void emulator::run_clicked() { assert(!running); running = true; gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE); gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE); gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE); g_thread_create(c_run_thread, this, FALSE, NULL); } void emulator::pause_clicked() { assert(running); running = false; gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE); gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE); gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE); } gboolean emulator::keyboard_callback(GdkEventKey* event) { if (event->type == GDK_KEY_RELEASE) { ram.keyboard(0); } else { ram.keyboard(translate(event->keyval)); } return TRUE; } void emulator::run_thread() { int steps = 0; while (running) { cpu.step(&rom, &ram); if (steps>100) { g_usleep(10); steps = 0; } ++steps; } } int main(int argc, char *argv[]) { gtk_init(&argc, &argv); emulator e; gtk_main(); return 0; } <commit_msg>Use GtkDrawinfArea and Cairo<commit_after>// Copyright (c) 2012-2015 Dano Pernis // See LICENSE for details #include <gtk/gtk.h> #include <glib.h> #include <fstream> #include <iostream> #include <stdexcept> #include <cassert> #include "CPU.h" namespace hcc { struct ROM : public IROM { unsigned short *data; static const unsigned int size = 0x8000; ROM() { data = new unsigned short[size]; } virtual ~ROM() { delete[] data; } bool load(const char *filename) { std::ifstream input(filename); std::string line; unsigned int counter = 0; while (input.good() && counter < size) { getline(input, line); if (line.size() == 0) continue; if (line.size() != 16) return false; unsigned int instruction = 0; for (unsigned int i = 0; i<16; ++i) { instruction <<= 1; switch (line[i]) { case '0': break; case '1': instruction |= 1; break; default: return false; } } data[counter++] = instruction; } // clear the rest while (counter < size) { data[counter++] = 0; } return true; } virtual unsigned short get(unsigned int address) const { if (address < size) { return data[address]; } else { std::cerr << "requested memory at " << address << '\n'; throw std::runtime_error("Memory::get"); } } }; } // end namespace gboolean on_draw(GtkWidget*, cairo_t* cr, gpointer data) { GdkPixbuf* pixbuf = reinterpret_cast<GdkPixbuf*>(data); gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0); cairo_paint(cr); return FALSE; } struct GUIEmulatorRAM : public hcc::IRAM { static const unsigned int CHANNELS = 3; static const unsigned int SCREEN_WIDTH = 512; static const unsigned int SCREEN_HEIGHT = 256; static const unsigned int size = 0x6001; unsigned short *data; GdkPixbuf *pixbuf; GtkWidget *screen; void putpixel(unsigned short x, unsigned short y, bool black) { int color = black ? 0x00 : 0xff; int n_channels = gdk_pixbuf_get_n_channels (pixbuf); int rowstride = gdk_pixbuf_get_rowstride (pixbuf); guchar* pixels = gdk_pixbuf_get_pixels(pixbuf); guchar* p = pixels + y * rowstride + x * n_channels; p[0] = color; p[1] = color; p[2] = color; } public: GUIEmulatorRAM() { data = new unsigned short[size]; pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT); gdk_pixbuf_fill(pixbuf, 0x0000000); screen = gtk_drawing_area_new(); gtk_widget_set_size_request(screen, SCREEN_WIDTH, SCREEN_HEIGHT); g_signal_connect(screen, "draw", G_CALLBACK(on_draw), pixbuf); } virtual ~GUIEmulatorRAM() { delete[] data; } void keyboard(unsigned short value) { data[0x6000] = value; } GtkWidget* getScreenWidget() { return screen; } virtual void set(unsigned int address, unsigned short value) { if (address >= size) { throw std::runtime_error("RAM::set"); } data[address] = value; // check if we are writing to video RAM if (0x4000 <= address && address <0x6000) { address -= 0x4000; unsigned short y = address / 32; unsigned short x = 16*(address % 32); for (int bit = 0; bit<16; ++bit) { putpixel(x + bit, y, value & 1); value = value >> 1; } gdk_threads_enter(); gtk_widget_queue_draw(screen); gdk_threads_leave(); } } virtual unsigned short get(unsigned int address) const { if (address >= size) { throw std::runtime_error("RAM::get"); } return data[address]; } }; struct emulator { emulator(); void load_clicked(); void run_clicked(); void pause_clicked(); gboolean keyboard_callback(GdkEventKey* event); void run_thread(); GtkToolItem* create_button(const gchar* stock_id, const gchar* text, GCallback callback); hcc::ROM rom; GUIEmulatorRAM ram; hcc::CPU cpu; bool running = false; GtkWidget* window; GtkWidget* load_dialog; GtkWidget* error_dialog; GtkToolItem* button_load; GtkToolItem* button_run; GtkToolItem* button_pause; }; gboolean c_keyboard_callback(GtkWidget*, GdkEventKey *event, gpointer user_data) { return reinterpret_cast<emulator*>(user_data)->keyboard_callback(event); } void c_load_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->load_clicked(); } void c_run_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->run_clicked(); } void c_pause_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->pause_clicked(); } gpointer c_run_thread(gpointer user_data) { reinterpret_cast<emulator*>(user_data)->run_thread(); return NULL; } // Translate special keys. See Figure 5.6 in TECS book. unsigned short translate(guint keyval) { switch (keyval) { case GDK_KEY_Return: return 128; case GDK_KEY_BackSpace: return 129; case GDK_KEY_Left: return 130; case GDK_KEY_Up: return 131; case GDK_KEY_Right: return 132; case GDK_KEY_Down: return 133; case GDK_KEY_Home: return 134; case GDK_KEY_End: return 135; case GDK_KEY_Page_Up: return 136; case GDK_KEY_Page_Down: return 137; case GDK_KEY_Insert: return 138; case GDK_KEY_Delete: return 139; case GDK_KEY_Escape: return 140; case GDK_KEY_F1: return 141; case GDK_KEY_F2: return 142; case GDK_KEY_F3: return 143; case GDK_KEY_F4: return 144; case GDK_KEY_F5: return 145; case GDK_KEY_F6: return 146; case GDK_KEY_F7: return 147; case GDK_KEY_F8: return 148; case GDK_KEY_F9: return 149; case GDK_KEY_F10: return 150; case GDK_KEY_F11: return 151; case GDK_KEY_F12: return 152; } return keyval; } emulator::emulator() { /* toolbar buttons */ button_load = create_button("document-open", "Load...", G_CALLBACK(c_load_clicked)); button_run = create_button("media-playback-start", "Run", G_CALLBACK(c_run_clicked)); button_pause = create_button("media-playback-pause", "Pause", G_CALLBACK(c_pause_clicked)); GtkToolItem *separator1 = gtk_separator_tool_item_new(); gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE); /* toolbar itself */ GtkWidget *toolbar = gtk_toolbar_new(); gtk_widget_set_hexpand(toolbar, TRUE); gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1); /* keyboard */ GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus"); gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); g_signal_connect(keyboard, "key-press-event", G_CALLBACK(c_keyboard_callback), this); g_signal_connect(keyboard, "key-release-event", G_CALLBACK(c_keyboard_callback), this); /* main layout */ GtkWidget *grid = gtk_grid_new(); gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1); gtk_grid_attach(GTK_GRID(grid), ram.getScreenWidget(), 0, 1, 1, 1); gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1); /* main window */ window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "HACK emulator"); gtk_window_set_resizable(GTK_WINDOW(window), FALSE); gtk_window_set_focus(GTK_WINDOW(window), NULL); g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL); gtk_container_add(GTK_CONTAINER(window), grid); gtk_widget_show_all(window); gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE); load_dialog = gtk_file_chooser_dialog_new( "Load ROM", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN, "gtk-cancel", GTK_RESPONSE_CANCEL, "gtk-open", GTK_RESPONSE_ACCEPT, NULL); error_dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "Error loading program"); } GtkToolItem* emulator::create_button(const gchar* stock_id, const gchar* text, GCallback callback) { GtkToolItem *button = gtk_tool_button_new(NULL, text); gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id); gtk_tool_item_set_tooltip_text(button, text); g_signal_connect(button, "clicked", callback, this); return button; } void emulator::load_clicked() { const gint result = gtk_dialog_run(GTK_DIALOG(load_dialog)); gtk_widget_hide(load_dialog); if (result != GTK_RESPONSE_ACCEPT) { return; } char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(load_dialog)); const bool loaded = rom.load(filename); g_free(filename); if (!loaded) { gtk_dialog_run(GTK_DIALOG(error_dialog)); gtk_widget_hide(error_dialog); return; } cpu.reset(); gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE); } void emulator::run_clicked() { assert(!running); running = true; gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE); gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE); gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE); g_thread_create(c_run_thread, this, FALSE, NULL); } void emulator::pause_clicked() { assert(running); running = false; gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE); gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE); gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE); } gboolean emulator::keyboard_callback(GdkEventKey* event) { if (event->type == GDK_KEY_RELEASE) { ram.keyboard(0); } else { ram.keyboard(translate(event->keyval)); } return TRUE; } void emulator::run_thread() { int steps = 0; while (running) { cpu.step(&rom, &ram); if (steps>100) { g_usleep(10); steps = 0; } ++steps; } } int main(int argc, char *argv[]) { gtk_init(&argc, &argv); emulator e; gtk_main(); return 0; } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh/edge.h" #include "libmesh/node_elem.h" namespace libMesh { AutoPtr<Elem> Edge::side (const unsigned int i) const { libmesh_assert_less (i, 2); const Elem* parent = this; Elem *nodeelem = new NodeElem(const_cast<Elem*>(parent)); nodeelem->set_node(0) = this->get_node(i); return AutoPtr<Elem>(nodeelem); } AutoPtr<Elem> Edge::build_side (const unsigned int i, bool) const { libmesh_assert_less (i, 2); const Elem* parent = this; Elem *nodeelem = new NodeElem(const_cast<Elem*>(parent)); nodeelem->set_node(0) = this->get_node(i); return AutoPtr<Elem>(nodeelem); } bool Edge::is_child_on_side(const unsigned int c, const unsigned int s) const { libmesh_assert_less (c, this->n_children()); libmesh_assert_less (s, this->n_sides()); return (c == s); } unsigned int Edge::opposite_side(const unsigned int side) const { libmesh_assert_less (side, 2); return 1 - side; } unsigned int Edge::opposite_node(const unsigned int node, const unsigned int libmesh_dbg_var(side)) const { libmesh_assert_less (node, 2); libmesh_assert_less (side, this->n_sides()); libmesh_assert(this->is_node_on_side(node, side)); return 1 - node; } } // namespace libMesh <commit_msg>Changes in edge.C for -Wshadow.<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh/edge.h" #include "libmesh/node_elem.h" namespace libMesh { AutoPtr<Elem> Edge::side (const unsigned int i) const { libmesh_assert_less (i, 2); const Elem* the_parent = this; Elem *nodeelem = new NodeElem(const_cast<Elem*>(the_parent)); nodeelem->set_node(0) = this->get_node(i); return AutoPtr<Elem>(nodeelem); } AutoPtr<Elem> Edge::build_side (const unsigned int i, bool) const { libmesh_assert_less (i, 2); const Elem* the_parent = this; Elem *nodeelem = new NodeElem(const_cast<Elem*>(the_parent)); nodeelem->set_node(0) = this->get_node(i); return AutoPtr<Elem>(nodeelem); } bool Edge::is_child_on_side(const unsigned int c, const unsigned int s) const { libmesh_assert_less (c, this->n_children()); libmesh_assert_less (s, this->n_sides()); return (c == s); } unsigned int Edge::opposite_side(const unsigned int side_in) const { libmesh_assert_less (side_in, 2); return 1 - side_in; } unsigned int Edge::opposite_node(const unsigned int node_in, const unsigned int libmesh_dbg_var(side_in)) const { libmesh_assert_less (node_in, 2); libmesh_assert_less (side_in, this->n_sides()); libmesh_assert(this->is_node_on_side(node_in, side_in)); return 1 - node_in; } } // namespace libMesh <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <kernel/syscalls.hpp> #include <hw/acpi.hpp> #include <hw/ioport.hpp> #include <debug> #include <info> extern "C" void reboot(); namespace hw { struct RSDPDescriptor { char Signature[8]; uint8_t Checksum; char OEMID[6]; uint8_t Revision; uint32_t RsdtAddress; } __attribute__ ((packed)); struct RSDPDescriptor20 { RSDPDescriptor rdsp10; uint32_t Length; uint64_t XsdtAddress; uint8_t ExtendedChecksum; uint8_t reserved[3]; } __attribute__ ((packed)); struct SDTHeader { char Signature[4]; uint32_t Length; uint8_t Revision; uint8_t Checksum; char OEMID[6]; char OEMTableID[8]; uint32_t OEMRevision; uint32_t CreatorID; uint32_t CreatorRevision; uint32_t sigint() const { return *(uint32_t*) Signature; } }; struct MADTRecord { uint8_t type; uint8_t length; uint8_t data[0]; }; struct MADTHeader { SDTHeader hdr; uintptr_t lapic_addr; uint32_t flags; // 1 = dual 8259 PICs MADTRecord record[0]; }; struct FACPHeader { SDTHeader sdt; uint32_t unneded1; uint32_t* DSDT; uint8_t unneded2[48 - 44]; uint32_t* SMI_CMD; uint8_t ACPI_ENABLE; uint8_t ACPI_DISABLE; uint8_t unneded3[64 - 54]; uint32_t* PM1a_CNT_BLK; uint32_t* PM1b_CNT_BLK; uint8_t unneded4[89 - 72]; uint8_t PM1_CNT_LEN; }; struct AddressStructure { uint8_t address_space_id; // 0 - system memory, 1 - system I/O uint8_t register_bit_width; uint8_t register_bit_offset; uint8_t reserved; uint64_t address; }; struct pci_vendor_t { uint16_t ven_id; const char* ven_name; }; struct HPET { uint8_t hardware_rev_id; uint8_t comparator_count :5; uint8_t counter_size :1; uint8_t reserved :1; uint8_t legacy_replacem :1; pci_vendor_t pci_vendor_id; AddressStructure address; uint8_t hpet_number; uint16_t minimum_tick; uint8_t page_protection; } __attribute__((packed)); uint64_t ACPI::time() { return 0; } void ACPI::begin(const void* addr) { auto* rdsp = (RSDPDescriptor20*) addr; INFO("ACPI", "Reading headers"); INFO2("OEM: %.*s Rev. %u", 6, rdsp->rdsp10.OEMID, rdsp->rdsp10.Revision); auto* rsdt = (SDTHeader*) rdsp->rdsp10.RsdtAddress; // verify Root SDT if (!checksum((char*) rsdt, rsdt->Length)) { printf("ACPI: SDT failed checksum!"); panic("SDT checksum failed"); } // walk through system description table headers // remember the interesting ones, and count CPUs walk_sdts((char*) rsdt); } constexpr uint32_t bake(char a, char b , char c, char d) { return a | (b << 8) | (c << 16) | (d << 24); } void ACPI::walk_sdts(const char* addr) { // find total number of SDTs auto* rsdt = (SDTHeader*) addr; int total = (rsdt->Length - sizeof(SDTHeader)) / 4; // go past rsdt addr += sizeof(SDTHeader); // parse all tables constexpr uint32_t APIC_t = bake('A', 'P', 'I', 'C'); constexpr uint32_t HPET_t = bake('H', 'P', 'E', 'T'); constexpr uint32_t FACP_t = bake('F', 'A', 'C', 'P'); while (total) { // convert *addr to SDT-address auto sdt_ptr = *(intptr_t*) addr; // create SDT pointer auto* sdt = (SDTHeader*) sdt_ptr; // find out which SDT it is switch (sdt->sigint()) { case APIC_t: debug("APIC found: P=%p L=%u\n", sdt, sdt->Length); walk_madt((char*) sdt); break; case HPET_t: debug("HPET found: P=%p L=%u\n", sdt, sdt->Length); this->hpet_base = sdt_ptr + sizeof(SDTHeader); break; case FACP_t: printf("FACP found: P=%p L=%u\n", sdt, sdt->Length); walk_facp((char*) sdt); break; default: debug("Signature: %.*s (u=%u)\n", 4, sdt->Signature, sdt->sigint()); } addr += 4; total--; } debug("Finished walking SDTs\n"); } void ACPI::walk_madt(const char* addr) { auto* hdr = (MADTHeader*) addr; INFO("ACPI", "Reading APIC information"); // the base address for APIC registers INFO2("LAPIC base: 0x%x (flags: 0x%x)", hdr->lapic_addr, hdr->flags); this->apic_base = hdr->lapic_addr; // the length remaining after MADT header int len = hdr->hdr.Length - sizeof(MADTHeader); // start walking const char* ptr = (char*) hdr->record; while (len) { auto* rec = (MADTRecord*) ptr; switch (rec->type) { case 0: { auto& lapic = *(LAPIC*) rec; lapics.push_back(lapic); INFO2("-> CPU %u ID %u (flags=0x%x)", lapic.cpu, lapic.id, lapic.flags); } break; case 1: { auto& ioapic = *(IOAPIC*) rec; ioapics.push_back(ioapic); INFO2("I/O APIC %u ADDR 0x%x INTR 0x%x", ioapic.id, ioapic.addr_base, ioapic.intr_base); } break; case 2: { auto& redirect = *(override_t*) rec; overrides.push_back(redirect); INFO2("IRQ redirect for bus %u from IRQ %u to VEC %u", redirect.bus_source, redirect.irq_source, redirect.global_intr); } break; default: debug("Unrecognized ACPI MADT type: %u\n", rec->type); } // decrease length as we go len -= rec->length; // go to next entry ptr += rec->length; } } void ACPI::walk_facp(const char* addr) { auto* facp = (FACPHeader*) addr; // verify DSDT constexpr uint32_t DSDT_t = bake('D', 'S', 'D', 'T'); assert(*facp->DSDT == DSDT_t); /// big thanks to kaworu from OSdev.org forums for algo /// http://forum.osdev.org/viewtopic.php?t=16990 char* S5Addr = (char*) facp->DSDT + 36; // skip header int dsdtLength = ((SDTHeader*) facp->DSDT)->Length; // some ting wong dsdtLength *= 2; while (dsdtLength-- > 0) { if (memcmp(S5Addr, "_S5_", 4) == 0) break; S5Addr++; } // check if \_S5 was found if (dsdtLength <= 0) { printf("WARNING: _S5 not present in ACPI\n"); return; } // check for valid AML structure if ( ( *(S5Addr-1) == 0x08 || ( *(S5Addr-2) == 0x08 && *(S5Addr-1) == '\\') ) && *(S5Addr+4) == 0x12 ) { S5Addr += 5; S5Addr += ((*S5Addr &0xC0)>>6) + 2; // calculate PkgLength size if (*S5Addr == 0x0A) S5Addr++; // skip byteprefix SLP_TYPa = *(S5Addr) << 10; S5Addr++; if (*S5Addr == 0x0A) S5Addr++; // skip byteprefix SLP_TYPb = *(S5Addr)<<10; SMI_CMD = facp->SMI_CMD; ACPI_ENABLE = facp->ACPI_ENABLE; ACPI_DISABLE = facp->ACPI_DISABLE; PM1a_CNT = facp->PM1a_CNT_BLK; PM1b_CNT = facp->PM1b_CNT_BLK; PM1_CNT_LEN = facp->PM1_CNT_LEN; SLP_EN = 1<<13; SCI_EN = 1; printf("ACPI: Found shutdown information\n"); return; } else { printf("WARNING: Failed to parse _S5 in ACPI\n"); } // disable ACPI shutdown SCI_EN = 0; } bool ACPI::checksum(const char* addr, size_t size) const { const char* end = addr + size; uint8_t sum = 0; while (addr < end) { sum += *addr; addr++; } return sum == 0; } void ACPI::discover() { // "RSD PTR " const uint64_t sign = 0x2052545020445352; // guess at QEMU location of RDSP const auto* guess = (char*) 0xf6450; if (*(uint64_t*) guess == sign) { if (checksum(guess, sizeof(RSDPDescriptor))) { debug("Found ACPI located at QEMU-guess (%p)\n", guess); begin(guess); return; } } // search in BIOS area (below 1mb) const auto* addr = (char*) 0x000e0000; const auto* end = (char*) 0x000fffff; debug("Looking for ACPI at %p\n", addr); while (addr < end) { if (*(uint64_t*) addr == sign) { // verify checksum of potential RDSP if (checksum(addr, sizeof(RSDPDescriptor))) { debug("Found ACPI located at %p\n", addr); begin(addr); return; } } addr++; } panic("ACPI RDST-search failed\n"); } void ACPI::reboot() { ::reboot(); } void ACPI::acpi_shutdown() { // check if shutdown enabled if (SCI_EN == 1) { // write shutdown commands hw::outw((uint32_t) PM1a_CNT, SLP_TYPa | SLP_EN); if (PM1b_CNT != 0) hw::outw((uint32_t) PM1b_CNT, SLP_TYPb | SLP_EN); printf("*** ACPI shutdown failed\n"); } } __attribute__((noreturn)) void ACPI::shutdown() { asm volatile("cli"); // ACPI shutdown get().acpi_shutdown(); // http://forum.osdev.org/viewtopic.php?t=16990 hw::outw (0xB004, 0x2000); const char s[] = "Shutdown"; const char *p; for (p = s; *p; p++) // magic code for bochs and qemu hw::outb (0x8900, *s); // VMWare poweroff when "gui.exitOnCLIHLT" is true printf("Shutdown failed :(\n"); while (true) { asm volatile("cli; hlt" : : : "memory"); } } } <commit_msg>acpi: Silence some output<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <kernel/syscalls.hpp> #include <hw/acpi.hpp> #include <hw/ioport.hpp> #include <debug> #include <info> extern "C" void reboot(); namespace hw { struct RSDPDescriptor { char Signature[8]; uint8_t Checksum; char OEMID[6]; uint8_t Revision; uint32_t RsdtAddress; } __attribute__ ((packed)); struct RSDPDescriptor20 { RSDPDescriptor rdsp10; uint32_t Length; uint64_t XsdtAddress; uint8_t ExtendedChecksum; uint8_t reserved[3]; } __attribute__ ((packed)); struct SDTHeader { char Signature[4]; uint32_t Length; uint8_t Revision; uint8_t Checksum; char OEMID[6]; char OEMTableID[8]; uint32_t OEMRevision; uint32_t CreatorID; uint32_t CreatorRevision; uint32_t sigint() const { return *(uint32_t*) Signature; } }; struct MADTRecord { uint8_t type; uint8_t length; uint8_t data[0]; }; struct MADTHeader { SDTHeader hdr; uintptr_t lapic_addr; uint32_t flags; // 1 = dual 8259 PICs MADTRecord record[0]; }; struct FACPHeader { SDTHeader sdt; uint32_t unneded1; uint32_t* DSDT; uint8_t unneded2[48 - 44]; uint32_t* SMI_CMD; uint8_t ACPI_ENABLE; uint8_t ACPI_DISABLE; uint8_t unneded3[64 - 54]; uint32_t* PM1a_CNT_BLK; uint32_t* PM1b_CNT_BLK; uint8_t unneded4[89 - 72]; uint8_t PM1_CNT_LEN; }; struct AddressStructure { uint8_t address_space_id; // 0 - system memory, 1 - system I/O uint8_t register_bit_width; uint8_t register_bit_offset; uint8_t reserved; uint64_t address; }; struct pci_vendor_t { uint16_t ven_id; const char* ven_name; }; struct HPET { uint8_t hardware_rev_id; uint8_t comparator_count :5; uint8_t counter_size :1; uint8_t reserved :1; uint8_t legacy_replacem :1; pci_vendor_t pci_vendor_id; AddressStructure address; uint8_t hpet_number; uint16_t minimum_tick; uint8_t page_protection; } __attribute__((packed)); uint64_t ACPI::time() { return 0; } void ACPI::begin(const void* addr) { auto* rdsp = (RSDPDescriptor20*) addr; INFO("ACPI", "Reading headers"); INFO2("OEM: %.*s Rev. %u", 6, rdsp->rdsp10.OEMID, rdsp->rdsp10.Revision); auto* rsdt = (SDTHeader*) rdsp->rdsp10.RsdtAddress; // verify Root SDT if (!checksum((char*) rsdt, rsdt->Length)) { printf("ACPI: SDT failed checksum!"); panic("SDT checksum failed"); } // walk through system description table headers // remember the interesting ones, and count CPUs walk_sdts((char*) rsdt); } constexpr uint32_t bake(char a, char b , char c, char d) { return a | (b << 8) | (c << 16) | (d << 24); } void ACPI::walk_sdts(const char* addr) { // find total number of SDTs auto* rsdt = (SDTHeader*) addr; int total = (rsdt->Length - sizeof(SDTHeader)) / 4; // go past rsdt addr += sizeof(SDTHeader); // parse all tables constexpr uint32_t APIC_t = bake('A', 'P', 'I', 'C'); constexpr uint32_t HPET_t = bake('H', 'P', 'E', 'T'); constexpr uint32_t FACP_t = bake('F', 'A', 'C', 'P'); while (total) { // convert *addr to SDT-address auto sdt_ptr = *(intptr_t*) addr; // create SDT pointer auto* sdt = (SDTHeader*) sdt_ptr; // find out which SDT it is switch (sdt->sigint()) { case APIC_t: debug("APIC found: P=%p L=%u\n", sdt, sdt->Length); walk_madt((char*) sdt); break; case HPET_t: debug("HPET found: P=%p L=%u\n", sdt, sdt->Length); this->hpet_base = sdt_ptr + sizeof(SDTHeader); break; case FACP_t: debug("FACP found: P=%p L=%u\n", sdt, sdt->Length); walk_facp((char*) sdt); break; default: debug("Signature: %.*s (u=%u)\n", 4, sdt->Signature, sdt->sigint()); } addr += 4; total--; } debug("Finished walking SDTs\n"); } void ACPI::walk_madt(const char* addr) { auto* hdr = (MADTHeader*) addr; INFO("ACPI", "Reading APIC information"); // the base address for APIC registers INFO2("LAPIC base: 0x%x (flags: 0x%x)", hdr->lapic_addr, hdr->flags); this->apic_base = hdr->lapic_addr; // the length remaining after MADT header int len = hdr->hdr.Length - sizeof(MADTHeader); // start walking const char* ptr = (char*) hdr->record; while (len) { auto* rec = (MADTRecord*) ptr; switch (rec->type) { case 0: { auto& lapic = *(LAPIC*) rec; lapics.push_back(lapic); INFO2("-> CPU %u ID %u (flags=0x%x)", lapic.cpu, lapic.id, lapic.flags); } break; case 1: { auto& ioapic = *(IOAPIC*) rec; ioapics.push_back(ioapic); INFO2("I/O APIC %u ADDR 0x%x INTR 0x%x", ioapic.id, ioapic.addr_base, ioapic.intr_base); } break; case 2: { auto& redirect = *(override_t*) rec; overrides.push_back(redirect); INFO2("IRQ redirect for bus %u from IRQ %u to VEC %u", redirect.bus_source, redirect.irq_source, redirect.global_intr); } break; default: debug("Unrecognized ACPI MADT type: %u\n", rec->type); } // decrease length as we go len -= rec->length; // go to next entry ptr += rec->length; } } void ACPI::walk_facp(const char* addr) { auto* facp = (FACPHeader*) addr; // verify DSDT constexpr uint32_t DSDT_t = bake('D', 'S', 'D', 'T'); assert(*facp->DSDT == DSDT_t); /// big thanks to kaworu from OSdev.org forums for algo /// http://forum.osdev.org/viewtopic.php?t=16990 char* S5Addr = (char*) facp->DSDT + 36; // skip header int dsdtLength = ((SDTHeader*) facp->DSDT)->Length; // some ting wong dsdtLength *= 2; while (dsdtLength-- > 0) { if (memcmp(S5Addr, "_S5_", 4) == 0) break; S5Addr++; } // check if \_S5 was found if (dsdtLength <= 0) { printf("WARNING: _S5 not present in ACPI\n"); return; } // check for valid AML structure if ( ( *(S5Addr-1) == 0x08 || ( *(S5Addr-2) == 0x08 && *(S5Addr-1) == '\\') ) && *(S5Addr+4) == 0x12 ) { S5Addr += 5; S5Addr += ((*S5Addr &0xC0)>>6) + 2; // calculate PkgLength size if (*S5Addr == 0x0A) S5Addr++; // skip byteprefix SLP_TYPa = *(S5Addr) << 10; S5Addr++; if (*S5Addr == 0x0A) S5Addr++; // skip byteprefix SLP_TYPb = *(S5Addr)<<10; SMI_CMD = facp->SMI_CMD; ACPI_ENABLE = facp->ACPI_ENABLE; ACPI_DISABLE = facp->ACPI_DISABLE; PM1a_CNT = facp->PM1a_CNT_BLK; PM1b_CNT = facp->PM1b_CNT_BLK; PM1_CNT_LEN = facp->PM1_CNT_LEN; SLP_EN = 1<<13; SCI_EN = 1; debug("ACPI: Found shutdown information\n"); return; } else { printf("WARNING: Failed to parse _S5 in ACPI\n"); } // disable ACPI shutdown SCI_EN = 0; } bool ACPI::checksum(const char* addr, size_t size) const { const char* end = addr + size; uint8_t sum = 0; while (addr < end) { sum += *addr; addr++; } return sum == 0; } void ACPI::discover() { // "RSD PTR " const uint64_t sign = 0x2052545020445352; // guess at QEMU location of RDSP const auto* guess = (char*) 0xf6450; if (*(uint64_t*) guess == sign) { if (checksum(guess, sizeof(RSDPDescriptor))) { debug("Found ACPI located at QEMU-guess (%p)\n", guess); begin(guess); return; } } // search in BIOS area (below 1mb) const auto* addr = (char*) 0x000e0000; const auto* end = (char*) 0x000fffff; debug("Looking for ACPI at %p\n", addr); while (addr < end) { if (*(uint64_t*) addr == sign) { // verify checksum of potential RDSP if (checksum(addr, sizeof(RSDPDescriptor))) { debug("Found ACPI located at %p\n", addr); begin(addr); return; } } addr++; } panic("ACPI RDST-search failed\n"); } void ACPI::reboot() { ::reboot(); } void ACPI::acpi_shutdown() { // check if shutdown enabled if (SCI_EN == 1) { // write shutdown commands hw::outw((uint32_t) PM1a_CNT, SLP_TYPa | SLP_EN); if (PM1b_CNT != 0) hw::outw((uint32_t) PM1b_CNT, SLP_TYPb | SLP_EN); printf("*** ACPI shutdown failed\n"); } } __attribute__((noreturn)) void ACPI::shutdown() { asm volatile("cli"); // ACPI shutdown get().acpi_shutdown(); // http://forum.osdev.org/viewtopic.php?t=16990 hw::outw (0xB004, 0x2000); const char s[] = "Shutdown"; const char *p; for (p = s; *p; p++) // magic code for bochs and qemu hw::outb (0x8900, *s); // VMWare poweroff when "gui.exitOnCLIHLT" is true printf("Shutdown failed :(\n"); while (true) { asm volatile("cli; hlt" : : : "memory"); } } } <|endoftext|>
<commit_before>/* * Handler for HTTP requests. * * author: Max Kellermann <mk@cm4all.com> */ #include "lb_http.hxx" #include "lb_instance.hxx" #include "lb_connection.hxx" #include "lb_config.hxx" #include "lb_session.hxx" #include "lb_cookie.hxx" #include "lb_jvm_route.hxx" #include "lb_headers.hxx" #include "lb_log.hxx" #include "ssl/ssl_filter.hxx" #include "address_sticky.hxx" #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_server/Handler.hxx" #include "http_client.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "header_writer.hxx" #include "http_response.hxx" #include "http_headers.hxx" #include "stock/GetHandler.hxx" #include "stock/Item.hxx" #include "stock/Lease.hxx" #include "access_log.hxx" #include "strmap.hxx" #include "failure.hxx" #include "bulldog.h" #include "pool.hxx" #include "net/SocketAddress.hxx" #include "istream/istream.hxx" #include "istream/UnusedHoldPtr.hxx" #include "gerrno.h" #include "util/Cancellable.hxx" #include <http/status.h> #include <daemon/log.h> struct LbRequest final : Cancellable, StockGetHandler, HttpResponseHandler { LbConnection &connection; const LbClusterConfig *cluster; TcpBalancer &balancer; HttpServerRequest &request; /** * The request body. */ UnusedHoldIstreamPtr body; CancellablePointer cancel_ptr; StockItem *stock_item; unsigned new_cookie = 0; LbRequest(LbConnection &_connection, TcpBalancer &_balancer, HttpServerRequest &_request, CancellablePointer &_cancel_ptr) :connection(_connection), balancer(_balancer), request(_request), body(request.pool, request.body) { _cancel_ptr = *this; } void Destroy() { DeleteFromPool(request.pool, this); } /* virtual methods from class Cancellable */ void Cancel() override { body.Clear(); CancellablePointer c(std::move(cancel_ptr)); Destroy(); c.Cancel(); } /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(GError *error) override; /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t status, StringMap &&headers, Istream *body) override; void OnHttpError(GError *error) override; }; static bool send_fallback(HttpServerRequest *request, const LbFallbackConfig *fallback) { if (!fallback->location.empty()) { http_server_send_redirect(request, HTTP_STATUS_FOUND, fallback->location.c_str(), "Found"); return true; } else if (!fallback->message.empty()) { /* custom status + error message */ http_server_send_message(request, fallback->status, fallback->message.c_str()); return true; } else return false; } /** * Generate a cookie for sticky worker selection. Return only worker * numbers that are not known to be failing. Returns 0 on total * failure. */ static unsigned generate_cookie(const AddressList *list) { assert(list->GetSize() >= 2); const unsigned first = lb_cookie_generate(list->GetSize()); unsigned i = first; do { assert(i >= 1 && i <= list->GetSize()); const SocketAddress address = list->addresses[i % list->GetSize()]; if (failure_get_status(address) == FAILURE_OK && bulldog_check(address.GetAddress(), address.GetSize()) && !bulldog_is_fading(address.GetAddress(), address.GetSize())) return i; i = lb_cookie_next(list->GetSize(), i); } while (i != first); /* all nodes have failed */ return first; } /** * Is the specified error a server failure, that justifies * blacklisting the server for a while? */ static bool is_server_failure(GError *error) { return error->domain == http_client_quark() && error->code != HTTP_CLIENT_UNSPECIFIED; } /* * HTTP response handler * */ void LbRequest::OnHttpResponse(http_status_t status, StringMap &&_headers, Istream *response_body) { HttpHeaders headers(std::move(_headers)); if (request.method == HTTP_METHOD_HEAD) /* pass Content-Length, even though there is no response body (RFC 2616 14.13) */ headers.MoveToBuffer("content-length"); if (new_cookie != 0) { char buffer[64]; /* "Discard" must be last, to work around an Android bug*/ snprintf(buffer, sizeof(buffer), "beng_lb_node=0-%x; HttpOnly; Path=/; Version=1; Discard", new_cookie); headers.Write("cookie2", "$Version=\"1\""); headers.Write("set-cookie", buffer); } http_server_response(&request, status, std::move(headers), response_body); Destroy(); } void LbRequest::OnHttpError(GError *error) { if (is_server_failure(error)) failure_add(tcp_stock_item_get_address(*stock_item)); lb_connection_log_gerror(2, &connection, "Error", error); if (!send_fallback(&request, &cluster->fallback)) { const char *msg = connection.listener.verbose_response ? error->message : "Server failure"; http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY, msg); } g_error_free(error); Destroy(); } /* * stock callback * */ void LbRequest::OnStockItemReady(StockItem &item) { stock_item = &item; const char *peer_subject = connection.ssl_filter != nullptr ? ssl_filter_get_peer_subject(connection.ssl_filter) : nullptr; const char *peer_issuer_subject = connection.ssl_filter != nullptr ? ssl_filter_get_peer_issuer_subject(connection.ssl_filter) : nullptr; auto &headers = request.headers; lb_forward_request_headers(request.pool, headers, request.local_host_and_port, request.remote_host, peer_subject, peer_issuer_subject, cluster->mangle_via); auto *lease = NewFromPool<StockItemLease>(request.pool, item); http_client_request(request.pool, connection.instance.event_loop, tcp_stock_item_get(item), tcp_stock_item_get_domain(item) == AF_LOCAL ? FdType::FD_SOCKET : FdType::FD_TCP, *lease, item.GetStockName(), NULL, NULL, request.method, request.uri, HttpHeaders(std::move(headers)), body.Steal(), true, *this, cancel_ptr); } void LbRequest::OnStockItemError(GError *error) { lb_connection_log_gerror(2, &connection, "Connect error", error); body.Clear(); if (!send_fallback(&request, &cluster->fallback)) { const char *msg = connection.listener.verbose_response ? error->message : "Connection failure"; http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY, msg); } g_error_free(error); } /* * http connection handler * */ void LbConnection::HandleHttpRequest(HttpServerRequest &request, CancellablePointer &cancel_ptr) { ++instance.http_request_counter; request_start_time = std::chrono::steady_clock::now(); const auto &goto_ = listener.destination.FindRequestLeaf(request); if (goto_.status != http_status_t(0)) { http_server_simple_response(request, goto_.status, nullptr, nullptr); return; } const auto request2 = NewFromPool<LbRequest>(request.pool, *this, *instance.tcp_balancer, request, cancel_ptr); const auto *cluster = request2->cluster = goto_.cluster; SocketAddress bind_address = SocketAddress::Null(); const bool transparent_source = cluster->transparent_source; if (transparent_source) { bind_address = request.remote_address; /* reset the port to 0 to allow the kernel to choose one */ if (bind_address.GetFamily() == AF_INET) { struct sockaddr_in *s_in = (struct sockaddr_in *) p_memdup(&request.pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } else if (bind_address.GetFamily() == AF_INET6) { struct sockaddr_in6 *s_in = (struct sockaddr_in6 *) p_memdup(&request.pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin6_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } } if (cluster->HasZeroConf()) { /* TODO: generalize the Zeroconf code, implement sticky */ auto *cluster2 = instance.clusters.Find(cluster->name); if (cluster2 == nullptr) { http_server_send_message(&request, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Zeroconf cluster not found"); return; } const auto member = cluster2->Pick(); if (member.first == nullptr) { http_server_send_message(&request, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Zeroconf cluster is empty"); return; } assert(member.second.IsDefined()); tcp_stock_get(instance.tcp_stock, &request.pool, member.first, transparent_source, bind_address, member.second, 20, *request2, request2->cancel_ptr); return; } /* prepare for the balancer */ unsigned session_sticky = 0; switch (cluster->address_list.sticky_mode) { case StickyMode::NONE: case StickyMode::FAILOVER: /* these modes require no preparation; they are handled completely by balancer_get() */ break; case StickyMode::SOURCE_IP: /* calculate session_sticky from remote address */ session_sticky = socket_address_sticky(request.remote_address); break; case StickyMode::SESSION_MODULO: /* calculate session_sticky from beng-proxy session id */ session_sticky = lb_session_get(request.headers, cluster->session_cookie.c_str()); break; case StickyMode::COOKIE: /* calculate session_sticky from beng-lb cookie */ session_sticky = lb_cookie_get(request.headers); if (session_sticky == 0) request2->new_cookie = session_sticky = generate_cookie(&cluster->address_list); break; case StickyMode::JVM_ROUTE: /* calculate session_sticky from JSESSIONID cookie suffix */ session_sticky = lb_jvm_route_get(request.headers, *cluster); break; } tcp_balancer_get(request2->balancer, request.pool, transparent_source, bind_address, session_sticky, cluster->address_list, 20, *request2, request2->cancel_ptr); } void LbConnection::LogHttpRequest(HttpServerRequest &request, http_status_t status, int64_t length, uint64_t bytes_received, uint64_t bytes_sent) { access_log(&request, nullptr, request.headers.Get("referer"), request.headers.Get("user-agent"), status, length, bytes_received, bytes_sent, std::chrono::steady_clock::now() - request_start_time); } void LbConnection::HttpConnectionError(GError *error) { int level = 2; if (error->domain == errno_quark() && error->code == ECONNRESET) level = 4; lb_connection_log_gerror(level, this, "Error", error); g_error_free(error); assert(http != nullptr); http = nullptr; lb_connection_remove(this); } void LbConnection::HttpConnectionClosed() { assert(http != nullptr); http = nullptr; lb_connection_remove(this); } <commit_msg>lb_http: use http_server_simple_response() in send_fallback()<commit_after>/* * Handler for HTTP requests. * * author: Max Kellermann <mk@cm4all.com> */ #include "lb_http.hxx" #include "lb_instance.hxx" #include "lb_connection.hxx" #include "lb_config.hxx" #include "lb_session.hxx" #include "lb_cookie.hxx" #include "lb_jvm_route.hxx" #include "lb_headers.hxx" #include "lb_log.hxx" #include "ssl/ssl_filter.hxx" #include "address_sticky.hxx" #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_server/Handler.hxx" #include "http_client.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "header_writer.hxx" #include "http_response.hxx" #include "http_headers.hxx" #include "stock/GetHandler.hxx" #include "stock/Item.hxx" #include "stock/Lease.hxx" #include "access_log.hxx" #include "strmap.hxx" #include "failure.hxx" #include "bulldog.h" #include "pool.hxx" #include "net/SocketAddress.hxx" #include "istream/istream.hxx" #include "istream/UnusedHoldPtr.hxx" #include "gerrno.h" #include "util/Cancellable.hxx" #include <http/status.h> #include <daemon/log.h> struct LbRequest final : Cancellable, StockGetHandler, HttpResponseHandler { LbConnection &connection; const LbClusterConfig *cluster; TcpBalancer &balancer; HttpServerRequest &request; /** * The request body. */ UnusedHoldIstreamPtr body; CancellablePointer cancel_ptr; StockItem *stock_item; unsigned new_cookie = 0; LbRequest(LbConnection &_connection, TcpBalancer &_balancer, HttpServerRequest &_request, CancellablePointer &_cancel_ptr) :connection(_connection), balancer(_balancer), request(_request), body(request.pool, request.body) { _cancel_ptr = *this; } void Destroy() { DeleteFromPool(request.pool, this); } /* virtual methods from class Cancellable */ void Cancel() override { body.Clear(); CancellablePointer c(std::move(cancel_ptr)); Destroy(); c.Cancel(); } /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(GError *error) override; /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t status, StringMap &&headers, Istream *body) override; void OnHttpError(GError *error) override; }; static bool send_fallback(HttpServerRequest *request, const LbFallbackConfig *fallback) { if (!fallback->location.empty()) { http_server_simple_response(*request, HTTP_STATUS_FOUND, fallback->location.c_str(), nullptr); return true; } else if (!fallback->message.empty()) { /* custom status + error message */ http_server_simple_response(*request, fallback->status, nullptr, fallback->message.c_str()); return true; } else return false; } /** * Generate a cookie for sticky worker selection. Return only worker * numbers that are not known to be failing. Returns 0 on total * failure. */ static unsigned generate_cookie(const AddressList *list) { assert(list->GetSize() >= 2); const unsigned first = lb_cookie_generate(list->GetSize()); unsigned i = first; do { assert(i >= 1 && i <= list->GetSize()); const SocketAddress address = list->addresses[i % list->GetSize()]; if (failure_get_status(address) == FAILURE_OK && bulldog_check(address.GetAddress(), address.GetSize()) && !bulldog_is_fading(address.GetAddress(), address.GetSize())) return i; i = lb_cookie_next(list->GetSize(), i); } while (i != first); /* all nodes have failed */ return first; } /** * Is the specified error a server failure, that justifies * blacklisting the server for a while? */ static bool is_server_failure(GError *error) { return error->domain == http_client_quark() && error->code != HTTP_CLIENT_UNSPECIFIED; } /* * HTTP response handler * */ void LbRequest::OnHttpResponse(http_status_t status, StringMap &&_headers, Istream *response_body) { HttpHeaders headers(std::move(_headers)); if (request.method == HTTP_METHOD_HEAD) /* pass Content-Length, even though there is no response body (RFC 2616 14.13) */ headers.MoveToBuffer("content-length"); if (new_cookie != 0) { char buffer[64]; /* "Discard" must be last, to work around an Android bug*/ snprintf(buffer, sizeof(buffer), "beng_lb_node=0-%x; HttpOnly; Path=/; Version=1; Discard", new_cookie); headers.Write("cookie2", "$Version=\"1\""); headers.Write("set-cookie", buffer); } http_server_response(&request, status, std::move(headers), response_body); Destroy(); } void LbRequest::OnHttpError(GError *error) { if (is_server_failure(error)) failure_add(tcp_stock_item_get_address(*stock_item)); lb_connection_log_gerror(2, &connection, "Error", error); if (!send_fallback(&request, &cluster->fallback)) { const char *msg = connection.listener.verbose_response ? error->message : "Server failure"; http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY, msg); } g_error_free(error); Destroy(); } /* * stock callback * */ void LbRequest::OnStockItemReady(StockItem &item) { stock_item = &item; const char *peer_subject = connection.ssl_filter != nullptr ? ssl_filter_get_peer_subject(connection.ssl_filter) : nullptr; const char *peer_issuer_subject = connection.ssl_filter != nullptr ? ssl_filter_get_peer_issuer_subject(connection.ssl_filter) : nullptr; auto &headers = request.headers; lb_forward_request_headers(request.pool, headers, request.local_host_and_port, request.remote_host, peer_subject, peer_issuer_subject, cluster->mangle_via); auto *lease = NewFromPool<StockItemLease>(request.pool, item); http_client_request(request.pool, connection.instance.event_loop, tcp_stock_item_get(item), tcp_stock_item_get_domain(item) == AF_LOCAL ? FdType::FD_SOCKET : FdType::FD_TCP, *lease, item.GetStockName(), NULL, NULL, request.method, request.uri, HttpHeaders(std::move(headers)), body.Steal(), true, *this, cancel_ptr); } void LbRequest::OnStockItemError(GError *error) { lb_connection_log_gerror(2, &connection, "Connect error", error); body.Clear(); if (!send_fallback(&request, &cluster->fallback)) { const char *msg = connection.listener.verbose_response ? error->message : "Connection failure"; http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY, msg); } g_error_free(error); } /* * http connection handler * */ void LbConnection::HandleHttpRequest(HttpServerRequest &request, CancellablePointer &cancel_ptr) { ++instance.http_request_counter; request_start_time = std::chrono::steady_clock::now(); const auto &goto_ = listener.destination.FindRequestLeaf(request); if (goto_.status != http_status_t(0)) { http_server_simple_response(request, goto_.status, nullptr, nullptr); return; } const auto request2 = NewFromPool<LbRequest>(request.pool, *this, *instance.tcp_balancer, request, cancel_ptr); const auto *cluster = request2->cluster = goto_.cluster; SocketAddress bind_address = SocketAddress::Null(); const bool transparent_source = cluster->transparent_source; if (transparent_source) { bind_address = request.remote_address; /* reset the port to 0 to allow the kernel to choose one */ if (bind_address.GetFamily() == AF_INET) { struct sockaddr_in *s_in = (struct sockaddr_in *) p_memdup(&request.pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } else if (bind_address.GetFamily() == AF_INET6) { struct sockaddr_in6 *s_in = (struct sockaddr_in6 *) p_memdup(&request.pool, bind_address.GetAddress(), bind_address.GetSize()); s_in->sin6_port = 0; bind_address = SocketAddress((const struct sockaddr *)s_in, bind_address.GetSize()); } } if (cluster->HasZeroConf()) { /* TODO: generalize the Zeroconf code, implement sticky */ auto *cluster2 = instance.clusters.Find(cluster->name); if (cluster2 == nullptr) { http_server_send_message(&request, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Zeroconf cluster not found"); return; } const auto member = cluster2->Pick(); if (member.first == nullptr) { http_server_send_message(&request, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Zeroconf cluster is empty"); return; } assert(member.second.IsDefined()); tcp_stock_get(instance.tcp_stock, &request.pool, member.first, transparent_source, bind_address, member.second, 20, *request2, request2->cancel_ptr); return; } /* prepare for the balancer */ unsigned session_sticky = 0; switch (cluster->address_list.sticky_mode) { case StickyMode::NONE: case StickyMode::FAILOVER: /* these modes require no preparation; they are handled completely by balancer_get() */ break; case StickyMode::SOURCE_IP: /* calculate session_sticky from remote address */ session_sticky = socket_address_sticky(request.remote_address); break; case StickyMode::SESSION_MODULO: /* calculate session_sticky from beng-proxy session id */ session_sticky = lb_session_get(request.headers, cluster->session_cookie.c_str()); break; case StickyMode::COOKIE: /* calculate session_sticky from beng-lb cookie */ session_sticky = lb_cookie_get(request.headers); if (session_sticky == 0) request2->new_cookie = session_sticky = generate_cookie(&cluster->address_list); break; case StickyMode::JVM_ROUTE: /* calculate session_sticky from JSESSIONID cookie suffix */ session_sticky = lb_jvm_route_get(request.headers, *cluster); break; } tcp_balancer_get(request2->balancer, request.pool, transparent_source, bind_address, session_sticky, cluster->address_list, 20, *request2, request2->cancel_ptr); } void LbConnection::LogHttpRequest(HttpServerRequest &request, http_status_t status, int64_t length, uint64_t bytes_received, uint64_t bytes_sent) { access_log(&request, nullptr, request.headers.Get("referer"), request.headers.Get("user-agent"), status, length, bytes_received, bytes_sent, std::chrono::steady_clock::now() - request_start_time); } void LbConnection::HttpConnectionError(GError *error) { int level = 2; if (error->domain == errno_quark() && error->code == ECONNRESET) level = 4; lb_connection_log_gerror(level, this, "Error", error); g_error_free(error); assert(http != nullptr); http = nullptr; lb_connection_remove(this); } void LbConnection::HttpConnectionClosed() { assert(http != nullptr); http = nullptr; lb_connection_remove(this); } <|endoftext|>
<commit_before>#include <algorithm> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include "demoloop.h" #include "graphics/2d_primitives.h" #include "hsl.h" using namespace std; using namespace demoloop; const uint32_t NUM_VERTS = 3; float t = 0; const float CYCLE_LENGTH = 6; template < typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type > constexpr T mix(T const &a, T const &b, const float &ratio) { return a * (1.0f - ratio) + b * ratio; } class Loop021 : public Demoloop { public: Loop021() : Demoloop(150, 150, 150), RADIUS(height / 6) { glDisable(GL_DEPTH_TEST); float phi = 0.0f; const float interval = DEMOLOOP_M_PI * 2 / NUM_VERTS; for (uint32_t i = 0; i < (NUM_VERTS * 2) - 1; i+=2, phi += interval) { vertices[i].x = RADIUS * cosf(phi); vertices[i].y = RADIUS * sinf(phi); vertices[i].z = 0; vertices[i + 1].x = RADIUS * cosf(phi + interval); vertices[i + 1].y = RADIUS * sinf(phi + interval); vertices[i + 1].z = 0; } gl.getTransform() = glm::translate(gl.getTransform(), glm::vec3(width / 2, height / 2, 0)); } void Update(float dt) { t += dt; float cycle = fmod(t, CYCLE_LENGTH); float cycle_ratio = cycle / CYCLE_LENGTH; setColor(255, 255, 255); gl.lines(vertices, (NUM_VERTS * 2)); const float interval = DEMOLOOP_M_PI * 2 / NUM_VERTS; const glm::vec3 twoDAxis = {0, 0, 1}; for (uint32_t i = 0; i < NUM_VERTS; ++i) { float internal_cycle_ratio = fmod(cycle_ratio * NUM_VERTS, 1); int current_vertex = fmod(floor(i + cycle_ratio * NUM_VERTS), NUM_VERTS); float x1 = cosf(current_vertex * interval) * RADIUS; float y1 = sinf(current_vertex * interval) * RADIUS; float x2 = cosf((current_vertex + 1) * interval) * RADIUS; float y2 = sinf((current_vertex + 1) * interval) * RADIUS; float x = mix(x1, x2, internal_cycle_ratio); float y = mix(y1, y2, internal_cycle_ratio); glm::mat4 m; m = glm::translate(m, {x, y, 0}); m = glm::rotate(m, (float)DEMOLOOP_M_PI * cycle_ratio * 2, twoDAxis); m = glm::rotate(m, i * (float)DEMOLOOP_M_PI * 2 / NUM_VERTS, twoDAxis); m = glm::translate(m, {RADIUS, 0, 0}); m = glm::rotate(m, (float)DEMOLOOP_M_PI, twoDAxis); setColor(hsl2rgb(static_cast<float>(i) / NUM_VERTS, 1, 0.5)); gl.lines(vertices, (NUM_VERTS * 2), m); } } private: const float RADIUS; Vertex vertices[NUM_VERTS * 2]; }; int main(int, char**){ Loop021 loop; loop.Run(); return 0; } <commit_msg>baseline functional tiling<commit_after>#include <array> #include <vector> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include <glm/gtx/matrix_decompose.hpp> #include "demoloop.h" #include "hsl.h" #include "math_helpers.h" using namespace std; using namespace demoloop; const glm::vec3 twoDAxis = {0, 0, 1}; float t = 0; const float CYCLE_LENGTH = 5; const uint32_t MAX_VERTS = 12; float randFloat() { return static_cast <float> (rand()) / static_cast <float> (RAND_MAX); } template<uint N> typename std::enable_if<N >= 3, array<Vertex, N>>::type polygonVertices(const float &radius) { array<Vertex, N> r; const float interval = DEMOLOOP_M_PI * 2 / N; float phi = 0.0f; // float phi = rotationOffset(N); for (uint i = 0; i < N; ++i, phi += interval) { r[i].x = cosf(phi) * radius; r[i].y = sinf(phi) * radius; r[i].z = 0; RGB c = hsl2rgb(phi / (DEMOLOOP_M_PI * 2), 1, 0.5); r[i].r = c.r; r[i].g = c.g; r[i].b = c.b; } return r; } template<uint32_t N, uint32_t I = 3> typename std::enable_if<I == N, void>::type buffer(float, GLuint*) {} template<uint32_t N, uint32_t I = 3> typename std::enable_if<I < N, void>::type buffer(float RADIUS, GLuint *vbos) { const array<Vertex, I> vertex_data = polygonVertices<I>(RADIUS); glBindBuffer(GL_ARRAY_BUFFER, vbos[I - 3]); glBufferData(GL_ARRAY_BUFFER, I * sizeof(Vertex), vertex_data.data(), GL_DYNAMIC_DRAW); buffer<N, I + 1>(RADIUS, vbos); } struct Polygon { uint32_t num_verts; glm::mat4 transform; }; bool doShapesIntersect(const float radius, const Polygon &a, const Polygon &b) { static glm::vec3 scaleA; static glm::vec3 translationA; static glm::vec3 scaleB; static glm::vec3 translationB; static glm::quat rotation; static glm::vec3 skew; static glm::vec4 perspective; glm::decompose(a.transform, scaleA, rotation, translationA, skew, perspective); glm::decompose(b.transform, scaleB, rotation, translationB, skew, perspective); float x1 = translationA.x, y1 = translationA.y; float x2 = translationB.x, y2 = translationB.y; uint32_t v1 = a.num_verts, v2 = b.num_verts; float r1 = radius * scaleA.x * cosf(DEMOLOOP_M_PI / v1), r2 = radius * scaleB.x * cosf(DEMOLOOP_M_PI / v2); float dx = x1 - x2, dy = y1 - y2; float d = sqrt(dx * dx + dy * dy); bool inscriptions_overlap = d < (r1 + r2 - 0.1); return inscriptions_overlap; } bool intersectsAny(const float radius, const Polygon &shape, const vector<Polygon> &shapes) { for (const Polygon &other : shapes) { if (doShapesIntersect(radius, shape, other)) { return true; } } return false; } vector<vector<Polygon>> build(const float radius, const uint32_t num_layers) { vector<vector<Polygon>> tree(num_layers); vector<Polygon> all_shapes; { Polygon p = {3, glm::mat4()}; tree[0].push_back(p); all_shapes.push_back(p); } for (uint32_t layer_index = 1; layer_index < num_layers; ++layer_index) { // printf("layer_index: %u\n", layer_index); vector<Polygon> &previous_layer = tree[layer_index - 1]; vector<Polygon> &current_layer = tree[layer_index]; Polygon previous_shape = previous_layer[0]; uint32_t previous_vertex_count = previous_shape.num_verts; float previous_side_length = sinf(DEMOLOOP_M_PI / previous_vertex_count) * 2 * radius; // printf("previous_vertex_count: %u\n", previous_vertex_count); uint32_t current_vertex_count = layer_index + 3; current_vertex_count = randFloat() * (MAX_VERTS - 3) + 3; float current_side_length = sinf(DEMOLOOP_M_PI / current_vertex_count) * 2 * radius; // printf("current_vertex_count: %u\n", current_vertex_count); glm::vec3 scale; glm::quat rotation; glm::vec3 translation; glm::vec3 skew; glm::vec4 perspective; glm::decompose(previous_shape.transform, scale, rotation, translation, skew, perspective); float t = (DEMOLOOP_M_PI * 2) / previous_vertex_count; float inner_outer_ratio = previous_side_length / current_side_length; // printf("inner_outer_ratio: %f\n", inner_outer_ratio); float previous_distance = radius * cosf(DEMOLOOP_M_PI / previous_vertex_count); float current_distance = radius * cosf(DEMOLOOP_M_PI / current_vertex_count) * inner_outer_ratio; float d = previous_distance + current_distance; // printf("%f\n", d); float PI = DEMOLOOP_M_PI; for (uint32_t i = 0; i < previous_vertex_count; ++i) { for (const Polygon &previous_shape : previous_layer) { glm::mat4 transform = previous_shape.transform; transform = glm::rotate(transform, i * t, twoDAxis); transform = glm::rotate(transform, PI / previous_vertex_count, twoDAxis); transform = glm::translate(transform, {d, 0, 0}); transform = glm::rotate(transform, PI / current_vertex_count + PI, twoDAxis); transform = glm::scale(transform, {inner_outer_ratio, inner_outer_ratio, 1}); Polygon p = {current_vertex_count, transform}; if (intersectsAny(radius, p, all_shapes) == false) { current_layer.push_back(p); all_shapes.push_back(p); } } } // printf("\n"); } return tree; } class Loop021 : public Demoloop { public: Loop021() : Demoloop(1280, 720, 150, 150, 150), RADIUS(height / 20) { glDisable(GL_DEPTH_TEST); glGenBuffers(MAX_VERTS - 3, vbos); buffer<MAX_VERTS>(RADIUS, vbos); auto start = std::chrono::high_resolution_clock::now(); tree = build(RADIUS, 10); auto delta = std::chrono::high_resolution_clock::now() - start; printf("built in %f\n", std::chrono::duration_cast<std::chrono::duration<float>>(delta).count()); } ~Loop021() { glDeleteBuffers(MAX_VERTS - 3, vbos); } void Update(float dt) { t += dt; float cycle = fmod(t, CYCLE_LENGTH); float cycle_ratio = cycle / CYCLE_LENGTH; float scale = 1-pow(sin(cycle_ratio * DEMOLOOP_M_PI), 2)*0.99; GL::TempTransform t1(gl); t1.get() = glm::scale(glm::translate(t1.get(), glm::vec3(width / 2, height / 2, 0)), glm::vec3(scale, scale, 1) ); for(const vector<Polygon> &layer : tree) { for(const Polygon &p : layer) { gl.prepareDraw(p.transform); glBindBuffer(GL_ARRAY_BUFFER, vbos[p.num_verts - 3]); gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR); glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x)); glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, r)); gl.drawArrays(GL_TRIANGLE_FAN, 0, p.num_verts); } } // const uint32_t N = jmap(cycle_ratio, 0, 1, 3, MAX_VERTS); // gl.prepareDraw(); // glBindBuffer(GL_ARRAY_BUFFER, vbos[N - 3]); // gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR); // glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x)); // glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, r)); // gl.drawArrays(GL_TRIANGLE_FAN, 0, N); } private: const float RADIUS; GLuint vbos[MAX_VERTS - 3]; vector<vector<Polygon>> tree; }; int main(int, char**){ Loop021 loop; loop.Run(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <iterator> #include <map> #include <fcntl.h> #include <netdb.h> #include <net/if.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include "net_util.h" namespace net { #ifndef INET6_ADDRSTRLEN /* for non IPv6 machines */ #define INET6_ADDRSTRLEN 46 #endif bool ParseIPLiteralToNumber(const std::string& ip_literal, IPAddressNumber* ip_number) { char buf[sizeof(struct in6_addr)]; int size = sizeof(struct in_addr); int mode = AF_INET; if (ip_literal.find(':') != std::string::npos) { mode = AF_INET6; size = sizeof(struct in6_addr); } inet_pton(mode, ip_literal.c_str(), buf); for (int i = 0; i < size; i++) { (*ip_number)[i] = buf[i]; } return true; } IPAddressNumber ConvertIPv4NumberToIPv6Number( const IPAddressNumber& ipv4_number) { // IPv4-mapped addresses are formed by: // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>. IPAddressNumber ipv6_number; ipv6_number.reserve(16); ipv6_number.insert(ipv6_number.end(), 10, 0); ipv6_number.push_back(0xFF); ipv6_number.push_back(0xFF); ipv6_number.insert(ipv6_number.end(), ipv4_number.begin(), ipv4_number.end()); return ipv6_number; } bool ParseCIDRBlock(const std::string& cidr_literal, IPAddressNumber* ip_number, size_t* prefix_length_in_bits) { // We expect CIDR notation to match one of these two templates: // <IPv4-literal> "/" <number of bits> // <IPv6-literal> "/" <number of bits> std::vector<std::string> parts; unsigned int split = cidr_literal.find('/'); if (split == std::string::npos) return false; parts.push_back(cidr_literal.substr(0, split)); parts.push_back(cidr_literal.substr(split + 1)); if (parts[1].find('/') != std::string::npos) return false; // Parse the IP address. if (!ParseIPLiteralToNumber(parts[0], ip_number)) return false; // Parse the prefix length. int number_of_bits = atoi(parts[1].c_str()); // Make sure the prefix length is in a valid range. if (number_of_bits < 0 || number_of_bits > static_cast<int>(ip_number->size() * 8)) return false; *prefix_length_in_bits = static_cast<size_t>(number_of_bits); return true; } bool IPNumberMatchesPrefix(const IPAddressNumber& ip_number, const IPAddressNumber& ip_prefix, size_t prefix_length_in_bits) { // Both the input IP address and the prefix IP address should be // either IPv4 or IPv6. // In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to // IPv6 addresses in order to do the comparison. if (ip_number.size() != ip_prefix.size()) { if (ip_number.size() == 4) { return IPNumberMatchesPrefix(ConvertIPv4NumberToIPv6Number(ip_number), ip_prefix, prefix_length_in_bits); } return IPNumberMatchesPrefix(ip_number, ConvertIPv4NumberToIPv6Number(ip_prefix), 96 + prefix_length_in_bits); } // Otherwise we are comparing two IPv4 addresses, or two IPv6 addresses. // Compare all the bytes that fall entirely within the prefix. int num_entire_bytes_in_prefix = prefix_length_in_bits / 8; for (int i = 0; i < num_entire_bytes_in_prefix; ++i) { if (ip_number[i] != ip_prefix[i]) return false; } // In case the prefix was not a multiple of 8, there will be 1 byte // which is only partially masked. int remaining_bits = prefix_length_in_bits % 8; if (remaining_bits != 0) { unsigned char mask = 0xFF << (8 - remaining_bits); int i = num_entire_bytes_in_prefix; if ((ip_number[i] & mask) != (ip_prefix[i] & mask)) return false; } return true; } } // namespace net <commit_msg>Fix crash in ParseIpLiteralToNumber<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <iterator> #include <map> #include <fcntl.h> #include <netdb.h> #include <net/if.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include "net_util.h" namespace net { #ifndef INET6_ADDRSTRLEN /* for non IPv6 machines */ #define INET6_ADDRSTRLEN 46 #endif bool ParseIPLiteralToNumber(const std::string& ip_literal, IPAddressNumber* ip_number) { char buf[sizeof(struct in6_addr)]; int size = sizeof(struct in_addr); int mode = AF_INET; if (ip_literal.find(':') != std::string::npos) { mode = AF_INET6; size = sizeof(struct in6_addr); } if (inet_pton(mode, ip_literal.c_str(), buf) != 1) { return false; } ip_number->resize(size); for (int i = 0; i < size; i++) { (*ip_number)[i] = buf[i]; } return true; } IPAddressNumber ConvertIPv4NumberToIPv6Number( const IPAddressNumber& ipv4_number) { // IPv4-mapped addresses are formed by: // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>. IPAddressNumber ipv6_number; ipv6_number.reserve(16); ipv6_number.insert(ipv6_number.end(), 10, 0); ipv6_number.push_back(0xFF); ipv6_number.push_back(0xFF); ipv6_number.insert(ipv6_number.end(), ipv4_number.begin(), ipv4_number.end()); return ipv6_number; } bool ParseCIDRBlock(const std::string& cidr_literal, IPAddressNumber* ip_number, size_t* prefix_length_in_bits) { // We expect CIDR notation to match one of these two templates: // <IPv4-literal> "/" <number of bits> // <IPv6-literal> "/" <number of bits> std::vector<std::string> parts; unsigned int split = cidr_literal.find('/'); if (split == std::string::npos) return false; parts.push_back(cidr_literal.substr(0, split)); parts.push_back(cidr_literal.substr(split + 1)); if (parts[1].find('/') != std::string::npos) return false; // Parse the IP address. if (!ParseIPLiteralToNumber(parts[0], ip_number)) return false; // Parse the prefix length. int number_of_bits = atoi(parts[1].c_str()); // Make sure the prefix length is in a valid range. if (number_of_bits < 0 || number_of_bits > static_cast<int>(ip_number->size() * 8)) return false; *prefix_length_in_bits = static_cast<size_t>(number_of_bits); return true; } bool IPNumberMatchesPrefix(const IPAddressNumber& ip_number, const IPAddressNumber& ip_prefix, size_t prefix_length_in_bits) { // Both the input IP address and the prefix IP address should be // either IPv4 or IPv6. // In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to // IPv6 addresses in order to do the comparison. if (ip_number.size() != ip_prefix.size()) { if (ip_number.size() == 4) { return IPNumberMatchesPrefix(ConvertIPv4NumberToIPv6Number(ip_number), ip_prefix, prefix_length_in_bits); } return IPNumberMatchesPrefix(ip_number, ConvertIPv4NumberToIPv6Number(ip_prefix), 96 + prefix_length_in_bits); } // Otherwise we are comparing two IPv4 addresses, or two IPv6 addresses. // Compare all the bytes that fall entirely within the prefix. int num_entire_bytes_in_prefix = prefix_length_in_bits / 8; for (int i = 0; i < num_entire_bytes_in_prefix; ++i) { if (ip_number[i] != ip_prefix[i]) return false; } // In case the prefix was not a multiple of 8, there will be 1 byte // which is only partially masked. int remaining_bits = prefix_length_in_bits % 8; if (remaining_bits != 0) { unsigned char mask = 0xFF << (8 - remaining_bits); int i = num_entire_bytes_in_prefix; if ((ip_number[i] & mask) != (ip_prefix[i] & mask)) return false; } return true; } } // namespace net <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "sparse_merge_function.h" #include "generic_merge.h" #include <vespa/eval/eval/fast_value.hpp> #include <vespa/vespalib/util/typify.h> namespace vespalib::eval { using namespace tensor_function; using namespace operation; using namespace instruction; namespace { template <typename CT, bool single_dim, typename Fun> const Value& my_fast_sparse_merge(const FastAddrMap &a_map, const FastAddrMap &b_map, const CT *a_cells, const CT *b_cells, const MergeParam &params, Stash &stash) { Fun fun(params.function); size_t guess_size = a_map.size() + b_map.size(); auto &result = stash.create<FastValue<CT,true>>(params.res_type, params.num_mapped_dimensions, 1u, guess_size); if constexpr (single_dim) { string_id cur_label; ConstArrayRef<string_id> addr(&cur_label, 1); const auto &a_labels = a_map.labels(); for (size_t i = 0; i < a_labels.size(); ++i) { cur_label = a_labels[i]; result.add_mapping(addr, cur_label.hash()); result.my_cells.push_back_fast(a_cells[i]); } const auto &b_labels = b_map.labels(); for (size_t i = 0; i < b_labels.size(); ++i) { cur_label = b_labels[i]; auto result_subspace = result.my_index.map.lookup_singledim(cur_label); if (result_subspace == FastAddrMap::npos()) { result.add_mapping(addr, cur_label.hash()); result.my_cells.push_back_fast(b_cells[i]); } else { CT *out_cell = result.my_cells.get(result_subspace); out_cell[0] = fun(out_cell[0], b_cells[i]); } } } else { a_map.each_map_entry([&](auto lhs_subspace, auto hash) { result.add_mapping(a_map.get_addr(lhs_subspace), hash); result.my_cells.push_back_fast(a_cells[lhs_subspace]); }); b_map.each_map_entry([&](auto rhs_subspace, auto hash) { auto rhs_addr = b_map.get_addr(rhs_subspace); auto result_subspace = result.my_index.map.lookup(rhs_addr, hash); if (result_subspace == FastAddrMap::npos()) { result.add_mapping(rhs_addr, hash); result.my_cells.push_back_fast(b_cells[rhs_subspace]); } else { CT *out_cell = result.my_cells.get(result_subspace); out_cell[0] = fun(out_cell[0], b_cells[rhs_subspace]); } }); } return result; } template <typename CT, bool single_dim, typename Fun> void my_sparse_merge_op(InterpretedFunction::State &state, uint64_t param_in) { const auto &param = unwrap_param<MergeParam>(param_in); assert(param.dense_subspace_size == 1u); const Value &a = state.peek(1); const Value &b = state.peek(0); const auto &a_idx = a.index(); const auto &b_idx = b.index(); if (__builtin_expect(are_fast(a_idx, b_idx), true)) { auto a_cells = a.cells().typify<CT>(); auto b_cells = b.cells().typify<CT>(); const Value &v = my_fast_sparse_merge<CT,single_dim,Fun>(as_fast(a_idx).map, as_fast(b_idx).map, a_cells.cbegin(), b_cells.cbegin(), param, state.stash); state.pop_pop_push(v); } else { auto up = generic_mixed_merge<CT,CT,CT,Fun>(a, b, param); state.pop_pop_push(*state.stash.create<std::unique_ptr<Value>>(std::move(up))); } } struct SelectSparseMergeOp { template <typename CT, typename SINGLE_DIM, typename Fun> static auto invoke() { return my_sparse_merge_op<CT,SINGLE_DIM::value,Fun>; } }; using MyTypify = TypifyValue<TypifyCellType,TypifyBool,operation::TypifyOp2>; } // namespace <unnamed> SparseMergeFunction::SparseMergeFunction(const tensor_function::Merge &original) : tensor_function::Merge(original.result_type(), original.lhs(), original.rhs(), original.function()) { assert(compatible_types(result_type(), lhs().result_type(), rhs().result_type())); } InterpretedFunction::Instruction SparseMergeFunction::compile_self(const ValueBuilderFactory &factory, Stash &stash) const { const auto &param = stash.create<MergeParam>(result_type(), lhs().result_type(), rhs().result_type(), function(), factory); size_t num_dims = result_type().count_mapped_dimensions(); auto op = typify_invoke<3,MyTypify,SelectSparseMergeOp>(result_type().cell_type(), num_dims == 1, function()); return InterpretedFunction::Instruction(op, wrap_param<MergeParam>(param)); } bool SparseMergeFunction::compatible_types(const ValueType &res, const ValueType &lhs, const ValueType &rhs) { if ((lhs.cell_type() == rhs.cell_type()) && (lhs.count_mapped_dimensions() > 0) && (lhs.dense_subspace_size() == 1)) { assert(res == lhs); assert(res == rhs); return true; } return false; } const TensorFunction & SparseMergeFunction::optimize(const TensorFunction &expr, Stash &stash) { if (auto merge = as<Merge>(expr)) { const TensorFunction &lhs = merge->lhs(); const TensorFunction &rhs = merge->rhs(); if (compatible_types(expr.result_type(), lhs.result_type(), rhs.result_type())) { return stash.create<SparseMergeFunction>(*merge); } } return expr; } } // namespace <commit_msg>use TypifyCellMeta in sparse merge optimizer<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "sparse_merge_function.h" #include "generic_merge.h" #include <vespa/eval/eval/fast_value.hpp> #include <vespa/vespalib/util/typify.h> namespace vespalib::eval { using namespace tensor_function; using namespace operation; using namespace instruction; namespace { template <typename CT, bool single_dim, typename Fun> const Value& my_fast_sparse_merge(const FastAddrMap &a_map, const FastAddrMap &b_map, const CT *a_cells, const CT *b_cells, const MergeParam &params, Stash &stash) { Fun fun(params.function); size_t guess_size = a_map.size() + b_map.size(); auto &result = stash.create<FastValue<CT,true>>(params.res_type, params.num_mapped_dimensions, 1u, guess_size); if constexpr (single_dim) { string_id cur_label; ConstArrayRef<string_id> addr(&cur_label, 1); const auto &a_labels = a_map.labels(); for (size_t i = 0; i < a_labels.size(); ++i) { cur_label = a_labels[i]; result.add_mapping(addr, cur_label.hash()); result.my_cells.push_back_fast(a_cells[i]); } const auto &b_labels = b_map.labels(); for (size_t i = 0; i < b_labels.size(); ++i) { cur_label = b_labels[i]; auto result_subspace = result.my_index.map.lookup_singledim(cur_label); if (result_subspace == FastAddrMap::npos()) { result.add_mapping(addr, cur_label.hash()); result.my_cells.push_back_fast(b_cells[i]); } else { CT *out_cell = result.my_cells.get(result_subspace); out_cell[0] = fun(out_cell[0], b_cells[i]); } } } else { a_map.each_map_entry([&](auto lhs_subspace, auto hash) { result.add_mapping(a_map.get_addr(lhs_subspace), hash); result.my_cells.push_back_fast(a_cells[lhs_subspace]); }); b_map.each_map_entry([&](auto rhs_subspace, auto hash) { auto rhs_addr = b_map.get_addr(rhs_subspace); auto result_subspace = result.my_index.map.lookup(rhs_addr, hash); if (result_subspace == FastAddrMap::npos()) { result.add_mapping(rhs_addr, hash); result.my_cells.push_back_fast(b_cells[rhs_subspace]); } else { CT *out_cell = result.my_cells.get(result_subspace); out_cell[0] = fun(out_cell[0], b_cells[rhs_subspace]); } }); } return result; } template <typename CT, bool single_dim, typename Fun> void my_sparse_merge_op(InterpretedFunction::State &state, uint64_t param_in) { const auto &param = unwrap_param<MergeParam>(param_in); assert(param.dense_subspace_size == 1u); const Value &a = state.peek(1); const Value &b = state.peek(0); const auto &a_idx = a.index(); const auto &b_idx = b.index(); if (__builtin_expect(are_fast(a_idx, b_idx), true)) { auto a_cells = a.cells().typify<CT>(); auto b_cells = b.cells().typify<CT>(); const Value &v = my_fast_sparse_merge<CT,single_dim,Fun>(as_fast(a_idx).map, as_fast(b_idx).map, a_cells.cbegin(), b_cells.cbegin(), param, state.stash); state.pop_pop_push(v); } else { auto up = generic_mixed_merge<CT,CT,CT,Fun>(a, b, param); state.pop_pop_push(*state.stash.create<std::unique_ptr<Value>>(std::move(up))); } } struct SelectSparseMergeOp { template <typename R1, typename SINGLE_DIM, typename Fun> static auto invoke() { using CT = CellValueType<R1::value.cell_type>; return my_sparse_merge_op<CT,SINGLE_DIM::value,Fun>; } }; using MyTypify = TypifyValue<TypifyCellMeta,TypifyBool,operation::TypifyOp2>; } // namespace <unnamed> SparseMergeFunction::SparseMergeFunction(const tensor_function::Merge &original) : tensor_function::Merge(original.result_type(), original.lhs(), original.rhs(), original.function()) { assert(compatible_types(result_type(), lhs().result_type(), rhs().result_type())); } InterpretedFunction::Instruction SparseMergeFunction::compile_self(const ValueBuilderFactory &factory, Stash &stash) const { const auto &param = stash.create<MergeParam>(result_type(), lhs().result_type(), rhs().result_type(), function(), factory); size_t num_dims = result_type().count_mapped_dimensions(); auto op = typify_invoke<3,MyTypify,SelectSparseMergeOp>(result_type().cell_meta().limit(), num_dims == 1, function()); return InterpretedFunction::Instruction(op, wrap_param<MergeParam>(param)); } bool SparseMergeFunction::compatible_types(const ValueType &res, const ValueType &lhs, const ValueType &rhs) { if ((lhs.cell_type() == rhs.cell_type()) && (lhs.cell_type() == res.cell_type()) && (lhs.count_mapped_dimensions() > 0) && (lhs.dense_subspace_size() == 1)) { assert(res == lhs); assert(res == rhs); return true; } return false; } const TensorFunction & SparseMergeFunction::optimize(const TensorFunction &expr, Stash &stash) { if (auto merge = as<Merge>(expr)) { const TensorFunction &lhs = merge->lhs(); const TensorFunction &rhs = merge->rhs(); if (compatible_types(expr.result_type(), lhs.result_type(), rhs.result_type())) { return stash.create<SparseMergeFunction>(*merge); } } return expr; } } // namespace <|endoftext|>
<commit_before>#pragma once #include <opencv2/core/cuda.hpp> #include <thrust/iterator/permutation_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/device_ptr.h> /* @Brief step_functor is an object to correctly step a thrust iterator according to the stride of a matrix */ //! [step_functor] template<typename T> struct step_functor : public thrust::unary_function<int, int> { int columns; int step; int channels; __host__ __device__ step_functor(int columns_, int step_, int channels_ = 1) : columns(columns_), step(step_), channels(channels_) { }; __host__ step_functor(cv::cuda::GpuMat& mat) { CV_Assert(mat.depth() == cv::DataType<T>::depth); columns = mat.cols; step = mat.step / sizeof(T); channels = mat.channels(); } __host__ __device__ int operator()(int x) const { int row = x / columns; int idx = (row * step) + (x % columns)*channels; return idx; } }; //! [step_functor] //! [begin_itr] /* @Brief GpuMatBeginItr returns a thrust compatible iterator to the beginning of a GPU mat's memory. @Param mat is the input matrix @Param channel is the channel of the matrix that the iterator is accessing. If set to -1, the iterator will access every element in sequential order */ template<typename T> thrust::permutation_iterator<thrust::device_ptr<T>, thrust::transform_iterator<step_functor<T>, thrust::counting_iterator<int>>> GpuMatBeginItr(cv::cuda::GpuMat mat, int channel = 0) { if (channel == -1) mat = mat.reshape(1); CV_Assert(mat.depth() == cv::DataType<T>::depth); CV_Assert(channel < mat.channels()); return thrust::make_permutation_iterator(thrust::device_pointer_cast(mat.ptr<T>(0) + channel), thrust::make_transform_iterator(thrust::make_counting_iterator(0), step_functor<T>(mat.cols, mat.step / sizeof(T), mat.channels()))); } //! [begin_itr] //! [end_itr] /* @Brief GpuMatEndItr returns a thrust compatible iterator to the end of a GPU mat's memory. @Param mat is the input matrix @Param channel is the channel of the matrix that the iterator is accessing. If set to -1, the iterator will access every element in sequential order */ template<typename T> thrust::permutation_iterator<thrust::device_ptr<T>, thrust::transform_iterator<step_functor<T>, thrust::counting_iterator<int>>> GpuMatEndItr(cv::cuda::GpuMat mat, int channel = 0) { if (channel == -1) mat = mat.reshape(1); CV_Assert(mat.depth() == cv::DataType<T>::depth); CV_Assert(channel < mat.channels()); return thrust::make_permutation_iterator(thrust::device_pointer_cast(mat.ptr<T>(0) + channel), thrust::make_transform_iterator(thrust::make_counting_iterator(mat.rows*mat.cols), step_functor<T>(mat.cols, mat.step / sizeof(T), mat.channels()))); } //! [end_itr] <commit_msg>More whitespace fixes.<commit_after>#pragma once #include <opencv2/core/cuda.hpp> #include <thrust/iterator/permutation_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/device_ptr.h> /* @Brief step_functor is an object to correctly step a thrust iterator according to the stride of a matrix */ //! [step_functor] template<typename T> struct step_functor : public thrust::unary_function<int, int> { int columns; int step; int channels; __host__ __device__ step_functor(int columns_, int step_, int channels_ = 1) : columns(columns_), step(step_), channels(channels_) { }; __host__ step_functor(cv::cuda::GpuMat& mat) { CV_Assert(mat.depth() == cv::DataType<T>::depth); columns = mat.cols; step = mat.step / sizeof(T); channels = mat.channels(); } __host__ __device__ int operator()(int x) const { int row = x / columns; int idx = (row * step) + (x % columns)*channels; return idx; } }; //! [step_functor] //! [begin_itr] /* @Brief GpuMatBeginItr returns a thrust compatible iterator to the beginning of a GPU mat's memory. @Param mat is the input matrix @Param channel is the channel of the matrix that the iterator is accessing. If set to -1, the iterator will access every element in sequential order */ template<typename T> thrust::permutation_iterator<thrust::device_ptr<T>, thrust::transform_iterator<step_functor<T>, thrust::counting_iterator<int>>> GpuMatBeginItr(cv::cuda::GpuMat mat, int channel = 0) { if (channel == -1) mat = mat.reshape(1); CV_Assert(mat.depth() == cv::DataType<T>::depth); CV_Assert(channel < mat.channels()); return thrust::make_permutation_iterator(thrust::device_pointer_cast(mat.ptr<T>(0) + channel), thrust::make_transform_iterator(thrust::make_counting_iterator(0), step_functor<T>(mat.cols, mat.step / sizeof(T), mat.channels()))); } //! [begin_itr] //! [end_itr] /* @Brief GpuMatEndItr returns a thrust compatible iterator to the end of a GPU mat's memory. @Param mat is the input matrix @Param channel is the channel of the matrix that the iterator is accessing. If set to -1, the iterator will access every element in sequential order */ template<typename T> thrust::permutation_iterator<thrust::device_ptr<T>, thrust::transform_iterator<step_functor<T>, thrust::counting_iterator<int>>> GpuMatEndItr(cv::cuda::GpuMat mat, int channel = 0) { if (channel == -1) mat = mat.reshape(1); CV_Assert(mat.depth() == cv::DataType<T>::depth); CV_Assert(channel < mat.channels()); return thrust::make_permutation_iterator(thrust::device_pointer_cast(mat.ptr<T>(0) + channel), thrust::make_transform_iterator(thrust::make_counting_iterator(mat.rows*mat.cols), step_functor<T>(mat.cols, mat.step / sizeof(T), mat.channels()))); } //! [end_itr]<|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "console/console.h" #include "SDL.h" #include "windowManager/sdl/sdlWindow.h" static SDL_Window* gSplashWindow = nullptr; static SDL_Surface* gSplashImage = nullptr; static SDL_Texture* gSplashTexture = nullptr; static SDL_Renderer* gSplashRenderer = nullptr; bool Platform::displaySplashWindow( String path ) { if(path.isEmpty()) return false; gSplashImage = SDL_LoadBMP(path); //now the pop-up window gSplashWindow = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, gSplashImage->w, gSplashImage->h, SDL_WINDOW_BORDERLESS | SDL_WINDOW_SHOWN); gSplashRenderer = SDL_CreateRenderer(gSplashWindow, -1, SDL_RENDERER_ACCELERATED); gSplashTexture = SDL_CreateTextureFromSurface(gSplashRenderer, gSplashImage); SDL_RenderCopy(gSplashRenderer, gSplashTexture, NULL, NULL); SDL_RenderPresent(gSplashRenderer); return true; } bool Platform::closeSplashWindow() { SDL_DestroyTexture(gSplashTexture); SDL_FreeSurface(gSplashImage); SDL_DestroyRenderer(gSplashRenderer); SDL_DestroyWindow(gSplashWindow); return true; }<commit_msg>Also adds a sanity check in the event a splash image isn't found.<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "console/console.h" #include "SDL.h" #include "windowManager/sdl/sdlWindow.h" static SDL_Window* gSplashWindow = nullptr; static SDL_Surface* gSplashImage = nullptr; static SDL_Texture* gSplashTexture = nullptr; static SDL_Renderer* gSplashRenderer = nullptr; bool Platform::displaySplashWindow( String path ) { if(path.isEmpty()) return false; gSplashImage = SDL_LoadBMP(path); //now the pop-up window if (gSplashImage) { gSplashWindow = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, gSplashImage->w, gSplashImage->h, SDL_WINDOW_BORDERLESS | SDL_WINDOW_SHOWN); gSplashRenderer = SDL_CreateRenderer(gSplashWindow, -1, SDL_RENDERER_ACCELERATED); gSplashTexture = SDL_CreateTextureFromSurface(gSplashRenderer, gSplashImage); SDL_RenderCopy(gSplashRenderer, gSplashTexture, NULL, NULL); SDL_RenderPresent(gSplashRenderer); } return true; } bool Platform::closeSplashWindow() { SDL_DestroyTexture(gSplashTexture); SDL_FreeSurface(gSplashImage); SDL_DestroyRenderer(gSplashRenderer); SDL_DestroyWindow(gSplashWindow); return true; }<|endoftext|>
<commit_before>#include "ProjectWidgetDemoWindow.h" #include "Required/Project/ProjectSerializer.h" #include "Required/Project/ProjectException.h" #include "Required/Project/FileCategory.h" #include <QDebug> #include <QFile> #include <QMessageBox> #include <QRegExp> ProjectWidgetDemoWindow::ProjectWidgetDemoWindow(QWidget *parent) : QMainWindow(parent) { Required::FileCategory::registerCategory("txt", "Text files", QRegExp("*.txt", Qt::CaseSensitive, QRegExp::Wildcard)); Required::FileCategory::registerCategory("json", "JSON data", QRegExp("*.json", Qt::CaseSensitive, QRegExp::Wildcard)); // load project data from file QFile file("project.xml"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { Required::ProjectSerializer serializer(&file); try { m_project = serializer.deserialize(); } catch (Required::ProjectException& e) { m_project = new Required::Project(this); m_project->setName("My Awesome Project"); } file.close(); } else { m_project = new Required::Project(this); m_project->setName("My Awesome Project"); } m_project->setParent(this); m_projectWidget = new Required::ProjectWidget(this); m_projectWidget->setProject(m_project); setCentralWidget(m_projectWidget); connect(m_projectWidget, &Required::ProjectWidget::fileOpened, [&](QString filename) { QMessageBox::information(this, "File opened!", filename); }); } void ProjectWidgetDemoWindow::closeEvent(QCloseEvent* event) { // store project data in file QFile file("project.xml"); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { Required::ProjectSerializer serializer(&file); try { serializer.serialize(*m_project); } catch (Required::ProjectException& e) { qDebug() << e.what(); } file.close(); } } <commit_msg>Back to default regexp syntax in project_widget example.<commit_after>#include "ProjectWidgetDemoWindow.h" #include "Required/Project/ProjectSerializer.h" #include "Required/Project/ProjectException.h" #include "Required/Project/FileCategory.h" #include <QDebug> #include <QFile> #include <QMessageBox> #include <QRegExp> ProjectWidgetDemoWindow::ProjectWidgetDemoWindow(QWidget *parent) : QMainWindow(parent) { Required::FileCategory::registerCategory("txt", "Text files", QRegExp(".*\\.txt$")); Required::FileCategory::registerCategory("json", "JSON data", QRegExp(".*\\.json$")); // load project data from file QFile file("project.xml"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { Required::ProjectSerializer serializer(&file); try { m_project = serializer.deserialize(); } catch (Required::ProjectException& e) { m_project = new Required::Project(this); m_project->setName("My Awesome Project"); } file.close(); } else { m_project = new Required::Project(this); m_project->setName("My Awesome Project"); } m_project->setParent(this); m_projectWidget = new Required::ProjectWidget(this); m_projectWidget->setProject(m_project); setCentralWidget(m_projectWidget); connect(m_projectWidget, &Required::ProjectWidget::fileOpened, [&](QString filename) { QMessageBox::information(this, "File opened!", filename); }); } void ProjectWidgetDemoWindow::closeEvent(QCloseEvent* event) { // store project data in file QFile file("project.xml"); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { Required::ProjectSerializer serializer(&file); try { serializer.serialize(*m_project); } catch (Required::ProjectException& e) { qDebug() << e.what(); } file.close(); } } <|endoftext|>
<commit_before>#ifndef SiconosVisitables_hpp #define SiconosVisitables_hpp #undef REGISTER #define SICONOS_VISITABLES() \ REGISTER(DynamicalSystem) \ REGISTER(DynamicalSystemXML) \ REGISTER(DiskPlanR) \ REGISTER(DiskMovingPlanR) \ REGISTER(CircleCircleR) \ REGISTER(DiskDiskR) \ REGISTER(SphereNEDSPlanR) \ REGISTER(SphereNEDSSphereNEDSR) \ REGISTER(SphereLDSSphereLDSR) \ REGISTER(SphereLDSPlanR) \ REGISTER(NonSmoothLaw) \ REGISTER(MixedComplementarityConditionNSL) \ REGISTER(EqualityConditionNSL) \ REGISTER(ComplementarityConditionNSL) \ REGISTER(RelayNSL) \ REGISTER(NewtonImpactNSL) \ REGISTER(NewtonImpactFrictionNSL) \ REGISTER(Simulation) \ REGISTER(TimeStepping) \ REGISTER(EventDriven) \ REGISTER(OneStepNSProblem) \ REGISTER(LCP) \ REGISTER(FrictionContact) \ REGISTER(SimpleVector) \ REGISTER(BlockVector) \ REGISTER(LagrangianDS) \ REGISTER(LagrangianLinearTIDS) \ REGISTER(FirstOrderLinearDS) \ REGISTER(FirstOrderNonLinearDS) \ REGISTER(FirstOrderLinearTIDS) \ REGISTER(FirstOrderType1R) \ REGISTER(FirstOrderType2R) \ REGISTER(FirstOrderLinearR) \ REGISTER(FirstOrderLinearTIR) \ REGISTER(LagrangianScleronomousR) \ REGISTER(LagrangianRheonomousR) \ REGISTER(LagrangianCompliantR) \ REGISTER(LagrangianLinearTIR) \ REGISTER(NewtonEulerDS) \ REGISTER(NewtonEulerR) \ REGISTER_BASE(ExternalBody, LagrangianDS) \ REGISTER_BASE(Lmgc2DDSK, LagrangianDS) \ REGISTER_BASE(Disk, LagrangianDS) \ REGISTER_BASE(Circle, LagrangianDS) \ REGISTER_BASE(SphereLDS, LagrangianDS) \ REGISTER_BASE(SphereNEDS, NewtonEulerDS) \ #endif <commit_msg>add Lmgc2DPOLYG<commit_after>#ifndef SiconosVisitables_hpp #define SiconosVisitables_hpp #undef REGISTER #define SICONOS_VISITABLES() \ REGISTER(DynamicalSystem) \ REGISTER(DynamicalSystemXML) \ REGISTER(DiskPlanR) \ REGISTER(DiskMovingPlanR) \ REGISTER(CircleCircleR) \ REGISTER(DiskDiskR) \ REGISTER(SphereNEDSPlanR) \ REGISTER(SphereNEDSSphereNEDSR) \ REGISTER(SphereLDSSphereLDSR) \ REGISTER(SphereLDSPlanR) \ REGISTER(NonSmoothLaw) \ REGISTER(MixedComplementarityConditionNSL) \ REGISTER(EqualityConditionNSL) \ REGISTER(ComplementarityConditionNSL) \ REGISTER(RelayNSL) \ REGISTER(NewtonImpactNSL) \ REGISTER(NewtonImpactFrictionNSL) \ REGISTER(Simulation) \ REGISTER(TimeStepping) \ REGISTER(EventDriven) \ REGISTER(OneStepNSProblem) \ REGISTER(LCP) \ REGISTER(FrictionContact) \ REGISTER(SimpleVector) \ REGISTER(BlockVector) \ REGISTER(LagrangianDS) \ REGISTER(LagrangianLinearTIDS) \ REGISTER(FirstOrderLinearDS) \ REGISTER(FirstOrderNonLinearDS) \ REGISTER(FirstOrderLinearTIDS) \ REGISTER(FirstOrderType1R) \ REGISTER(FirstOrderType2R) \ REGISTER(FirstOrderLinearR) \ REGISTER(FirstOrderLinearTIR) \ REGISTER(LagrangianScleronomousR) \ REGISTER(LagrangianRheonomousR) \ REGISTER(LagrangianCompliantR) \ REGISTER(LagrangianLinearTIR) \ REGISTER(NewtonEulerDS) \ REGISTER(NewtonEulerR) \ REGISTER_BASE(ExternalBody, LagrangianDS) \ REGISTER_BASE(Lmgc2DDSK, LagrangianDS) \ REGISTER_BASE(Lmgc2DPOLYG, LagrangianDS) \ REGISTER_BASE(Disk, LagrangianDS) \ REGISTER_BASE(Circle, LagrangianDS) \ REGISTER_BASE(SphereLDS, LagrangianDS) \ REGISTER_BASE(SphereNEDS, NewtonEulerDS) \ #endif <|endoftext|>
<commit_before>#pragma once #include "screenrect.hpp" #include "../updater.hpp" #include "../glresource.hpp" namespace rs { namespace util { class PostEffect : public DrawableObjT<PostEffect> { private: using base_t = DrawableObjT<PostEffect>; using ParamF = std::function<void (IEffect&)>; using ParamFV = std::vector<std::pair<IdValue, ParamF>>; IdValue _idTech; ParamFV _param; ScreenRect _rect; void _applyParam(IEffect& e) const; public: PostEffect(IdValue idTech, Priority dprio); template <class T> void setParam(IdValue id, const T& t) { setParamFunc(id, [id,tv=t](auto& e){ e.setUniform(id, tv); }); } void setParamFunc(IdValue id, const ParamF& f); void clearParam(); void onDraw(IEffect& e) const override; }; class FBSwitch : public DrawableObjT<FBSwitch> { private: HLFb _hlFb; using ClearParam_OP = spn::Optional<draw::ClearParam>; ClearParam_OP _cparam; public: FBSwitch(Priority dprio, HFb hFb, const ClearParam_OP& p=spn::none); void onDraw(IEffect& e) const override; void setClearParam(const ClearParam_OP& p); }; class FBClear : public DrawableObjT<FBClear> { private: draw::ClearParam _param; public: FBClear(Priority dprio, const draw::ClearParam& p); void onDraw(IEffect& e) const override; }; } } #include "luaimport.hpp" DEF_LUAIMPORT(rs::util::FBSwitch) DEF_LUAIMPORT(rs::util::FBClear) <commit_msg>インクルードパスの修正<commit_after>#pragma once #include "screenrect.hpp" #include "../updater.hpp" #include "../glresource.hpp" namespace rs { namespace util { class PostEffect : public DrawableObjT<PostEffect> { private: using base_t = DrawableObjT<PostEffect>; using ParamF = std::function<void (IEffect&)>; using ParamFV = std::vector<std::pair<IdValue, ParamF>>; IdValue _idTech; ParamFV _param; ScreenRect _rect; void _applyParam(IEffect& e) const; public: PostEffect(IdValue idTech, Priority dprio); template <class T> void setParam(IdValue id, const T& t) { setParamFunc(id, [id,tv=t](auto& e){ e.setUniform(id, tv); }); } void setParamFunc(IdValue id, const ParamF& f); void clearParam(); void onDraw(IEffect& e) const override; }; class FBSwitch : public DrawableObjT<FBSwitch> { private: HLFb _hlFb; using ClearParam_OP = spn::Optional<draw::ClearParam>; ClearParam_OP _cparam; public: FBSwitch(Priority dprio, HFb hFb, const ClearParam_OP& p=spn::none); void onDraw(IEffect& e) const override; void setClearParam(const ClearParam_OP& p); }; class FBClear : public DrawableObjT<FBClear> { private: draw::ClearParam _param; public: FBClear(Priority dprio, const draw::ClearParam& p); void onDraw(IEffect& e) const override; }; } } #include "../luaimport.hpp" DEF_LUAIMPORT(rs::util::FBSwitch) DEF_LUAIMPORT(rs::util::FBClear) <|endoftext|>
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */ #define GRANARY_INTERNAL #define GRANARY_ARCH_INTERNAL #include "granary/base/string.h" #include "granary/cfg/basic_block.h" #include "granary/cfg/control_flow_graph.h" #include "granary/cfg/instruction.h" #include "granary/code/inline_assembly.h" #include "granary/arch/x86-64/instruction.h" #include "granary/arch/x86-64/select.h" #include "granary/breakpoint.h" namespace granary { namespace arch { // Categories of every iclass. extern xed_category_enum_t ICLASS_CATEGORIES[]; // Number of implicit operands for each iclass. extern const int NUM_IMPLICIT_OPERANDS[]; } // namespace arch namespace { // Not very pretty, but implements a simple top-down parser for parsing // Granary's inline assembly instructions. class InlineAssemblyParser { public: InlineAssemblyParser(LocalControlFlowGraph *cfg_, InlineAssemblyScope *scope_, DecodedBasicBlock *block_, Instruction *instr_, const char *ch_) : op(nullptr), num_immediates(0), cfg(cfg_), scope(scope_), block(block_), instr(instr_), ch(ch_), branch_target(nullptr) {} // Parse the inline assembly as a sequence of instructions. void ParseInstructions(void) { char buff[20] = {'\0'}; while (*ch) { ConsumeWhiteSpace(); ParseWord(buff); if (buff[0]) { if (StringsMatch(buff, "LABEL")) { ParseLabel(); Accept(':'); } else { memset(&data, 0, sizeof data); auto iclass = str2xed_iclass_enum_t(buff); GRANARY_ASSERT(XED_ICLASS_INVALID != iclass); data.iclass = iclass; data.category = arch::ICLASS_CATEGORIES[iclass]; op = &(data.ops[0]); num_immediates = 0; branch_target = nullptr; do { if (Peek(',')) { Accept(','); } ConsumeWhiteSpace(); } while (ParseOperand()); Accept(';'); FinalizeInstruction(); } } } } private: bool Peek(char next) { return *ch == next; } void Accept(char GRANARY_IF_DEBUG(next)) { GRANARY_ASSERT(Peek(next)); ch++; } bool PeekWhitespace(void) { return ' ' == *ch || '\t' == *ch || '\n' == *ch; } void ConsumeWhiteSpace(void) { for (; *ch && PeekWhitespace(); ++ch) {} } void ParseWord(char *buff) { for (; *ch; ) { if (PeekWhitespace() || Peek(';') || Peek(',') || Peek(':')) { break; } *buff++ = *ch++; } *buff = '\0'; } // Get a label. LabelInstruction *GetLabel(unsigned var_num) { if (!scope->var_is_initialized.Get(var_num)) { scope->var_is_initialized.Set(var_num, true); scope->vars[var_num].label = new LabelInstruction(); } return scope->vars[var_num].label; } void ParseLabel(void) { ConsumeWhiteSpace(); auto var_num = ParseVar(); auto label = GetLabel(var_num); instr->InsertBefore(std::unique_ptr<Instruction>(label)); } int ParseNumber(void) { char buff[20] = {'\0'}; ParseWord(buff); int num = -1; GRANARY_IF_DEBUG( auto got = ) DeFormat(buff, "%d", &num); GRANARY_ASSERT(1 == got); return num; } unsigned ParseVar(void) { Accept('%'); auto num = ParseNumber(); GRANARY_ASSERT(0 <= num && MAX_NUM_INLINE_VARS > num); return static_cast<unsigned>(num); } int ParseWidth(void) { auto width = ParseNumber(); GRANARY_ASSERT(8 == width || 16 == width || 32 == width || 64 == width); return width; } void ParseArchReg(void) { char buff[20] = {'\0'}; ParseWord(buff); auto reg = str2xed_reg_enum_t(buff); GRANARY_ASSERT(XED_REG_INVALID != reg); op->reg.DecodeFromNative(static_cast<int>(reg)); } void ParseInPlaceOp(void) { auto var_num = ParseVar(); GRANARY_ASSERT(scope->var_is_initialized.Get(var_num)); auto &untyped_op(scope->vars[var_num].mem); // Operand containers overlap. memcpy(op, untyped_op->Extract(), sizeof *op); } // TODO(pag): Only supports base form right now, i.e. `[%0]` and not the full // `segment:[disp + base + index * scale]` form. void ParseMemoryOp(void) { Accept('['); ConsumeWhiteSpace(); auto var_num = ParseVar(); GRANARY_ASSERT(scope->var_is_initialized.Get(var_num)); auto &reg_op(scope->vars[var_num].reg); op->type = XED_ENCODER_OPERAND_TYPE_MEM; op->reg = reg_op->Register(); ConsumeWhiteSpace(); Accept(']'); } // Like labels, this will create/initialize a new reg op if it isn't already // initialized. void ParseRegOp(void) { auto var_num = ParseVar(); auto &reg_op(scope->vars[var_num].reg); if (!scope->var_is_initialized.Get(var_num)) { op->type = XED_ENCODER_OPERAND_TYPE_REG; op->reg = block->AllocateVirtualRegister(); reg_op->UnsafeReplace(op); scope->var_is_initialized.Set(var_num, true); } else { memcpy(op, reg_op->Extract(), sizeof *op); } } void ParseImmediate(void) { char buff[20] = {'\0'}; ParseWord(buff); auto negate = false; auto offset = 0; if (buff[0] == '-') { negate = true; offset = 1; } auto format = "%lu"; if ('0' == buff[offset] && ('x' == buff[offset + 1] || 'X' == buff[offset + 1])) { offset += 2; format = "%lx"; } auto num = 0UL; GRANARY_IF_DEBUG( auto got = ) DeFormat(&(buff[offset]), format, &num); GRANARY_ASSERT(1 == got); if (!num_immediates) { op->type = negate ? XED_ENCODER_OPERAND_TYPE_SIMM0 : XED_ENCODER_OPERAND_TYPE_IMM0; num = negate ? static_cast<unsigned long>(-static_cast<long>(num)) : num; num_immediates++; } else { op->type = XED_ENCODER_OPERAND_TYPE_IMM1; } op->imm.as_uint = num; } // Parse an inline assembly operand. bool ParseOperand(void) { auto op_type = *ch++; if ('l' == op_type) { // Handle labels as special cases. ConsumeWhiteSpace(); branch_target = GetLabel(ParseVar()); op->type = XED_ENCODER_OPERAND_TYPE_BRDISP; op->rw = XED_OPERAND_ACTION_R; } else if ('m' == op_type || 'i' == op_type || 'r' == op_type) { auto width = ParseWidth(); ConsumeWhiteSpace(); switch (op_type) { case 'm': // Memory. if (Peek('%')) { ParseInPlaceOp(); } else { ParseMemoryOp(); } break; case 'i': // Immediate. if (Peek('%')) { ParseInPlaceOp(); } else { ParseImmediate(); } break; case 'r': // Register. if (Peek('%')) { ParseRegOp(); } else { ParseArchReg(); } op->reg.Widen(width / 8); break; default: break; } op->width = static_cast<decltype(op->width)>(width); } else { ch--; return false; } ++data.num_explicit_ops; ++op; return true; } // Fix-up the operands by matching the instruction to a specific instruction // selection, and then super-imposing the r/w actions of those operands onto // the assembled operands. void FixupOperands(void) { auto xedi = SelectInstruction(&data); GRANARY_ASSERT(nullptr != xedi); auto i = 0U; for (auto &instr_op : data.ops) { if (XED_ENCODER_OPERAND_TYPE_INVALID == instr_op.type) { break; } else { auto xedi_op = xed_inst_operand(xedi, i++); instr_op.rw = xed_operand_rw(xedi_op); instr_op.is_explicit = true; } } } // Finalize the instruction by adding it to the basic block's instruction // list. void FinalizeInstruction(void) { std::unique_ptr<Instruction> new_instr; FixupOperands(); // Don't allow instructions the read or modify the stack pointer as this // will break invariants set up by early mangling about stack pointer // definedness. data.AnalyzeStackUsage(); GRANARY_ASSERT(!data.ReadsFromStackPointer() && !data.WritesToStackPointer()); if (data.IsJump()) { GRANARY_ASSERT(nullptr != branch_target); new_instr.reset(new BranchInstruction(&data, branch_target)); } else if (data.IsFunctionCall()) { auto bb = new NativeBasicBlock( data.HasIndirectTarget() ? nullptr : data.BranchTargetPC()); cfg->AddBlock(bb); new_instr.reset(new ControlFlowInstruction(&data, bb)); } else if (data.IsFunctionReturn()) { auto bb = new ReturnBasicBlock(nullptr /* no meta-data */); cfg->AddBlock(bb); new_instr.reset(new ControlFlowInstruction(&data, bb)); } else { new_instr.reset(new NativeInstruction(&data)); } instr->InsertBefore(std::move(new_instr)); } // Holds an in-progress instructions. arch::Instruction data; // The next operand to decode. arch::Operand *op; // The number of immediates already seen. int num_immediates; // The control-flow graph; used to materialize basic blocks. LocalControlFlowGraph *cfg; // Scope from which local/input variables can be looked up. InlineAssemblyScope * const scope; // Basic block into which instructions are being placed. Used to allocate // new virtual registers. DecodedBasicBlock * const block; // Instruction before which all assembly instructions will be placed. Instruction * const instr; // The next character to parse. const char *ch; // Label that is the target of this instruction, in the event that this // instruction is a branch. LabelInstruction *branch_target; }; } // namespace // Compile this inline assembly into some instructions within the block // `block`. This places the inlined instructions before `instr`, which is // assumed to be the `AnnotationInstruction` containing the inline assembly // instructions. void CompileInlineAssemblyBlock(LocalControlFlowGraph *cfg, DecodedBasicBlock *block, Instruction *instr, InlineAssemblyBlock *asm_block) { InlineAssemblyParser parser(cfg, asm_block->scope, block, instr, asm_block->assembly); parser.ParseInstructions(); } } // namespace granary <commit_msg>Added an extra check into the step 0 of assembly that compiles the inline assembly. The step is an early check that the direction flag is not modified by inline assembly. This check mirrors a similar check in step 5.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */ #define GRANARY_INTERNAL #define GRANARY_ARCH_INTERNAL #include "granary/base/string.h" #include "granary/cfg/basic_block.h" #include "granary/cfg/control_flow_graph.h" #include "granary/cfg/instruction.h" #include "granary/code/inline_assembly.h" #include "granary/arch/x86-64/instruction.h" #include "granary/arch/x86-64/select.h" #include "granary/breakpoint.h" namespace granary { namespace arch { // Categories of every iclass. extern xed_category_enum_t ICLASS_CATEGORIES[]; // Number of implicit operands for each iclass. extern const int NUM_IMPLICIT_OPERANDS[]; // Table mapping each iclass to the set of read and written flags by *any* // selection of that iclass. extern FlagsSet ICLASS_FLAGS[]; } // namespace arch namespace { // Not very pretty, but implements a simple top-down parser for parsing // Granary's inline assembly instructions. class InlineAssemblyParser { public: InlineAssemblyParser(LocalControlFlowGraph *cfg_, InlineAssemblyScope *scope_, DecodedBasicBlock *block_, Instruction *instr_, const char *ch_) : op(nullptr), num_immediates(0), cfg(cfg_), scope(scope_), block(block_), instr(instr_), ch(ch_), branch_target(nullptr) {} // Parse the inline assembly as a sequence of instructions. void ParseInstructions(void) { char buff[20] = {'\0'}; while (*ch) { ConsumeWhiteSpace(); ParseWord(buff); if (buff[0]) { if (StringsMatch(buff, "LABEL")) { ParseLabel(); Accept(':'); } else { memset(&data, 0, sizeof data); auto iclass = str2xed_iclass_enum_t(buff); GRANARY_ASSERT(XED_ICLASS_INVALID != iclass); data.iclass = iclass; data.category = arch::ICLASS_CATEGORIES[iclass]; op = &(data.ops[0]); num_immediates = 0; branch_target = nullptr; do { if (Peek(',')) { Accept(','); } ConsumeWhiteSpace(); } while (ParseOperand()); Accept(';'); FinalizeInstruction(); } } } } private: bool Peek(char next) { return *ch == next; } void Accept(char GRANARY_IF_DEBUG(next)) { GRANARY_ASSERT(Peek(next)); ch++; } bool PeekWhitespace(void) { return ' ' == *ch || '\t' == *ch || '\n' == *ch; } void ConsumeWhiteSpace(void) { for (; *ch && PeekWhitespace(); ++ch) {} } void ParseWord(char *buff) { for (; *ch; ) { if (PeekWhitespace() || Peek(';') || Peek(',') || Peek(':')) { break; } *buff++ = *ch++; } *buff = '\0'; } // Get a label. LabelInstruction *GetLabel(unsigned var_num) { if (!scope->var_is_initialized.Get(var_num)) { scope->var_is_initialized.Set(var_num, true); scope->vars[var_num].label = new LabelInstruction(); } return scope->vars[var_num].label; } void ParseLabel(void) { ConsumeWhiteSpace(); auto var_num = ParseVar(); auto label = GetLabel(var_num); instr->InsertBefore(std::unique_ptr<Instruction>(label)); } int ParseNumber(void) { char buff[20] = {'\0'}; ParseWord(buff); int num = -1; GRANARY_IF_DEBUG( auto got = ) DeFormat(buff, "%d", &num); GRANARY_ASSERT(1 == got); return num; } unsigned ParseVar(void) { Accept('%'); auto num = ParseNumber(); GRANARY_ASSERT(0 <= num && MAX_NUM_INLINE_VARS > num); return static_cast<unsigned>(num); } int ParseWidth(void) { auto width = ParseNumber(); GRANARY_ASSERT(8 == width || 16 == width || 32 == width || 64 == width); return width; } void ParseArchReg(void) { char buff[20] = {'\0'}; ParseWord(buff); auto reg = str2xed_reg_enum_t(buff); GRANARY_ASSERT(XED_REG_INVALID != reg); op->reg.DecodeFromNative(static_cast<int>(reg)); } void ParseInPlaceOp(void) { auto var_num = ParseVar(); GRANARY_ASSERT(scope->var_is_initialized.Get(var_num)); auto &untyped_op(scope->vars[var_num].mem); // Operand containers overlap. memcpy(op, untyped_op->Extract(), sizeof *op); } // TODO(pag): Only supports base form right now, i.e. `[%0]` and not the full // `segment:[disp + base + index * scale]` form. void ParseMemoryOp(void) { Accept('['); ConsumeWhiteSpace(); auto var_num = ParseVar(); GRANARY_ASSERT(scope->var_is_initialized.Get(var_num)); auto &reg_op(scope->vars[var_num].reg); op->type = XED_ENCODER_OPERAND_TYPE_MEM; op->reg = reg_op->Register(); ConsumeWhiteSpace(); Accept(']'); } // Like labels, this will create/initialize a new reg op if it isn't already // initialized. void ParseRegOp(void) { auto var_num = ParseVar(); auto &reg_op(scope->vars[var_num].reg); if (!scope->var_is_initialized.Get(var_num)) { op->type = XED_ENCODER_OPERAND_TYPE_REG; op->reg = block->AllocateVirtualRegister(); reg_op->UnsafeReplace(op); scope->var_is_initialized.Set(var_num, true); } else { memcpy(op, reg_op->Extract(), sizeof *op); } } void ParseImmediate(void) { char buff[20] = {'\0'}; ParseWord(buff); auto negate = false; auto offset = 0; if (buff[0] == '-') { negate = true; offset = 1; } auto format = "%lu"; if ('0' == buff[offset] && ('x' == buff[offset + 1] || 'X' == buff[offset + 1])) { offset += 2; format = "%lx"; } auto num = 0UL; GRANARY_IF_DEBUG( auto got = ) DeFormat(&(buff[offset]), format, &num); GRANARY_ASSERT(1 == got); if (!num_immediates) { op->type = negate ? XED_ENCODER_OPERAND_TYPE_SIMM0 : XED_ENCODER_OPERAND_TYPE_IMM0; num = negate ? static_cast<unsigned long>(-static_cast<long>(num)) : num; num_immediates++; } else { op->type = XED_ENCODER_OPERAND_TYPE_IMM1; } op->imm.as_uint = num; } // Parse an inline assembly operand. bool ParseOperand(void) { auto op_type = *ch++; if ('l' == op_type) { // Handle labels as special cases. ConsumeWhiteSpace(); branch_target = GetLabel(ParseVar()); op->type = XED_ENCODER_OPERAND_TYPE_BRDISP; op->rw = XED_OPERAND_ACTION_R; } else if ('m' == op_type || 'i' == op_type || 'r' == op_type) { auto width = ParseWidth(); ConsumeWhiteSpace(); switch (op_type) { case 'm': // Memory. if (Peek('%')) { ParseInPlaceOp(); } else { ParseMemoryOp(); } break; case 'i': // Immediate. if (Peek('%')) { ParseInPlaceOp(); } else { ParseImmediate(); } break; case 'r': // Register. if (Peek('%')) { ParseRegOp(); } else { ParseArchReg(); } op->reg.Widen(width / 8); break; default: break; } op->width = static_cast<decltype(op->width)>(width); } else { ch--; return false; } ++data.num_explicit_ops; ++op; return true; } // Fix-up the operands by matching the instruction to a specific instruction // selection, and then super-imposing the r/w actions of those operands onto // the assembled operands. void FixupOperands(void) { auto xedi = SelectInstruction(&data); GRANARY_ASSERT(nullptr != xedi); auto i = 0U; for (auto &instr_op : data.ops) { if (XED_ENCODER_OPERAND_TYPE_INVALID == instr_op.type) { break; } else { auto xedi_op = xed_inst_operand(xedi, i++); instr_op.rw = xed_operand_rw(xedi_op); instr_op.is_explicit = true; } } } // Finalize the instruction by adding it to the basic block's instruction // list. void FinalizeInstruction(void) { std::unique_ptr<Instruction> new_instr; FixupOperands(); // Don't allow instructions the read or modify the stack pointer as this // will break invariants set up by early mangling about stack pointer // definedness. data.AnalyzeStackUsage(); GRANARY_ASSERT(!data.ReadsFromStackPointer() && !data.WritesToStackPointer()); // Ensure that instrumentation instructions do not alter the direction // flag! This is because we have no reliable way of saving and restoring // the direction flag (lest we use `PUSHF` and `POPF`) when the stack // pointer is not known to be valid. GRANARY_IF_DEBUG( auto flags = arch::ICLASS_FLAGS[data.iclass]; ) GRANARY_ASSERT(!flags.written.s.df); if (data.IsJump()) { GRANARY_ASSERT(nullptr != branch_target); new_instr.reset(new BranchInstruction(&data, branch_target)); } else if (data.IsFunctionCall()) { auto bb = new NativeBasicBlock( data.HasIndirectTarget() ? nullptr : data.BranchTargetPC()); cfg->AddBlock(bb); new_instr.reset(new ControlFlowInstruction(&data, bb)); } else if (data.IsFunctionReturn()) { auto bb = new ReturnBasicBlock(nullptr /* no meta-data */); cfg->AddBlock(bb); new_instr.reset(new ControlFlowInstruction(&data, bb)); } else { new_instr.reset(new NativeInstruction(&data)); } instr->InsertBefore(std::move(new_instr)); } // Holds an in-progress instructions. arch::Instruction data; // The next operand to decode. arch::Operand *op; // The number of immediates already seen. int num_immediates; // The control-flow graph; used to materialize basic blocks. LocalControlFlowGraph *cfg; // Scope from which local/input variables can be looked up. InlineAssemblyScope * const scope; // Basic block into which instructions are being placed. Used to allocate // new virtual registers. DecodedBasicBlock * const block; // Instruction before which all assembly instructions will be placed. Instruction * const instr; // The next character to parse. const char *ch; // Label that is the target of this instruction, in the event that this // instruction is a branch. LabelInstruction *branch_target; }; } // namespace // Compile this inline assembly into some instructions within the block // `block`. This places the inlined instructions before `instr`, which is // assumed to be the `AnnotationInstruction` containing the inline assembly // instructions. void CompileInlineAssemblyBlock(LocalControlFlowGraph *cfg, DecodedBasicBlock *block, Instruction *instr, InlineAssemblyBlock *asm_block) { InlineAssemblyParser parser(cfg, asm_block->scope, block, instr, asm_block->assembly); parser.ParseInstructions(); } } // namespace granary <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/json/extract_bounding_box_grammar.hpp> #include <mapnik/geometry_fusion_adapted.hpp> // boost #include <boost/spirit/include/qi_omit.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/repository/include/qi_iter_pos.hpp> #include <boost/spirit/include/phoenix_function.hpp> // stl #include <iostream> #include <string> namespace mapnik { namespace json { struct calculate_bounding_box_impl { using result_type = void; template <typename T0, typename T1> result_type operator() (T0 & bbox, T1 const& pos) const { if (pos) { typename T0::value_type x = pos->x; typename T0::value_type y = pos->y; if (!bbox.valid()) { bbox.init(x, y); } else { bbox.expand_to_include(x, y); } } } }; struct push_box_impl { using result_type = void; template <typename T0, typename T1, typename T2, typename T3> void operator() (T0 & boxes, T1 const& begin, T2 const& box, T3 const& range) const { if (box.valid()) boxes.emplace_back(box, std::make_pair(std::distance(begin, range.begin()), std::distance(range.begin(), range.end()))); } }; namespace repo = boost::spirit::repository; template <typename Iterator, typename Boxes, typename ErrorHandler> extract_bounding_box_grammar<Iterator, Boxes, ErrorHandler>::extract_bounding_box_grammar() : extract_bounding_box_grammar::base_type(start, "GeoJSON bounding boxes") { qi::lit_type lit; qi::double_type double_; qi::_val_type _val; qi::_1_type _1; qi::_2_type _2; qi::_3_type _3; qi::_4_type _4; qi::omit_type omit; qi::_r1_type _r1; qi::_r2_type _r2; qi::_a_type _a; qi::_b_type _b; qi::eps_type eps; qi::raw_type raw; qi::char_type char_; qi::no_skip_type no_skip; boost::spirit::repository::qi::iter_pos_type iter_pos; using qi::fail; using qi::on_error; // phoenix functions boost::phoenix::function<push_box_impl> push_box; boost::phoenix::function<calculate_bounding_box_impl> calculate_bounding_box; // error handler boost::phoenix::function<ErrorHandler> const error_handler; start = features(_r1) ; features = no_skip[iter_pos[_a = _1]] >> -(lit('{') >> *((json.key_value - lit("\"features\"")) >> lit(',')) >> lit("\"features\"") >> lit(':')) >> lit('[') >> (feature(_r1,_a) % lit(',')) >> lit(']') ; feature = raw[lit('{')[_a = 1] >> *(eps(_a > 0) >> ( lit("\"FeatureCollection\"") > eps(false) // fail if nested FeatureCollection | lit('{')[_a += 1] | lit('}')[_a -= 1] | coords[_b = _1] | json.string_ | char_))][push_box(_r1, _r2, _b, _1)] ; coords = lit("\"coordinates\"") >> lit(':') >> (rings_array(_a) | rings (_a) | ring(_a) | pos[calculate_bounding_box(_a,_1)])[_val = _a] ; pos = lit('[') > -(double_ > lit(',') > double_) > omit[*(lit(',') > double_)] > lit(']') ; ring = lit('[') >> pos[calculate_bounding_box(_r1,_1)] % lit(',') > lit(']') ; rings = lit('[') >> ring(_r1) % lit(',') > lit(']') ; rings_array = lit('[') >> rings(_r1) % lit(',') > lit(']') ; // generic json types json.value = json.object | json.array | json.string_ | json.number ; json.key_value = json.string_ >> lit(':') >> json.value ; json.object = lit('{') >> json.key_value % lit(',') >> lit('}') ; json.array = lit('[') >> json.value >> *(lit(',') >> json.value) >> lit(']') ; json.number = json.strict_double | json.int__ | lit("true") | lit("false") | lit("null") ; coords.name("Coordinates"); pos.name("Position"); ring.name("Ring"); rings.name("Rings"); rings_array.name("Rings array"); // error handler on_error<fail>(coords, error_handler(_1, _2, _3, _4)); } }} <commit_msg>extract_bounding_box_grammar - make features optional / ref #3463<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/json/extract_bounding_box_grammar.hpp> #include <mapnik/geometry_fusion_adapted.hpp> // boost #include <boost/spirit/include/qi_omit.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/repository/include/qi_iter_pos.hpp> #include <boost/spirit/include/phoenix_function.hpp> // stl #include <iostream> #include <string> namespace mapnik { namespace json { struct calculate_bounding_box_impl { using result_type = void; template <typename T0, typename T1> result_type operator() (T0 & bbox, T1 const& pos) const { if (pos) { typename T0::value_type x = pos->x; typename T0::value_type y = pos->y; if (!bbox.valid()) { bbox.init(x, y); } else { bbox.expand_to_include(x, y); } } } }; struct push_box_impl { using result_type = void; template <typename T0, typename T1, typename T2, typename T3> void operator() (T0 & boxes, T1 const& begin, T2 const& box, T3 const& range) const { if (box.valid()) boxes.emplace_back(box, std::make_pair(std::distance(begin, range.begin()), std::distance(range.begin(), range.end()))); } }; namespace repo = boost::spirit::repository; template <typename Iterator, typename Boxes, typename ErrorHandler> extract_bounding_box_grammar<Iterator, Boxes, ErrorHandler>::extract_bounding_box_grammar() : extract_bounding_box_grammar::base_type(start, "GeoJSON bounding boxes") { qi::lit_type lit; qi::double_type double_; qi::_val_type _val; qi::_1_type _1; qi::_2_type _2; qi::_3_type _3; qi::_4_type _4; qi::omit_type omit; qi::_r1_type _r1; qi::_r2_type _r2; qi::_a_type _a; qi::_b_type _b; qi::eps_type eps; qi::raw_type raw; qi::char_type char_; qi::no_skip_type no_skip; boost::spirit::repository::qi::iter_pos_type iter_pos; using qi::fail; using qi::on_error; // phoenix functions boost::phoenix::function<push_box_impl> push_box; boost::phoenix::function<calculate_bounding_box_impl> calculate_bounding_box; // error handler boost::phoenix::function<ErrorHandler> const error_handler; start = features(_r1) ; features = no_skip[iter_pos[_a = _1]] >> -(lit('{') >> *((json.key_value - lit("\"features\"")) >> lit(',')) >> lit("\"features\"") >> lit(':')) >> lit('[') >> -(feature(_r1,_a) % lit(',')) >> lit(']') ; feature = raw[lit('{')[_a = 1] >> *(eps(_a > 0) >> ( lit("\"FeatureCollection\"") > eps(false) // fail if nested FeatureCollection | lit('{')[_a += 1] | lit('}')[_a -= 1] | coords[_b = _1] | json.string_ | char_))][push_box(_r1, _r2, _b, _1)] ; coords = lit("\"coordinates\"") >> lit(':') >> (rings_array(_a) | rings (_a) | ring(_a) | pos[calculate_bounding_box(_a,_1)])[_val = _a] ; pos = lit('[') > -(double_ > lit(',') > double_) > omit[*(lit(',') > double_)] > lit(']') ; ring = lit('[') >> pos[calculate_bounding_box(_r1,_1)] % lit(',') > lit(']') ; rings = lit('[') >> ring(_r1) % lit(',') > lit(']') ; rings_array = lit('[') >> rings(_r1) % lit(',') > lit(']') ; // generic json types json.value = json.object | json.array | json.string_ | json.number ; json.key_value = json.string_ >> lit(':') >> json.value ; json.object = lit('{') >> json.key_value % lit(',') >> lit('}') ; json.array = lit('[') >> json.value >> *(lit(',') >> json.value) >> lit(']') ; json.number = json.strict_double | json.int__ | lit("true") | lit("false") | lit("null") ; coords.name("Coordinates"); pos.name("Position"); ring.name("Ring"); rings.name("Rings"); rings_array.name("Rings array"); // error handler on_error<fail>(coords, error_handler(_1, _2, _3, _4)); } }} <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP #define RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/background/background_manager.hpp> #include <rectojump/game/components/star5.hpp> #include <rectojump/game/components/triangles4.hpp> #include <rectojump/global/config_settings.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <mlk/time/simple_timer.h> #include <mlk/tools/random_utl.h> namespace rj { template<typename Main_Menu> class background_main_menu { Main_Menu& m_mainmenu; background_manager& m_backgroundmgr; sf::Texture m_sides_tx; const sf::Color& m_fillcolor; mlk::tm::simple_timer m_timer{300}; public: background_main_menu(Main_Menu& mm) : m_mainmenu{mm}, m_backgroundmgr{mm.get_gamehandler().get_backgroundmgr()}, m_sides_tx{mm.get_gamehandler().get_datamgr().template get_as<sf::Texture>("menu_side.png")}, m_fillcolor{mm.get_act_fontcolor()} {this->init();} void update(dur duration) { this->update_bg_objs(duration); } void update_bg_objs(dur duration) noexcept { if(m_timer.timed_out()) { auto size(settings::get_window_size<vec2f>()); auto pos_x(mlk::rnd(0.f, size.x)); auto length(mlk::rnd(30.f, 60.f)); auto rotatestep(mlk::rnd(-0.1f, 0.5f)); vec2f movestep{mlk::rnd(-0.1f, 0.5f), mlk::rnd(0.05f, 0.5f)}; auto object_type(mlk::rnd(0, 1)); if(object_type) { auto ptr(m_backgroundmgr.create_object<star5>(vec2f{pos_x, 0.f}, vec2f{0.f, length}, 5000, rotatestep, movestep)); ptr->render_object().setFillColor({m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); } else { // auto ptr(m_backgroundmgr.create_object<sf::RectangleShape>(vec2f{pos_x, 0.f}, vec2f{50.f, 50.f}, 5000, rotatestep, movestep)); // ptr->render_object().setFillColor({m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); // ptr->render_object().setOrigin(ptr->render_object().getSize() / 2.f); // m_timer.restart(mlk::rnd<mlk::ullong>(100, 300)); auto ptr(m_backgroundmgr.create_object<triangles4>(vec2f{pos_x, 0.f}, vec2f{15.5f, 30.f}, 5000, rotatestep, movestep)); ptr->render_object().setColor({m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); // ptr->render_object().setOrigin(ptr->render_object().getSize() / 2.f); } m_timer.restart(static_cast<mlk::ullong>(mlk::rnd<mlk::ullong>(100, 300) / duration)); } } void render() { } private: void init() { auto size(settings::get_window_size<vec2f>()); // nova auto triangles(m_backgroundmgr.create_object<triangles4>(vec2f{size.x / 2.f, size.y}, vec2f{200.f, 900.f}, 0, 0.1f, vec2f{0.f, 0.f})); triangles->render_object().setColor(to_rgb("#bdbdbd", 100)); // background sf::RectangleShape tx_shape{size}; tx_shape.setTexture(&m_sides_tx); m_backgroundmgr.set_tx_shape(tx_shape); m_backgroundmgr.set_bg_shape({size, to_rgb("#e3e3e3"), to_rgb("#e3e3e3"), 1}); // timer m_timer.run(); } }; } #endif // RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP <commit_msg>background_main_menu: fixed nova size<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP #define RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/background/background_manager.hpp> #include <rectojump/game/components/star5.hpp> #include <rectojump/game/components/triangles4.hpp> #include <rectojump/global/config_settings.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <mlk/time/simple_timer.h> #include <mlk/tools/random_utl.h> namespace rj { template<typename Main_Menu> class background_main_menu { Main_Menu& m_mainmenu; background_manager& m_backgroundmgr; sf::Texture m_sides_tx; const sf::Color& m_fillcolor; mlk::tm::simple_timer m_timer{300}; public: background_main_menu(Main_Menu& mm) : m_mainmenu{mm}, m_backgroundmgr{mm.get_gamehandler().get_backgroundmgr()}, m_sides_tx{mm.get_gamehandler().get_datamgr().template get_as<sf::Texture>("menu_side.png")}, m_fillcolor{mm.get_act_fontcolor()} {this->init();} void update(dur duration) { this->update_bg_objs(duration); } void update_bg_objs(dur duration) noexcept { if(m_timer.timed_out()) { auto size(settings::get_window_size<vec2f>()); auto pos_x(mlk::rnd(0.f, size.x)); auto length(mlk::rnd(30.f, 60.f)); auto rotatestep(mlk::rnd(-0.1f, 0.5f)); vec2f movestep{mlk::rnd(-0.1f, 0.5f), mlk::rnd(0.05f, 0.5f)}; auto object_type(mlk::rnd(0, 1)); if(object_type) { auto ptr(m_backgroundmgr.create_object<star5>(vec2f{pos_x, 0.f}, vec2f{0.f, length}, 5000, rotatestep, movestep)); ptr->render_object().setFillColor({m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); } else { // auto ptr(m_backgroundmgr.create_object<sf::RectangleShape>(vec2f{pos_x, 0.f}, vec2f{50.f, 50.f}, 5000, rotatestep, movestep)); // ptr->render_object().setFillColor({m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); // ptr->render_object().setOrigin(ptr->render_object().getSize() / 2.f); // m_timer.restart(mlk::rnd<mlk::ullong>(100, 300)); auto ptr(m_backgroundmgr.create_object<triangles4>(vec2f{pos_x, 0.f}, vec2f{15.5f, 30.f}, 5000, rotatestep, movestep)); ptr->render_object().setColor({m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); // ptr->render_object().setOrigin(ptr->render_object().getSize() / 2.f); } m_timer.restart(static_cast<mlk::ullong>(mlk::rnd<mlk::ullong>(100, 300) / duration)); } } void render() { } private: void init() { auto window_size(settings::get_window_size<vec2f>()); // nova auto nova(m_backgroundmgr.create_object<triangles4>(vec2f{window_size.x / 2.f, window_size.y}, vec2f{window_size.y / 3.f, window_size.x}, 0, 0.1f, vec2f{0.f, 0.f})); nova->render_object().setColor(to_rgb("#bdbdbd", 100)); // background sf::RectangleShape tx_shape{window_size}; tx_shape.setTexture(&m_sides_tx); m_backgroundmgr.set_tx_shape(tx_shape); m_backgroundmgr.set_bg_shape({window_size, to_rgb("#e3e3e3"), to_rgb("#e3e3e3"), 1}); // timer m_timer.run(); } }; } #endif // RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP <|endoftext|>
<commit_before>/** * This file is part of Slideshow. * Copyright (C) 2008 David Sveningsson <ext@sidvind.com> * * Slideshow 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. * * Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #include "mysqlbrowser.h" #include "Log.h" #include <cstring> #include <cstdlib> #include <cstdio> #include <cassert> #include <stdarg.h> #include <mysql/mysql.h> MySQLBrowser::MySQLBrowser(const char* username, const char* password, const char* database, const char* hostname): _username(NULL), _password(NULL), _database(NULL), _hostname(NULL), _conn(NULL), _fields(NULL), _nr_of_fields(0), _current_field(0){ set_username(username); set_password(password); set_database(database); set_hostname(hostname); connect(); } MySQLBrowser::~MySQLBrowser(){ disconnect(); clear_fields(); free(_username); free(_password); free(_database); free(_hostname); } const char* MySQLBrowser::get_next_file(){ return get_field(_current_field++);; } void MySQLBrowser::set_username(const char* username){ free(_username); assert( username && "Must supply a mysql username using the --db_user flag" ); _username = (char*)malloc( strlen(username) + 1 ); strcpy( _username, username); } void MySQLBrowser::set_password(const char* password){ free(_password); assert( password && "Must supply a mysql password using the --db_pass flag" ); _password = (char*)malloc( strlen(password) + 1 ); strcpy( _password, password); } void MySQLBrowser::set_database(const char* database){ free(_database); assert( database && "Must supply a mysql database using the --db_name flag" ); _database = (char*)malloc( strlen(database) + 1 ); strcpy( _database, database); } void MySQLBrowser::set_hostname(const char* hostname){ free(_hostname); assert( hostname ); _hostname = (char*)malloc( strlen(hostname) + 1 ); strcpy( _hostname, hostname); } void MySQLBrowser::connect(){ _conn = mysql_init(NULL); if (!mysql_real_connect(_conn, _hostname, _username, _password, _database, 0, NULL, 0)) { Log::message(Log::Fatal, "MySQLBrowser: Could not connect to database: %s\n", mysql_error(_conn)); exit(2); } } void MySQLBrowser::disconnect(){ mysql_close(_conn); } struct st_mysql_res* MySQLBrowser::query(const char* str, ...){ va_list arg; va_start(arg, str); char* query_str; vasprintf(&query_str, str, arg); if ( mysql_query(_conn, query_str) != 0 ) { Log::message(Log::Warning, "MySQLBrowser: Could not execute query '%s': %s\n", query_str, mysql_error(_conn)); } free(query_str); va_end(arg); return mysql_store_result(_conn); } void MySQLBrowser::reload(){ clear_fields(); MYSQL_RES *res = query("SELECT fullpath FROM files WHERE bin_id = %d AND active = true ORDER BY id", current_bin()); MYSQL_ROW row; _nr_of_fields = mysql_num_rows(res); allocate_fields( _nr_of_fields + 1 ); // The last field is set to NULL unsigned int i; for ( i = 0; i < _nr_of_fields; i++ ){ row = mysql_fetch_row(res); assert(row); set_field(i, row[0]); } set_field(i, NULL); mysql_free_result(res); } void MySQLBrowser::clear_fields(){ if ( !_fields ){ return; } unsigned int index = 0; while ( _fields[index] ){ free(_fields[index]); _fields[index] = NULL; index++; } free(_fields); _fields = NULL; } void MySQLBrowser::allocate_fields(unsigned int n){ _fields = (char**)malloc( sizeof(char*) * n ); for ( unsigned int i = 0; i < 0; i++ ){ _fields[i] = NULL; } } void MySQLBrowser::set_field(unsigned int n, const char* str){ if ( !str ){ _fields[n] = NULL; return; } _fields[n] = (char*)malloc( strlen(str)+1); strcpy( _fields[n], str ); } const char* MySQLBrowser::get_field(unsigned int n){ if ( _nr_of_fields == 0 ){ return NULL; } return _fields[n % _nr_of_fields]; } void MySQLBrowser::dump_queue(){ Log::message(Log::Debug, "MySQLBrowser: Dumping queue\n"); unsigned int index = 0; while ( _fields[index] ){ Log::message(Log::Debug, " %s\n", _fields[index++]); } } <commit_msg>Daemon must order by sortorder to maintain same order as frontend<commit_after>/** * This file is part of Slideshow. * Copyright (C) 2008 David Sveningsson <ext@sidvind.com> * * Slideshow 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. * * Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #include "mysqlbrowser.h" #include "Log.h" #include <cstring> #include <cstdlib> #include <cstdio> #include <cassert> #include <stdarg.h> #include <mysql/mysql.h> MySQLBrowser::MySQLBrowser(const char* username, const char* password, const char* database, const char* hostname): _username(NULL), _password(NULL), _database(NULL), _hostname(NULL), _conn(NULL), _fields(NULL), _nr_of_fields(0), _current_field(0){ set_username(username); set_password(password); set_database(database); set_hostname(hostname); connect(); } MySQLBrowser::~MySQLBrowser(){ disconnect(); clear_fields(); free(_username); free(_password); free(_database); free(_hostname); } const char* MySQLBrowser::get_next_file(){ return get_field(_current_field++);; } void MySQLBrowser::set_username(const char* username){ free(_username); assert( username && "Must supply a mysql username using the --db_user flag" ); _username = (char*)malloc( strlen(username) + 1 ); strcpy( _username, username); } void MySQLBrowser::set_password(const char* password){ free(_password); assert( password && "Must supply a mysql password using the --db_pass flag" ); _password = (char*)malloc( strlen(password) + 1 ); strcpy( _password, password); } void MySQLBrowser::set_database(const char* database){ free(_database); assert( database && "Must supply a mysql database using the --db_name flag" ); _database = (char*)malloc( strlen(database) + 1 ); strcpy( _database, database); } void MySQLBrowser::set_hostname(const char* hostname){ free(_hostname); assert( hostname ); _hostname = (char*)malloc( strlen(hostname) + 1 ); strcpy( _hostname, hostname); } void MySQLBrowser::connect(){ _conn = mysql_init(NULL); if (!mysql_real_connect(_conn, _hostname, _username, _password, _database, 0, NULL, 0)) { Log::message(Log::Fatal, "MySQLBrowser: Could not connect to database: %s\n", mysql_error(_conn)); exit(2); } } void MySQLBrowser::disconnect(){ mysql_close(_conn); } struct st_mysql_res* MySQLBrowser::query(const char* str, ...){ va_list arg; va_start(arg, str); char* query_str; vasprintf(&query_str, str, arg); if ( mysql_query(_conn, query_str) != 0 ) { Log::message(Log::Warning, "MySQLBrowser: Could not execute query '%s': %s\n", query_str, mysql_error(_conn)); } free(query_str); va_end(arg); return mysql_store_result(_conn); } void MySQLBrowser::reload(){ clear_fields(); MYSQL_RES *res = query("SELECT fullpath FROM files WHERE bin_id = %d AND active = true ORDER BY sortorder, id", current_bin()); MYSQL_ROW row; _nr_of_fields = mysql_num_rows(res); allocate_fields( _nr_of_fields + 1 ); // The last field is set to NULL unsigned int i; for ( i = 0; i < _nr_of_fields; i++ ){ row = mysql_fetch_row(res); assert(row); set_field(i, row[0]); } set_field(i, NULL); mysql_free_result(res); } void MySQLBrowser::clear_fields(){ if ( !_fields ){ return; } unsigned int index = 0; while ( _fields[index] ){ free(_fields[index]); _fields[index] = NULL; index++; } free(_fields); _fields = NULL; } void MySQLBrowser::allocate_fields(unsigned int n){ _fields = (char**)malloc( sizeof(char*) * n ); for ( unsigned int i = 0; i < 0; i++ ){ _fields[i] = NULL; } } void MySQLBrowser::set_field(unsigned int n, const char* str){ if ( !str ){ _fields[n] = NULL; return; } _fields[n] = (char*)malloc( strlen(str)+1); strcpy( _fields[n], str ); } const char* MySQLBrowser::get_field(unsigned int n){ if ( _nr_of_fields == 0 ){ return NULL; } return _fields[n % _nr_of_fields]; } void MySQLBrowser::dump_queue(){ Log::message(Log::Debug, "MySQLBrowser: Dumping queue\n"); unsigned int index = 0; while ( _fields[index] ){ Log::message(Log::Debug, " %s\n", _fields[index++]); } } <|endoftext|>
<commit_before>// fastmap.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include "plugin_utils.h" #include <map> #include <string> BZ_GET_PLUGIN_VERSION class FastMapEventHandler; class FastMapClient : public bz_NonPlayerConnectionHandler { public: FastMapClient( int connectionID = -1, FastMapEventHandler *h = NULL); virtual ~FastMapClient(); virtual void pending ( int connectionID, void *d, unsigned int s ); virtual void disconnect ( int connectionID ); void startTransfer ( unsigned char * d, unsigned int s ); bool updateTransfer ( void ); int conID; unsigned char *data; unsigned int size; unsigned int currerntPos; std::string command; FastMapEventHandler* handler; }; class FastMapEventHandler : public bz_EventHandler { public: FastMapEventHandler(); virtual ~FastMapEventHandler(); virtual void process ( bz_EventData *eventData ); void updateHTTPServer ( void ); void killHTTPServer ( void ); std::string mapName; std::map<int,FastMapClient*> clients; unsigned char* mapData; unsigned int mapDataSize; }; FastMapEventHandler fastMapEventHandler; BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_debugMessage(4,"fastmap plugin loaded"); bz_registerEvent (bz_eWorldFinalized,&fastMapEventHandler); bz_registerEvent (bz_eTickEvent,&fastMapEventHandler); bz_registerEvent (bz_eListServerUpdateEvent,&fastMapEventHandler); bz_registerEvent (bz_eNewNonPlayerConnection,&fastMapEventHandler); return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { fastMapEventHandler.killHTTPServer(); bz_debugMessage(4,"fastmap plugin unloaded"); bz_removeEvent (bz_eWorldFinalized,&fastMapEventHandler); bz_removeEvent (bz_eTickEvent,&fastMapEventHandler); bz_removeEvent (bz_eListServerUpdateEvent,&fastMapEventHandler); bz_removeEvent (bz_eNewNonPlayerConnection,&fastMapEventHandler); return 0; } FastMapEventHandler::FastMapEventHandler() { mapName = format("PrivateMap%d",(unsigned int)this); mapData = NULL; mapDataSize = 0; } FastMapEventHandler::~FastMapEventHandler() { killHTTPServer(); } void FastMapEventHandler::process ( bz_EventData *eventData ) { if ( eventData->eventType == bz_eListServerUpdateEvent ) { bz_ListServerUpdateEvent_V1 *updateData = (bz_ListServerUpdateEvent_V1*)eventData; mapName = format("%s%d",updateData->address,(unsigned int)this); } else if ( eventData->eventType == bz_eWorldFinalized ) { killHTTPServer(); if (!bz_getPublic() || bz_getClientWorldDowloadURL().size()) return; mapDataSize = bz_getWorldCacheSize(); mapData = (unsigned char*)malloc(mapDataSize); bz_getWorldCacheData(mapData); if (mapDataSize) bz_setClientWorldDowloadURL(format("HTTP:/%s/%s",bz_getPublicAddr().c_str(),mapName.c_str()).c_str()); } else if ( eventData->eventType == bz_eTickEvent) { if ( mapDataSize ) updateHTTPServer(); } else if ( eventData->eventType == bz_eNewNonPlayerConnection ) { if ( mapDataSize ) { bz_NewNonPlayerConnectionEventData_V1 *connData = (bz_NewNonPlayerConnectionEventData_V1*)eventData; if (connData->size >= 3 && strncmp((const char*)connData->data,"GET",3)) { FastMapClient * handler = new FastMapClient(connData->connectionID,this); if(bz_registerNonPlayerConnectionHandler ( connData->connectionID, handler ) ) { clients[connData->connectionID] = handler; handler->pending (connData->connectionID,connData->data, connData->size); } else delete(handler); } } } else if ( eventData->eventType == bz_eIdleNewNonPlayerConnection ) { bz_NewNonPlayerConnectionEventData_V1 *connData = (bz_NewNonPlayerConnectionEventData_V1*)eventData; std::map<int,FastMapClient*>::iterator itr = clients.find(connData->connectionID); if( itr != clients.end() ) { bz_removeNonPlayerConnectionHandler ( itr->second->conID, itr->second ); delete(itr->second); clients.erase(itr); } bz_disconectNonPlayerConnection ( connData->connectionID ); } } void FastMapEventHandler::updateHTTPServer ( void ) { std::vector<int> killList; std::map<int,FastMapClient*>::iterator itr = clients.begin(); while (itr != clients.end()) { if(itr->second->conID == -1 || !itr->second->updateTransfer() ) killList.push_back(itr->first); itr++; } for ( unsigned int i = 0; i < (unsigned int)killList.size(); i++) clients.erase(clients.find(killList[i])); if (clients.size()) bz_setMaxWaitTime(0.001f); else bz_setMaxWaitTime(2.0f); } void FastMapEventHandler::killHTTPServer ( void ) { if ( mapData ) free(mapData); mapData = NULL; mapDataSize = 0; } FastMapClient::FastMapClient( int connectionID, FastMapEventHandler *h ) { conID = connectionID; data = NULL; size = 0; currerntPos = 0; handler = h; } FastMapClient::~FastMapClient() { if (data) free(data); } void FastMapClient::pending ( int connectionID, void *s, unsigned int d ) { if ( connectionID != conID ) return; char *c = (char*)malloc(d+1); memcpy(c,s,d); c[d] = 0; command += c; free (c); // parse the command std::vector<std::string> commandList = tokenize(command,std::string("\r\n"),0,false); if ( commandList.size() == 1 && commandList[0].size() == command.size() ) // there were no delims, we are done. return; for (unsigned int i = 0; i < (unsigned int)commandList.size();i++) { command.erase(command.begin(),command.begin()+commandList[i].size()); std::string thisLine = commandList[i]; if (strncmp(thisLine.c_str(),"GET",3) == 0 && !data) // it's a get and we arn't in a transfer { std::vector<std::string> params = tokenize(thisLine,std::string(" "),0,false); if ( params.size() <= 3 ) { std::string urlPath = params[1]; if (urlPath.size()>2 && handler->mapName == urlPath.c_str()+1 ) { startTransfer(handler->mapData,handler->mapDataSize); } } } } } void FastMapClient::disconnect ( int connectionID ) { if (connectionID != conID) return; bz_removeNonPlayerConnectionHandler ( conID, this ); bz_disconectNonPlayerConnection ( conID ); conID = -1; } void FastMapClient::startTransfer ( unsigned char * d, unsigned int s ) { if (data) free (data); data = NULL; size = 0; currerntPos = 0; if (!s) return; data = (unsigned char*)malloc(s); memcpy(data,d,s); size = s; if (!updateTransfer()) disconnect(conID); } bool FastMapClient::updateTransfer ( void ) { int chunkToSend = 1000; if ( currerntPos <= size ) return false; // wait till the current data is sent if (bz_getNonPlayerConnectionOutboundPacketCount(conID) != 0) return true; if ( currerntPos + chunkToSend > size) chunkToSend = size-currerntPos; bool worked = bz_sendNonPlayerData ( conID, data+currerntPos, chunkToSend ); currerntPos += chunkToSend; return worked; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>send out the HTTP responce headers when sending back a map.<commit_after>// fastmap.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include "plugin_utils.h" #include <map> #include <string> BZ_GET_PLUGIN_VERSION class FastMapEventHandler; class FastMapClient : public bz_NonPlayerConnectionHandler { public: FastMapClient( int connectionID = -1, FastMapEventHandler *h = NULL); virtual ~FastMapClient(); virtual void pending ( int connectionID, void *d, unsigned int s ); virtual void disconnect ( int connectionID ); void startTransfer ( unsigned char * d, unsigned int s ); bool updateTransfer ( void ); int conID; unsigned char *data; unsigned int size; unsigned int currerntPos; std::string command; FastMapEventHandler* handler; }; class FastMapEventHandler : public bz_EventHandler { public: FastMapEventHandler(); virtual ~FastMapEventHandler(); virtual void process ( bz_EventData *eventData ); void updateHTTPServer ( void ); void killHTTPServer ( void ); std::string mapName; std::map<int,FastMapClient*> clients; unsigned char* mapData; unsigned int mapDataSize; }; FastMapEventHandler fastMapEventHandler; BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_debugMessage(4,"fastmap plugin loaded"); bz_registerEvent (bz_eWorldFinalized,&fastMapEventHandler); bz_registerEvent (bz_eTickEvent,&fastMapEventHandler); bz_registerEvent (bz_eListServerUpdateEvent,&fastMapEventHandler); bz_registerEvent (bz_eNewNonPlayerConnection,&fastMapEventHandler); return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { fastMapEventHandler.killHTTPServer(); bz_debugMessage(4,"fastmap plugin unloaded"); bz_removeEvent (bz_eWorldFinalized,&fastMapEventHandler); bz_removeEvent (bz_eTickEvent,&fastMapEventHandler); bz_removeEvent (bz_eListServerUpdateEvent,&fastMapEventHandler); bz_removeEvent (bz_eNewNonPlayerConnection,&fastMapEventHandler); return 0; } FastMapEventHandler::FastMapEventHandler() { mapName = format("PrivateMap%d",(unsigned int)this); mapData = NULL; mapDataSize = 0; } FastMapEventHandler::~FastMapEventHandler() { killHTTPServer(); } void FastMapEventHandler::process ( bz_EventData *eventData ) { if ( eventData->eventType == bz_eListServerUpdateEvent ) { bz_ListServerUpdateEvent_V1 *updateData = (bz_ListServerUpdateEvent_V1*)eventData; mapName = format("%s%d",updateData->address,(unsigned int)this); } else if ( eventData->eventType == bz_eWorldFinalized ) { killHTTPServer(); if (!bz_getPublic() || bz_getClientWorldDowloadURL().size()) return; mapDataSize = bz_getWorldCacheSize(); mapData = (unsigned char*)malloc(mapDataSize); bz_getWorldCacheData(mapData); if (mapDataSize) bz_setClientWorldDowloadURL(format("HTTP:/%s/%s",bz_getPublicAddr().c_str(),mapName.c_str()).c_str()); } else if ( eventData->eventType == bz_eTickEvent) { if ( mapDataSize ) updateHTTPServer(); } else if ( eventData->eventType == bz_eNewNonPlayerConnection ) { if ( mapDataSize ) { bz_NewNonPlayerConnectionEventData_V1 *connData = (bz_NewNonPlayerConnectionEventData_V1*)eventData; if (connData->size >= 3 && strncmp((const char*)connData->data,"GET",3)) { FastMapClient * handler = new FastMapClient(connData->connectionID,this); if(bz_registerNonPlayerConnectionHandler ( connData->connectionID, handler ) ) { clients[connData->connectionID] = handler; handler->pending (connData->connectionID,connData->data, connData->size); } else delete(handler); } } } else if ( eventData->eventType == bz_eIdleNewNonPlayerConnection ) { bz_NewNonPlayerConnectionEventData_V1 *connData = (bz_NewNonPlayerConnectionEventData_V1*)eventData; std::map<int,FastMapClient*>::iterator itr = clients.find(connData->connectionID); if( itr != clients.end() ) { bz_removeNonPlayerConnectionHandler ( itr->second->conID, itr->second ); delete(itr->second); clients.erase(itr); } bz_disconectNonPlayerConnection ( connData->connectionID ); } } void FastMapEventHandler::updateHTTPServer ( void ) { std::vector<int> killList; std::map<int,FastMapClient*>::iterator itr = clients.begin(); while (itr != clients.end()) { if(itr->second->conID == -1 || !itr->second->updateTransfer() ) killList.push_back(itr->first); itr++; } for ( unsigned int i = 0; i < (unsigned int)killList.size(); i++) clients.erase(clients.find(killList[i])); if (clients.size()) bz_setMaxWaitTime(0.001f); else bz_setMaxWaitTime(2.0f); } void FastMapEventHandler::killHTTPServer ( void ) { if ( mapData ) free(mapData); mapData = NULL; mapDataSize = 0; } FastMapClient::FastMapClient( int connectionID, FastMapEventHandler *h ) { conID = connectionID; data = NULL; size = 0; currerntPos = 0; handler = h; } FastMapClient::~FastMapClient() { if (data) free(data); } void FastMapClient::pending ( int connectionID, void *s, unsigned int d ) { if ( connectionID != conID ) return; char *c = (char*)malloc(d+1); memcpy(c,s,d); c[d] = 0; command += c; free (c); // parse the command std::vector<std::string> commandList = tokenize(command,std::string("\r\n"),0,false); if ( commandList.size() == 1 && commandList[0].size() == command.size() ) // there were no delims, we are done. return; for (unsigned int i = 0; i < (unsigned int)commandList.size();i++) { command.erase(command.begin(),command.begin()+commandList[i].size()); std::string thisLine = commandList[i]; if (strncmp(thisLine.c_str(),"GET",3) == 0 && !data) // it's a get and we arn't in a transfer { std::vector<std::string> params = tokenize(thisLine,std::string(" "),0,false); if ( params.size() <= 3 ) { std::string urlPath = params[1]; if (urlPath.size()>2 && handler->mapName == urlPath.c_str()+1 ) { startTransfer(handler->mapData,handler->mapDataSize); } } } } } void FastMapClient::disconnect ( int connectionID ) { if (connectionID != conID) return; bz_removeNonPlayerConnectionHandler ( conID, this ); bz_disconectNonPlayerConnection ( conID ); conID = -1; } void FastMapClient::startTransfer ( unsigned char * d, unsigned int s ) { if (data) free (data); data = NULL; size = 0; currerntPos = 0; if (!s) return; data = (unsigned char*)malloc(s); memcpy(data,d,s); size = s; std::string httpHeaders; httpHeaders += "HTTP/1.1 200 OK\n"; httpHeaders += format("Content-Length: %d\n", size); httpHeaders += "Connection: close\n"; httpHeaders += "Content-Type: application/binary\n"; httpHeaders += "\n"; if (!bz_sendNonPlayerData ( conID, httpHeaders.c_str(), httpHeaders.size() ) || !updateTransfer()) disconnect(conID); } bool FastMapClient::updateTransfer ( void ) { int chunkToSend = 1000; if ( currerntPos <= size ) return false; // wait till the current data is sent if (bz_getNonPlayerConnectionOutboundPacketCount(conID) != 0) return true; if ( currerntPos + chunkToSend > size) chunkToSend = size-currerntPos; bool worked = bz_sendNonPlayerData ( conID, data+currerntPos, chunkToSend ); currerntPos += chunkToSend; return worked; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/*! * \file calibration_from_carl.cpp * \brief External camera calibration from an AR tag with known position on the CARL robot * * \author David Kent, WPI - davidkent@wpi.edu * \date November 14, 2014 */ #include <rail_ceiling/calibration_from_carl.h> using namespace std; CalibrationFromCarl::CalibrationFromCarl() { // private node handle ros::NodeHandle private_nh("~"); // get number of marker topics (i.e. number of overhead cameras), and the id of the calibration marker int numCameras; private_nh.param("num_cameras", numCameras, 5); private_nh.param("calibration_marker_id", markerID, 200); calibrationEnabled.resize(numCameras); transformSamples.resize(numCameras); finalTransforms.resize(numCameras); calibrated.resize(numCameras); markerSubscribers.resize(numCameras); for (unsigned int i = 0; i < numCameras; i ++) { transformSamples[i].clear(); calibrationEnabled[i] = false; calibrated[i] = false; stringstream topicStream; topicStream << "ceiling_cam_tracker_" << i << "/ar_pose_marker"; markerSubscribers[i] = n.subscribe(topicStream.str(), 1, &CalibrationFromCarl::markerCallback, this); } startCalibrationSubscriber = n.subscribe("start_calibration", 1, &CalibrationFromCarl::startCalibrationCallback, this); calibrationComplete = false; } void CalibrationFromCarl::startCalibrationCallback(const std_msgs::Int16::ConstPtr& msg) { //enable calibration for the specified camera and clear out any previous samples calibrationEnabled[msg->data] = true; calibrated[msg->data] = false; transformSamples[msg->data].clear(); calibrationComplete = false; } void CalibrationFromCarl::markerCallback(const ar_track_alvar_msgs::AlvarMarkers::ConstPtr& msg) { for (unsigned int i = 0; i < msg->markers.size(); i ++) { //check if the marker detected is the calibration marker if (msg->markers[i].id == markerID) { //get the marker index, this assumes the camera coordinate frames contain the string "cam_n", where n is an //integer denoting the camera number size_t pos = msg->markers[i].header.frame_id.find("cam_"); int cameraid = atoi((msg->markers[i].header.frame_id.substr(pos + 4)).c_str()); if (calibrationEnabled[cameraid]) { geometry_msgs::PoseStamped sample = msg->markers[i].pose; sample.header.frame_id=msg->markers[i].header.frame_id; // transform pose to map frame tf::Transform tfSample; tf::StampedTransform finalTransform; tfSample.setOrigin(tf::Vector3(sample.pose.position.x, sample.pose.position.y, sample.pose.position.z)); tfSample.setRotation(tf::Quaternion(sample.pose.orientation.x, sample.pose.orientation.y, sample.pose.orientation.z, sample.pose.orientation.w).normalize()); // invert it tf::Transform tfSampleInverse = tfSample.inverse(); ros::Time time = ros::Time::now(); br.sendTransform(tf::StampedTransform(tfSampleInverse, time, "calibration_link", sample.header.frame_id.c_str())); tfListener.waitForTransform("map", "calibration_link", time, ros::Duration(1.0)); tfListener.lookupTransform("map", sample.header.frame_id, time, finalTransform); transformSamples[cameraid].push_back(finalTransform); if (transformSamples[cameraid].size() >= REQUIRED_SAMPLES) { ROS_INFO("Finished calibration for camera %d", cameraid); calibrationEnabled[cameraid] = false; } } } } } void CalibrationFromCarl::publishTransforms() { // go through each marker bool finished = true; for (unsigned int i = 0; i < transformSamples.size(); i ++) { // publish the average pose from the camera if it's received enough samples if (transformSamples[i].size() >= REQUIRED_SAMPLES) { if (!calibrated[i]) { //calculate average pose //TODO: find a better way to approximate average rotation in 3D tf::StampedTransform avgTransform; avgTransform.frame_id_ = transformSamples[i][0].frame_id_; avgTransform.child_frame_id_ = transformSamples[i][0].child_frame_id_; avgTransform.stamp_ = ros::Time::now(); float x = 0.0, y = 0.0, z = 0.0; //float qx = 0.0, qy = 0.0, qz = 0.0, qw = 0.0; tf::Quaternion avgQuat; for (unsigned int j = 0; j < transformSamples[i].size(); j++) { x += transformSamples[i][j].getOrigin().x(); y += transformSamples[i][j].getOrigin().y(); z += transformSamples[i][j].getOrigin().z(); if (j == 0) { avgQuat = transformSamples[i][j].getRotation(); } else { avgQuat.slerp(transformSamples[i][j].getRotation(), 1 - (1/(j + 1))); } /* qx += transformSamples[i][j].getRotation().getX(); qy += transformSamples[i][j].getRotation().getY(); qz += transformSamples[i][j].getRotation().getZ(); qw += transformSamples[i][j].getRotation().getW(); */ } int numSamples = transformSamples[i].size(); avgTransform.setOrigin(tf::Vector3(x/numSamples, y/numSamples, z/numSamples)); //avgTransform.setRotation(tf::Quaternion(qx/numSamples, qy/numSamples, qz/numSamples, qw/numSamples).normalize()); avgTransform.setRotation(avgQuat); finalTransforms[i] = avgTransform; calibrated[i] = true; } br.sendTransform(finalTransforms[i]); } else { finished = false; } } if (finished && !calibrationComplete) { //write calibration file ROS_INFO("Writing calibration..."); stringstream ss; //TODO: update ss << getenv("HOME") << "/testCalibrationFile.urdf"; string file_name = ss.str(); // open the file for writing ofstream urdf; urdf.open(file_name.c_str()); if (!urdf.is_open()) ROS_ERROR("Failed to open '~/%s' for writing.", file_name.c_str()); else { urdf << "<?xml version=\"1.0\"?>\n"; urdf << "<robot xmlns:xacro=\"http://www.ros.org/wiki/xacro\" name=\"ceiling\">\n\n"; urdf << " <!-- Auto-Generated from rail_ceiling/calibration Node -->\n\n"; urdf << " <xacro:include filename=\"$(find rail_ceiling)/urdf/camera.urdf.xacro\" />\n\n"; urdf << " <xacro:property name=\"PARENT\" value=\"" << "map" << "\" />\n\n"; urdf << " <!-- fixed frame -->\n"; urdf << " <link name=\"${PARENT}\" />\n\n"; urdf << " <!-- " << finalTransforms.size() << " Camera(s) -->\n"; for (int i = 0; i < finalTransforms.size(); i++) { // grab the TF info tf::StampedTransform &tf = finalTransforms.at(i); tf::Vector3 &pos = tf.getOrigin(); double roll, pitch, yaw; tf.getBasis().getRPY(roll, pitch, yaw); urdf << " <xacro:ceiling_cam parent=\"${PARENT}\" link=\"" << tf.child_frame_id_ << i << "\">\n"; urdf << " <origin xyz=\"" << pos.getX() << " " << pos.getY() << " " << pos.getZ() << "\" rpy=\"" << roll << " " << pitch << " " << yaw << "\" />\n"; urdf << " </xacro:ceiling_cam>\n"; } urdf << "</robot>\n\n"; urdf.close(); ROS_INFO("Calibration written to '%s'.", file_name.c_str()); } calibrationComplete = true; } } int main(int argc, char **argv) { ros::init(argc, argv, "calibration_from_carl"); CalibrationFromCarl c; ros::Rate loop_rate(30); while (ros::ok()) { c.publishTransforms(); ros::spinOnce(); loop_rate.sleep(); } } <commit_msg>corrected the ratio for the slerp averaging; it was originally backwards<commit_after>/*! * \file calibration_from_carl.cpp * \brief External camera calibration from an AR tag with known position on the CARL robot * * \author David Kent, WPI - davidkent@wpi.edu * \date November 14, 2014 */ #include <rail_ceiling/calibration_from_carl.h> using namespace std; CalibrationFromCarl::CalibrationFromCarl() { // private node handle ros::NodeHandle private_nh("~"); // get number of marker topics (i.e. number of overhead cameras), and the id of the calibration marker int numCameras; private_nh.param("num_cameras", numCameras, 5); private_nh.param("calibration_marker_id", markerID, 200); calibrationEnabled.resize(numCameras); transformSamples.resize(numCameras); finalTransforms.resize(numCameras); calibrated.resize(numCameras); markerSubscribers.resize(numCameras); for (unsigned int i = 0; i < numCameras; i ++) { transformSamples[i].clear(); calibrationEnabled[i] = false; calibrated[i] = false; stringstream topicStream; topicStream << "ceiling_cam_tracker_" << i << "/ar_pose_marker"; markerSubscribers[i] = n.subscribe(topicStream.str(), 1, &CalibrationFromCarl::markerCallback, this); } startCalibrationSubscriber = n.subscribe("start_calibration", 1, &CalibrationFromCarl::startCalibrationCallback, this); calibrationComplete = false; } void CalibrationFromCarl::startCalibrationCallback(const std_msgs::Int16::ConstPtr& msg) { //enable calibration for the specified camera and clear out any previous samples calibrationEnabled[msg->data] = true; calibrated[msg->data] = false; transformSamples[msg->data].clear(); calibrationComplete = false; } void CalibrationFromCarl::markerCallback(const ar_track_alvar_msgs::AlvarMarkers::ConstPtr& msg) { for (unsigned int i = 0; i < msg->markers.size(); i ++) { //check if the marker detected is the calibration marker if (msg->markers[i].id == markerID) { //get the marker index, this assumes the camera coordinate frames contain the string "cam_n", where n is an //integer denoting the camera number size_t pos = msg->markers[i].header.frame_id.find("cam_"); int cameraid = atoi((msg->markers[i].header.frame_id.substr(pos + 4)).c_str()); if (calibrationEnabled[cameraid]) { geometry_msgs::PoseStamped sample = msg->markers[i].pose; sample.header.frame_id=msg->markers[i].header.frame_id; // transform pose to map frame tf::Transform tfSample; tf::StampedTransform finalTransform; tfSample.setOrigin(tf::Vector3(sample.pose.position.x, sample.pose.position.y, sample.pose.position.z)); tfSample.setRotation(tf::Quaternion(sample.pose.orientation.x, sample.pose.orientation.y, sample.pose.orientation.z, sample.pose.orientation.w).normalize()); // invert it tf::Transform tfSampleInverse = tfSample.inverse(); ros::Time time = ros::Time::now(); br.sendTransform(tf::StampedTransform(tfSampleInverse, time, "calibration_link", sample.header.frame_id.c_str())); tfListener.waitForTransform("map", "calibration_link", time, ros::Duration(1.0)); tfListener.lookupTransform("map", sample.header.frame_id, time, finalTransform); transformSamples[cameraid].push_back(finalTransform); if (transformSamples[cameraid].size() >= REQUIRED_SAMPLES) { ROS_INFO("Finished calibration for camera %d", cameraid); calibrationEnabled[cameraid] = false; } } } } } void CalibrationFromCarl::publishTransforms() { // go through each marker bool finished = true; for (unsigned int i = 0; i < transformSamples.size(); i ++) { // publish the average pose from the camera if it's received enough samples if (transformSamples[i].size() >= REQUIRED_SAMPLES) { if (!calibrated[i]) { //calculate average pose //TODO: find a better way to approximate average rotation in 3D tf::StampedTransform avgTransform; avgTransform.frame_id_ = transformSamples[i][0].frame_id_; avgTransform.child_frame_id_ = transformSamples[i][0].child_frame_id_; avgTransform.stamp_ = ros::Time::now(); float x = 0.0, y = 0.0, z = 0.0; //float qx = 0.0, qy = 0.0, qz = 0.0, qw = 0.0; tf::Quaternion avgQuat; for (unsigned int j = 0; j < transformSamples[i].size(); j++) { x += transformSamples[i][j].getOrigin().x(); y += transformSamples[i][j].getOrigin().y(); z += transformSamples[i][j].getOrigin().z(); if (j == 0) { avgQuat = transformSamples[i][j].getRotation(); } else { avgQuat.slerp(transformSamples[i][j].getRotation(), 1.0/((float)(j + 1))); } /* qx += transformSamples[i][j].getRotation().getX(); qy += transformSamples[i][j].getRotation().getY(); qz += transformSamples[i][j].getRotation().getZ(); qw += transformSamples[i][j].getRotation().getW(); */ } int numSamples = transformSamples[i].size(); avgTransform.setOrigin(tf::Vector3(x/numSamples, y/numSamples, z/numSamples)); //avgTransform.setRotation(tf::Quaternion(qx/numSamples, qy/numSamples, qz/numSamples, qw/numSamples).normalize()); avgTransform.setRotation(avgQuat); finalTransforms[i] = avgTransform; calibrated[i] = true; } br.sendTransform(finalTransforms[i]); } else { finished = false; } } if (finished && !calibrationComplete) { //write calibration file ROS_INFO("Writing calibration..."); stringstream ss; //TODO: update ss << getenv("HOME") << "/testCalibrationFile.urdf"; string file_name = ss.str(); // open the file for writing ofstream urdf; urdf.open(file_name.c_str()); if (!urdf.is_open()) ROS_ERROR("Failed to open '~/%s' for writing.", file_name.c_str()); else { urdf << "<?xml version=\"1.0\"?>\n"; urdf << "<robot xmlns:xacro=\"http://www.ros.org/wiki/xacro\" name=\"ceiling\">\n\n"; urdf << " <!-- Auto-Generated from rail_ceiling/calibration Node -->\n\n"; urdf << " <xacro:include filename=\"$(find rail_ceiling)/urdf/camera.urdf.xacro\" />\n\n"; urdf << " <xacro:property name=\"PARENT\" value=\"" << "map" << "\" />\n\n"; urdf << " <!-- fixed frame -->\n"; urdf << " <link name=\"${PARENT}\" />\n\n"; urdf << " <!-- " << finalTransforms.size() << " Camera(s) -->\n"; for (int i = 0; i < finalTransforms.size(); i++) { // grab the TF info tf::StampedTransform &tf = finalTransforms.at(i); tf::Vector3 &pos = tf.getOrigin(); double roll, pitch, yaw; tf.getBasis().getRPY(roll, pitch, yaw); urdf << " <xacro:ceiling_cam parent=\"${PARENT}\" link=\"" << tf.child_frame_id_ << i << "\">\n"; urdf << " <origin xyz=\"" << pos.getX() << " " << pos.getY() << " " << pos.getZ() << "\" rpy=\"" << roll << " " << pitch << " " << yaw << "\" />\n"; urdf << " </xacro:ceiling_cam>\n"; } urdf << "</robot>\n\n"; urdf.close(); ROS_INFO("Calibration written to '%s'.", file_name.c_str()); } calibrationComplete = true; } } int main(int argc, char **argv) { ros::init(argc, argv, "calibration_from_carl"); CalibrationFromCarl c; ros::Rate loop_rate(30); while (ros::ok()) { c.publishTransforms(); ros::spinOnce(); loop_rate.sleep(); } } <|endoftext|>
<commit_before>/** * @file PathPlanner.cpp * * @author <a href="mailto:akcayyig@hu-berlin.de">Yigit Can Akcay</a> * Implementation of class PathPlanner */ #include "PathPlanner.h" PathPlanner::PathPlanner() : step_buffer({}), foot_to_use(Foot::RIGHT), last_stepcontrol_stepID(0), kick_planned(false) { DEBUG_REQUEST_REGISTER("PathPlanner:walk_forward", "Walks forward with y=0 and x=40", false); } void PathPlanner::execute() { getPathModel().kick_executed = false; DEBUG_REQUEST("PathPlanner:walk_forward", Pose2D pose = Pose2D(0.0, 40.0, 0.0); WalkRequest::Coordinate coordinate = WalkRequest::Hip; if (step_buffer.empty()) { add_step(pose, StepType::WALKSTEP, coordinate); } ); STOPWATCH_START("PathPlanner"); // Always executed first manage_step_buffer(); if (kick_planned && step_buffer.empty()) { getPathModel().kick_executed = true; } switch (getPathModel().path_routine) { case PathModel::PathRoutine::NONE: // Reset routine_executed, so that XABSL // can jump out of option (PathRoutine) that is // being executed //kick_planned = false; if (kick_planned) { kick_planned = false; } if (step_buffer.empty()) { return; } break; case PathModel::PathRoutine::GO_TO_BALL_FAST: walk_to_ball(Foot::NONE , true); break; case PathModel::PathRoutine::GO_TO_BALL_SLOW: walk_to_ball(Foot::NONE); break; case PathModel::PathRoutine::MOVE_AROUND_BALL: move_around_ball(getPathModel().direction, getPathModel().radius); break; case PathModel::PathRoutine::APPROACH_BALL_LEFT: approach_ball(Foot::LEFT); break; case PathModel::PathRoutine::APPROACH_BALL_RIGHT: approach_ball(Foot::RIGHT); break; case PathModel::PathRoutine::SHORT_KICK_LEFT: short_kick(Foot::LEFT); break; case PathModel::PathRoutine::SHORT_KICK_RIGHT: short_kick(Foot::RIGHT); break; case PathModel::PathRoutine::LONG_KICK_LEFT: long_kick(Foot::LEFT); break; case PathModel::PathRoutine::LONG_KICK_RIGHT: long_kick(Foot::RIGHT); break; case PathModel::PathRoutine::SIDEKICK_LEFT: sidekick(Foot::LEFT); break; case PathModel::PathRoutine::SIDEKICK_RIGHT: sidekick(Foot::RIGHT); break; } // Always executed last execute_step_buffer(); STOPWATCH_STOP("PathPlanner"); } // Primitive Maneuvers void PathPlanner::walk_to_ball(const Foot foot, const bool go_fast) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ballPos = getBallModel().positionPreview; coordinate = WalkRequest::Hip; break; } double ballRotation = ballPos.angle(); Pose2D pose = { ballRotation, 0.7*(ballPos.x - getPathModel().distance), ballPos.y }; if (step_buffer.empty()) { if (go_fast) { add_step(pose, StepType::WALKSTEP, coordinate, 1.0); } else { add_step(pose, StepType::WALKSTEP, coordinate, 0.3); } } else { update_step(pose); } } void PathPlanner::move_around_ball(const double direction, const double radius) { Vector2d ballPos = getBallModel().positionPreview; double ballRotation = ballPos.angle(); double ballDistance = ballPos.abs(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double min1; double min2; double max1; double max2; if (direction <= 0) { min1 = 0.0; min2 = 0.0; max1 = 45.0; max2 = 100.0; } else { min1 = -45; min2 = -100; max1 = 0; max2 = 0; } double stepX = (ballDistance - radius) * std::cos(ballRotation); double stepY = Math::clamp(radius * std::tan(Math::clamp(Math::toDegrees(-direction), min1, max1)), min2, max2) * std::cos(ballRotation); Pose2D pose = { ballRotation, stepX, stepY }; if (step_buffer.empty()) { add_step(pose, StepType::WALKSTEP, coordinate, 0.7); } else { update_step(pose); } } void PathPlanner::approach_ball(const Foot foot) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double stepX = 0.0; double stepY = 0.0; double ballRadius = getFieldInfo().ballRadius; double stepRotation = ballPos.abs() > 250 ? ballPos.angle() : 0; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; stepX = ballPos.x - std::abs(ballPos.y - getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y - getPathModel().yOffset; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; stepX = ballPos.x - std::abs(ballPos.y + getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y + getPathModel().yOffset; break; case Foot::NONE: ASSERT(false); } Pose2D pose = { stepRotation, 0.7 * stepX, 0.7 * stepY }; if (step_buffer.empty()) { add_step(pose, StepType::WALKSTEP, coordinate, 0.7); } else { update_step(pose); } } void PathPlanner::short_kick(const Foot foot) { if (!kick_planned) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, ballPos.x + 500 , 0.0 }; add_step(pose, StepType::KICKSTEP, coordinate, 1.0, foot, 0.7); add_step(pose, StepType::ZEROSTEP, coordinate, 1.0, foot); pose = { 0.0, 0.0, 0.0 }; add_step(pose, StepType::WALKSTEP, coordinate, 1.0, foot); kick_planned = true; } } } void PathPlanner::long_kick(const Foot foot) { if (!kick_planned) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, ballPos.x + 500, 0.0 }; add_step(pose, StepType::KICKSTEP, coordinate, 1.0, foot, 0.7); add_step(pose, StepType::ZEROSTEP, coordinate, 1.0, foot); pose = { 0.0, 0.0, 0.0 }; add_step(pose, StepType::WALKSTEP, coordinate, 1.0, foot); kick_planned = true; } } } void PathPlanner::sidekick(const Foot foot) { if (!kick_planned) { double speedDirection = 0.0; double stepY = 0.0; Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; speedDirection = 90; stepY = 100; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; speedDirection = -90; stepY = -100; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, stepY }; add_step(pose, StepType::KICKSTEP, coordinate, 1.0, foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT, 1.0, speedDirection); add_step(pose, StepType::ZEROSTEP, coordinate, 1.0, foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT); pose = { 0.0, 0.0, 0.0 }; add_step(pose, StepType::WALKSTEP, coordinate, 1.0, foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT); kick_planned = true; } } } // Stepcontrol void PathPlanner::add_step(Pose2D &pose, const StepType &type, const WalkRequest::Coordinate &coordinate, const double character, const Foot foot, const double scale, const double speedDirection) { // taken out of the stepplanner // limiting the steps if walksteps // 0.75 because 0.5 * character(usually 0.5) + 0.5 (taken from stepplanner) /* if (type == StepType::WALKSTEP) { double maxStepTurn = Math::fromDegrees(30) * 0.75; double maxStep = 40.0f; pose.rotation = Math::clamp(pose.rotation, -maxStepTurn, maxStepTurn); pose.translation.x = Math::clamp(pose.translation.x, -maxStep, maxStep) * cos(pose.rotation / maxStepTurn * Math::pi / 2); pose.translation.y = Math::clamp(pose.translation.y, -maxStep, maxStep) * cos(pose.rotation / maxStepTurn * Math::pi / 2); } */ step_buffer.push_back(Step_Buffer_Element({ pose, speedDirection, type, type == StepType::KICKSTEP ? 300 : 250, character, scale, foot, coordinate})); } void PathPlanner::update_step(Pose2D &pose) { ASSERT(step_buffer.size() > 0); // taken out of the stepplanner // limiting the steps if walksteps // 0.75 because 0.5 * character(usually 0.5) + 0.5 (taken from stepplanner) /* if (step_buffer.front().type == StepType::WALKSTEP) { double maxStepTurn = Math::fromDegrees(30) * 0.75; double maxStep = 40.0f; pose.rotation = Math::clamp(pose.rotation, -maxStepTurn, maxStepTurn); pose.translation.x = Math::clamp(pose.translation.x, -maxStep, maxStep) * cos(pose.rotation / maxStepTurn * Math::pi / 2); pose.translation.y = Math::clamp(pose.translation.y, -maxStep, maxStep) * cos(pose.rotation / maxStepTurn * Math::pi / 2); }*/ Step_Buffer_Element updatedElement = step_buffer.front(); updatedElement.pose = pose; step_buffer.front() = updatedElement; } void PathPlanner::manage_step_buffer() { if (step_buffer.empty()) { return; } // stepID higher than the last one means, stepControl request with the // last_stepcontrol_stepID has been accepted if (last_stepcontrol_stepID < getMotionStatus().stepControl.stepID) { step_buffer.erase(step_buffer.begin()); last_stepcontrol_stepID = getMotionStatus().stepControl.stepID; } // Correct last_stepcontrol_stepID if neccessary if (getMotionStatus().stepControl.stepID < last_stepcontrol_stepID) { last_stepcontrol_stepID = getMotionStatus().stepControl.stepID; } } void PathPlanner::execute_step_buffer() { if (step_buffer.empty()) { return; } STOPWATCH_START("PathPlanner:execute_steplist"); getMotionRequest().id = motion::walk; getMotionRequest().standardStand = false; getMotionRequest().walkRequest.coordinate = step_buffer.front().coordinate; getMotionRequest().walkRequest.character = step_buffer.front().character; getMotionRequest().walkRequest.stepControl.scale = step_buffer.front().scale; getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID; getMotionRequest().walkRequest.stepControl.type = step_buffer.front().type; getMotionRequest().walkRequest.stepControl.time = step_buffer.front().time; getMotionRequest().walkRequest.stepControl.speedDirection = step_buffer.front().speedDirection; getMotionRequest().walkRequest.stepControl.target = step_buffer.front().pose; // normal walking WALKSTEPs use Foot::NONE, for KICKSTEPs the foot to use has to be specified if (step_buffer.front().foot == Foot::NONE) { switch (getMotionStatus().stepControl.moveableFoot) { case MotionStatus::StepControlStatus::LEFT: foot_to_use = Foot::LEFT; break; case MotionStatus::StepControlStatus::RIGHT: foot_to_use = Foot::RIGHT; break; // TODO: choose foot more intelligently when both feet are usable case MotionStatus::StepControlStatus::BOTH: if (step_buffer.front().pose.translation.y > 0.0f || step_buffer.front().pose.rotation > 0.0f) { foot_to_use = Foot::LEFT; } else { foot_to_use = Foot::RIGHT; } break; case MotionStatus::StepControlStatus::NONE: foot_to_use = Foot::RIGHT; break; } } else { foot_to_use = step_buffer.front().foot; } // false means right foot getMotionRequest().walkRequest.stepControl.moveLeftFoot = foot_to_use == Foot::RIGHT ? false : true; STOPWATCH_STOP("PathPlanner:execute_steplist"); }<commit_msg>clean up (default function parameters are bad and some comments made more clear/corrected). got rid of two useless functions.<commit_after>/** * @file PathPlanner.cpp * * @author <a href="mailto:akcayyig@hu-berlin.de">Yigit Can Akcay</a> * Implementation of class PathPlanner */ #include "PathPlanner.h" PathPlanner::PathPlanner() : step_buffer({}), foot_to_use(Foot::RIGHT), last_stepcontrol_stepID(0), kick_planned(false) {} void PathPlanner::execute() { getPathModel().kick_executed = false; STOPWATCH_START("PathPlanner"); // Always executed first manage_step_buffer(); // The kick has been executed // Tells XABSL to jump into next state if (kick_planned && step_buffer.empty()) { getPathModel().kick_executed = true; } switch (getPathModel().path_routine) { case PathModel::PathRoutine::NONE: // There is no kick planned, since the kick has been executed // and XABSL is in a different state now if (kick_planned) { kick_planned = false; } if (step_buffer.empty()) { return; } break; case PathModel::PathRoutine::GO_TO_BALL_FAST: walk_to_ball(Foot::NONE , true); break; case PathModel::PathRoutine::GO_TO_BALL_SLOW: walk_to_ball(Foot::NONE); break; case PathModel::PathRoutine::MOVE_AROUND_BALL: move_around_ball(getPathModel().direction, getPathModel().radius); break; case PathModel::PathRoutine::APPROACH_BALL_LEFT: approach_ball(Foot::LEFT); break; case PathModel::PathRoutine::APPROACH_BALL_RIGHT: approach_ball(Foot::RIGHT); break; case PathModel::PathRoutine::SHORT_KICK_LEFT: short_kick(Foot::LEFT); break; case PathModel::PathRoutine::SHORT_KICK_RIGHT: short_kick(Foot::RIGHT); break; case PathModel::PathRoutine::LONG_KICK_LEFT: long_kick(Foot::LEFT); break; case PathModel::PathRoutine::LONG_KICK_RIGHT: long_kick(Foot::RIGHT); break; case PathModel::PathRoutine::SIDEKICK_LEFT: sidekick(Foot::LEFT); break; case PathModel::PathRoutine::SIDEKICK_RIGHT: sidekick(Foot::RIGHT); break; } // Always executed last execute_step_buffer(); STOPWATCH_STOP("PathPlanner"); } // Primitive Maneuvers void PathPlanner::walk_to_ball(const Foot foot, const bool go_fast) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ballPos = getBallModel().positionPreview; coordinate = WalkRequest::Hip; break; } double ballRotation = ballPos.angle(); Pose2D pose = { ballRotation, 0.7*(ballPos.x - getPathModel().distance), ballPos.y }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double scale = 1.0; double speed_direction = 0.0; if (go_fast) { double character = 1.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction); } else { double character = 0.3; add_step(pose, type, coordinate, character, foot, scale, speed_direction); } } else { update_step(pose); } } void PathPlanner::move_around_ball(const double direction, const double radius) { Vector2d ballPos = getBallModel().positionPreview; double ballRotation = ballPos.angle(); double ballDistance = ballPos.abs(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double min1; double min2; double max1; double max2; if (direction <= 0) { min1 = 0.0; min2 = 0.0; max1 = 45.0; max2 = 100.0; } else { min1 = -45; min2 = -100; max1 = 0; max2 = 0; } double stepX = (ballDistance - radius) * std::cos(ballRotation); double stepY = Math::clamp(radius * std::tan(Math::clamp(Math::toDegrees(-direction), min1, max1)), min2, max2) * std::cos(ballRotation); Pose2D pose = { ballRotation, stepX, stepY }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; Foot foot = Foot::NONE; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction); } else { update_step(pose); } } void PathPlanner::approach_ball(const Foot foot) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double stepX = 0.0; double stepY = 0.0; double ballRadius = getFieldInfo().ballRadius; double stepRotation = ballPos.abs() > 250 ? ballPos.angle() : 0; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; stepX = ballPos.x - std::abs(ballPos.y - getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y - getPathModel().yOffset; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; stepX = ballPos.x - std::abs(ballPos.y + getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y + getPathModel().yOffset; break; case Foot::NONE: ASSERT(false); } Pose2D pose = { stepRotation, 0.7 * stepX, 0.7 * stepY }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction); } else { update_step(pose); } } void PathPlanner::short_kick(const Foot foot) { if (!kick_planned) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, ballPos.x + 500 , 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction); kick_planned = true; } } } void PathPlanner::long_kick(const Foot foot) { if (!kick_planned) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, ballPos.x + 500, 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction); kick_planned = true; } } } void PathPlanner::sidekick(const Foot foot) { if (!kick_planned) { double speed_direction = 0.0; double stepY = 0.0; Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; speed_direction = 90; stepY = 100; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; speed_direction = -90; stepY = -100; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, stepY }; StepType type = StepType::KICKSTEP; double character = 1.0; Foot step_foot = foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT; double scale = 1.0; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction); kick_planned = true; } } } // Stepcontrol void PathPlanner::add_step(Pose2D &pose, const StepType &type, const WalkRequest::Coordinate &coordinate, const double character, const Foot foot, const double scale, const double speedDirection) { step_buffer.push_back(Step_Buffer_Element({ pose, speedDirection, type, type == StepType::KICKSTEP ? 300 : 250, character, scale, foot, coordinate})); } void PathPlanner::update_step(Pose2D &pose) { ASSERT(step_buffer.size() > 0); Step_Buffer_Element updatedElement = step_buffer.front(); updatedElement.pose = pose; step_buffer.front() = updatedElement; } void PathPlanner::manage_step_buffer() { if (step_buffer.empty()) { return; } // stepID higher than the last one means, stepControl request with the // last_stepcontrol_stepID has been accepted if (last_stepcontrol_stepID < getMotionStatus().stepControl.stepID) { step_buffer.erase(step_buffer.begin()); last_stepcontrol_stepID = getMotionStatus().stepControl.stepID; } // Correct last_stepcontrol_stepID if neccessary if (getMotionStatus().stepControl.stepID < last_stepcontrol_stepID) { last_stepcontrol_stepID = getMotionStatus().stepControl.stepID; } } void PathPlanner::execute_step_buffer() { if (step_buffer.empty()) { return; } STOPWATCH_START("PathPlanner:execute_steplist"); getMotionRequest().id = motion::walk; getMotionRequest().standardStand = false; getMotionRequest().walkRequest.coordinate = step_buffer.front().coordinate; getMotionRequest().walkRequest.character = step_buffer.front().character; getMotionRequest().walkRequest.stepControl.scale = step_buffer.front().scale; getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID; getMotionRequest().walkRequest.stepControl.type = step_buffer.front().type; getMotionRequest().walkRequest.stepControl.time = step_buffer.front().time; getMotionRequest().walkRequest.stepControl.speedDirection = step_buffer.front().speedDirection; getMotionRequest().walkRequest.stepControl.target = step_buffer.front().pose; // normal walking WALKSTEPs use Foot::NONE, for KICKSTEPs the foot to use has to be specified if (step_buffer.front().foot == Foot::NONE) { switch (getMotionStatus().stepControl.moveableFoot) { case MotionStatus::StepControlStatus::LEFT: foot_to_use = Foot::LEFT; break; case MotionStatus::StepControlStatus::RIGHT: foot_to_use = Foot::RIGHT; break; case MotionStatus::StepControlStatus::BOTH: if (step_buffer.front().pose.translation.y > 0.0f || step_buffer.front().pose.rotation > 0.0f) { foot_to_use = Foot::LEFT; } else { foot_to_use = Foot::RIGHT; } break; case MotionStatus::StepControlStatus::NONE: foot_to_use = Foot::RIGHT; break; } } else { foot_to_use = step_buffer.front().foot; } // false means right foot getMotionRequest().walkRequest.stepControl.moveLeftFoot = foot_to_use == Foot::RIGHT ? false : true; STOPWATCH_STOP("PathPlanner:execute_steplist"); } <|endoftext|>
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file NewtonEulerFrom1DLocalFrameR.hpp */ #ifndef NEWTONEULERIMPACT_H #define NEWTONEULERIMPACT_H #include "NewtonEulerR.hpp" #include "NewtonEulerDS.hpp" /** NewtonEulerFrom1DLocalFrameR * * \author O. Bonnefon * \version 3.0.0. * \date Dec, 2010 * * This class is an interface for a relation with impact. It * implements the computation of the jacoboian of h from the points of * contacts and the normal. Use this class consists in overloading * the method computeh, by setting the member pc1, pc2, nc and y. The * matrix jachq is used both for the building of the OSNSP (with T) * and for the predictor of activation of deactivation of the Interaction. * */ class NewtonEulerFrom1DLocalFrameR : public NewtonEulerR { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(NewtonEulerFrom1DLocalFrameR); /* Current Contact Points, may be updated within Newton loop based * on _relPc1, _relPc2. */ SP::SiconosVector _Pc1; SP::SiconosVector _Pc2; /* Contact Points in coordinates relative to attached DS->q. Set * these if _Pc1/_Pc2 are not calculated within the Newton loop. */ SP::SiconosVector _relPc1; SP::SiconosVector _relPc2; /* Inward Normal at the contact. * \todo The meaning of "Inward" has to be explained carefully. */ SP::SiconosVector _Nc; /* _Nc must be calculated relative to q2 */ SP::SiconosVector _relNc; /* Rotation matrix converting the absolute coordinate to the contact frame coordinate. * This matrix contains the unit vector(s)of the contact frame in row. */ SP::SimpleMatrix _RotationAbsToContactFrame; /* Matrix converting */ SP::SimpleMatrix _rotationMatrixAbsToBody; /* Cross product matrices that correspond the lever arm from * contact point to center of mass*/ SP::SimpleMatrix _NPG1; SP::SimpleMatrix _NPG2; /*buffer matrices*/ SP::SimpleMatrix _AUX1; SP::SimpleMatrix _AUX2; private: void NIcomputeJachqTFromContacts(SP::SiconosVector q1); void NIcomputeJachqTFromContacts(SP::SiconosVector q1, SP::SiconosVector q2); public: /** V.A. boolean _isOnCOntact ?? Why is it public members ? * seems parametrize the projection algorithm * the projection is done on the surface \f$y=0\f$ or on \f$y \geq 0\f$ */ bool _isOnContact; /** constructorx */ NewtonEulerFrom1DLocalFrameR(): NewtonEulerR(), _Pc1(new SiconosVector(3)), _Pc2(new SiconosVector(3)), _relPc1(new SiconosVector(3)), _relPc2(new SiconosVector(3)), _Nc(new SiconosVector(3)), _relNc(new SiconosVector(3)) { /*_ds1=NULL;_ds2=NULL;*/ } /** destructor */ virtual ~NewtonEulerFrom1DLocalFrameR() {}; virtual void computeJachq(double time, Interaction& inter, SP::BlockVector q0); virtual void initializeWorkVectorsAndMatrices(Interaction& inter, VectorOfBlockVectors& DSlink, VectorOfVectors& workV, VectorOfSMatrices& workM); virtual void initialize(Interaction& inter); /* Default implementation consists in multiplying jachq and T (see NewtonEulerR::computeJachqT) * but here we compute the operator from the the contact point locations * and the local frame at contact * \param inter interaction that owns the relation * \param q0 the block vector to the dynamical system position */ virtual void computeJachqT(Interaction& inter, SP::BlockVector q0); /* Default implementation of computeh updates contact points and * distance for q if different than qold. */ virtual void computeh(double time, BlockVector& q0, SiconosVector &y); /** Return the distance between pc1 and pc, with sign according to normal */ double distance() const; inline SP::SiconosVector pc1() const { return _Pc1; } inline SP::SiconosVector pc2() const { return _Pc2; } inline SP::SiconosVector nc() const { return _Nc; } inline SP::SiconosVector relPc1() const { return _relPc1; } inline SP::SiconosVector relPc2() const { return _relPc2; } inline SP::SiconosVector relNc() const { return _relNc; } /** set the coordinates of first contact point * \param npc new coordinates */ void setpc1(SP::SiconosVector npc) { _Pc1 = npc; }; /** set the coordinates of second contact point * \param npc new coordinates */ void setpc2(SP::SiconosVector npc) { _Pc2 = npc; }; /** set the coordinates of inside normal vector at the contact point * \param nnc new coordinates */ void setnc(SP::SiconosVector nnc) { _Nc = nnc; }; /** Set the coordinates of first contact point in ds1 frame. * It will be used to compute _Pc1 during computeh(). * \param npc new coordinates */ void setRelPc1(SP::SiconosVector npc) { _relPc1 = npc; }; /** Set the coordinates of second contact point in ds2 frame * It will be used to compute _Pc2 during computeh(). * \param npc new coordinates */ void setRelPc2(SP::SiconosVector npc) { _relPc2 = npc; }; /** Set the coordinates of inside normal vector at the contact point in ds2 frame. * It will be used to compute _Nc during computeh(). * \param nnc new coordinates */ void setRelNc(SP::SiconosVector nnc) { _relNc = nnc; }; // visitors hook ACCEPT_STD_VISITORS(); }; #endif // NEWTONEULERRIMPACT_H <commit_msg>[kernel] move setpc1,setpc2,setnc to protected<commit_after>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file NewtonEulerFrom1DLocalFrameR.hpp */ #ifndef NEWTONEULERIMPACT_H #define NEWTONEULERIMPACT_H #include "NewtonEulerR.hpp" #include "NewtonEulerDS.hpp" /** NewtonEulerFrom1DLocalFrameR * * \author O. Bonnefon * \version 3.0.0. * \date Dec, 2010 * * This class is an interface for a relation with impact. It * implements the computation of the jacoboian of h from the points of * contacts and the normal. Use this class consists in overloading * the method computeh, by setting the member pc1, pc2, nc and y. The * matrix jachq is used both for the building of the OSNSP (with T) * and for the predictor of activation of deactivation of the Interaction. * */ class NewtonEulerFrom1DLocalFrameR : public NewtonEulerR { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(NewtonEulerFrom1DLocalFrameR); /* Current Contact Points, may be updated within Newton loop based * on _relPc1, _relPc2. */ SP::SiconosVector _Pc1; SP::SiconosVector _Pc2; /* Contact Points in coordinates relative to attached DS->q. Set * these if _Pc1/_Pc2 are not calculated within the Newton loop. */ SP::SiconosVector _relPc1; SP::SiconosVector _relPc2; /* Inward Normal at the contact. * \todo The meaning of "Inward" has to be explained carefully. */ SP::SiconosVector _Nc; /* _Nc must be calculated relative to q2 */ SP::SiconosVector _relNc; /* Rotation matrix converting the absolute coordinate to the contact frame coordinate. * This matrix contains the unit vector(s)of the contact frame in row. */ SP::SimpleMatrix _RotationAbsToContactFrame; /* Matrix converting */ SP::SimpleMatrix _rotationMatrixAbsToBody; /* Cross product matrices that correspond the lever arm from * contact point to center of mass*/ SP::SimpleMatrix _NPG1; SP::SimpleMatrix _NPG2; /*buffer matrices*/ SP::SimpleMatrix _AUX1; SP::SimpleMatrix _AUX2; /** Set the coordinates of first contact point. Must only be done * in a computeh() override. * \param npc new coordinates */ void setpc1(SP::SiconosVector npc) { _Pc1 = npc; }; /** Set the coordinates of second contact point. Must only be done * in a computeh() override. * \param npc new coordinates */ void setpc2(SP::SiconosVector npc) { _Pc2 = npc; }; /** Set the coordinates of inside normal vector at the contact point. * Must only be done in a computeh() override. * \param nnc new coordinates */ void setnc(SP::SiconosVector nnc) { _Nc = nnc; }; private: void NIcomputeJachqTFromContacts(SP::SiconosVector q1); void NIcomputeJachqTFromContacts(SP::SiconosVector q1, SP::SiconosVector q2); public: /** V.A. boolean _isOnCOntact ?? Why is it public members ? * seems parametrize the projection algorithm * the projection is done on the surface \f$y=0\f$ or on \f$y \geq 0\f$ */ bool _isOnContact; /** constructorx */ NewtonEulerFrom1DLocalFrameR(): NewtonEulerR(), _Pc1(new SiconosVector(3)), _Pc2(new SiconosVector(3)), _relPc1(new SiconosVector(3)), _relPc2(new SiconosVector(3)), _Nc(new SiconosVector(3)), _relNc(new SiconosVector(3)) { /*_ds1=NULL;_ds2=NULL;*/ } /** destructor */ virtual ~NewtonEulerFrom1DLocalFrameR() {}; virtual void computeJachq(double time, Interaction& inter, SP::BlockVector q0); virtual void initializeWorkVectorsAndMatrices(Interaction& inter, VectorOfBlockVectors& DSlink, VectorOfVectors& workV, VectorOfSMatrices& workM); virtual void initialize(Interaction& inter); /* Default implementation consists in multiplying jachq and T (see NewtonEulerR::computeJachqT) * but here we compute the operator from the the contact point locations * and the local frame at contact * \param inter interaction that owns the relation * \param q0 the block vector to the dynamical system position */ virtual void computeJachqT(Interaction& inter, SP::BlockVector q0); /* Default implementation of computeh updates contact points and * distance for q if different than qold. */ virtual void computeh(double time, BlockVector& q0, SiconosVector &y); /** Return the distance between pc1 and pc, with sign according to normal */ double distance() const; inline SP::SiconosVector pc1() const { return _Pc1; } inline SP::SiconosVector pc2() const { return _Pc2; } inline SP::SiconosVector nc() const { return _Nc; } inline SP::SiconosVector relPc1() const { return _relPc1; } inline SP::SiconosVector relPc2() const { return _relPc2; } inline SP::SiconosVector relNc() const { return _relNc; } /** Set the coordinates of first contact point in ds1 frame. * It will be used to compute _Pc1 during computeh(). * \param npc new coordinates */ void setRelPc1(SP::SiconosVector npc) { _relPc1 = npc; }; /** Set the coordinates of second contact point in ds2 frame * It will be used to compute _Pc2 during computeh(). * \param npc new coordinates */ void setRelPc2(SP::SiconosVector npc) { _relPc2 = npc; }; /** Set the coordinates of inside normal vector at the contact point in ds2 frame. * It will be used to compute _Nc during computeh(). * \param nnc new coordinates */ void setRelNc(SP::SiconosVector nnc) { _relNc = nnc; }; // visitors hook ACCEPT_STD_VISITORS(); }; #endif // NEWTONEULERRIMPACT_H <|endoftext|>
<commit_before> ///////////////////////////////////////////////////////////////////////////// // Copyright (c) 1996, California Institute of Technology. // ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged. // // Please read the full copyright notice in the file COPYRIGH // in this directory. // // Author: Todd Karakashian, NASA/Jet Propulsion Laboratory // Todd.K.Karakashian@jpl.nasa.gov // // $RCSfile: escaping.cc,v $ - Miscellaneous routines for DODS HDF server // // $Log: escaping.cc,v $ // Revision 1.3 1997/02/14 02:24:44 jimg // Removed reliance on the dods-hdf code. // Introduced a const int MAXSTR with value 256. This matches the length of // ID_MAX in the parser.h header (which I did not include since it defines // a lot of software that is irrelevant to this module). // // Revision 1.2 1997/02/14 02:18:16 jimg // Added to DODS core // // Revision 1.2 1996/10/07 21:15:17 todd // Changes escape character to % from _. // // Revision 1.1 1996/09/24 22:38:16 todd // Initial revision // // ///////////////////////////////////////////////////////////////////////////// // These two routines are for escaping/unescaping strings that are identifiers // in DODS // id2dods() -- escape (using WWW hex codes) non-allowable characters in a // DODS identifier // dods2id() -- given an WWW hexcode escaped identifier, restore it // // These two routines are for escaping/unescaping strings storing attribute // values. They use traditional octal escapes (\nnn) because they are // intended to be viewed by a user // escattr() -- escape (using traditional octal backslash) non-allowable // characters in the value of a DODS attribute // unescattr() -- given an octally escaped string, restore it // // These are routines used by the above, not intended to be called directly: // // hexstring() // unhexstring() // octstring() // unoctstring() // // -Todd #include <ctype.h> #include <strstream.h> #include <iomanip.h> #include <String.h> #if 0 #include <mfhdf.h> #include <hdfclass.h> #include "HDFStructure.h" #include "HDFArray.h" #include "hdfutil.h" #include "dhdferr.h" #endif const int MAXSTR = 256; String hexstring(int val) { static char buf[MAXSTR]; ostrstream(buf,MAXSTR) << hex << setw(2) << setfill('0') << val << ends; return (String)buf; } char unhexstring(String s) { int val; static char buf[MAXSTR]; strcpy(buf,(const char *)s); istrstream(buf,MAXSTR) >> hex >> val; return (char)val; } String octstring(int val) { static char buf[MAXSTR]; ostrstream(buf,MAXSTR) << oct << setw(3) << setfill('0') << val << ends; return (String)buf; } char unoctstring(String s) { int val; static char buf[MAXSTR]; strcpy(buf,(const char *)s); istrstream(buf,MAXSTR) >> oct >> val; return (char)val; } // replace characters that are not allowed in DODS identifiers String id2dods(String s) { static Regex badregx = "[^0-9a-zA-Z_%]"; const char ESC = '%'; int index; while ( (index = s.index(badregx)) >= 0) s.at(index,1) = ESC + hexstring(toascii(s[index])); if (isdigit(s[0])) s.before(0) = '_'; return s; } String dods2id(String s) { static Regex escregx = "%[0-7][0-9a-fA-F]"; int index; while ( (index = s.index(escregx)) >= 0) s.at(index,3) = unhexstring(s.at(index+1,2)); return s; } // Escape non-printable characters and quotes from an HDF attribute String escattr(String s) { static Regex nonprintable = "[^ !-~]"; const char ESC = '\\'; const char QUOTE = '\"'; const String ESCQUOTE = (String)ESC + (String)QUOTE; // escape non-printing characters with octal escape int index = 0; while ( (index = s.index(nonprintable)) >= 0) s.at(index,1) = ESC + octstring(toascii(s[index])); // escape " with backslash index = 0; while ( (index = s.index(QUOTE,index)) >= 0) { s.at(index,1) = ESCQUOTE; index += ESCQUOTE.length(); } return s; } // Un-escape special characters, quotes and backslashes from an HDF attribute. // Note: A regex to match one \ must be defined as // Regex foo = "\\\\"; // because both C++ strings and libg++ regex's also employ \ as // an escape character! String unescattr(String s) { static Regex escregx = "\\\\[01][0-7][0-7]"; // matches 4 characters static Regex escquoteregex = "[^\\\\]\\\\\""; // matches 3 characters static Regex escescregex = "\\\\\\\\"; // matches 2 characters const char ESC = '\\'; const char QUOTE = '\"'; const String ESCQUOTE = (String)ESC + (String)QUOTE; // unescape any octal-escaped ASCII characters int index = 0; while ( (index = s.index(escregx,index)) >= 0) { s.at(index,4) = unoctstring(s.at(index+1,3)); index++; } // unescape any escaped quotes index = 0; while ( (index = s.index(escquoteregex,index)) >= 0) { s.at(index+1,2) = QUOTE; index++; } // unescape any escaped backslashes index = 0; while ( (index = s.index(escescregex,index)) >= 0) { s.at(index,2) = ESC; index++; } return s; } <commit_msg>Added allowable and escape parameters to id2dods and dods2id so that the builtin regexs can be overridden if needed. Switched to the `fast compile' mode for the Regex objects.<commit_after> ///////////////////////////////////////////////////////////////////////////// // Copyright (c) 1996, California Institute of Technology. // ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged. // // Please read the full copyright notice in the file COPYRIGH // in this directory. // // Author: Todd Karakashian, NASA/Jet Propulsion Laboratory // Todd.K.Karakashian@jpl.nasa.gov // // $RCSfile: escaping.cc,v $ - Miscellaneous routines for DODS HDF server // // $Log: escaping.cc,v $ // Revision 1.4 1997/02/14 04:18:10 jimg // Added allowable and escape parameters to id2dods and dods2id so that the // builtin regexs can be overridden if needed. // Switched to the `fast compile' mode for the Regex objects. // // Revision 1.3 1997/02/14 02:24:44 jimg // Removed reliance on the dods-hdf code. // Introduced a const int MAXSTR with value 256. This matches the length of // ID_MAX in the parser.h header (which I did not include since it defines // a lot of software that is irrelevant to this module). // // Revision 1.2 1997/02/14 02:18:16 jimg // Added to DODS core // // Revision 1.2 1996/10/07 21:15:17 todd // Changes escape character to % from _. // // Revision 1.1 1996/09/24 22:38:16 todd // Initial revision // // ///////////////////////////////////////////////////////////////////////////// // These two routines are for escaping/unescaping strings that are identifiers // in DODS // id2dods() -- escape (using WWW hex codes) non-allowable characters in a // DODS identifier // dods2id() -- given an WWW hexcode escaped identifier, restore it // // These two routines are for escaping/unescaping strings storing attribute // values. They use traditional octal escapes (\nnn) because they are // intended to be viewed by a user // escattr() -- escape (using traditional octal backslash) non-allowable // characters in the value of a DODS attribute // unescattr() -- given an octally escaped string, restore it // // These are routines used by the above, not intended to be called directly: // // hexstring() // unhexstring() // octstring() // unoctstring() // // -Todd #include <ctype.h> #include <strstream.h> #include <iomanip.h> #include <String.h> #if 0 #include <mfhdf.h> #include <hdfclass.h> #include "HDFStructure.h" #include "HDFArray.h" #include "hdfutil.h" #include "dhdferr.h" #endif const int MAXSTR = 256; String hexstring(int val) { static char buf[MAXSTR]; ostrstream(buf,MAXSTR) << hex << setw(2) << setfill('0') << val << ends; return (String)buf; } char unhexstring(String s) { int val; static char buf[MAXSTR]; strcpy(buf,(const char *)s); istrstream(buf,MAXSTR) >> hex >> val; return (char)val; } String octstring(int val) { static char buf[MAXSTR]; ostrstream(buf,MAXSTR) << oct << setw(3) << setfill('0') << val << ends; return (String)buf; } char unoctstring(String s) { int val; static char buf[MAXSTR]; strcpy(buf,(const char *)s); istrstream(buf,MAXSTR) >> oct >> val; return (char)val; } // replace characters that are not allowed in DODS identifiers String id2dods(String s, const String allowable = (char *)0) { static Regex badregx("[^0-9a-zA-Z_%]", 1); static const char ESC = '%'; if (allowable) { Regex badregx2(allowable, 1); int index; while ((index = s.index(badregx2)) >= 0) s.at(index,1) = ESC + hexstring(toascii(s[index])); } else { int index; while ((index = s.index(badregx)) >= 0) s.at(index,1) = ESC + hexstring(toascii(s[index])); } if (isdigit(s[0])) s.before(0) = '_'; return s; } String dods2id(String s, const String escape = (char *)0) { static Regex escregx("%[0-7][0-9a-fA-F]", 1); if (escape) { Regex escregx2(escape, 1); int index; while ((index = s.index(escregx2)) >= 0) s.at(index,3) = unhexstring(s.at(index+1,2)); } else { int index; while ((index = s.index(escregx)) >= 0) s.at(index,3) = unhexstring(s.at(index+1,2)); } return s; } // Escape non-printable characters and quotes from an HDF attribute String escattr(String s) { static Regex nonprintable = "[^ !-~]"; const char ESC = '\\'; const char QUOTE = '\"'; const String ESCQUOTE = (String)ESC + (String)QUOTE; // escape non-printing characters with octal escape int index = 0; while ( (index = s.index(nonprintable)) >= 0) s.at(index,1) = ESC + octstring(toascii(s[index])); // escape " with backslash index = 0; while ( (index = s.index(QUOTE,index)) >= 0) { s.at(index,1) = ESCQUOTE; index += ESCQUOTE.length(); } return s; } // Un-escape special characters, quotes and backslashes from an HDF attribute. // Note: A regex to match one \ must be defined as // Regex foo = "\\\\"; // because both C++ strings and libg++ regex's also employ \ as // an escape character! String unescattr(String s) { static Regex escregx = "\\\\[01][0-7][0-7]"; // matches 4 characters static Regex escquoteregex = "[^\\\\]\\\\\""; // matches 3 characters static Regex escescregex = "\\\\\\\\"; // matches 2 characters const char ESC = '\\'; const char QUOTE = '\"'; const String ESCQUOTE = (String)ESC + (String)QUOTE; // unescape any octal-escaped ASCII characters int index = 0; while ( (index = s.index(escregx,index)) >= 0) { s.at(index,4) = unoctstring(s.at(index+1,3)); index++; } // unescape any escaped quotes index = 0; while ( (index = s.index(escquoteregex,index)) >= 0) { s.at(index+1,2) = QUOTE; index++; } // unescape any escaped backslashes index = 0; while ( (index = s.index(escescregex,index)) >= 0) { s.at(index,2) = ESC; index++; } return s; } <|endoftext|>
<commit_before>// // C++ exception wrappers // // These will allow you to detect where an exception is thrown, // and where it is caught. // #include <core/System.h> #include <core/Interpose.h> #include <stack/ThrowHandler.h> #include <stack/CatchHandler.h> #include <cxxabi.h> #include <exception> using namespace exray; typedef void (*CxaThrowFuncPtr)(void *, std::type_info *, void(*)(void *)); typedef void* (*CxaBeginCatchFuncPtr)(void *); namespace exray { namespace CXX { CxaThrowFuncPtr throwFunc = NULL; CxaBeginCatchFuncPtr catchFunc = NULL; } } extern "C" { void __cxa_throw(void *thrownException, std::type_info *tinfo, void (*dest) (void *)) { if (exray::CXX::throwFunc == NULL) { exray::CXX::throwFunc = (CxaThrowFuncPtr)exray::Interpose::loadFuncPtr("__cxa_throw"); } if (System::isThreadUnwinding() == false) { ThrowHandler *handler = System::getThrowHandler(); handler->captureFrames(*tinfo, "__cxa_throw"); System::setThreadUnwinding(); } exray::CXX::throwFunc(thrownException, tinfo, dest); } void *__cxa_begin_catch(void *exceptionObject) throw() { if (exray::CXX::catchFunc == NULL) { exray::CXX::catchFunc = (CxaBeginCatchFuncPtr)exray::Interpose::loadFuncPtr("__cxa_begin_catch"); } System::clearThreadUnwinding(); CatchHandler *handler = System::getCatchHandler(); handler->captureFrames("__cxa_begin_catch"); exray::CXX::catchFunc(exceptionObject); } } #if defined(CPPMODE) && (CPPMODE == CPP11) typedef void (*CxaRethrowExceptionFuncPtr)(std::__exception_ptr::exception_ptr); namespace exray { namespace CXX { CxaRethrowExceptionFuncPtr rethrowExceptionFunc __attribute__ ((__noreturn__)) = NULL; } } namespace std { static const char *RETHROW_FUNC_MANGLED = "_ZSt17rethrow_exceptionNSt15__exception_ptr13exception_ptrE"; void rethrow_exception(__exception_ptr::exception_ptr p) { if (CXX::rethrowExceptionFunc == NULL) { CXX::rethrowExceptionFunc = (CxaRethrowExceptionFuncPtr)exray::Interpose::loadFuncPtr(RETHROW_FUNC_MANGLED); } if (System::isThreadUnwinding() == false) { ThrowHandler *handler = System::getThrowHandler(); handler->captureFrames(*p.__cxa_exception_type(), "__cxa_rethrow"); System::setThreadUnwinding(); } CXX::rethrowExceptionFunc(p); } } #endif <commit_msg>Fixing signature for std::rethrow_exception()<commit_after>// // C++ exception wrappers // // These will allow you to detect where an exception is thrown, // and where it is caught. // #include <core/System.h> #include <core/Interpose.h> #include <stack/ThrowHandler.h> #include <stack/CatchHandler.h> #include <cxxabi.h> #include <exception> using namespace exray; typedef void (*CxaThrowFuncPtr)(void *, std::type_info *, void(*)(void *)); typedef void* (*CxaBeginCatchFuncPtr)(void *); namespace exray { namespace CXX { CxaThrowFuncPtr throwFunc = NULL; CxaBeginCatchFuncPtr catchFunc = NULL; } } extern "C" { void __cxa_throw(void *thrownException, std::type_info *tinfo, void (*dest) (void *)) { if (exray::CXX::throwFunc == NULL) { exray::CXX::throwFunc = (CxaThrowFuncPtr)exray::Interpose::loadFuncPtr("__cxa_throw"); } if (System::isThreadUnwinding() == false) { ThrowHandler *handler = System::getThrowHandler(); handler->captureFrames(*tinfo, "__cxa_throw"); System::setThreadUnwinding(); } exray::CXX::throwFunc(thrownException, tinfo, dest); } void *__cxa_begin_catch(void *exceptionObject) throw() { if (exray::CXX::catchFunc == NULL) { exray::CXX::catchFunc = (CxaBeginCatchFuncPtr)exray::Interpose::loadFuncPtr("__cxa_begin_catch"); } System::clearThreadUnwinding(); CatchHandler *handler = System::getCatchHandler(); handler->captureFrames("__cxa_begin_catch"); exray::CXX::catchFunc(exceptionObject); } } #if defined(CPPMODE) && (CPPMODE == CPP11) typedef void (*CxaRethrowExceptionFuncPtr)(std::__exception_ptr::exception_ptr); namespace exray { namespace CXX { CxaRethrowExceptionFuncPtr rethrowExceptionFunc __attribute__ ((__noreturn__)) = NULL; } } namespace std { static const char *RETHROW_FUNC_MANGLED = "_ZSt17rethrow_exceptionNSt15__exception_ptr13exception_ptrE"; void rethrow_exception(__exception_ptr::exception_ptr p) { if (CXX::rethrowExceptionFunc == NULL) { CXX::rethrowExceptionFunc = (CxaRethrowExceptionFuncPtr)exray::Interpose::loadFuncPtr(RETHROW_FUNC_MANGLED); } if (System::isThreadUnwinding() == false) { ThrowHandler *handler = System::getThrowHandler(); handler->captureFrames(*p.__cxa_exception_type(), "std::rethrow_exception()"); System::setThreadUnwinding(); } CXX::rethrowExceptionFunc(p); } } #endif <|endoftext|>
<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include <nvcore/Debug.h> #include "CudaUtils.h" #if defined HAVE_CUDA #include <cuda_runtime.h> #endif using namespace nv; using namespace cuda; #if NV_OS_WIN32 #define WINDOWS_LEAN_AND_MEAN #include <windows.h> static bool isWindowsVista() { OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); ::GetVersionEx(&osvi); return osvi.dwMajorVersion >= 6; } typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); static bool isWow32() { LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process"); BOOL bIsWow64 = FALSE; if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) { // Assume 32 bits. return true; } } return !bIsWow64; } #endif /// Determine if CUDA is available. bool nv::cuda::isHardwarePresent() { #if defined HAVE_CUDA #if NV_OS_WIN32 //if (isWindowsVista()) return false; //if (isWindowsVista() || !isWow32()) return false; #endif int count = deviceCount(); if (count == 1) { // Make sure it's not an emulation device. cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, 0); // deviceProp.name != Device Emulation (CPU) if (deviceProp.major == -1 || deviceProp.minor == -1) { return false; } // @@ Make sure that warp size == 32 } return count > 0; #else return false; #endif } /// Get number of CUDA enabled devices. int nv::cuda::deviceCount() { #if defined HAVE_CUDA int gpuCount = 0; cudaError_t result = cudaGetDeviceCount(&gpuCount); if (result == cudaSuccess) { return gpuCount; } #endif return 0; } /// Activate the given devices. bool nv::cuda::setDevice(int i) { nvCheck(i < deviceCount()); #if defined HAVE_CUDA cudaError_t result = cudaSetDevice(i); return result == cudaSuccess; #else return false; #endif } <commit_msg>Workaround bug in CUDA runtime. When using CUDA 2.0, it's required to use a driver that supports CUDA 2.0.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include <nvcore/Debug.h> #include "CudaUtils.h" #if defined HAVE_CUDA #include <cuda_runtime.h> #endif using namespace nv; using namespace cuda; #if NV_OS_WIN32 #define WINDOWS_LEAN_AND_MEAN #include <windows.h> static bool isWindowsVista() { OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); ::GetVersionEx(&osvi); return osvi.dwMajorVersion >= 6; } typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); static bool isWow32() { LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process"); BOOL bIsWow64 = FALSE; if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) { // Assume 32 bits. return true; } } return !bIsWow64; } #endif #if NV_OS_WIN32 static bool isCuda20DriverAvailable() { bool result = false; HINSTANCE nvcuda = LoadLibraryExA( "nvcuda.dll", NULL, 0 ); if (nvcuda != NULL) { FARPROC lcuStreamCreate = GetProcAddress( nvcuda, "cuStreamCreate" ); result = lcuStreamCreate != NULL; FreeLibrary( nvcuda ); } return result; } #endif /// Determine if CUDA is available. bool nv::cuda::isHardwarePresent() { #if defined HAVE_CUDA #if NV_OS_WIN32 //if (isWindowsVista()) return false; //if (isWindowsVista() || !isWow32()) return false; #endif int count = deviceCount(); if (count == 1) { // Make sure it's not an emulation device. cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, 0); // deviceProp.name != Device Emulation (CPU) if (deviceProp.major == -1 || deviceProp.minor == -1) { return false; } // Make sure that CUDA driver matches CUDA runtime. #if NV_OS_WIN32 && CUDART_VERSION >= 2000 if (!isCuda20DriverAvailable()) { return false; } #endif // @@ Make sure that warp size == 32 } return count > 0; #else return false; #endif } /// Get number of CUDA enabled devices. int nv::cuda::deviceCount() { #if defined HAVE_CUDA int gpuCount = 0; cudaError_t result = cudaGetDeviceCount(&gpuCount); if (result == cudaSuccess) { return gpuCount; } #endif return 0; } /// Activate the given devices. bool nv::cuda::setDevice(int i) { nvCheck(i < deviceCount()); #if defined HAVE_CUDA cudaError_t result = cudaSetDevice(i); return result == cudaSuccess; #else return false; #endif } <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer 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/explorer/commands/send-tx-node.hpp> #include <iostream> #include <boost/format.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/async_client.hpp> #include <bitcoin/explorer/callback_state.hpp> #include <bitcoin/explorer/define.hpp> #include <bitcoin/explorer/primitives/transaction.hpp> #include <bitcoin/explorer/utility.hpp> using namespace bc; using namespace bc::explorer; using namespace bc::explorer::commands; using namespace bc::explorer::primitives; console_result send_tx_node::invoke(std::ostream& output, std::ostream& error) { // Bound parameters. const auto& node = get_host_option(); const auto& port = get_port_option(); const tx_type& transaction = get_transaction_argument(); const auto& debug_file = get_logging_debug_file_setting(); const auto& error_file = get_logging_error_file_setting(); bc::ofstream debug_log(debug_file.string(), log_open_mode); bc::ofstream error_log(error_file.string(), log_open_mode); bind_debug_log(debug_log); bind_error_log(error_log); const static auto headline = "================= Startup ================="; log_fatal(LOG_NETWORK) << headline; log_error(LOG_NETWORK) << headline; log_warning(LOG_NETWORK) << headline; log_info(LOG_NETWORK) << headline; log_debug(LOG_NETWORK) << headline; constexpr size_t threads = 4; constexpr size_t poll_period_ms = 2000; async_client client(threads); auto& pool = client.get_threadpool(); bc::network::hosts host(pool); bc::network::handshake shake(pool); bc::network::network net(pool); bc::network::protocol proto(pool, host, shake, net); callback_state state(error, output); const auto start_handler = [&state](const std::error_code& code) { state.handle_error(code); }; const auto send_handler = [&state](const std::error_code& code) { if (state.handle_error(code)) state.output(format(BX_SEND_TX_OUTPUT) % now()); --state; }; const auto channel_handler = [&state, &send_handler]( const std::error_code& code, bc::network::channel_ptr node, bc::network::protocol&, const tx_type& tx) { if (state.handle_error(code)) node->send(tx, send_handler); }; bool stopped = false; const auto stop_handler = [&state, &stopped](const std::error_code& code) { state.handle_error(code); stopped = true; }; ++state; // Handle each successful connection. proto.subscribe_channel( std::bind(channel_handler, ph::_1, ph::_2, std::ref(proto), std::ref(transaction))); // Connect to the explicitly-specified host. proto.maintain_connection(node, port); client.poll(state.stopped(), poll_period_ms); proto.stop(stop_handler); // Delay until the protocol stop handler has been called. while (!stopped) sleep_ms(1); client.stop(); // BUGBUG: The server may not have time to process the message before the // connection is dropped. return state.get_result(); } <commit_msg>Handle ctrl-c, fix constant, remove redundant loop, disable tx relays.<commit_after>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer 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/explorer/commands/send-tx-node.hpp> #include <csignal> #include <iostream> #include <boost/format.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/async_client.hpp> #include <bitcoin/explorer/callback_state.hpp> #include <bitcoin/explorer/define.hpp> #include <bitcoin/explorer/primitives/transaction.hpp> #include <bitcoin/explorer/utility.hpp> using namespace bc; using namespace bc::explorer; using namespace bc::explorer::commands; using namespace bc::explorer::primitives; static void handle_signal(int signal) { // Can't pass args using lambda capture for a simple function pointer. // This means there's no way to terminate without using a global variable // or process termination. Since the variable would screw with testing all // other methods we opt for process termination here. exit(console_result::failure); } console_result send_tx_node::invoke(std::ostream& output, std::ostream& error) { // Bound parameters. const auto& node = get_host_option(); const auto& port = get_port_option(); const tx_type& transaction = get_transaction_argument(); const auto& debug_file = get_logging_debug_file_setting(); const auto& error_file = get_logging_error_file_setting(); // These haven't been used for node (or p2p) connections. const auto retries = get_general_retries_setting(); const auto wait = get_general_wait_setting(); bc::ofstream debug_log(debug_file.string(), log_open_mode); bc::ofstream error_log(error_file.string(), log_open_mode); bind_debug_log(debug_log); bind_error_log(error_log); const static auto headline = "================= Startup ================="; log_fatal(LOG_NETWORK) << headline; log_error(LOG_NETWORK) << headline; log_warning(LOG_NETWORK) << headline; log_info(LOG_NETWORK) << headline; log_debug(LOG_NETWORK) << headline; constexpr size_t threads = 4; constexpr size_t poll_period_ms = 2000; async_client client(threads); auto& pool = client.get_threadpool(); bc::network::hosts host(pool, 0); bc::network::handshake shake(pool); bc::network::network net(pool); bc::network::protocol proto(pool, host, shake, net); callback_state state(error, output); const auto start_handler = [&state](const std::error_code& code) { state.handle_error(code); }; const auto send_handler = [&state](const std::error_code& code) { if (state.handle_error(code)) state.output(format(BX_SEND_TX_NODE_OUTPUT) % now()); --state; }; const auto channel_handler = [&state, &send_handler]( const std::error_code& code, bc::network::channel_ptr node, bc::network::protocol&, const tx_type& tx) { if (state.handle_error(code)) node->send(tx, send_handler); }; bool stopped = false; const auto stop_handler = [&state, &stopped](const std::error_code& code) { state.handle_error(code); stopped = true; }; ++state; // Handle each successful connection. proto.subscribe_channel( std::bind(channel_handler, ph::_1, ph::_2, std::ref(proto), std::ref(transaction))); // Connect to the explicitly-specified host. proto.maintain_connection(node, port, false); // Catch C signals for aborting the program. signal(SIGABRT, handle_signal); signal(SIGTERM, handle_signal); signal(SIGINT, handle_signal); client.poll(state.stopped(), poll_period_ms); proto.stop(stop_handler); client.stop(); return state.get_result(); } <|endoftext|>
<commit_before>#include "tgatexture.h" #include "detail/TextureImpl.h" #include "ifile.h" #include <boost/assert.hpp> #include <algorithm> namespace platform { namespace { struct Header { uint8_t mData[18]; // don't wanna pragma pack uint8_t IdLength()const { return mData[0]; } uint8_t ColorMapType()const { return mData[1]; } uint8_t ImageType()const { return mData[2]; } uint16_t ColMapStart()const { return mData[3] | ( ( uint16_t )mData[4] << 8 ); } uint16_t ColMapLength()const { return mData[5] | ( ( uint16_t )mData[6] << 8 ); } uint8_t ColMapDepth()const { return mData[7]; } uint16_t Origin()const { return mData[8] | ( ( uint16_t )mData[9] << 8 ); } uint16_t OriginY()const { return mData[10] | ( ( uint16_t )mData[11] << 8 ); } uint16_t Width()const { return mData[12] | ( ( uint16_t )mData[13] << 8 ); } uint16_t Height()const { return mData[14] | ( ( uint16_t )mData[15] << 8 ); } uint8_t PixelDepth()const { return mData[16]; } uint8_t ImageDescriptor()const { return mData[17]; } }; void Reorder( uint8_t* Data, size_t Size ); detail::TextureImpl* Load( File& F ) { Header Head; std::auto_ptr<detail::TextureImpl> impl( new detail::TextureImpl ); if( !F.Read( Head.mData, sizeof( Header ) ) ) { return NULL; } static uint16_t const MaxSupportedImageSize = 1 << 15; assert( Head.Width() <= MaxSupportedImageSize && Head.Height() < MaxSupportedImageSize ); impl->mWidth = Head.Width(); impl->mHeight = Head.Height(); assert( Head.PixelDepth() == 24 || Head.PixelDepth() == 32 ); if( Head.PixelDepth() != 24 && Head.PixelDepth() != 32 ) { return NULL; } size_t const ImgSize = impl->mWidth * impl->mHeight; size_t const DataSize = detail::TextureImpl::mChannels * ImgSize; impl->mData.resize( DataSize ); bool Succ; if( Head.PixelDepth() == 32 ) { assert( ( Head.ImageDescriptor() & 15 ) == 8 ); Succ = F.Read( static_cast< void* >( &impl->mData.at( 0 ) ), DataSize ); } else { std::string Buf; size_t const InSize = ImgSize * 3; Succ = F.Read( Buf, InSize ); if( Succ ) { detail::TextureImpl::ConvertRGBtoRGBA( ( uint8_t* )( void* )Buf.c_str(), ImgSize, &impl->mData.at( 0 ) ); } } if( !Succ ) { impl->mData.clear(); return NULL; } else { Reorder( &impl->mData.at( 0 ), ImgSize ); } return impl.release(); } void Reorder( uint8_t* Data, size_t Size ) { for( size_t x = 0; x < Size; x++ ) { unsigned char* pixel_out = &Data[x * 4]; std::swap( pixel_out[0], pixel_out[2] ); } } } // namespace anonymous TgaTexture::TgaTexture( File& F ) { if( F.IsValid() ) { mImpl.reset( Load( F ) ); } } } // namespace platform <commit_msg>B: < vs <= typo<commit_after>#include "tgatexture.h" #include "detail/TextureImpl.h" #include "ifile.h" #include <boost/assert.hpp> #include <algorithm> namespace platform { namespace { struct Header { uint8_t mData[18]; // don't wanna pragma pack uint8_t IdLength()const { return mData[0]; } uint8_t ColorMapType()const { return mData[1]; } uint8_t ImageType()const { return mData[2]; } uint16_t ColMapStart()const { return mData[3] | ( ( uint16_t )mData[4] << 8 ); } uint16_t ColMapLength()const { return mData[5] | ( ( uint16_t )mData[6] << 8 ); } uint8_t ColMapDepth()const { return mData[7]; } uint16_t Origin()const { return mData[8] | ( ( uint16_t )mData[9] << 8 ); } uint16_t OriginY()const { return mData[10] | ( ( uint16_t )mData[11] << 8 ); } uint16_t Width()const { return mData[12] | ( ( uint16_t )mData[13] << 8 ); } uint16_t Height()const { return mData[14] | ( ( uint16_t )mData[15] << 8 ); } uint8_t PixelDepth()const { return mData[16]; } uint8_t ImageDescriptor()const { return mData[17]; } }; void Reorder( uint8_t* Data, size_t Size ); detail::TextureImpl* Load( File& F ) { Header Head; std::auto_ptr<detail::TextureImpl> impl( new detail::TextureImpl ); if( !F.Read( Head.mData, sizeof( Header ) ) ) { return NULL; } static uint16_t const MaxSupportedImageSize = 1 << 15; assert( Head.Width() <= MaxSupportedImageSize && Head.Height() <= MaxSupportedImageSize ); impl->mWidth = Head.Width(); impl->mHeight = Head.Height(); assert( Head.PixelDepth() == 24 || Head.PixelDepth() == 32 ); if( Head.PixelDepth() != 24 && Head.PixelDepth() != 32 ) { return NULL; } size_t const ImgSize = impl->mWidth * impl->mHeight; size_t const DataSize = detail::TextureImpl::mChannels * ImgSize; impl->mData.resize( DataSize ); bool Succ; if( Head.PixelDepth() == 32 ) { assert( ( Head.ImageDescriptor() & 15 ) == 8 ); Succ = F.Read( static_cast< void* >( &impl->mData.at( 0 ) ), DataSize ); } else { std::string Buf; size_t const InSize = ImgSize * 3; Succ = F.Read( Buf, InSize ); if( Succ ) { detail::TextureImpl::ConvertRGBtoRGBA( ( uint8_t* )( void* )Buf.c_str(), ImgSize, &impl->mData.at( 0 ) ); } } if( !Succ ) { impl->mData.clear(); return NULL; } else { Reorder( &impl->mData.at( 0 ), ImgSize ); } return impl.release(); } void Reorder( uint8_t* Data, size_t Size ) { for( size_t x = 0; x < Size; x++ ) { unsigned char* pixel_out = &Data[x * 4]; std::swap( pixel_out[0], pixel_out[2] ); } } } // namespace anonymous TgaTexture::TgaTexture( File& F ) { if( F.IsValid() ) { mImpl.reset( Load( F ) ); } } } // namespace platform <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fmpgeimp.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2005-03-18 18:43:38 $ * * 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 _SVX_FMUNOPGE_HXX #define _SVX_FMUNOPGE_HXX #ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_ #include <com/sun/star/sdbc/XDataSource.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_FORM_XFORMCOMPONENT_HPP_ #include <com/sun/star/form/XFormComponent.hpp> #endif #ifndef _COM_SUN_STAR_FORM_XFORM_HPP_ #include <com/sun/star/form/XForm.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/dllapi.h" #endif class SvStream; //BFS01class SdrIOHeader; class FmFormObj; class SdrObject; //FORWARD_DECLARE_INTERFACE(uno,Reference) FORWARD_DECLARE_INTERFACE(io,XObjectOutputStream) FORWARD_DECLARE_INTERFACE(io,XObjectInputStream) FORWARD_DECLARE_INTERFACE(container,XIndexContainer) class SdrObjList; DECLARE_LIST(FmObjectList, FmFormObj*); //================================================================== // FmFormPageImpl // lauscht an allen Containern, um festzustellen, wann Objecte // eingefuegt worden sind und wann diese entfernt wurden //================================================================== class SVX_DLLPRIVATE FmFormPageImpl { friend class FmFormPage; friend class FmFormObj; friend class FmXFormShell; ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> xCurrentForm; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer> m_xForms; FmFormPage* pPage; sal_Bool m_bFirstActivation : 1; sal_Bool m_bAttemptedFormCreation : 2; protected: FmFormPageImpl(FmFormPage* _pPage); FmFormPageImpl(FmFormPage* _pPage, const FmFormPageImpl& rImpl); ~FmFormPageImpl(); void Init(); public: // nur wichtig fuer den DesignMode void setCurForm(::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> xForm); ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> getDefaultForm(); /** inserts a form component into the form component hierarchy If the given component does not yet belong into the form hierarchy, a suitable place for it is found, using <member>findFormForDataSource</member>, if possible. If no sutiable form is found, a new one is created, and also inserted into the hierarchy. */ ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> placeInFormComponentHierarchy( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent>& rContent, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>& rDatabase = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>(), const ::rtl::OUString& rDBTitle = ::rtl::OUString(), const ::rtl::OUString& rCursorSource = ::rtl::OUString(), sal_Int32 nCommandType = 0 ); // activation handling inline sal_Bool hasEverBeenActivated( ) const { return !m_bFirstActivation; } inline void setHasBeenActivated( ) { m_bFirstActivation = sal_False; } protected: // lesen und schreiben der Objecte //BFS01 void WriteData(SvStream& rOut) const; // //BFS01 void ReadData(const SdrIOHeader& rHead, SvStream& rIn); // void write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& OutStream) const; void read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& InStream); const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer>& getForms( bool _bForceCreate = true ); void fillList(FmObjectList& rList, const SdrObjList& rObjList, sal_Bool bConnected) const; /** finds a form with a given data source signature @param rForm the form to start the search with. This form, including all possible sub forms, will be examined @param rDatabase the data source which to which the found form must be bound @param rCommand the desired Command property value of the sought-after form @param nCommandType the desired CommandType property value of the sought-after form */ ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> findFormForDataSource( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm>& rForm, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>& rDatabase, const ::rtl::OUString& rCommand, sal_Int32 nCommandType ); ::rtl::OUString getDefaultName( sal_Int16 _nClassId, const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm>& _rxControls, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XServiceInfo >& _rxObject ) const; private: /** validates whether <member>xCurrentForm</member> is still valid and to be used There are situations where our current form becomes invalid, without us noticing this. Thus, every method which accesses <member>xCurrentForm</member> should beforehand validate the current form by calling this method. If <member>xCurrentForm</member> is not valid anymore, it is reset to <NULL/>. @since #i40086# */ void validateCurForm(); public: static UniString getDefaultName( sal_Int16 nClassId, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XServiceInfo >& _rxObject ); ::rtl::OUString setUniqueName(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent>& xFormComponent, const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm>& xControls); ::rtl::OUString getUniqueName(const ::rtl::OUString& rName, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& xNamedSet) const; }; #endif // _SVX_FMUNOPGE_HXX <commit_msg>INTEGRATION: CWS gcc4fwdecl (1.12.108); FILE MERGED 2005/06/01 18:18:20 pmladek 1.12.108.1: #i50075# Fixed forward declarations for gcc4 in svx<commit_after>/************************************************************************* * * $RCSfile: fmpgeimp.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2005-06-14 16:33:47 $ * * 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 _SVX_FMUNOPGE_HXX #define _SVX_FMUNOPGE_HXX #ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_ #include <com/sun/star/sdbc/XDataSource.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_FORM_XFORMCOMPONENT_HPP_ #include <com/sun/star/form/XFormComponent.hpp> #endif #ifndef _COM_SUN_STAR_FORM_XFORM_HPP_ #include <com/sun/star/form/XForm.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/dllapi.h" #endif class SvStream; //BFS01class SdrIOHeader; class FmFormObj; class FmFormPage; class SdrObject; //FORWARD_DECLARE_INTERFACE(uno,Reference) FORWARD_DECLARE_INTERFACE(io,XObjectOutputStream) FORWARD_DECLARE_INTERFACE(io,XObjectInputStream) FORWARD_DECLARE_INTERFACE(container,XIndexContainer) class SdrObjList; DECLARE_LIST(FmObjectList, FmFormObj*); //================================================================== // FmFormPageImpl // lauscht an allen Containern, um festzustellen, wann Objecte // eingefuegt worden sind und wann diese entfernt wurden //================================================================== class SVX_DLLPRIVATE FmFormPageImpl { friend class FmFormPage; friend class FmFormObj; friend class FmXFormShell; ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> xCurrentForm; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer> m_xForms; FmFormPage* pPage; sal_Bool m_bFirstActivation : 1; sal_Bool m_bAttemptedFormCreation : 2; protected: FmFormPageImpl(FmFormPage* _pPage); FmFormPageImpl(FmFormPage* _pPage, const FmFormPageImpl& rImpl); ~FmFormPageImpl(); void Init(); public: // nur wichtig fuer den DesignMode void setCurForm(::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> xForm); ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> getDefaultForm(); /** inserts a form component into the form component hierarchy If the given component does not yet belong into the form hierarchy, a suitable place for it is found, using <member>findFormForDataSource</member>, if possible. If no sutiable form is found, a new one is created, and also inserted into the hierarchy. */ ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> placeInFormComponentHierarchy( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent>& rContent, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>& rDatabase = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>(), const ::rtl::OUString& rDBTitle = ::rtl::OUString(), const ::rtl::OUString& rCursorSource = ::rtl::OUString(), sal_Int32 nCommandType = 0 ); // activation handling inline sal_Bool hasEverBeenActivated( ) const { return !m_bFirstActivation; } inline void setHasBeenActivated( ) { m_bFirstActivation = sal_False; } protected: // lesen und schreiben der Objecte //BFS01 void WriteData(SvStream& rOut) const; // //BFS01 void ReadData(const SdrIOHeader& rHead, SvStream& rIn); // void write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& OutStream) const; void read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& InStream); const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer>& getForms( bool _bForceCreate = true ); void fillList(FmObjectList& rList, const SdrObjList& rObjList, sal_Bool bConnected) const; /** finds a form with a given data source signature @param rForm the form to start the search with. This form, including all possible sub forms, will be examined @param rDatabase the data source which to which the found form must be bound @param rCommand the desired Command property value of the sought-after form @param nCommandType the desired CommandType property value of the sought-after form */ ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm> findFormForDataSource( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm>& rForm, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>& rDatabase, const ::rtl::OUString& rCommand, sal_Int32 nCommandType ); ::rtl::OUString getDefaultName( sal_Int16 _nClassId, const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm>& _rxControls, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XServiceInfo >& _rxObject ) const; private: /** validates whether <member>xCurrentForm</member> is still valid and to be used There are situations where our current form becomes invalid, without us noticing this. Thus, every method which accesses <member>xCurrentForm</member> should beforehand validate the current form by calling this method. If <member>xCurrentForm</member> is not valid anymore, it is reset to <NULL/>. @since #i40086# */ void validateCurForm(); public: static UniString getDefaultName( sal_Int16 nClassId, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XServiceInfo >& _rxObject ); ::rtl::OUString setUniqueName(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent>& xFormComponent, const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm>& xControls); ::rtl::OUString getUniqueName(const ::rtl::OUString& rName, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& xNamedSet) const; }; #endif // _SVX_FMUNOPGE_HXX <|endoftext|>
<commit_before>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -lpthread -shared-libgcc opencv.cpp -o opencv #include "evision.h" #include "tracer.h" #include "gpio.h" // Global variables GPIO pwm_right(1, "out"), pwm_left(3, "out"); // led_right(2 , "out"); GPIO led_front(5, "out"), led_R(4, "out"), start(7 ,"out"); // 0,2,6 bulit int high_right = 600, high_left = 600, period = 20000; //PWM high time in us int top_edge = 50, servo_offset = 0, road_offset = 0; int car_left_offset = 0, obstacle_offset = 0; // GUI globals cv::Mat guiframe; bool new_frame = false; bool running = true; // Window titles char main_window_name[] = "Lightning Asystant :: Team eVision"; char settings_window_name[] = "Settings :: Team eVision"; // Settings variables int settings_show_step = 0; int settings_contrast = 0; int settings_blur = 1; int settings_threshold = 128; int settings_servo_offset = 500; int settings_road_approx = 5; int settings_middle_line = 240; // Graphics std::vector<std::vector<cv::Point>> contours; //Functions declaration void pwm_servo_right(int); void pwm_servo_left(int); void set_servo_offset(int); void set_road_offset(int); void set_car_left_offset(int); void set_obstacle_offset(int); int main(int argc, char** argv) { pthread_t processing_thread; long time_old; int fps_counter = 0; int gui_key; // for cpu affinity cpu_set_t cpuset; int cpu = 0; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); // process priority setpriority(PRIO_PROCESS, 0, -20); // GUI setup cv::namedWindow(main_window_name); // Setup window cv::namedWindow(settings_window_name); cv::createTrackbar("Show Step ", settings_window_name, &settings_show_step, LAST_STEP-1); cv::createTrackbar("Contrast ", settings_window_name, &settings_contrast, 1); cv::createTrackbar("Mean Blur ", settings_window_name, &settings_blur, 1); cv::createTrackbar("Threshold ", settings_window_name, &settings_threshold, 255); cv::createTrackbar("Road Approx ", settings_window_name, &settings_road_approx, 30); cv::createTrackbar("Middle Line ", settings_window_name, &settings_middle_line, 320); cv::createTrackbar("Servo Offset", settings_window_name, &settings_servo_offset, 1000); cv::createTrackbar("Servo Right ", settings_window_name, &high_right, 1500); cv::createTrackbar("Servo Left ", settings_window_name, &high_left, 1500); pthread_create(&processing_thread, NULL, processing_thread_function, NULL); //pthread_create(&pwm_thread, NULL, pwm_thread_function, NULL); while(running){ while(!new_frame){ } // loop cv::imshow(main_window_name, guiframe); // calculate fps if(time(NULL) != time_old){ add_info(fps_counter); fps_counter = 1; time_old = time(NULL); } else { fps_counter++; } new_frame = 0; gui_key = cv::waitKey(5); if(gui_key >= 0) { gui_key %= 0xFF; // ESC if((gui_key == 43) || (gui_key == 27)){ led_front.low(); led_R.low(); running = false; } else if((gui_key == 48) || (gui_key == 32)) { start.high(); // 1 = start/stop usleep(50000); start.low(); } else if((gui_key == 50) || (gui_key == 66)) { led_front.toggle(); // 2 = faruri } else if((gui_key == 51) || (gui_key == 67)) { led_R.toggle(); // 3 = far pieton } else { std::cout << gui_key << std::endl; } } } pthread_join(processing_thread, NULL); // the camera will be deinitialized automatically in VideoCapture destructor return 0; } void send_frame_to_gui(cv::Mat &frame, int step){ if((new_frame == 0) && (step == settings_show_step)){ //cv::pyrUp(frame, guiframe); frame.copyTo(guiframe); new_frame = 1; } } bool contour_area(int a, int b){ return cv::contourArea(contours[a]) > cv::contourArea(contours[b]); } bool get_obstacle( int parent, std::vector<std::vector<cv::Point>> contours, std::vector<cv::Vec4i> hierarchy, cv::Rect &obstacle){ int start = hierarchy[parent][2]; int closest = -1; bool found = false; while(start > 0){ if(closest == -1){ closest = start; found = true; } else if(cv::boundingRect(contours[start]).y > cv::boundingRect(contours[closest]).y){ closest = start; } start = hierarchy[start][0]; } if(found){ obstacle = cv::boundingRect(contours[closest]); } return found; } void *processing_thread_function(void* unsused) { cv::VideoCapture cap(0); // camera interface cv::Mat frame, cam_frame, bw_frame, blur_frame, contrast_frame; cv::Mat threshold_frame, canny_frame, contour_frame; Tracer processing_tracer; std::vector<std::vector<cv::Point>> road(2); std::vector<cv::Vec4i> hierarchy; // for cpu affinity cpu_set_t cpuset; int cpu = 1; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); if(!cap.isOpened()) // check if we succeeded { std::cout << "Could not open default video device" << std::endl; pthread_exit(NULL); } while(running) { if( !cap.read(frame) ){ std::cout << "Camera was disconected"; break; } cv::pyrDown(frame, cam_frame); send_frame_to_gui(cam_frame, SENSOR_IMAGE); processing_tracer.start(); // All processing are done on gray image cv::cvtColor(cam_frame, bw_frame, CV_BGR2GRAY); processing_tracer.event("Convert to Gray"); send_frame_to_gui(bw_frame, GRAY_IMAGE); // Increase contrast by distributing color histogram to contain all values if(settings_contrast){ cv::equalizeHist(bw_frame, contrast_frame); } else { contrast_frame = bw_frame; } processing_tracer.event("Equalize histogram"); send_frame_to_gui(contrast_frame, CONTRAST_IMAGE); // Apply a special blur filter which preserves edges if(settings_blur){ cv::medianBlur(contrast_frame, blur_frame, 7); } else { blur_frame = contrast_frame; } processing_tracer.event("Median blur"); send_frame_to_gui(blur_frame, BLUR_IMAGE); // detect edges using histeresys cv::Canny(contrast_frame, canny_frame, 30, 100); processing_tracer.event("Edge detection"); send_frame_to_gui(canny_frame, CANNY_IMAGE); // Apply threshhold threshold(blur_frame, threshold_frame, settings_threshold, 255, CV_THRESH_BINARY); // Disable image top from detection to remove false edges cv::rectangle(threshold_frame, cv::Rect(0, 0, 320, top_edge), cv::Scalar(0), CV_FILLED); processing_tracer.event("Appling threshold"); send_frame_to_gui(threshold_frame, THRESHOLD_IMAGE); // detect and paint contours cv::findContours(threshold_frame, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); if(contours.size() > 1){ std::vector<int> contour_indexes(contours.size()); // create index vector for(unsigned int i = 0; i < contours.size(); i++){ contour_indexes[i] = i; } // sorting index vector acording to controur area std::sort(contour_indexes.begin(), contour_indexes.end(), contour_area); cv::approxPolyDP(cv::Mat(contours[contour_indexes[0]]), road[0], settings_road_approx, true); cv::drawContours(cam_frame, road, 0, cv::Scalar(0, 255 ,0), 2); cv::approxPolyDP(cv::Mat(contours[contour_indexes[1]]), road[1], settings_road_approx, true); cv::drawContours(cam_frame, road, 1, cv::Scalar(255, 0, 0), 2); // get road offset int road_tmp = 600; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y == top_edge) && (road[0][i].x < road_tmp)){ road_tmp = road[0][i].x; } } std::cout << road_tmp << std::endl; cv::Rect obstacle; if(get_obstacle(contour_indexes[0], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(0, 0, 255)); std::cout << cv::Point(obstacle.x + (obstacle.width / 2), obstacle.y + (obstacle.height / 2)) << std::endl; } if(get_obstacle(contour_indexes[1], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(255, 0, 255)); } cv::line(cam_frame, cv::Point(settings_middle_line, 320), cv::Point(settings_middle_line, top_edge), cv::Scalar(0, 255, 255)); } processing_tracer.event("Contour detection"); send_frame_to_gui(cam_frame, CONTOUR_IMAGE); pwm_servo_right(high_right); pwm_servo_left(high_left); } processing_tracer.end(); pthread_exit(NULL); } void pwm_servo_right(int h_r){ int static local_hr = 0; if(abs(h_r - local_hr) > 5){ local_hr = h_r; pwm_right.high(); usleep(local_hr); pwm_right.low(); usleep(period - local_hr); } } void pwm_servo_left(int h_l){ int static local_hl = 0; if(abs(h_l - local_hl) > 5){ local_hl = h_l; pwm_left.high(); usleep(local_hl); pwm_left.low(); usleep(period - local_hl); } } void set_servo_offset(int servo_offset){ high_right = high_right + servo_offset; high_left = high_left + servo_offset; } void set_road_offset(int road_offset){ high_right = high_right + road_offset; high_left = high_left + road_offset; } void set_obstacle_offset(int y_position){ obstacle_offset = int (0.9 * y_position + 15); high_right = high_right + obstacle_offset; //de facut dezactivarea obstacle_offset } void set_car_offset(int y_position){ //????? high_left = high_left + car_left_offset; } void add_info(int fps){ // white canvas cv::Mat img_info (25, 320, CV_8UC3, cv::Scalar(255, 255, 255)); cv::putText(img_info, std::string("FPS: ") + std::to_string(fps), cv::Point(5, 20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,0,255), 1, CV_AA); cv::imshow(settings_window_name, img_info); } <commit_msg>Road offset wit limitations, should be between 50 and 250px<commit_after>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -lpthread -shared-libgcc opencv.cpp -o opencv #include "evision.h" #include "tracer.h" #include "gpio.h" // Global variables GPIO pwm_right(1, "out"), pwm_left(3, "out"); // led_right(2 , "out"); GPIO led_front(5, "out"), led_R(4, "out"), start(7 ,"out"); // 0,2,6 bulit int high_right = 600, high_left = 600, period = 20000; //PWM high time in us int top_edge = 50, servo_offset = 0, road_offset = 0; int car_left_offset = 0, obstacle_offset = 0; // GUI globals cv::Mat guiframe; bool new_frame = false; bool running = true; // Window titles char main_window_name[] = "Lightning Asystant :: Team eVision"; char settings_window_name[] = "Settings :: Team eVision"; // Settings variables int settings_show_step = 0; int settings_contrast = 0; int settings_blur = 1; int settings_threshold = 128; int settings_servo_offset = 500; int settings_road_approx = 5; int settings_middle_line = 240; // Graphics std::vector<std::vector<cv::Point>> contours; //Functions declaration void pwm_servo_right(int); void pwm_servo_left(int); void set_servo_offset(int); void set_road_offset(int); void set_car_left_offset(int); void set_obstacle_offset(int); int main(int argc, char** argv) { pthread_t processing_thread; long time_old; int fps_counter = 0; int gui_key; // for cpu affinity cpu_set_t cpuset; int cpu = 0; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); // process priority setpriority(PRIO_PROCESS, 0, -20); // GUI setup cv::namedWindow(main_window_name); // Setup window cv::namedWindow(settings_window_name); cv::createTrackbar("Show Step ", settings_window_name, &settings_show_step, LAST_STEP-1); cv::createTrackbar("Contrast ", settings_window_name, &settings_contrast, 1); cv::createTrackbar("Mean Blur ", settings_window_name, &settings_blur, 1); cv::createTrackbar("Threshold ", settings_window_name, &settings_threshold, 255); cv::createTrackbar("Road Approx ", settings_window_name, &settings_road_approx, 30); cv::createTrackbar("Middle Line ", settings_window_name, &settings_middle_line, 320); cv::createTrackbar("Servo Offset", settings_window_name, &settings_servo_offset, 1000); cv::createTrackbar("Servo Right ", settings_window_name, &high_right, 1500); cv::createTrackbar("Servo Left ", settings_window_name, &high_left, 1500); pthread_create(&processing_thread, NULL, processing_thread_function, NULL); //pthread_create(&pwm_thread, NULL, pwm_thread_function, NULL); while(running){ while(!new_frame){ } // loop cv::imshow(main_window_name, guiframe); // calculate fps if(time(NULL) != time_old){ add_info(fps_counter); fps_counter = 1; time_old = time(NULL); } else { fps_counter++; } new_frame = 0; gui_key = cv::waitKey(5); if(gui_key >= 0) { gui_key %= 0xFF; // ESC if((gui_key == 43) || (gui_key == 27)){ led_front.low(); led_R.low(); running = false; } else if((gui_key == 48) || (gui_key == 32)) { start.high(); // 1 = start/stop usleep(50000); start.low(); } else if((gui_key == 50) || (gui_key == 66)) { led_front.toggle(); // 2 = faruri } else if((gui_key == 51) || (gui_key == 67)) { led_R.toggle(); // 3 = far pieton } else { std::cout << gui_key << std::endl; } } } pthread_join(processing_thread, NULL); // the camera will be deinitialized automatically in VideoCapture destructor return 0; } void send_frame_to_gui(cv::Mat &frame, int step){ if((new_frame == 0) && (step == settings_show_step)){ //cv::pyrUp(frame, guiframe); frame.copyTo(guiframe); new_frame = 1; } } bool contour_area(int a, int b){ return cv::contourArea(contours[a]) > cv::contourArea(contours[b]); } bool get_obstacle( int parent, std::vector<std::vector<cv::Point>> contours, std::vector<cv::Vec4i> hierarchy, cv::Rect &obstacle){ int start = hierarchy[parent][2]; int closest = -1; bool found = false; while(start > 0){ if(closest == -1){ closest = start; found = true; } else if(cv::boundingRect(contours[start]).y > cv::boundingRect(contours[closest]).y){ closest = start; } start = hierarchy[start][0]; } if(found){ obstacle = cv::boundingRect(contours[closest]); } return found; } void *processing_thread_function(void* unsused) { cv::VideoCapture cap(0); // camera interface cv::Mat frame, cam_frame, bw_frame, blur_frame, contrast_frame; cv::Mat threshold_frame, canny_frame, contour_frame; Tracer processing_tracer; std::vector<std::vector<cv::Point>> road(2); std::vector<cv::Vec4i> hierarchy; // for cpu affinity cpu_set_t cpuset; int cpu = 1; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); if(!cap.isOpened()) // check if we succeeded { std::cout << "Could not open default video device" << std::endl; pthread_exit(NULL); } while(running) { if( !cap.read(frame) ){ std::cout << "Camera was disconected"; break; } cv::pyrDown(frame, cam_frame); send_frame_to_gui(cam_frame, SENSOR_IMAGE); processing_tracer.start(); // All processing are done on gray image cv::cvtColor(cam_frame, bw_frame, CV_BGR2GRAY); processing_tracer.event("Convert to Gray"); send_frame_to_gui(bw_frame, GRAY_IMAGE); // Increase contrast by distributing color histogram to contain all values if(settings_contrast){ cv::equalizeHist(bw_frame, contrast_frame); } else { contrast_frame = bw_frame; } processing_tracer.event("Equalize histogram"); send_frame_to_gui(contrast_frame, CONTRAST_IMAGE); // Apply a special blur filter which preserves edges if(settings_blur){ cv::medianBlur(contrast_frame, blur_frame, 7); } else { blur_frame = contrast_frame; } processing_tracer.event("Median blur"); send_frame_to_gui(blur_frame, BLUR_IMAGE); // detect edges using histeresys cv::Canny(contrast_frame, canny_frame, 30, 100); processing_tracer.event("Edge detection"); send_frame_to_gui(canny_frame, CANNY_IMAGE); // Apply threshhold threshold(blur_frame, threshold_frame, settings_threshold, 255, CV_THRESH_BINARY); // Disable image top from detection to remove false edges cv::rectangle(threshold_frame, cv::Rect(0, 0, 320, top_edge), cv::Scalar(0), CV_FILLED); processing_tracer.event("Appling threshold"); send_frame_to_gui(threshold_frame, THRESHOLD_IMAGE); // detect and paint contours cv::findContours(threshold_frame, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); if(contours.size() > 1){ std::vector<int> contour_indexes(contours.size()); // create index vector for(unsigned int i = 0; i < contours.size(); i++){ contour_indexes[i] = i; } // sorting index vector acording to controur area std::sort(contour_indexes.begin(), contour_indexes.end(), contour_area); cv::approxPolyDP(cv::Mat(contours[contour_indexes[0]]), road[0], settings_road_approx, true); cv::drawContours(cam_frame, road, 0, cv::Scalar(0, 255 ,0), 2); cv::approxPolyDP(cv::Mat(contours[contour_indexes[1]]), road[1], settings_road_approx, true); cv::drawContours(cam_frame, road, 1, cv::Scalar(255, 0, 0), 2); // get road offset // reference point is the left most point from the top edge of road contour int new_road_offset = 600; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y == top_edge) && (road[0][i].x < new_road_offset)){ new_road_offset = road[0][i].x; } } if((new_road_offset > 50) && (new_road_offset < 250)){ road_offset = new_road_offset; } std::cout << road_offset << std::endl; cv::Rect obstacle; if(get_obstacle(contour_indexes[0], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(0, 0, 255)); std::cout << cv::Point(obstacle.x + (obstacle.width / 2), obstacle.y + (obstacle.height / 2)) << std::endl; } if(get_obstacle(contour_indexes[1], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(255, 0, 255)); } cv::line(cam_frame, cv::Point(settings_middle_line, 320), cv::Point(settings_middle_line, top_edge), cv::Scalar(0, 255, 255)); } processing_tracer.event("Contour detection"); send_frame_to_gui(cam_frame, CONTOUR_IMAGE); pwm_servo_right(high_right); pwm_servo_left(high_left); } processing_tracer.end(); pthread_exit(NULL); } void pwm_servo_right(int h_r){ int static local_hr = 0; if(abs(h_r - local_hr) > 5){ local_hr = h_r; pwm_right.high(); usleep(local_hr); pwm_right.low(); usleep(period - local_hr); } } void pwm_servo_left(int h_l){ int static local_hl = 0; if(abs(h_l - local_hl) > 5){ local_hl = h_l; pwm_left.high(); usleep(local_hl); pwm_left.low(); usleep(period - local_hl); } } void set_servo_offset(int servo_offset){ high_right = high_right + servo_offset; high_left = high_left + servo_offset; } void set_road_offset(int road_offset){ high_right = high_right + road_offset; high_left = high_left + road_offset; } void set_obstacle_offset(int y_position){ obstacle_offset = int (0.9 * y_position + 15); high_right = high_right + obstacle_offset; //de facut dezactivarea obstacle_offset } void set_car_offset(int y_position){ //????? high_left = high_left + car_left_offset; } void add_info(int fps){ // white canvas cv::Mat img_info (25, 320, CV_8UC3, cv::Scalar(255, 255, 255)); cv::putText(img_info, std::string("FPS: ") + std::to_string(fps), cv::Point(5, 20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,0,255), 1, CV_AA); cv::imshow(settings_window_name, img_info); } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** 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 <QHash> #include <QDebug> #include <QX11Info> #include "windowinfo.h" #include "xtools/xatomcache.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <X11/extensions/Xcomposite.h> #include <X11/extensions/Xdamage.h> class WindowInfo::WindowData { public: //! Constructs a window data object WindowData(Window id) : window(id), transientFor(0), title(), types(), states(), pid(0), pixmapSerial(0) { } //! Destructor ~WindowData() { } //! The X window ID Window window; //! The ID of the window this window is transient for Window transientFor; //! The title of the window QString title; //! The window types associated with this window QList<Atom> types; //! The status atoms of this window QList<Atom> states; int pid; int pixmapSerial; }; //! Storage for the WindowInfo data objects. A central storage enables constructing //! new WindowInfo objects with shared data. static QHash<Window, WindowInfo * > windowDatas; WindowInfo *WindowInfo::windowFor(Qt::HANDLE wid) { if (WindowInfo *wi = windowDatas.value(wid)) { return wi; } else { return new WindowInfo(wid); } } WindowInfo::WindowInfo(Qt::HANDLE window) : d(new WindowData(window)) { qDebug() << Q_FUNC_INFO << "Created WindowInfo for " << window; updateWindowTitle(); updateWindowProperties(); windowDatas[window] = this; } WindowInfo::~WindowInfo() { qDebug() << Q_FUNC_INFO << "Destroyed windwo for " << d->window; windowDatas.remove(d->window); } const QString& WindowInfo::title() const { return d->title; } Qt::HANDLE WindowInfo::window() const { return d->window; } Qt::HANDLE WindowInfo::transientFor() const { return d->transientFor; } QList<Qt::HANDLE> WindowInfo::types() const { return d->types; } QList<Qt::HANDLE> WindowInfo::states() const { return d->states; } bool operator==(const WindowInfo &wi1, const WindowInfo &wi2) { return wi1.window() == wi2.window(); } bool WindowInfo::updateWindowTitle() { Display *dpy = QX11Info::display(); XTextProperty textProperty; bool updated = false; int result = XGetTextProperty(dpy, d->window, &textProperty, AtomCache::atom("_NET_WM_NAME")); if (result == 0) { result = XGetWMName(dpy, d->window, &textProperty); } if (result != 0) { d->title = QString::fromUtf8((const char *)textProperty.value); XFree(textProperty.value); updated = true; } return updated; } void WindowInfo::updateWindowProperties() { d->types = getWindowProperties(d->window, AtomCache::atom("_NET_WM_WINDOW_TYPE")); d->states = getWindowProperties(d->window, AtomCache::atom("_NET_WM_STATE")); if (!XGetTransientForHint(QX11Info::display(), d->window, &d->transientFor) || d->transientFor == d->window) { d->transientFor = 0; } } int WindowInfo::pid() const { return d->pid; } void WindowInfo::setPid(int pid) { d->pid = pid; } QList<Qt::HANDLE> WindowInfo::getWindowProperties(Qt::HANDLE winId, Qt::HANDLE propertyAtom, long maxCount) { QList<Atom> properties; Atom actualType; int actualFormat; unsigned long numTypeItems, bytesLeft; unsigned char *typeData = NULL; Status result = XGetWindowProperty(QX11Info::display(), winId, propertyAtom, 0L, maxCount, False, XA_ATOM, &actualType, &actualFormat, &numTypeItems, &bytesLeft, &typeData); if (result == Success) { Atom *type = (Atom *) typeData; for (unsigned int n = 0; n < numTypeItems; n++) { properties.append(type[n]); } XFree(typeData); } return properties; } Qt::HANDLE WindowInfo::pixmapSerial() const { return d->pixmapSerial; } void WindowInfo::setPixmapSerial(Qt::HANDLE pixmapSerial) { d->pixmapSerial = pixmapSerial; qDebug() << Q_FUNC_INFO << "Changed pixmap serial on " << d->window << " to " << d->pixmapSerial; emit pixmapSerialChanged(); } bool WindowInfo::handleXEvent(const XEvent &event) { if (event.type == PropertyNotify && (event.xproperty.atom == AtomCache::atom("_NET_WM_WINDOW_TYPE") || event.xproperty.atom == AtomCache::atom("_NET_WM_STATE"))) { emit visibleInSwitcherChanged(); return true; } return false; } static QVector<Atom> getNetWmState(Display *display, Window window) { QVector<Atom> atomList; Atom actualType; int actualFormat; ulong propertyLength; ulong bytesLeft; uchar *propertyData = 0; // Step 1: Get the size of the list bool result = XGetWindowProperty(display, window, AtomCache::atom("_NET_WM_STATE"), 0, 0x7fffffff, false, XA_ATOM, &actualType, &actualFormat, &propertyLength, &bytesLeft, &propertyData); if (result != Success || actualType != XA_ATOM || actualFormat != 32) return atomList; XFree(propertyData); atomList.resize(propertyLength); // Step 2: Get the actual list if (!XGetWindowProperty(display, window, AtomCache::atom("_NET_WM_STATE"), 0, atomList.size(), false, XA_ATOM, &actualType, &actualFormat, &propertyLength, &bytesLeft, &propertyData) == Success) { qWarning("Unable to retrieve window properties: %i", (int) window); return atomList; } if (!atomList.isEmpty()) memcpy(atomList.data(), propertyData, atomList.size() * sizeof(Atom)); XFree(propertyData); return atomList; } // TODO: ideally we can cache this and make it a simple getter // updated when properties change. bool WindowInfo::visibleInSwitcher() { Atom actualType; int actualFormat; unsigned char *typeData = NULL; unsigned long numTypeItems; unsigned long bytesLeft; bool result = XGetWindowProperty(QX11Info::display(), d->window, AtomCache::atom("_NET_WM_WINDOW_TYPE"), 0L, 16L, false, XA_ATOM, &actualType, &actualFormat, &numTypeItems, &bytesLeft, &typeData); if (result != Success) return false; Atom *type = (Atom *)typeData; bool includeInWindowList = false; // plain Xlib windows do not have a type if (numTypeItems == 0) includeInWindowList = true; for (unsigned int n = 0; n < numTypeItems; n++) { if (type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_DESKTOP") || type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_NOTIFICATION") || type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_DOCK") || type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_MENU")) { includeInWindowList = false; break; } if (type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_NORMAL")) { includeInWindowList = true; } } XFree(typeData); if (includeInWindowList) { if (getNetWmState(QX11Info::display(), d->window).contains(AtomCache::atom("_NET_WM_STATE_SKIP_TASKBAR"))) { includeInWindowList = false; } } return includeInWindowList; } <commit_msg>Request properties in one go<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** 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 <QHash> #include <QDebug> #include <QX11Info> #include "windowinfo.h" #include "xtools/xatomcache.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <X11/extensions/Xcomposite.h> #include <X11/extensions/Xdamage.h> class WindowInfo::WindowData { public: //! Constructs a window data object WindowData(Window id) : window(id), transientFor(0), title(), types(), states(), pid(0), pixmapSerial(0) { } //! Destructor ~WindowData() { } //! The X window ID Window window; //! The ID of the window this window is transient for Window transientFor; //! The title of the window QString title; //! The window types associated with this window QList<Atom> types; //! The status atoms of this window QList<Atom> states; int pid; int pixmapSerial; }; //! Storage for the WindowInfo data objects. A central storage enables constructing //! new WindowInfo objects with shared data. static QHash<Window, WindowInfo * > windowDatas; WindowInfo *WindowInfo::windowFor(Qt::HANDLE wid) { if (WindowInfo *wi = windowDatas.value(wid)) { return wi; } else { return new WindowInfo(wid); } } WindowInfo::WindowInfo(Qt::HANDLE window) : d(new WindowData(window)) { qDebug() << Q_FUNC_INFO << "Created WindowInfo for " << window; updateWindowTitle(); updateWindowProperties(); windowDatas[window] = this; } WindowInfo::~WindowInfo() { qDebug() << Q_FUNC_INFO << "Destroyed windwo for " << d->window; windowDatas.remove(d->window); } const QString& WindowInfo::title() const { return d->title; } Qt::HANDLE WindowInfo::window() const { return d->window; } Qt::HANDLE WindowInfo::transientFor() const { return d->transientFor; } QList<Qt::HANDLE> WindowInfo::types() const { return d->types; } QList<Qt::HANDLE> WindowInfo::states() const { return d->states; } bool operator==(const WindowInfo &wi1, const WindowInfo &wi2) { return wi1.window() == wi2.window(); } bool WindowInfo::updateWindowTitle() { Display *dpy = QX11Info::display(); XTextProperty textProperty; bool updated = false; int result = XGetTextProperty(dpy, d->window, &textProperty, AtomCache::atom("_NET_WM_NAME")); if (result == 0) { result = XGetWMName(dpy, d->window, &textProperty); } if (result != 0) { d->title = QString::fromUtf8((const char *)textProperty.value); XFree(textProperty.value); updated = true; } return updated; } void WindowInfo::updateWindowProperties() { d->types = getWindowProperties(d->window, AtomCache::atom("_NET_WM_WINDOW_TYPE")); d->states = getWindowProperties(d->window, AtomCache::atom("_NET_WM_STATE")); if (!XGetTransientForHint(QX11Info::display(), d->window, &d->transientFor) || d->transientFor == d->window) { d->transientFor = 0; } } int WindowInfo::pid() const { return d->pid; } void WindowInfo::setPid(int pid) { d->pid = pid; } QList<Qt::HANDLE> WindowInfo::getWindowProperties(Qt::HANDLE winId, Qt::HANDLE propertyAtom, long maxCount) { QList<Atom> properties; Atom actualType; int actualFormat; unsigned long numTypeItems, bytesLeft; unsigned char *typeData = NULL; Status result = XGetWindowProperty(QX11Info::display(), winId, propertyAtom, 0L, maxCount, False, XA_ATOM, &actualType, &actualFormat, &numTypeItems, &bytesLeft, &typeData); if (result == Success) { Atom *type = (Atom *) typeData; for (unsigned int n = 0; n < numTypeItems; n++) { properties.append(type[n]); } XFree(typeData); } return properties; } Qt::HANDLE WindowInfo::pixmapSerial() const { return d->pixmapSerial; } void WindowInfo::setPixmapSerial(Qt::HANDLE pixmapSerial) { d->pixmapSerial = pixmapSerial; qDebug() << Q_FUNC_INFO << "Changed pixmap serial on " << d->window << " to " << d->pixmapSerial; emit pixmapSerialChanged(); } bool WindowInfo::handleXEvent(const XEvent &event) { if (event.type == PropertyNotify && (event.xproperty.atom == AtomCache::atom("_NET_WM_WINDOW_TYPE") || event.xproperty.atom == AtomCache::atom("_NET_WM_STATE"))) { emit visibleInSwitcherChanged(); return true; } return false; } static QVector<Atom> getNetWmState(Display *display, Window window) { QVector<Atom> atomList; Atom actualType; int actualFormat; ulong propertyLength; ulong bytesLeft; uchar *propertyData = 0; bool result = XGetWindowProperty(display, window, AtomCache::atom("_NET_WM_STATE"), 0, 12L, false, XA_ATOM, &actualType, &actualFormat, &propertyLength, &bytesLeft, &propertyData); if (result != Success || actualType != XA_ATOM || actualFormat != 32) { if (propertyData) { XFree(propertyData); } return atomList; } atomList.resize(propertyLength); if (!atomList.isEmpty()) memcpy(atomList.data(), propertyData, atomList.size() * sizeof(Atom)); XFree(propertyData); return atomList; } // TODO: ideally we can cache this and make it a simple getter // updated when properties change. bool WindowInfo::visibleInSwitcher() { Atom actualType; int actualFormat; unsigned char *typeData = NULL; unsigned long numTypeItems; unsigned long bytesLeft; bool result = XGetWindowProperty(QX11Info::display(), d->window, AtomCache::atom("_NET_WM_WINDOW_TYPE"), 0L, 16L, false, XA_ATOM, &actualType, &actualFormat, &numTypeItems, &bytesLeft, &typeData); if (result != Success) return false; Atom *type = (Atom *)typeData; bool includeInWindowList = false; // plain Xlib windows do not have a type if (numTypeItems == 0) includeInWindowList = true; for (unsigned int n = 0; n < numTypeItems; n++) { if (type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_DESKTOP") || type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_NOTIFICATION") || type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_DOCK") || type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_MENU")) { includeInWindowList = false; break; } if (type[n] == AtomCache::atom("_NET_WM_WINDOW_TYPE_NORMAL")) { includeInWindowList = true; } } XFree(typeData); if (includeInWindowList) { if (getNetWmState(QX11Info::display(), d->window).contains(AtomCache::atom("_NET_WM_STATE_SKIP_TASKBAR"))) { includeInWindowList = false; } } return includeInWindowList; } <|endoftext|>
<commit_before>#include "server_state_game.hpp" #include "server_state_idle.hpp" #include "server_instance.hpp" #include <filesystem.hpp> namespace server { namespace state { game::game(server::instance& serv) : base(serv, server::state_id::game, "game") { // TODO: add all game components to this container save_chunks_.push_back(universe_.make_serializer()); } void game::register_callbacks() { pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::game_save>&& req) { try { save_to_directory(req.arg.save); req.answer(); } catch (request::server::game_save::failure& fail) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } req.fail(std::move(fail)); } catch (...) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } out_.error("unexpected exception in game::save_to_directory()"); throw; } }); pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::game_load>&& req) { try { load_from_directory(req.arg.save); req.answer(); } catch (request::server::game_load::failure& fail) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } req.fail(std::move(fail)); } catch (...) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } out_.error("unexpected exception in game::load_from_directory()"); throw; } }); pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::stop_and_idle>&& req) { serv_.set_state<server::state::idle>(); req.answer(); }); } void game::set_player_list(std::unique_ptr<server::player_list> plist) { plist_ = std::move(plist); } void game::save_to_directory(const std::string& dir) { using failure = request::server::game_save::failure; if (saving_) { throw failure{failure::reason::already_saving, ""}; } saving_ = true; // Block the game and bake all game data into serializable structures net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::gathering_game_data )); for (auto& c : save_chunks_) { c.save_data(); } // Save to disk in the background net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::saving_to_disk )); thread_ = std::thread([this, dir]() { for (auto& c : save_chunks_) { c.serialize(dir); } // Clear buffers for (auto& c : save_chunks_) { c.clear(); } net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::game_saved )); saving_ = false; }); } void game::load_from_directory(const std::string& dir) { using failure = request::server::game_load::failure; // The whole game will be blocked during the operation. if (saving_) { throw failure{failure::reason::cannot_load_while_saving, ""}; } if (!file::exists(dir)) { throw failure{failure::reason::no_such_saved_game, ""}; } if (!is_saved_game_directory(dir)) { throw failure{failure::reason::invalid_saved_game, ""}; } // NOTE: One might need to clear the game state before std::uint16_t s = 0; std::uint16_t nchunk = save_chunks_.size(); for (auto& c : save_chunks_) { net_.send_message(netcom::all_actor_id, make_packet<message::server::game_load_progress>( nchunk, s, c.name() )); c.deserialize(dir); c.load_data_first_pass(); ++s; } net_.send_message(netcom::all_actor_id, make_packet<message::server::game_load_progress>( nchunk, nchunk, "loading_second_pass" )); // A two pass loading is needed for some components for (auto& c : save_chunks_) { c.load_data_second_pass(); } // Clear buffers for (auto& c : save_chunks_) { c.clear(); } } bool game::is_saved_game_directory(const std::string& dir) const { for (auto& c : save_chunks_) { if (!c.is_valid_directory(dir)) { return false; } } return true; } } } <commit_msg>Fixed loading failing<commit_after>#include "server_state_game.hpp" #include "server_state_idle.hpp" #include "server_instance.hpp" #include <filesystem.hpp> namespace server { namespace state { game::game(server::instance& serv) : base(serv, server::state_id::game, "game"), saving_(false) { // TODO: add all game components to this container save_chunks_.push_back(universe_.make_serializer()); } void game::register_callbacks() { pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::game_save>&& req) { try { save_to_directory(req.arg.save); req.answer(); } catch (request::server::game_save::failure& fail) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } req.fail(std::move(fail)); } catch (...) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } out_.error("unexpected exception in game::save_to_directory()"); throw; } }); pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::game_load>&& req) { try { load_from_directory(req.arg.save); req.answer(); } catch (request::server::game_load::failure& fail) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } req.fail(std::move(fail)); } catch (...) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } out_.error("unexpected exception in game::load_from_directory()"); throw; } }); pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::stop_and_idle>&& req) { serv_.set_state<server::state::idle>(); req.answer(); }); } void game::set_player_list(std::unique_ptr<server::player_list> plist) { plist_ = std::move(plist); } void game::save_to_directory(const std::string& dir) { using failure = request::server::game_save::failure; if (saving_) { throw failure{failure::reason::already_saving, ""}; } saving_ = true; // Block the game and bake all game data into serializable structures net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::gathering_game_data )); for (auto& c : save_chunks_) { c.save_data(); } // Save to disk in the background net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::saving_to_disk )); thread_ = std::thread([this, dir]() { for (auto& c : save_chunks_) { c.serialize(dir); } // Clear buffers for (auto& c : save_chunks_) { c.clear(); } net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::game_saved )); saving_ = false; }); } void game::load_from_directory(const std::string& dir) { using failure = request::server::game_load::failure; // The whole game will be blocked during the operation. if (saving_) { throw failure{failure::reason::cannot_load_while_saving, ""}; } if (!file::exists(dir)) { throw failure{failure::reason::no_such_saved_game, ""}; } if (!is_saved_game_directory(dir)) { throw failure{failure::reason::invalid_saved_game, ""}; } // NOTE: One might need to clear the game state before std::uint16_t s = 0; std::uint16_t nchunk = save_chunks_.size(); for (auto& c : save_chunks_) { net_.send_message(netcom::all_actor_id, make_packet<message::server::game_load_progress>( nchunk, s, c.name() )); c.deserialize(dir); c.load_data_first_pass(); ++s; } net_.send_message(netcom::all_actor_id, make_packet<message::server::game_load_progress>( nchunk, nchunk, "loading_second_pass" )); // A two pass loading is needed for some components for (auto& c : save_chunks_) { c.load_data_second_pass(); } // Clear buffers for (auto& c : save_chunks_) { c.clear(); } } bool game::is_saved_game_directory(const std::string& dir) const { for (auto& c : save_chunks_) { if (!c.is_valid_directory(dir)) { return false; } } return true; } } } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ #undef UNICODE #undef _UNICODE #define _WIN32_WINDOWS 0x0410 #ifdef _MSC_VER #pragma warning(push, 1) /* disable warnings within system headers */ #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <msiquery.h> #include <shellapi.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <malloc.h> #include <assert.h> #include <string.h> #ifdef UNICODE #define _UNICODE #define _tstring wstring #else #define _tstring string #endif #include <tchar.h> #include <string> /** creates a temporary folder with a unique name. The returned string is a file URL. */ static std::_tstring createTempFolder() { BOOL bExist = FALSE; TCHAR szTempName[MAX_PATH]; do { bExist = FALSE; // Get the temp path. TCHAR lpPathBuffer[MAX_PATH]; DWORD dwRetVal = GetTempPath(MAX_PATH, lpPathBuffer); if (dwRetVal > MAX_PATH || (dwRetVal == 0)) { //fprintf (stderr, "GetTempPath failed with error %d.\n", GetLastError()); return TEXT(""); } // Create a temporary file. UINT uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files "upg", // temp file name prefix 0, // create unique name szTempName); // buffer for name if (uRetVal == 0) { //fprintf (stderr, "GetTempFileName failed with error %d.\n", GetLastError()); return TEXT(""); } //Delete the file BOOL bDel = DeleteFile(szTempName); if (FALSE == bDel) { //fprintf(stderr, "Could not delete temp file. Error %d.\n", GetLastError()); return TEXT(""); } // Create the directory BOOL bDir = CreateDirectory(szTempName, NULL); if (FALSE == bDir) { DWORD error =GetLastError(); if (ERROR_ALREADY_EXISTS == error) { bExist = TRUE; } else { //fprintf(stderr, "CreateDirectory failed with error %d.\n", error); return TEXT(""); } } } while(bExist); std::_tstring cur(szTempName); //make a file URL from the path std::_tstring ret(TEXT("file:///")); for (std::_tstring::iterator i = cur.begin(); i != cur.end(); i++) { if (*i == '\\') ret.append(TEXT("/")); else ret.push_back(*i); } // MessageBox(NULL, ret.c_str(), "createTempFolder", MB_OK); return ret.c_str(); } /** deletes the temporary folder. The argument must be a file URL. */ static void deleteTempFolder(const std::_tstring& sTempFolder) { if (sTempFolder.size() == 0) return; //convert the file URL to a path const std::_tstring path(sTempFolder.substr(8)); std::_tstring path2; // MessageBox(NULL, path.c_str(), "del1", MB_OK); for (std::_tstring::const_iterator i = path.begin(); i != path.end(); i++) { if (*i == '/') path2.append(TEXT("\\")); else path2.push_back(*i); } //We need a null terminated string with two nulls in the end //for the SHFILEOPSTRUCT const TCHAR * szTemp = path2.c_str(); size_t size = path2.size(); TCHAR * szTemp2 = new TCHAR[size + 2]; ZeroMemory(szTemp2, (size + 2) * sizeof(TCHAR)); memcpy(szTemp2, szTemp, size * sizeof(TCHAR)); // MessageBox(NULL, szTemp2, "del3", MB_OK); SHFILEOPSTRUCT operation = { NULL, FO_DELETE, szTemp2, NULL, FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR, FALSE, NULL, NULL }; SHFileOperation( &operation); delete [] szTemp2; } static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty ) { std::_tstring result; TCHAR szDummy[1] = TEXT(""); DWORD nChars = 0; if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA ) { DWORD nBytes = ++nChars * sizeof(TCHAR); LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes)); ZeroMemory( buffer, nBytes ); MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars); result = buffer; } return result; } /* creates a child process which is specified in lpCommand. out_exitCode is the exit code of the child process **/ static BOOL ExecuteCommand( LPCTSTR lpCommand, DWORD * out_exitCode) { BOOL fSuccess = FALSE; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); fSuccess = CreateProcess( NULL, (LPTSTR)lpCommand, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ); if ( fSuccess ) { WaitForSingleObject( pi.hProcess, INFINITE ); if (!GetExitCodeProcess( pi.hProcess, out_exitCode)) fSuccess = FALSE; CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); } return fSuccess; } static BOOL RemoveCompleteDirectory( std::_tstring sPath ) { bool bDirectoryRemoved = true; std::_tstring mystr; std::_tstring sPattern = sPath + TEXT("\\") + TEXT("*.*"); WIN32_FIND_DATA aFindData; // Finding all content in sPath HANDLE hFindContent = FindFirstFile( sPattern.c_str(), &aFindData ); if ( hFindContent != INVALID_HANDLE_VALUE ) { bool fNextFile = false; do { std::_tstring sFileName = aFindData.cFileName; std::_tstring sCurrentDir = TEXT("."); std::_tstring sParentDir = TEXT(".."); mystr = "Current short file: " + sFileName; // MessageBox(NULL, mystr.c_str(), "Current Content", MB_OK); if (( strcmp(sFileName.c_str(),sCurrentDir.c_str()) != 0 ) && ( strcmp(sFileName.c_str(),sParentDir.c_str()) != 0 )) { std::_tstring sCompleteFileName = sPath + TEXT("\\") + sFileName; if ( aFindData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY ) { bool fSuccess = RemoveCompleteDirectory(sCompleteFileName); if ( fSuccess ) { mystr = "Successfully removed content of dir " + sCompleteFileName; // MessageBox(NULL, mystr.c_str(), "Removed Directory", MB_OK); } else { mystr = "An error occured during removing content of " + sCompleteFileName; // MessageBox(NULL, mystr.c_str(), "Error removing directory", MB_OK); } } else { bool fSuccess = DeleteFile( sCompleteFileName.c_str() ); if ( fSuccess ) { mystr = "Successfully removed file " + sCompleteFileName; // MessageBox(NULL, mystr.c_str(), "Removed File", MB_OK); } else { mystr = "An error occured during removal of file " + sCompleteFileName; // MessageBox(NULL, mystr.c_str(), "Error removing file", MB_OK); } } } fNextFile = FindNextFile( hFindContent, &aFindData ); } while ( fNextFile ); FindClose( hFindContent ); // empty directory can be removed now // RemoveDirectory is only successful, if the last handle to the directory is closed // -> first removing content -> closing handle -> remove empty directory bool fRemoveDirSuccess = RemoveDirectory(sPath.c_str()); if ( fRemoveDirSuccess ) { mystr = "Successfully removed dir " + sPath; // MessageBox(NULL, mystr.c_str(), "Removed Directory", MB_OK); } else { mystr = "An error occured during removal of empty directory " + sPath; // MessageBox(NULL, mystr.c_str(), "Error removing directory", MB_OK); bDirectoryRemoved = false; } } return bDirectoryRemoved; } extern "C" UINT __stdcall RegisterExtensions(MSIHANDLE handle) { std::_tstring sInstDir = GetMsiProperty( handle, TEXT("INSTALLLOCATION") ); std::_tstring sUnoPkgFile = sInstDir + TEXT("program\\unopkg.exe"); std::_tstring mystr; WIN32_FIND_DATA aFindFileData; mystr = "unopkg file: " + sUnoPkgFile; //MessageBox(NULL, mystr.c_str(), "Command", MB_OK); // Find unopkg.exe HANDLE hFindUnopkg = FindFirstFile( sUnoPkgFile.c_str(), &aFindFileData ); if ( hFindUnopkg != INVALID_HANDLE_VALUE ) { // unopkg.exe exists in program directory const std::_tstring sTempFolder(createTempFolder()); std::_tstring sCommandPart1 = sUnoPkgFile + " sync"; std::_tstring sCommand = sCommandPart1 + TEXT(" -env:BUNDLED_EXTENSIONS_USER=$BRAND_BASE_DIR/share/prereg/bundled") + TEXT(" -env:UNO_JAVA_JFW_INSTALL_DATA=$OOO_BASE_DIR/share/config/javasettingsunopkginstall.xml") + TEXT(" -env:UserInstallation=") + sTempFolder; mystr = "Command: " + sCommand; //MessageBox(NULL, mystr.c_str(), "Command", MB_OK); DWORD exitCode = 0; bool fSuccess = ExecuteCommand( sCommand.c_str(), & exitCode); deleteTempFolder(sTempFolder); // if ( fSuccess ) // { // mystr = "Executed successfully!"; // MessageBox(NULL, mystr.c_str(), "Command", MB_OK); // } // else // { // mystr = "An error occured during execution!"; // MessageBox(NULL, mystr.c_str(), "Command", MB_OK); // } FindClose( hFindUnopkg ); } // else // { // mystr = "Error: Did not find " + sUnoPkgFile; // MessageBox(NULL, mystr.c_str(), "Command", MB_OK); // } return ERROR_SUCCESS; } extern "C" UINT __stdcall RemoveExtensions(MSIHANDLE handle) { std::_tstring mystr; // Finding the product with the help of the propery FINDPRODUCT, // that contains a Windows Registry key, that points to the install location. TCHAR szValue[8192]; DWORD nValueSize = sizeof(szValue); HKEY hKey; std::_tstring sInstDir; std::_tstring sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") ); //MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK ); if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER, sProductKey.c_str(), &hKey ) ) { if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) ) { sInstDir = szValue; } RegCloseKey( hKey ); } else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, sProductKey.c_str(), &hKey ) ) { if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) ) { sInstDir = szValue; } RegCloseKey( hKey ); } else { return ERROR_SUCCESS; } // Removing complete directory "Basis\presets\bundled" std::_tstring sCacheDir = sInstDir + TEXT("Basis\\presets\\bundled"); bool fSuccess = RemoveCompleteDirectory( sCacheDir ); // if ( fSuccess ) // { // mystr = "Executed successfully!"; // MessageBox(NULL, mystr.c_str(), "Main methode", MB_OK); // } // else // { // mystr = "An error occured during execution!"; // MessageBox(NULL, mystr.c_str(), "Main methode", MB_OK); // } return ERROR_SUCCESS; } <commit_msg>jl154 #i162868# changed RemoveExtensions custom action (windows) to delete brand/share/prereg/bundled<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ #undef UNICODE #undef _UNICODE #define _WIN32_WINDOWS 0x0410 #ifdef _MSC_VER #pragma warning(push, 1) /* disable warnings within system headers */ #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <msiquery.h> #include <shellapi.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <malloc.h> #include <assert.h> #include <string.h> #ifdef UNICODE #define _UNICODE #define _tstring wstring #else #define _tstring string #endif #include <tchar.h> #include <string> /** creates a temporary folder with a unique name. The returned string is a file URL. */ static std::_tstring createTempFolder() { BOOL bExist = FALSE; TCHAR szTempName[MAX_PATH]; do { bExist = FALSE; // Get the temp path. TCHAR lpPathBuffer[MAX_PATH]; DWORD dwRetVal = GetTempPath(MAX_PATH, lpPathBuffer); if (dwRetVal > MAX_PATH || (dwRetVal == 0)) { //fprintf (stderr, "GetTempPath failed with error %d.\n", GetLastError()); return TEXT(""); } // Create a temporary file. UINT uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files "upg", // temp file name prefix 0, // create unique name szTempName); // buffer for name if (uRetVal == 0) { //fprintf (stderr, "GetTempFileName failed with error %d.\n", GetLastError()); return TEXT(""); } //Delete the file BOOL bDel = DeleteFile(szTempName); if (FALSE == bDel) { //fprintf(stderr, "Could not delete temp file. Error %d.\n", GetLastError()); return TEXT(""); } // Create the directory BOOL bDir = CreateDirectory(szTempName, NULL); if (FALSE == bDir) { DWORD error =GetLastError(); if (ERROR_ALREADY_EXISTS == error) { bExist = TRUE; } else { //fprintf(stderr, "CreateDirectory failed with error %d.\n", error); return TEXT(""); } } } while(bExist); std::_tstring cur(szTempName); //make a file URL from the path std::_tstring ret(TEXT("file:///")); for (std::_tstring::iterator i = cur.begin(); i != cur.end(); i++) { if (*i == '\\') ret.append(TEXT("/")); else ret.push_back(*i); } // MessageBox(NULL, ret.c_str(), "createTempFolder", MB_OK); return ret.c_str(); } /** deletes the temporary folder. The argument must be a file URL. */ static void deleteTempFolder(const std::_tstring& sTempFolder) { if (sTempFolder.size() == 0) return; //convert the file URL to a path const std::_tstring path(sTempFolder.substr(8)); std::_tstring path2; // MessageBox(NULL, path.c_str(), "del1", MB_OK); for (std::_tstring::const_iterator i = path.begin(); i != path.end(); i++) { if (*i == '/') path2.append(TEXT("\\")); else path2.push_back(*i); } //We need a null terminated string with two nulls in the end //for the SHFILEOPSTRUCT const TCHAR * szTemp = path2.c_str(); size_t size = path2.size(); TCHAR * szTemp2 = new TCHAR[size + 2]; ZeroMemory(szTemp2, (size + 2) * sizeof(TCHAR)); memcpy(szTemp2, szTemp, size * sizeof(TCHAR)); // MessageBox(NULL, szTemp2, "del3", MB_OK); SHFILEOPSTRUCT operation = { NULL, FO_DELETE, szTemp2, NULL, FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR, FALSE, NULL, NULL }; SHFileOperation( &operation); delete [] szTemp2; } static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty ) { std::_tstring result; TCHAR szDummy[1] = TEXT(""); DWORD nChars = 0; if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA ) { DWORD nBytes = ++nChars * sizeof(TCHAR); LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes)); ZeroMemory( buffer, nBytes ); MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars); result = buffer; } return result; } /* creates a child process which is specified in lpCommand. out_exitCode is the exit code of the child process **/ static BOOL ExecuteCommand( LPCTSTR lpCommand, DWORD * out_exitCode) { BOOL fSuccess = FALSE; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); fSuccess = CreateProcess( NULL, (LPTSTR)lpCommand, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ); if ( fSuccess ) { WaitForSingleObject( pi.hProcess, INFINITE ); if (!GetExitCodeProcess( pi.hProcess, out_exitCode)) fSuccess = FALSE; CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); } return fSuccess; } static BOOL RemoveCompleteDirectory( std::_tstring sPath ) { bool bDirectoryRemoved = true; std::_tstring mystr; std::_tstring sPattern = sPath + TEXT("\\") + TEXT("*.*"); WIN32_FIND_DATA aFindData; // Finding all content in sPath HANDLE hFindContent = FindFirstFile( sPattern.c_str(), &aFindData ); if ( hFindContent != INVALID_HANDLE_VALUE ) { bool fNextFile = false; do { std::_tstring sFileName = aFindData.cFileName; std::_tstring sCurrentDir = TEXT("."); std::_tstring sParentDir = TEXT(".."); mystr = "Current short file: " + sFileName; // MessageBox(NULL, mystr.c_str(), "Current Content", MB_OK); if (( strcmp(sFileName.c_str(),sCurrentDir.c_str()) != 0 ) && ( strcmp(sFileName.c_str(),sParentDir.c_str()) != 0 )) { std::_tstring sCompleteFileName = sPath + TEXT("\\") + sFileName; if ( aFindData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY ) { bool fSuccess = RemoveCompleteDirectory(sCompleteFileName); if ( fSuccess ) { mystr = "Successfully removed content of dir " + sCompleteFileName; // MessageBox(NULL, mystr.c_str(), "Removed Directory", MB_OK); } else { mystr = "An error occured during removing content of " + sCompleteFileName; // MessageBox(NULL, mystr.c_str(), "Error removing directory", MB_OK); } } else { bool fSuccess = DeleteFile( sCompleteFileName.c_str() ); if ( fSuccess ) { mystr = "Successfully removed file " + sCompleteFileName; // MessageBox(NULL, mystr.c_str(), "Removed File", MB_OK); } else { mystr = "An error occured during removal of file " + sCompleteFileName; // MessageBox(NULL, mystr.c_str(), "Error removing file", MB_OK); } } } fNextFile = FindNextFile( hFindContent, &aFindData ); } while ( fNextFile ); FindClose( hFindContent ); // empty directory can be removed now // RemoveDirectory is only successful, if the last handle to the directory is closed // -> first removing content -> closing handle -> remove empty directory bool fRemoveDirSuccess = RemoveDirectory(sPath.c_str()); if ( fRemoveDirSuccess ) { mystr = "Successfully removed dir " + sPath; // MessageBox(NULL, mystr.c_str(), "Removed Directory", MB_OK); } else { mystr = "An error occured during removal of empty directory " + sPath; // MessageBox(NULL, mystr.c_str(), "Error removing directory", MB_OK); bDirectoryRemoved = false; } } return bDirectoryRemoved; } extern "C" UINT __stdcall RegisterExtensions(MSIHANDLE handle) { std::_tstring sInstDir = GetMsiProperty( handle, TEXT("INSTALLLOCATION") ); std::_tstring sUnoPkgFile = sInstDir + TEXT("program\\unopkg.exe"); std::_tstring mystr; WIN32_FIND_DATA aFindFileData; mystr = "unopkg file: " + sUnoPkgFile; //MessageBox(NULL, mystr.c_str(), "Command", MB_OK); // Find unopkg.exe HANDLE hFindUnopkg = FindFirstFile( sUnoPkgFile.c_str(), &aFindFileData ); if ( hFindUnopkg != INVALID_HANDLE_VALUE ) { // unopkg.exe exists in program directory const std::_tstring sTempFolder(createTempFolder()); std::_tstring sCommandPart1 = sUnoPkgFile + " sync"; std::_tstring sCommand = sCommandPart1 + TEXT(" -env:BUNDLED_EXTENSIONS_USER=$BRAND_BASE_DIR/share/prereg/bundled") + TEXT(" -env:UNO_JAVA_JFW_INSTALL_DATA=$OOO_BASE_DIR/share/config/javasettingsunopkginstall.xml") + TEXT(" -env:UserInstallation=") + sTempFolder; mystr = "Command: " + sCommand; //MessageBox(NULL, mystr.c_str(), "Command", MB_OK); DWORD exitCode = 0; bool fSuccess = ExecuteCommand( sCommand.c_str(), & exitCode); deleteTempFolder(sTempFolder); // if ( fSuccess ) // { // mystr = "Executed successfully!"; // MessageBox(NULL, mystr.c_str(), "Command", MB_OK); // } // else // { // mystr = "An error occured during execution!"; // MessageBox(NULL, mystr.c_str(), "Command", MB_OK); // } FindClose( hFindUnopkg ); } // else // { // mystr = "Error: Did not find " + sUnoPkgFile; // MessageBox(NULL, mystr.c_str(), "Command", MB_OK); // } return ERROR_SUCCESS; } extern "C" UINT __stdcall RemoveExtensions(MSIHANDLE handle) { std::_tstring mystr; // Finding the product with the help of the propery FINDPRODUCT, // that contains a Windows Registry key, that points to the install location. TCHAR szValue[8192]; DWORD nValueSize = sizeof(szValue); HKEY hKey; std::_tstring sInstDir; std::_tstring sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") ); //MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK ); if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER, sProductKey.c_str(), &hKey ) ) { if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) ) { sInstDir = szValue; } RegCloseKey( hKey ); } else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, sProductKey.c_str(), &hKey ) ) { if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) ) { sInstDir = szValue; } RegCloseKey( hKey ); } else { return ERROR_SUCCESS; } // Removing complete directory "Basis\presets\bundled" std::_tstring sCacheDir = sInstDir + TEXT("share\\prereg\\bundled"); bool fSuccess = RemoveCompleteDirectory( sCacheDir ); // if ( fSuccess ) // { // mystr = "Executed successfully!"; // MessageBox(NULL, mystr.c_str(), "Main methode", MB_OK); // } // else // { // mystr = "An error occured during execution!"; // MessageBox(NULL, mystr.c_str(), "Main methode", MB_OK); // } return ERROR_SUCCESS; } <|endoftext|>
<commit_before> // RcpMaker #include "Spectra/PidDataMaker.h" #include "Correction/SpectraCorrecter.h" // ROOT #include "TLine.h" // STL #define _USE_MATH_DEFINES #include <cmath> // for M_1_PI etc. void PidDataMaker::initialize() { InclusiveSpectra::initialize(); /** * Initialize the Phase Space Recentering Object */ tofSigmaIdeal = config.getDouble( nodePath+".ZRecentering.sigma:tof", 0.011); dedxSigmaIdeal = config.getDouble( nodePath+".ZRecentering.sigma:dedx", 0.033); zr = new ZRecentering( dedxSigmaIdeal, tofSigmaIdeal, config.getString( nodePath+".Bichsel.table", "dedxBichsel.root"), config.getInt( nodePath+".Bichsel.method", 0) ); // method for phase space recentering zrMethod = config.getString( nodePath + ".ZRecentering.method", "traditional" ); // alias the centered species for ease of use centerSpecies = config.getString( nodePath + ".ZRecentering.centerSpecies", "K" ); //Make the momentum transverse binning binsPt = unique_ptr<HistoBins>(new HistoBins( config, "binning.pt" )); // Get the list of charges we are looking at charges = config.getIntVector( "binning.charges" ); // apply corrections now at a tack-by-track level? trackBytrackCorrs = config.getBool( nodePath + ":trackBytrackCorrs", true ); INFO( classname(), "Applying Track by Track params : " << bts( trackBytrackCorrs )); if ( trackBytrackCorrs ){ // Efficiency corrector sc = unique_ptr<SpectraCorrecter>( new SpectraCorrecter( config, nodePath ) ); tpcSysNSigma = config.getDouble( nodePath + ".TpcEff:systematics", 0 ); INFO( classname(), "Systematic uncertainty on TpcEff = " << tpcSysNSigma << " sigma" ); } // make the energy loss params vector<int> charges = { -1, 1 }; if ( config.exists( nodePath + ".EnergyLossParams:path" ) ){ string path = config.getString( nodePath + ".EnergyLossParams:path" ); for ( int c : charges ){ string cfgName = path + centerSpecies + "_" + Common::chargeString( c ) + ".xml"; XmlConfig cfgEL( cfgName ); for ( int cb : config.getIntVector( nodePath + ".CentralityBins" ) ){ // Name like 'Pi_p_0' ... 'Pi_n_6' to be used for quick lookup string name = centerSpecies + "_" + Common::chargeString( c ) +"_" + ts( cb ); elParams[ name ] = unique_ptr<EnergyLossParams>( new EnergyLossParams(&cfgEL, "EnergyLossParams[" + ts(cb) + "]") ); } } } } PidDataMaker::~PidDataMaker(){ } void PidDataMaker::preEventLoop() { INFO( classname(), ""); InclusiveSpectra::preEventLoop(); book->cd(); // make the energy loss histograms book->cd( "energyLoss" ); for ( int c : charges ){ for ( int cb : centralityBins ) { book->clone( "/", "corrPt", "energyLoss", "corrPt_" + Common::chargeString(c) + "_" + ts(cb) ); } } for ( int c : charges ) { for ( string plc : Common::species ){ for ( int cb : centralityBins ) { for ( int iPt = 0; iPt < binsPt->nBins(); iPt++ ){ // create a PidPoint string nname = Common::speciesName( centerSpecies, c, cb, iPt ); pidPoints[ nname ] = unique_ptr<TNtuple>( new TNtuple( nname.c_str(), "PidData", "zb:zd:w" ) ); } } } } } void PidDataMaker::postEventLoop() { INFO( classname(), ""); book->cd(); // write the PidData trees to the file book->cd( "PidPoints" ); for ( auto &k : pidPoints ){ k.second->Write( k.first.c_str() ); } } void PidDataMaker::analyzeTofTrack( int iTrack ){ InclusiveSpectra::analyzeTofTrack( iTrack ); book->cd(); // Alias Track Traits int charge = pico->trackCharge( iTrack ); double pt = pico->trackPt( iTrack ); double p = pico->trackP( iTrack ); double eta = pico->trackEta( iTrack ); trackPt = pt; // saved for whole track calculations /************ Energy Loss Corrections **********/ // Apply Energy Loss Corrections if given string elName = centerSpecies + "_" + Common::chargeString( charge ) +"_" + ts( cBin ); if ( elParams.count( elName ) ){ double corrPt = pt - elParams[ elName ]->eval( pt ); // QA book->cd( "energyLoss" ); book->fill( "corrPt_" + Common::chargeString( charge ) + "_" + ts(cBin), pt, pt - corrPt ); book->cd( ); // recalc the p from corrPt and eta p = Common::p( corrPt, eta ); pt = corrPt; } else { ERROR( classname(), "No Energy Loss Params Given - These must be applied here" ) } /************ Energy Loss Corrections **********/ // Must be done after corrections int ptBin = binsPt->findBin( pt ); corrTrackPt = pt; double avgP = binAverageP( ptBin ); // Require valid p bin if ( ptBin < 0 ){ // only caused by pT outside of range we are interested in DEBUG( classname(), "invalid ptBin = " << ptBin << " pT = " << pt << ", track pT = " << trackPt ); return; } double ptBinWidth = binsPt->binWidth( ptBin ); book->cd(); // Traditionally Recentered values double tof = zr->rTof(centerSpecies, pico->trackBeta(iTrack), p ); double dedx = zr->rDedx(centerSpecies, pico->trackDedx(iTrack), p ); // Non-Linearly Recentered values double tofNL = zr->nlTof(centerSpecies, pico->trackBeta(iTrack), p, avgP ); double dedxNL = zr->nlDedx(centerSpecies, pico->trackDedx(iTrack), p, avgP ); // Choose recentered values if ( "nonlinear" == zrMethod ){ tof = tofNL; dedx = dedxNL; } // event weight from RefMult correction double trackWeight = eventWeight; if ( trackBytrackCorrs ){ trackWeight = trackWeight * M_1_PI * 0.5; // 1.0 / ( 2 pi ) trackWeight = trackWeight * ( 1.0 / corrTrackPt ); // 1.0 / pT trackWeight = trackWeight * ( 1.0 / ptBinWidth ); // 1.0 / ( bin width ) trackWeight = trackWeight * ( 1.0 / ( cut_rapidity->max - cut_rapidity->min ) ); // 1.0 / dy // correct for TPC matching efficiency trackWeight = trackWeight * sc->tpcEffWeight( centerSpecies, corrTrackPt, cBin, charge, tpcSysNSigma ); } // fill the tree string name = Common::speciesName( centerSpecies, charge, cBin, ptBin ); pidPoints[ name ]->Fill( tof, dedx, trackWeight ); book->cd(); } <commit_msg>debug messages for PidDataMaker<commit_after> // RcpMaker #include "Spectra/PidDataMaker.h" #include "Correction/SpectraCorrecter.h" // ROOT #include "TLine.h" // STL #define _USE_MATH_DEFINES #include <cmath> // for M_1_PI etc. void PidDataMaker::initialize() { InclusiveSpectra::initialize(); /** * Initialize the Phase Space Recentering Object */ tofSigmaIdeal = config.getDouble( nodePath+".ZRecentering.sigma:tof", 0.011); dedxSigmaIdeal = config.getDouble( nodePath+".ZRecentering.sigma:dedx", 0.033); zr = new ZRecentering( dedxSigmaIdeal, tofSigmaIdeal, config.getString( nodePath+".Bichsel.table", "dedxBichsel.root"), config.getInt( nodePath+".Bichsel.method", 0) ); // method for phase space recentering zrMethod = config.getString( nodePath + ".ZRecentering.method", "traditional" ); // alias the centered species for ease of use centerSpecies = config.getString( nodePath + ".ZRecentering.centerSpecies", "K" ); //Make the momentum transverse binning binsPt = unique_ptr<HistoBins>(new HistoBins( config, "binning.pt" )); // Get the list of charges we are looking at charges = config.getIntVector( "binning.charges" ); // apply corrections now at a tack-by-track level? trackBytrackCorrs = config.getBool( nodePath + ":trackBytrackCorrs", true ); INFO( classname(), "Applying Track by Track params : " << bts( trackBytrackCorrs )); if ( trackBytrackCorrs ){ // Efficiency corrector sc = unique_ptr<SpectraCorrecter>( new SpectraCorrecter( config, nodePath ) ); tpcSysNSigma = config.getDouble( nodePath + ".TpcEff:systematics", 0 ); INFO( classname(), "Systematic uncertainty on TpcEff = " << tpcSysNSigma << " sigma" ); } // make the energy loss params vector<int> charges = { -1, 1 }; if ( config.exists( nodePath + ".EnergyLossParams:path" ) ){ string path = config.getString( nodePath + ".EnergyLossParams:path" ); for ( int c : charges ){ string cfgName = path + centerSpecies + "_" + Common::chargeString( c ) + ".xml"; XmlConfig cfgEL( cfgName ); for ( int cb : config.getIntVector( nodePath + ".CentralityBins" ) ){ // Name like 'Pi_p_0' ... 'Pi_n_6' to be used for quick lookup string name = centerSpecies + "_" + Common::chargeString( c ) +"_" + ts( cb ); elParams[ name ] = unique_ptr<EnergyLossParams>( new EnergyLossParams(&cfgEL, "EnergyLossParams[" + ts(cb) + "]") ); } } } } PidDataMaker::~PidDataMaker(){ } void PidDataMaker::preEventLoop() { INFO( classname(), ""); InclusiveSpectra::preEventLoop(); book->cd(); // make the energy loss histograms book->cd( "energyLoss" ); for ( int c : charges ){ for ( int cb : centralityBins ) { book->clone( "/", "corrPt", "energyLoss", "corrPt_" + Common::chargeString(c) + "_" + ts(cb) ); } } for ( int c : charges ) { for ( string plc : Common::species ){ for ( int cb : centralityBins ) { for ( int iPt = 0; iPt < binsPt->nBins(); iPt++ ){ // create a PidPoint string nname = Common::speciesName( centerSpecies, c, cb, iPt ); pidPoints[ nname ] = unique_ptr<TNtuple>( new TNtuple( nname.c_str(), "PidData", "zb:zd:w" ) ); } } } } } void PidDataMaker::postEventLoop() { INFO( classname(), ""); book->cd(); // write the PidData trees to the file book->cd( "PidPoints" ); for ( auto &k : pidPoints ){ k.second->Write( k.first.c_str() ); } } void PidDataMaker::analyzeTofTrack( int iTrack ){ InclusiveSpectra::analyzeTofTrack( iTrack ); book->cd(); // Alias Track Traits int charge = pico->trackCharge( iTrack ); double pt = pico->trackPt( iTrack ); double p = pico->trackP( iTrack ); double eta = pico->trackEta( iTrack ); trackPt = pt; // saved for whole track calculations /************ Energy Loss Corrections **********/ // Apply Energy Loss Corrections if given string elName = centerSpecies + "_" + Common::chargeString( charge ) +"_" + ts( cBin ); if ( elParams.count( elName ) ){ double corrPt = pt - elParams[ elName ]->eval( pt ); // QA book->cd( "energyLoss" ); book->fill( "corrPt_" + Common::chargeString( charge ) + "_" + ts(cBin), pt, pt - corrPt ); book->cd( ); // recalc the p from corrPt and eta p = Common::p( corrPt, eta ); pt = corrPt; } else { ERROR( classname(), "No Energy Loss Params Given - These must be applied here" ) } /************ Energy Loss Corrections **********/ // Must be done after corrections int ptBin = binsPt->findBin( pt ); corrTrackPt = pt; double avgP = binAverageP( ptBin ); // Require valid p bin if ( ptBin < 0 ){ // only caused by pT outside of range we are interested in DEBUG( classname(), "invalid ptBin = " << ptBin << " pT = " << pt << ", track pT = " << trackPt ); return; } double ptBinWidth = binsPt->binWidth( ptBin ); book->cd(); // Traditionally Recentered values double tof = zr->rTof(centerSpecies, pico->trackBeta(iTrack), p ); double dedx = zr->rDedx(centerSpecies, pico->trackDedx(iTrack), p ); // Non-Linearly Recentered values double tofNL = zr->nlTof(centerSpecies, pico->trackBeta(iTrack), p, avgP ); double dedxNL = zr->nlDedx(centerSpecies, pico->trackDedx(iTrack), p, avgP ); // Choose recentered values if ( "nonlinear" == zrMethod ){ tof = tofNL; dedx = dedxNL; } // event weight from RefMult correction double trackWeight = eventWeight; if ( trackBytrackCorrs ){ trackWeight = trackWeight * M_1_PI * 0.5; // 1.0 / ( 2 pi ) trackWeight = trackWeight * ( 1.0 / corrTrackPt ); // 1.0 / pT trackWeight = trackWeight * ( 1.0 / ptBinWidth ); // 1.0 / ( bin width ) trackWeight = trackWeight * ( 1.0 / ( cut_rapidity->max - cut_rapidity->min ) ); // 1.0 / dy // correct for TPC matching efficiency trackWeight = trackWeight * sc->tpcEffWeight( centerSpecies, corrTrackPt, cBin, charge, tpcSysNSigma ); if ( ptBin == 12 ){ INFO( classname(), "pT = " << corrTrackPt ); INFO( classname(), "pTBinWidth = " << ptBinWidth ); INFO( classname(), "dy = " << ( cut_rapidity->max - cut_rapidity->min ) ); INFO( classname(), "tpcEff = " << (1.0 / sc->tpcEffWeight( centerSpecies, corrTrackPt, cBin, charge, tpcSysNSigma )) ); INFO( classname(), "w = " << trackWeight ); } } // fill the tree string name = Common::speciesName( centerSpecies, charge, cBin, ptBin ); pidPoints[ name ]->Fill( tof, dedx, trackWeight ); book->cd(); } <|endoftext|>
<commit_before>#ifndef MOBS_HPP #define MOBS_HPP #include <iostream> { public: mob(std::string, std::string std::string, int, int, int, int); void setName(std::string); void setArea(std::string); void setSkill(std::string); void setLevel(int); void setEXP(int); void setHP(int); void setMaxHealth(int); void setDamage(); void setEXP(); std::string getName; std::string getArea; int getLevel(); int getEXP(); int getHP(); int getMaxHealth(); int getDamage(); int getEXP(); private: std::string mobName; std::string mobArea; int mobLevel; int mobHealth; int mobMaxHealth; int mobDamage; int mobEXP; }; #endif <commit_msg>Update mobs.hpp<commit_after>#ifndef MOBS_HPP #define MOBS_HPP #include <iostream> class Mob { public: mob(std::string, std::string std::string, int, int, int, int); void setName(std::string); void setArea(std::string); void setSkill(std::string); void setLevel(int); void setEXP(int); void setHP(int); void setMaxHealth(int); void setDamage(); void setEXP(); std::string getName; std::string getArea; int getLevel(); int getEXP(); int getHP(); int getMaxHealth(); int getDamage(); int getEXP(); private: std::string mobName; std::string mobArea; int mobLevel; int mobHealth; int mobMaxHealth; int mobDamage; int mobEXP; }; #endif <|endoftext|>
<commit_before>#ifndef DATAMANAGER_H #define DATAMANAGER_H #include "StdIncl.hpp" #include "types/Data.hpp" #include "InvalidConfigException.hpp" #include "Utils.hpp" namespace uipf{ using namespace std; // Provides and controls access to Parameters, Input and Outputdata class DataManager { public: DataManager(std::map < std::string, Data::ptr& >& input, std::map < std::string,std::string >& params, std::map < std::string, Data::ptr >& output) :input_(input),params_(params),output_(output) {} ~DataManager(){} //returns a typesafe readonly smartpointer to input/output data by name if it is available template <typename T> const T* getInputData( const std::string& strName) const; //returns a typesafe smartpointer to input/output data by name if it is available template <typename T> T* getOutputData( const std::string& strName) const; //returns a typesafe smartpointer to input/output data by name if it is available template <typename T> void setOutputData( const std::string& strName, T*) ; //returns a typesafe parameter by name if it is available. otherwise a defaultValue is used template <typename T> T getParam(const std::string& strName, T defaultValue) const; //print given parameters void listParams( ) const; private: std::map < std::string, Data::ptr& >& input_; std::map < std::string, std::string >& params_; std::map < std::string, Data::ptr >& output_; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //templates need to be implemented in headers template <typename T> const T* DataManager::getInputData( const std::string& strName) const { if (input_.find(strName) != input_.end()) { //do downcasting.. Data::ptr& ptr = input_.find(strName)->second; return dynamic_cast<T*>(ptr.get()); } else { throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!")); } } template <typename T> T* DataManager::getOutputData( const std::string& strName) const { if (output_.find(strName) != output_.end()) { //do downcasting.. Data::ptr& ptr = output_.find(strName)->second; return dynamic_cast<T*>(ptr.get()); } else { throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!")); } } template <typename T> void DataManager::setOutputData( const std::string& strName, T* outputData) { output_.insert (pair < string, Data::ptr >(strName, typename T::ptr(outputData))); } //2DO other type specialisations e.g. float with atof() etc. template <typename T> T DataManager::getParam( const std::string& strName, T defaultValue) const { if (params_.find(strName) != params_.end()) { return static_cast<T>(params_[strName]); } else { return defaultValue; } } template <> inline int DataManager::getParam( const std::string& strName, int defaultValue) const { if (params_.find(strName) != params_.end()) { return atoi(params_[strName].c_str()); } else { return defaultValue; } } template <> inline float DataManager::getParam(const std::string& strName, float defaultValue) const { if (params_.find(strName) != params_.end()) { return atof(params_[strName].c_str()); } else { return defaultValue; } } template <> inline double DataManager::getParam( const std::string& strName, double defaultValue) const { if (params_.find(strName) != params_.end()) { return atof(params_[strName].c_str()); } else { return defaultValue; } } template <> inline bool DataManager::getParam( const std::string& strName, bool defaultValue) const { if (params_.find(strName) != params_.end()) { return (utils::toLower(params_[strName]).compare("true")==0); } else { return defaultValue; } } } //namespace #endif // DATAMANAGER_H <commit_msg>shared pointers issue #56<commit_after>#ifndef DATAMANAGER_H #define DATAMANAGER_H #include "StdIncl.hpp" #include "types/Data.hpp" #include "InvalidConfigException.hpp" #include "Utils.hpp" namespace uipf{ using namespace std; // Provides and controls access to Parameters, Input and Outputdata class DataManager { public: DataManager(std::map < std::string, Data::ptr& >& input, std::map < std::string,std::string >& params, std::map < std::string, Data::ptr >& output) :input_(input),params_(params),output_(output) {} ~DataManager(){} //returns a typesafe readonly smartpointer to input/output data by name if it is available template <typename T> const typename T::ptr getInputData( const std::string& strName) const; //returns a typesafe smartpointer to input/output data by name if it is available template <typename T> typename T::ptr getOutputData( const std::string& strName) const; //returns a typesafe smartpointer to input/output data by name if it is available template <typename T> void setOutputData( const std::string& strName, T*) ; //returns a typesafe parameter by name if it is available. otherwise a defaultValue is used template <typename T> T getParam(const std::string& strName, T defaultValue) const; //print given parameters void listParams( ) const; private: std::map < std::string, Data::ptr& >& input_; std::map < std::string, std::string >& params_; std::map < std::string, Data::ptr >& output_; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //templates need to be implemented in headers template <typename T> const typename T::ptr DataManager::getInputData( const std::string& strName) const { if (input_.find(strName) != input_.end()) { //do downcasting.. Data::ptr& ptr = input_.find(strName)->second; return std::dynamic_pointer_cast<T>(ptr); } else { throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!")); } } template <typename T> typename T::ptr DataManager::getOutputData( const std::string& strName) const { if (output_.find(strName) != output_.end()) { //do downcasting.. Data::ptr& ptr = input_.find(strName)->second; return std::dynamic_pointer_cast<T>(ptr); } else { throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!")); } } template <typename T> void DataManager::setOutputData( const std::string& strName, T* outputData) { output_.insert (pair < string, Data::ptr >(strName, typename T::ptr(outputData))); } //2DO other type specialisations e.g. float with atof() etc. template <typename T> T DataManager::getParam( const std::string& strName, T defaultValue) const { if (params_.find(strName) != params_.end()) { return static_cast<T>(params_[strName]); } else { return defaultValue; } } template <> inline int DataManager::getParam( const std::string& strName, int defaultValue) const { if (params_.find(strName) != params_.end()) { return atoi(params_[strName].c_str()); } else { return defaultValue; } } template <> inline float DataManager::getParam(const std::string& strName, float defaultValue) const { if (params_.find(strName) != params_.end()) { return atof(params_[strName].c_str()); } else { return defaultValue; } } template <> inline double DataManager::getParam( const std::string& strName, double defaultValue) const { if (params_.find(strName) != params_.end()) { return atof(params_[strName].c_str()); } else { return defaultValue; } } template <> inline bool DataManager::getParam( const std::string& strName, bool defaultValue) const { if (params_.find(strName) != params_.end()) { return (utils::toLower(params_[strName]).compare("true")==0); } else { return defaultValue; } } } //namespace #endif // DATAMANAGER_H <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2020 Antti Nuortimo. // // This program 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. // // 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 <https://www.gnu.org/licenses/>. #ifndef PI #define PI 3.14159265359f #endif #ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS #define DEGREES_TO_RADIANS(x) (x * PI / 180.0f) #endif #ifndef RADIANS_TO_DEGREES #define RADIANS_TO_DEGREES(x) (x * 180.0f / PI) #endif #include "gpgpu_test_scene.hpp" #include "code/ylikuutio/snippets/keyboard_callback_snippets.hpp" #include "code/ylikuutio/input/input.hpp" #include "code/ylikuutio/callback/callback_object.hpp" #include "code/ylikuutio/callback/callback_engine.hpp" #include "code/ylikuutio/callback/callback_magic_numbers.hpp" #include "code/ylikuutio/command_line/command_line_master.hpp" #include "code/ylikuutio/ontology/universe.hpp" #include "code/ylikuutio/ontology/font2D.hpp" #include "code/ylikuutio/ontology/world.hpp" #include "code/ylikuutio/ontology/world_struct.hpp" #include "code/ylikuutio/ontology/scene.hpp" #include "code/ylikuutio/ontology/shader.hpp" #include "code/ylikuutio/ontology/shader_struct.hpp" #include "code/ylikuutio/ontology/entity_factory.hpp" #include "code/ylikuutio/opengl/opengl.hpp" #include "code/ylikuutio/time/time.hpp" // Include GLEW #include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc. #define SDL_main main #include "SDL.h" // Include standard headers #include <exception> // try, catch, std::exception #include <iostream> // std::cout, std::cin, std::cerr #include <sstream> // std::istringstream, std::ostringstream, std::stringstream int main(const int argc, const char* const argv[]) try { yli::command_line::CommandLineMaster command_line_master(argc, argv); if (command_line_master.is_key("version")) { std::cout << "GPGPU test " << yli::ontology::Universe::version << ", powered by Ylikuutio " << yli::ontology::Universe::version << "\n"; return 0; } command_line_master.print_keys_and_values(); // Create the `Universe`, store it in `my_universe`. std::cout << "Creating yli::ontology::Entity* my_universe_entity ...\n"; yli::ontology::UniverseStruct universe_struct; std::stringstream window_title_stringstream; window_title_stringstream << "GPGPU test " << yli::ontology::Universe::version << ", powered by Ylikuutio " << yli::ontology::Universe::version; universe_struct.window_title = window_title_stringstream.str(); universe_struct.window_width = 512; universe_struct.window_height = 512; yli::ontology::Universe* const my_universe = new yli::ontology::Universe(universe_struct); my_universe->set_global_name("universe"); yli::ontology::EntityFactory* const entity_factory = my_universe->get_entity_factory(); std::cout << "Creating yli::callback::CallbackEngine cleanup_callback_engine ...\n"; yli::callback::CallbackEngine cleanup_callback_engine = yli::callback::CallbackEngine(); cleanup_callback_engine.create_callback_object(nullptr); if (my_universe->get_window() == nullptr) { std::cerr << "Failed to open SDL window.\n"; return -1; } // Initialize GLEW. if (!yli::opengl::init_glew()) { cleanup_callback_engine.execute(nullptr); return -1; } yli::input::disable_cursor(); yli::input::enable_relative_mouse_mode(); // Enable depth test. yli::opengl::enable_depth_test(); // Accept fragment if it closer to the camera than the former one. yli::opengl::set_depth_func_to_less(); // Cull triangles which normal is not towards the camera. yli::opengl::cull_triangles(); // Create the `World`. yli::ontology::WorldStruct world_struct; std::cout << "Creating yli::ontology::Entity* gpgpu_test_world_entity ...\n"; yli::ontology::Entity* const gpgpu_test_world_entity = entity_factory->create_world(world_struct); std::cout << "Creating yli::ontology::World* gpgpu_test_world ...\n"; yli::ontology::World* const gpgpu_test_world = dynamic_cast<yli::ontology::World*>(gpgpu_test_world_entity); if (gpgpu_test_world == nullptr) { return -1; } // Create the `Scene`s. // GPGPU test `Scene` begins here. std::cout << "Creating yli::ontology::Entity* gpgpu_test_scene_entity and its contents ...\n"; yli::ontology::Entity* const gpgpu_test_scene_entity = gpgpu_test::create_gpgpu_test_scene(entity_factory, gpgpu_test_world); if (gpgpu_test_scene_entity == nullptr) { return -1; } std::cout << "Creating yli::ontology::Scene* gpgpu_test_scene ...\n"; yli::ontology::Scene* const gpgpu_test_scene = dynamic_cast<yli::ontology::Scene*>(gpgpu_test_scene_entity); if (gpgpu_test_scene == nullptr) { cleanup_callback_engine.execute(nullptr); return -1; } // Set `gpgpu_test_scene` to be the currently active `Scene`. std::cout << "Setting gpgpu_test_scene as the active scene ...\n"; my_universe->set_active_scene(gpgpu_test_scene); // GPGPU test `Scene` ends here. // Clear the screen. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render the `Universe`. my_universe->render(); // do cleanup. cleanup_callback_engine.execute(nullptr); return 0; } catch (const std::exception& exception) { std::cerr << "ERROR: exception: " << exception.what() << "\n"; } <commit_msg>GPGPU test: remove obsolete cleanup code.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2020 Antti Nuortimo. // // This program 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. // // 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 <https://www.gnu.org/licenses/>. #ifndef PI #define PI 3.14159265359f #endif #ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS #define DEGREES_TO_RADIANS(x) (x * PI / 180.0f) #endif #ifndef RADIANS_TO_DEGREES #define RADIANS_TO_DEGREES(x) (x * 180.0f / PI) #endif #include "gpgpu_test_scene.hpp" #include "code/ylikuutio/snippets/keyboard_callback_snippets.hpp" #include "code/ylikuutio/input/input.hpp" #include "code/ylikuutio/callback/callback_object.hpp" #include "code/ylikuutio/callback/callback_magic_numbers.hpp" #include "code/ylikuutio/command_line/command_line_master.hpp" #include "code/ylikuutio/ontology/universe.hpp" #include "code/ylikuutio/ontology/font2D.hpp" #include "code/ylikuutio/ontology/world.hpp" #include "code/ylikuutio/ontology/world_struct.hpp" #include "code/ylikuutio/ontology/scene.hpp" #include "code/ylikuutio/ontology/shader.hpp" #include "code/ylikuutio/ontology/shader_struct.hpp" #include "code/ylikuutio/ontology/entity_factory.hpp" #include "code/ylikuutio/opengl/opengl.hpp" #include "code/ylikuutio/time/time.hpp" // Include GLEW #include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc. #define SDL_main main #include "SDL.h" // Include standard headers #include <exception> // try, catch, std::exception #include <iostream> // std::cout, std::cin, std::cerr #include <sstream> // std::istringstream, std::ostringstream, std::stringstream int main(const int argc, const char* const argv[]) try { yli::command_line::CommandLineMaster command_line_master(argc, argv); if (command_line_master.is_key("version")) { std::cout << "GPGPU test " << yli::ontology::Universe::version << ", powered by Ylikuutio " << yli::ontology::Universe::version << "\n"; return 0; } command_line_master.print_keys_and_values(); // Create the `Universe`, store it in `my_universe`. std::cout << "Creating yli::ontology::Entity* my_universe_entity ...\n"; yli::ontology::UniverseStruct universe_struct; std::stringstream window_title_stringstream; window_title_stringstream << "GPGPU test " << yli::ontology::Universe::version << ", powered by Ylikuutio " << yli::ontology::Universe::version; universe_struct.window_title = window_title_stringstream.str(); universe_struct.window_width = 512; universe_struct.window_height = 512; yli::ontology::Universe* const my_universe = new yli::ontology::Universe(universe_struct); my_universe->set_global_name("universe"); yli::ontology::EntityFactory* const entity_factory = my_universe->get_entity_factory(); if (my_universe->get_window() == nullptr) { std::cerr << "Failed to open SDL window.\n"; return -1; } // Initialize GLEW. if (!yli::opengl::init_glew()) { return -1; } yli::input::disable_cursor(); yli::input::enable_relative_mouse_mode(); // Enable depth test. yli::opengl::enable_depth_test(); // Accept fragment if it closer to the camera than the former one. yli::opengl::set_depth_func_to_less(); // Cull triangles which normal is not towards the camera. yli::opengl::cull_triangles(); // Create the `World`. yli::ontology::WorldStruct world_struct; std::cout << "Creating yli::ontology::Entity* gpgpu_test_world_entity ...\n"; yli::ontology::Entity* const gpgpu_test_world_entity = entity_factory->create_world(world_struct); std::cout << "Creating yli::ontology::World* gpgpu_test_world ...\n"; yli::ontology::World* const gpgpu_test_world = dynamic_cast<yli::ontology::World*>(gpgpu_test_world_entity); if (gpgpu_test_world == nullptr) { return -1; } // Create the `Scene`s. // GPGPU test `Scene` begins here. std::cout << "Creating yli::ontology::Entity* gpgpu_test_scene_entity and its contents ...\n"; yli::ontology::Entity* const gpgpu_test_scene_entity = gpgpu_test::create_gpgpu_test_scene(entity_factory, gpgpu_test_world); if (gpgpu_test_scene_entity == nullptr) { return -1; } std::cout << "Creating yli::ontology::Scene* gpgpu_test_scene ...\n"; yli::ontology::Scene* const gpgpu_test_scene = dynamic_cast<yli::ontology::Scene*>(gpgpu_test_scene_entity); if (gpgpu_test_scene == nullptr) { return -1; } // Set `gpgpu_test_scene` to be the currently active `Scene`. std::cout << "Setting gpgpu_test_scene as the active scene ...\n"; my_universe->set_active_scene(gpgpu_test_scene); // GPGPU test `Scene` ends here. // Clear the screen. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render the `Universe`. my_universe->render(); return 0; } catch (const std::exception& exception) { std::cerr << "ERROR: exception: " << exception.what() << "\n"; } <|endoftext|>
<commit_before>#include "TChain.h" #include "TFile.h" #include "TH1F.h" #include "TH2F.h" #include "TLorentzVector.h" #include <iostream> #include "x.h" #include "TCanvas.h" #include <math.h> #include <set> #include "TString.h" #include "TSystem.h" using namespace mini; const double PI = 4.0*atan(1.0); #include "TH1.h" #include "TH2.h" void fakerate(TString const& _input) { std::cout<<_input<<std::endl; TChain eventVars("eventVars");//define eventVars tree eventVars.Add("./"+_input+".root/eventVars"); TChain selectedObjects("selectedObjects"); //define eventVars tree selectedObjects.Add("./"+_input+".root/selectedObjects"); TChain allObjects("allObjects"); //define eventVars tree allObjects.Add("./"+_input+".root/allObjects"); allObjects.AddFriend("selectedObjects"); allObjects.AddFriend("eventVars"); //define variables bool hlt0; bool hlt1; float met; float metPhi; photon p, rp; muon m, rm; electron e, re; jet j, rj; genparticle gp; //link the branches to the variables defined above //this is where you add variables relevant to your analysis eventVars.SetBranchAddress("met", &met); eventVars.SetBranchAddress("metPhi", &metPhi); eventVars.SetBranchAddress("HLT_Photon70_CaloIdXL_PFHT400", &hlt0); eventVars.SetBranchAddress("HLT_Photon70_CaloIdXL_PFNoPUHT400", &hlt1); p.setAddress(selectedObjects); m.setAddress(selectedObjects); e.setAddress(selectedObjects); j.setAddress(selectedObjects); rp.setAddress(allObjects); re.setAddress(allObjects); rm.setAddress(allObjects); rj.setAddress(allObjects); gp.setAddress(eventVars); TH1F* h_N_tG = new TH1F("h_N_tG", "tight G Pt", 10, 0., 10.); TH1F* h_N_lE = new TH1F("h_N_lE", "Loose e Pt", 10, 0., 10.); TH1F* h_N_tE = new TH1F("h_N_tE", "Tight e Pt", 10, 0., 10.); TH1F* h_all_lE_pt = new TH1F("h_all_lE_pt", "Loose e Pt", 10, 0., 10.); TH1F* h_all_tE_pt = new TH1F("h_all_tE_pt", "Tight e Pt", 10, 0., 10.); TH1F* h_all_tG_pt = new TH1F("h_all_tG_pt", "Tight G Pt", 10, 0., 10.); TH1F* h_lE_pt = new TH1F("h_lE_pt", "Loose e Pt", 30, 0., 300.); TH1F* h_tE_pt = new TH1F("h_tE_pt", "Tight e Pt", 30, 0., 300.); TH1F* h_fE_pt = new TH1F("h_fE_pt", "Fail-tight e Pt", 30, 0., 300.); h_lE_pt->Sumw2(); h_tE_pt->Sumw2(); h_fE_pt->Sumw2(); TH1F* h_lE1_pt = new TH1F("h_lE1_pt", "Loose e Pt", 30, 0., 300.); TH1F* h_tE1_pt = new TH1F("h_tE1_pt", "Tight e Pt", 30, 0., 300.); TH1F* h_fE1_pt = new TH1F("h_fE1_pt", "Fail-tight e Pt", 30, 0., 300.); h_lE1_pt->Sumw2(); h_tE1_pt->Sumw2(); h_fE1_pt->Sumw2(); unsigned nCnt[20] = {0}; //loop over events long iEntry = 0; while(allObjects.GetEntry(iEntry++) != 0){ nCnt[0]++; std::set<unsigned> lE; std::set<unsigned> tE; std::set<unsigned> lG; std::set<unsigned>::iterator it; for(unsigned k(0);k<re.size;k++) { if(re.iSubdet[k]!=0) continue; if(re.isLoose[k]) { lE.insert(k); h_all_lE_pt->Fill(re.pt[k]); } if(re.isTight[k]) { tE.insert(k); h_all_tE_pt->Fill(re.pt[k]); } } h_N_lE->Fill(lE.size()); h_N_tE->Fill(tE.size()); for(unsigned k(0);k<rp.size;k++) { if (!p.isLoose[k]) continue; lG.insert(k); h_all_tG_pt->Fill(rp.pt[k]); } h_N_tG->Fill(lG.size()); //consider event with only 1 loose electron if(lE.size()!=1) continue; it = lE.begin(); ///remove electron close to a loose photon h_lE_pt->Fill(re.pt[*it]); if(tE.size()==1) { h_tE_pt->Fill(re.pt[*it]); } else {//did not pass tight h_fE_pt->Fill(re.pt[*it]); } int checkDR(0); for (std::set<unsigned int>::iterator ik=lG.begin(); ik!=lG.end(); ++ik) { if(deltaR(rp.eta[*ik],rp.phi[*ik],re.eta[*it],re.phi[*it])<0.1) { checkDR++; } } if(checkDR) continue; float MT = mini::mt(met,metPhi,re.pt[*it],re.phi[*it]); //if(MT>25.) continue; h_lE1_pt->Fill(re.pt[*it]); if(tE.size()==1) { h_tE1_pt->Fill(re.pt[*it]); } else {//did not pass tight h_fE1_pt->Fill(re.pt[*it]); } }//while TCanvas *plots = new TCanvas("plots","fake rate plots",800,800); plots->Divide(2,2); plots->cd(1); h_lE_pt->Draw(); h_tE_pt->Draw("same"); plots->cd(3); TH1F *h3 = (TH1F*)h_tE_pt->Clone("h3"); h3->Divide(h_lE_pt); h3->Draw("e"); plots->cd(2); h_lE1_pt->Draw(); h_tE1_pt->Draw("same"); plots->cd(4); TH1F *h4 = (TH1F*)h_tE1_pt->Clone("h3"); h4->Divide(h_lE1_pt); h4->Draw("e"); //h_lE_pt->Draw(); //h_tE_pt->Draw("same"); //save histograms inside sampleAnalysis.root TObjArray hlist(0); hlist.Add(h_lE_pt); hlist.Add(h_tE_pt); hlist.Add(h_fE_pt); hlist.Add(h_lE1_pt); hlist.Add(h_tE1_pt); hlist.Add(h_fE1_pt); TFile fout("fakerate.root", "recreate"); hlist.Write(); fout.Close(); } <commit_msg>fixed h3 bug in fakerate<commit_after>#include "TChain.h" #include "TFile.h" #include "TH1F.h" #include "TH2F.h" #include "TLorentzVector.h" #include <iostream> #include "x.h" #include "TCanvas.h" #include <math.h> #include <set> #include "TString.h" #include "TSystem.h" using namespace mini; const double PI = 4.0*atan(1.0); #include "TH1.h" #include "TH2.h" void fakerate(TString const& _input) { std::cout<<_input<<std::endl; TChain eventVars("eventVars");//define eventVars tree eventVars.Add("./"+_input+".root/eventVars"); TChain selectedObjects("selectedObjects"); //define eventVars tree selectedObjects.Add("./"+_input+".root/selectedObjects"); TChain allObjects("allObjects"); //define eventVars tree allObjects.Add("./"+_input+".root/allObjects"); allObjects.AddFriend("selectedObjects"); allObjects.AddFriend("eventVars"); //define variables bool hlt0; bool hlt1; float met; float metPhi; photon p, rp; muon m, rm; electron e, re; jet j, rj; genparticle gp; //link the branches to the variables defined above //this is where you add variables relevant to your analysis eventVars.SetBranchAddress("met", &met); eventVars.SetBranchAddress("metPhi", &metPhi); eventVars.SetBranchAddress("HLT_Photon70_CaloIdXL_PFHT400", &hlt0); eventVars.SetBranchAddress("HLT_Photon70_CaloIdXL_PFNoPUHT400", &hlt1); p.setAddress(selectedObjects); m.setAddress(selectedObjects); e.setAddress(selectedObjects); j.setAddress(selectedObjects); rp.setAddress(allObjects); re.setAddress(allObjects); rm.setAddress(allObjects); rj.setAddress(allObjects); gp.setAddress(eventVars); TH1F* h_N_tG = new TH1F("h_N_tG", "tight G Pt", 10, 0., 10.); TH1F* h_N_lE = new TH1F("h_N_lE", "Loose e Pt", 10, 0., 10.); TH1F* h_N_tE = new TH1F("h_N_tE", "Tight e Pt", 10, 0., 10.); TH1F* h_all_lE_pt = new TH1F("h_all_lE_pt", "Loose e Pt", 10, 0., 10.); TH1F* h_all_tE_pt = new TH1F("h_all_tE_pt", "Tight e Pt", 10, 0., 10.); TH1F* h_all_tG_pt = new TH1F("h_all_tG_pt", "Tight G Pt", 10, 0., 10.); TH1F* h_lE_pt = new TH1F("h_lE_pt", "Loose e Pt", 30, 0., 300.); TH1F* h_tE_pt = new TH1F("h_tE_pt", "Tight e Pt", 30, 0., 300.); TH1F* h_fE_pt = new TH1F("h_fE_pt", "Fail-tight e Pt", 30, 0., 300.); h_lE_pt->Sumw2(); h_tE_pt->Sumw2(); h_fE_pt->Sumw2(); TH1F* h_lE1_pt = new TH1F("h_lE1_pt", "Loose e Pt", 30, 0., 300.); TH1F* h_tE1_pt = new TH1F("h_tE1_pt", "Tight e Pt", 30, 0., 300.); TH1F* h_fE1_pt = new TH1F("h_fE1_pt", "Fail-tight e Pt", 30, 0., 300.); h_lE1_pt->Sumw2(); h_tE1_pt->Sumw2(); h_fE1_pt->Sumw2(); unsigned nCnt[20] = {0}; //loop over events long iEntry = 0; while(allObjects.GetEntry(iEntry++) != 0){ nCnt[0]++; std::set<unsigned> lE; std::set<unsigned> tE; std::set<unsigned> lG; std::set<unsigned>::iterator it; for(unsigned k(0);k<re.size;k++) { if(re.iSubdet[k]!=0) continue; if(re.isLoose[k]) { lE.insert(k); h_all_lE_pt->Fill(re.pt[k]); } if(re.isTight[k]) { tE.insert(k); h_all_tE_pt->Fill(re.pt[k]); } } h_N_lE->Fill(lE.size()); h_N_tE->Fill(tE.size()); for(unsigned k(0);k<rp.size;k++) { if (!p.isLoose[k]) continue; lG.insert(k); h_all_tG_pt->Fill(rp.pt[k]); } h_N_tG->Fill(lG.size()); //consider event with only 1 loose electron if(lE.size()!=1) continue; it = lE.begin(); ///remove electron close to a loose photon h_lE_pt->Fill(re.pt[*it]); if(tE.size()==1) { h_tE_pt->Fill(re.pt[*it]); } else {//did not pass tight h_fE_pt->Fill(re.pt[*it]); } int checkDR(0); for (std::set<unsigned int>::iterator ik=lG.begin(); ik!=lG.end(); ++ik) { if(deltaR(rp.eta[*ik],rp.phi[*ik],re.eta[*it],re.phi[*it])<0.1) { checkDR++; } } if(checkDR) continue; float MT = mini::mt(met,metPhi,re.pt[*it],re.phi[*it]); //if(MT>25.) continue; h_lE1_pt->Fill(re.pt[*it]); if(tE.size()==1) { h_tE1_pt->Fill(re.pt[*it]); } else {//did not pass tight h_fE1_pt->Fill(re.pt[*it]); } }//while TCanvas *plots = new TCanvas("plots","fake rate plots",800,800); plots->Divide(2,2); plots->cd(1); h_lE_pt->Draw(); h_tE_pt->Draw("same"); plots->cd(3); TH1F *h3 = (TH1F*)h_tE_pt->Clone("h3"); h3->Divide(h_lE_pt); h3->Draw("e"); plots->cd(2); h_lE1_pt->Draw(); h_tE1_pt->Draw("same"); plots->cd(4); TH1F *h4 = (TH1F*)h_tE1_pt->Clone("h4"); h4->Divide(h_lE1_pt); h4->Draw("e"); //h_lE_pt->Draw(); //h_tE_pt->Draw("same"); //save histograms inside sampleAnalysis.root TObjArray hlist(0); hlist.Add(h_lE_pt); hlist.Add(h_tE_pt); hlist.Add(h_fE_pt); hlist.Add(h_lE1_pt); hlist.Add(h_tE1_pt); hlist.Add(h_fE1_pt); TFile fout("fakerate.root", "recreate"); hlist.Write(); fout.Close(); } <|endoftext|>
<commit_before>#include "preferred_languages.hpp" #include "../base/string_utils.hpp" #include "../base/logging.hpp" #include "../std/target_os.hpp" #include "../std/set.hpp" #if defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE) #include <CoreFoundation/CFLocale.h> #include <CoreFoundation/CFString.h> #elif defined(OMIM_OS_WINDOWS) // @TODO #else #error "Define language preferences for your platform" #endif namespace languages { class LangFilter { set<string> & m_known; public: LangFilter(set<string> & known) : m_known(known) {} bool operator()(string const & t) { return !m_known.insert(t).second; } }; class NormalizeFilter { public: void operator()(string & t) { strings::SimpleTokenizer const iter(t, "-_ "); if (iter) t = *iter; else { LOG(LWARNING, ("Invalid language")); } } }; void FilterLanguages(vector<string> & langs) { // normalize languages: en-US -> en, ru_RU -> ru etc. for_each(langs.begin(), langs.end(), NormalizeFilter()); { // tmp storage set<string> known; // remove duplicate languages langs.erase(remove_if(langs.begin(), langs.end(), LangFilter(known)), langs.end()); } } void SystemPreferredLanguages(vector<string> & languages) { #if defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE) // Mac and iOS implementation CFArrayRef langs = CFLocaleCopyPreferredLanguages(); char buf[30]; for (CFIndex i = 0; i < CFArrayGetCount(langs); ++i) { CFStringRef strRef = (CFStringRef)CFArrayGetValueAtIndex(langs, i); CFStringGetCString(strRef, buf, 30, kCFStringEncodingUTF8); languages.push_back(buf); } CFRelease(langs); #elif defined(OMIM_OS_WINDOWS) // @TODO Windows implementation #else #error "Define language preferences for your platform" #endif FilterLanguages(languages); } string PreferredLanguages() { vector<string> arr; SystemPreferredLanguages(arr); // generate output string string result; for (size_t i = 0; i < arr.size(); ++i) { result.append(arr[i]); result.push_back('|'); } if (result.empty()) result = "default"; else result.resize(result.size() - 1); return result; } string CurrentLanguage() { vector<string> arr; SystemPreferredLanguages(arr); if (arr.empty()) return "en"; else return arr[0]; } } <commit_msg>Added preferred languages support for Linux<commit_after>#include "preferred_languages.hpp" #include "../base/string_utils.hpp" #include "../base/logging.hpp" #include "../std/target_os.hpp" #include "../std/set.hpp" #if defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE) #include <CoreFoundation/CFLocale.h> #include <CoreFoundation/CFString.h> #elif defined(OMIM_OS_WINDOWS) // @TODO #elif defined(OMIM_OS_LINUX) #include "../std/stdlib.hpp" #else #error "Define language preferences for your platform" #endif namespace languages { class LangFilter { set<string> & m_known; public: LangFilter(set<string> & known) : m_known(known) {} bool operator()(string const & t) { return !m_known.insert(t).second; } }; class NormalizeFilter { public: void operator()(string & t) { strings::SimpleTokenizer const iter(t, "-_ "); if (iter) t = *iter; else { LOG(LWARNING, ("Invalid language")); } } }; void FilterLanguages(vector<string> & langs) { // normalize languages: en-US -> en, ru_RU -> ru etc. for_each(langs.begin(), langs.end(), NormalizeFilter()); { // tmp storage set<string> known; // remove duplicate languages langs.erase(remove_if(langs.begin(), langs.end(), LangFilter(known)), langs.end()); } } void SystemPreferredLanguages(vector<string> & languages) { #if defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE) // Mac and iOS implementation CFArrayRef langs = CFLocaleCopyPreferredLanguages(); char buf[30]; for (CFIndex i = 0; i < CFArrayGetCount(langs); ++i) { CFStringRef strRef = (CFStringRef)CFArrayGetValueAtIndex(langs, i); CFStringGetCString(strRef, buf, 30, kCFStringEncodingUTF8); languages.push_back(buf); } CFRelease(langs); #elif defined(OMIM_OS_WINDOWS) // @TODO Windows implementation #elif defined(OMIM_OS_LINUX) // check environment variables char const * p = getenv("LANGUAGE"); if (p) // LANGUAGE can contain several values divided by ':' { string const str(p); strings::SimpleTokenizer iter(str, ":"); while (iter) { languages.push_back(*iter); ++iter; } } else if ((p = getenv("LC_ALL"))) languages.push_back(p); else if ((p = getenv("LC_MESSAGES"))) languages.push_back(p); else if ((p = getenv("LANG"))) languages.push_back(p); #else #error "Define language preferences for your platform" #endif FilterLanguages(languages); } string PreferredLanguages() { vector<string> arr; SystemPreferredLanguages(arr); // generate output string string result; for (size_t i = 0; i < arr.size(); ++i) { result.append(arr[i]); result.push_back('|'); } if (result.empty()) result = "default"; else result.resize(result.size() - 1); return result; } string CurrentLanguage() { vector<string> arr; SystemPreferredLanguages(arr); if (arr.empty()) return "en"; else return arr[0]; } } <|endoftext|>
<commit_before>/* Copyright (c) 2015 The Squash Authors * * 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. * * Authors: * Evan Nemerson <evan@nemerson.com> * Eugene Kliuchnikov <eustas.ru+squash@gmail.com> */ #include <assert.h> #include <squash/squash.h> #include "brotli/enc/encode.h" #include "brotli/dec/decode.h" enum SquashBrotliOptionIndex { SQUASH_BROTLI_OPT_LEVEL = 0, SQUASH_BROTLI_OPT_MODE }; /* C++ doesn't allow us to initialize this correctly here (or, at least, I can't figure out how to do it), so there is some extra code in the init_plugin func to finish it off. */ static SquashOptionInfo squash_brotli_options[] = { { .name = (char*) "level", .type = SQUASH_OPTION_TYPE_RANGE_INT }, { .name = (char*) "mode", .type = SQUASH_OPTION_TYPE_ENUM_STRING }, { NULL, SQUASH_OPTION_TYPE_NONE, } }; typedef struct SquashBrotliStream_s { SquashStream base_object; BrotliInput in; BrotliOutput out; BrotliState* decompressor; bool finished; brotli::BrotliCompressor* compressor; bool should_flush; size_t remaining_block_in; size_t remaining_out; uint8_t* next_out; } SquashBrotliStream; extern "C" SQUASH_PLUGIN_EXPORT SquashStatus squash_plugin_init_plugin (SquashPlugin* plugin); extern "C" SQUASH_PLUGIN_EXPORT SquashStatus squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl); static void squash_brotli_stream_init (SquashBrotliStream* stream, SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options, SquashDestroyNotify destroy_notify); static SquashBrotliStream* squash_brotli_stream_new (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options); static void squash_brotli_stream_destroy (void* stream); static void squash_brotli_stream_free (void* stream); static int squash_brotli_reader (void* user_data, uint8_t* buf, size_t size) { SquashBrotliStream* stream = (SquashBrotliStream*) user_data; size = (stream->base_object.avail_in < size) ? stream->base_object.avail_in : size; memcpy (buf, stream->base_object.next_in, size); stream->base_object.next_in += size; stream->base_object.avail_in -= size; return size; } static int squash_brotli_writer (void* user_data, const uint8_t* buf, size_t size) { SquashBrotliStream* stream = (SquashBrotliStream*) user_data; size = (stream->base_object.avail_out < size) ? stream->base_object.avail_out : size; memcpy (stream->base_object.next_out, buf, size); stream->base_object.next_out += size; stream->base_object.avail_out -= size; return size; } static SquashBrotliStream* squash_brotli_stream_new (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options) { SquashBrotliStream* stream; assert (codec != NULL); assert (stream_type == SQUASH_STREAM_COMPRESS || stream_type == SQUASH_STREAM_DECOMPRESS); stream = (SquashBrotliStream*) malloc (sizeof (SquashBrotliStream)); squash_brotli_stream_init (stream, codec, stream_type, options, squash_brotli_stream_free); return stream; } static void squash_brotli_stream_init (SquashBrotliStream* s, SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options, SquashDestroyNotify destroy_notify) { SquashStream* stream = (SquashStream*) s; squash_stream_init (stream, codec, stream_type, (SquashOptions*) options, destroy_notify); s->finished = false; if (stream_type == SQUASH_STREAM_COMPRESS) { brotli::BrotliParams params; params.quality = squash_codec_get_option_int_index (stream->codec, stream->options, SQUASH_BROTLI_OPT_LEVEL); params.mode = (brotli::BrotliParams::Mode) squash_codec_get_option_int_index (stream->codec, stream->options, SQUASH_BROTLI_OPT_MODE); s->compressor = new brotli::BrotliCompressor (params); s->remaining_block_in = s->compressor->input_block_size(); s->remaining_out = 0; s->next_out = NULL; s->should_flush = false; } else if (stream_type == SQUASH_STREAM_DECOMPRESS) { s->in.cb_ = squash_brotli_reader; s->in.data_ = (void*) stream; s->out.cb_ = squash_brotli_writer; s->out.data_ = (void*) stream; s->decompressor = new BrotliState (); BrotliStateInit(s->decompressor); } else { squash_assert_unreachable(); } } static void squash_brotli_stream_destroy (void* stream) { SquashBrotliStream* s = (SquashBrotliStream*) stream; if (((SquashStream*) stream)->stream_type == SQUASH_STREAM_COMPRESS) { delete s->compressor; } else if (((SquashStream*) stream)->stream_type == SQUASH_STREAM_DECOMPRESS) { BrotliStateCleanup(s->decompressor); delete s->decompressor; } else { squash_assert_unreachable(); } squash_stream_destroy (stream); } static void squash_brotli_stream_free (void* stream) { squash_brotli_stream_destroy (stream); free (stream); } static SquashStream* squash_brotli_create_stream (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options) { return (SquashStream*) squash_brotli_stream_new (codec, stream_type, options); } static SquashStatus squash_brotli_status_to_squash_status (BrotliResult status) { switch (status) { case BROTLI_RESULT_SUCCESS: return SQUASH_OK; case BROTLI_RESULT_NEEDS_MORE_INPUT: return squash_error (SQUASH_BUFFER_EMPTY); case BROTLI_RESULT_NEEDS_MORE_OUTPUT: return squash_error (SQUASH_BUFFER_FULL); case BROTLI_RESULT_ERROR: default: return squash_error (SQUASH_FAILED); } } static SquashStatus squash_brotli_compress_stream (SquashStream* stream, SquashOperation operation) { SquashBrotliStream* s = (SquashBrotliStream*) stream; if (operation == SQUASH_OPERATION_FLUSH) { s->should_flush = true; } bool end_of_input = false; while (true) { size_t out_size = s->remaining_out; if (out_size != 0) { out_size = (s->base_object.avail_out < out_size) ? s->base_object.avail_out : out_size; memcpy (s->base_object.next_out, s->next_out, out_size); s->base_object.next_out += out_size; s->base_object.avail_out -= out_size; s->next_out += out_size; s->remaining_out -= out_size; if (s->base_object.avail_out == 0) { return SQUASH_PROCESSING; } } if (end_of_input || s->finished) { return SQUASH_OK; } size_t in_size = s->base_object.avail_in; in_size = (in_size < s->remaining_block_in) ? in_size : s->remaining_block_in; if (in_size != 0) { s->compressor->CopyInputToRingBuffer (in_size, s->base_object.next_in); s->base_object.next_in += in_size; s->base_object.avail_in -= in_size; s->remaining_block_in -= in_size; if (s->remaining_block_in == 0) { s->remaining_block_in = s->compressor->input_block_size (); } } end_of_input = s->base_object.avail_in == 0; bool is_last = (operation == SQUASH_OPERATION_FINISH) && end_of_input; if (!s->compressor->WriteBrotliData(is_last, s->should_flush && end_of_input, &s->remaining_out, &s->next_out)) { return squash_error (SQUASH_FAILED); } if (is_last) { s->finished = true; } if (end_of_input) { s->should_flush = false; } } } static SquashStatus squash_brotli_decompress_stream (SquashStream* stream, SquashOperation operation) { SquashBrotliStream* s = (SquashBrotliStream*) stream; if (s->finished) { return SQUASH_OK; } try { bool final = (operation == SQUASH_OPERATION_FINISH) || (s->base_object.avail_in == 0); BrotliResult res = BrotliDecompressStreaming (s->in, s->out, final, s->decompressor); if (res == BROTLI_RESULT_SUCCESS) { s->finished = true; return SQUASH_OK; } if (res == BROTLI_RESULT_NEEDS_MORE_OUTPUT || res == BROTLI_RESULT_NEEDS_MORE_INPUT) { return (res == BROTLI_RESULT_NEEDS_MORE_OUTPUT) ? SQUASH_PROCESSING : SQUASH_OK; } return squash_error (SQUASH_FAILED); } catch (const std::bad_alloc& e) { return squash_error (SQUASH_MEMORY); } catch (...) { return squash_error (SQUASH_FAILED); } } static SquashStatus squash_brotli_process_stream (SquashStream* stream, SquashOperation operation) { if (stream->stream_type == SQUASH_STREAM_COMPRESS) return squash_brotli_compress_stream (stream, operation); else return squash_brotli_decompress_stream (stream, operation); } static size_t squash_brotli_get_max_compressed_size (SquashCodec* codec, size_t uncompressed_size) { return uncompressed_size + 5; } static SquashStatus squash_brotli_decompress_buffer (SquashCodec* codec, size_t* decompressed_size, uint8_t decompressed[SQUASH_ARRAY_PARAM(*decompressed_size)], size_t compressed_size, const uint8_t compressed[SQUASH_ARRAY_PARAM(compressed_size)], SquashOptions* options) { try { BrotliResult res = BrotliDecompressBuffer (compressed_size, compressed, decompressed_size, decompressed); return squash_brotli_status_to_squash_status (res); } catch (const std::bad_alloc& e) { return squash_error (SQUASH_MEMORY); } catch (...) { return squash_error (SQUASH_FAILED); } } static SquashStatus squash_brotli_compress_buffer (SquashCodec* codec, size_t* compressed_size, uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_size)], size_t uncompressed_size, const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_size)], SquashOptions* options) { brotli::BrotliParams params; params.quality = squash_codec_get_option_int_index (codec, options, SQUASH_BROTLI_OPT_LEVEL); params.mode = (brotli::BrotliParams::Mode) squash_codec_get_option_int_index (codec, options, SQUASH_BROTLI_OPT_MODE); try { int res = brotli::BrotliCompressBuffer (params, uncompressed_size, uncompressed, compressed_size, compressed); return (res == 1) ? SQUASH_OK : squash_error (SQUASH_FAILED); } catch (const std::bad_alloc& e) { return squash_error (SQUASH_MEMORY); } catch (...) { return squash_error (SQUASH_FAILED); } } extern "C" SquashStatus squash_plugin_init_plugin (SquashPlugin* plugin) { const SquashOptionInfoRangeInt level_range = { 1, 11, 0, false }; squash_brotli_options[SQUASH_BROTLI_OPT_LEVEL].default_value.int_value = 11; squash_brotli_options[SQUASH_BROTLI_OPT_LEVEL].info.range_int = level_range; squash_brotli_options[SQUASH_BROTLI_OPT_MODE].default_value.int_value = brotli::BrotliParams::MODE_GENERIC; squash_brotli_options[SQUASH_BROTLI_OPT_MODE].info.enum_string = { (const SquashOptionInfoEnumStringMap []) { { "generic", brotli::BrotliParams::MODE_GENERIC }, { "text", brotli::BrotliParams::MODE_TEXT }, { "font", brotli::BrotliParams::MODE_FONT }, { NULL, 0 } } }; return SQUASH_OK; } extern "C" SquashStatus squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl) { const char* name = squash_codec_get_name (codec); if (strcmp ("brotli", name) == 0) { impl->options = squash_brotli_options; impl->get_max_compressed_size = squash_brotli_get_max_compressed_size; impl->create_stream = squash_brotli_create_stream; impl->process_stream = squash_brotli_process_stream; impl->decompress_buffer = squash_brotli_decompress_buffer; impl->compress_buffer = squash_brotli_compress_buffer; } else { return squash_error (SQUASH_UNABLE_TO_LOAD); } return SQUASH_OK; } <commit_msg>Fix use of designated initializers in C++ code<commit_after>/* Copyright (c) 2015 The Squash Authors * * 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. * * Authors: * Evan Nemerson <evan@nemerson.com> * Eugene Kliuchnikov <eustas.ru+squash@gmail.com> */ #include <assert.h> #include <squash/squash.h> #include "brotli/enc/encode.h" #include "brotli/dec/decode.h" enum SquashBrotliOptionIndex { SQUASH_BROTLI_OPT_LEVEL = 0, SQUASH_BROTLI_OPT_MODE }; /* C++ doesn't allow us to initialize this correctly here (or, at least, I can't figure out how to do it), so there is some extra code in the init_plugin func to finish it off. */ static SquashOptionInfo squash_brotli_options[] = { { "level", SQUASH_OPTION_TYPE_RANGE_INT }, { "mode", SQUASH_OPTION_TYPE_ENUM_STRING }, { NULL, SQUASH_OPTION_TYPE_NONE } }; typedef struct SquashBrotliStream_s { SquashStream base_object; BrotliInput in; BrotliOutput out; BrotliState* decompressor; bool finished; brotli::BrotliCompressor* compressor; bool should_flush; size_t remaining_block_in; size_t remaining_out; uint8_t* next_out; } SquashBrotliStream; extern "C" SQUASH_PLUGIN_EXPORT SquashStatus squash_plugin_init_plugin (SquashPlugin* plugin); extern "C" SQUASH_PLUGIN_EXPORT SquashStatus squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl); static void squash_brotli_stream_init (SquashBrotliStream* stream, SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options, SquashDestroyNotify destroy_notify); static SquashBrotliStream* squash_brotli_stream_new (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options); static void squash_brotli_stream_destroy (void* stream); static void squash_brotli_stream_free (void* stream); static int squash_brotli_reader (void* user_data, uint8_t* buf, size_t size) { SquashBrotliStream* stream = (SquashBrotliStream*) user_data; size = (stream->base_object.avail_in < size) ? stream->base_object.avail_in : size; memcpy (buf, stream->base_object.next_in, size); stream->base_object.next_in += size; stream->base_object.avail_in -= size; return size; } static int squash_brotli_writer (void* user_data, const uint8_t* buf, size_t size) { SquashBrotliStream* stream = (SquashBrotliStream*) user_data; size = (stream->base_object.avail_out < size) ? stream->base_object.avail_out : size; memcpy (stream->base_object.next_out, buf, size); stream->base_object.next_out += size; stream->base_object.avail_out -= size; return size; } static SquashBrotliStream* squash_brotli_stream_new (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options) { SquashBrotliStream* stream; assert (codec != NULL); assert (stream_type == SQUASH_STREAM_COMPRESS || stream_type == SQUASH_STREAM_DECOMPRESS); stream = (SquashBrotliStream*) malloc (sizeof (SquashBrotliStream)); squash_brotli_stream_init (stream, codec, stream_type, options, squash_brotli_stream_free); return stream; } static void squash_brotli_stream_init (SquashBrotliStream* s, SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options, SquashDestroyNotify destroy_notify) { SquashStream* stream = (SquashStream*) s; squash_stream_init (stream, codec, stream_type, (SquashOptions*) options, destroy_notify); s->finished = false; if (stream_type == SQUASH_STREAM_COMPRESS) { brotli::BrotliParams params; params.quality = squash_codec_get_option_int_index (stream->codec, stream->options, SQUASH_BROTLI_OPT_LEVEL); params.mode = (brotli::BrotliParams::Mode) squash_codec_get_option_int_index (stream->codec, stream->options, SQUASH_BROTLI_OPT_MODE); s->compressor = new brotli::BrotliCompressor (params); s->remaining_block_in = s->compressor->input_block_size(); s->remaining_out = 0; s->next_out = NULL; s->should_flush = false; } else if (stream_type == SQUASH_STREAM_DECOMPRESS) { s->in.cb_ = squash_brotli_reader; s->in.data_ = (void*) stream; s->out.cb_ = squash_brotli_writer; s->out.data_ = (void*) stream; s->decompressor = new BrotliState (); BrotliStateInit(s->decompressor); } else { squash_assert_unreachable(); } } static void squash_brotli_stream_destroy (void* stream) { SquashBrotliStream* s = (SquashBrotliStream*) stream; if (((SquashStream*) stream)->stream_type == SQUASH_STREAM_COMPRESS) { delete s->compressor; } else if (((SquashStream*) stream)->stream_type == SQUASH_STREAM_DECOMPRESS) { BrotliStateCleanup(s->decompressor); delete s->decompressor; } else { squash_assert_unreachable(); } squash_stream_destroy (stream); } static void squash_brotli_stream_free (void* stream) { squash_brotli_stream_destroy (stream); free (stream); } static SquashStream* squash_brotli_create_stream (SquashCodec* codec, SquashStreamType stream_type, SquashOptions* options) { return (SquashStream*) squash_brotli_stream_new (codec, stream_type, options); } static SquashStatus squash_brotli_status_to_squash_status (BrotliResult status) { switch (status) { case BROTLI_RESULT_SUCCESS: return SQUASH_OK; case BROTLI_RESULT_NEEDS_MORE_INPUT: return squash_error (SQUASH_BUFFER_EMPTY); case BROTLI_RESULT_NEEDS_MORE_OUTPUT: return squash_error (SQUASH_BUFFER_FULL); case BROTLI_RESULT_ERROR: default: return squash_error (SQUASH_FAILED); } } static SquashStatus squash_brotli_compress_stream (SquashStream* stream, SquashOperation operation) { SquashBrotliStream* s = (SquashBrotliStream*) stream; if (operation == SQUASH_OPERATION_FLUSH) { s->should_flush = true; } bool end_of_input = false; while (true) { size_t out_size = s->remaining_out; if (out_size != 0) { out_size = (s->base_object.avail_out < out_size) ? s->base_object.avail_out : out_size; memcpy (s->base_object.next_out, s->next_out, out_size); s->base_object.next_out += out_size; s->base_object.avail_out -= out_size; s->next_out += out_size; s->remaining_out -= out_size; if (s->base_object.avail_out == 0) { return SQUASH_PROCESSING; } } if (end_of_input || s->finished) { return SQUASH_OK; } size_t in_size = s->base_object.avail_in; in_size = (in_size < s->remaining_block_in) ? in_size : s->remaining_block_in; if (in_size != 0) { s->compressor->CopyInputToRingBuffer (in_size, s->base_object.next_in); s->base_object.next_in += in_size; s->base_object.avail_in -= in_size; s->remaining_block_in -= in_size; if (s->remaining_block_in == 0) { s->remaining_block_in = s->compressor->input_block_size (); } } end_of_input = s->base_object.avail_in == 0; bool is_last = (operation == SQUASH_OPERATION_FINISH) && end_of_input; if (!s->compressor->WriteBrotliData(is_last, s->should_flush && end_of_input, &s->remaining_out, &s->next_out)) { return squash_error (SQUASH_FAILED); } if (is_last) { s->finished = true; } if (end_of_input) { s->should_flush = false; } } } static SquashStatus squash_brotli_decompress_stream (SquashStream* stream, SquashOperation operation) { SquashBrotliStream* s = (SquashBrotliStream*) stream; if (s->finished) { return SQUASH_OK; } try { bool final = (operation == SQUASH_OPERATION_FINISH) || (s->base_object.avail_in == 0); BrotliResult res = BrotliDecompressStreaming (s->in, s->out, final, s->decompressor); if (res == BROTLI_RESULT_SUCCESS) { s->finished = true; return SQUASH_OK; } if (res == BROTLI_RESULT_NEEDS_MORE_OUTPUT || res == BROTLI_RESULT_NEEDS_MORE_INPUT) { return (res == BROTLI_RESULT_NEEDS_MORE_OUTPUT) ? SQUASH_PROCESSING : SQUASH_OK; } return squash_error (SQUASH_FAILED); } catch (const std::bad_alloc& e) { return squash_error (SQUASH_MEMORY); } catch (...) { return squash_error (SQUASH_FAILED); } } static SquashStatus squash_brotli_process_stream (SquashStream* stream, SquashOperation operation) { if (stream->stream_type == SQUASH_STREAM_COMPRESS) return squash_brotli_compress_stream (stream, operation); else return squash_brotli_decompress_stream (stream, operation); } static size_t squash_brotli_get_max_compressed_size (SquashCodec* codec, size_t uncompressed_size) { return uncompressed_size + 5; } static SquashStatus squash_brotli_decompress_buffer (SquashCodec* codec, size_t* decompressed_size, uint8_t decompressed[SQUASH_ARRAY_PARAM(*decompressed_size)], size_t compressed_size, const uint8_t compressed[SQUASH_ARRAY_PARAM(compressed_size)], SquashOptions* options) { try { BrotliResult res = BrotliDecompressBuffer (compressed_size, compressed, decompressed_size, decompressed); return squash_brotli_status_to_squash_status (res); } catch (const std::bad_alloc& e) { return squash_error (SQUASH_MEMORY); } catch (...) { return squash_error (SQUASH_FAILED); } } static SquashStatus squash_brotli_compress_buffer (SquashCodec* codec, size_t* compressed_size, uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_size)], size_t uncompressed_size, const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_size)], SquashOptions* options) { brotli::BrotliParams params; params.quality = squash_codec_get_option_int_index (codec, options, SQUASH_BROTLI_OPT_LEVEL); params.mode = (brotli::BrotliParams::Mode) squash_codec_get_option_int_index (codec, options, SQUASH_BROTLI_OPT_MODE); try { int res = brotli::BrotliCompressBuffer (params, uncompressed_size, uncompressed, compressed_size, compressed); return (res == 1) ? SQUASH_OK : squash_error (SQUASH_FAILED); } catch (const std::bad_alloc& e) { return squash_error (SQUASH_MEMORY); } catch (...) { return squash_error (SQUASH_FAILED); } } extern "C" SquashStatus squash_plugin_init_plugin (SquashPlugin* plugin) { const SquashOptionInfoRangeInt level_range = { 1, 11, 0, false }; squash_brotli_options[SQUASH_BROTLI_OPT_LEVEL].default_value.int_value = 11; squash_brotli_options[SQUASH_BROTLI_OPT_LEVEL].info.range_int = level_range; static const SquashOptionInfoEnumStringMap option_strings[] = { { "generic", brotli::BrotliParams::MODE_GENERIC }, { "text", brotli::BrotliParams::MODE_TEXT }, { "font", brotli::BrotliParams::MODE_FONT }, { NULL, 0 } }; squash_brotli_options[SQUASH_BROTLI_OPT_MODE].default_value.int_value = brotli::BrotliParams::MODE_GENERIC; squash_brotli_options[SQUASH_BROTLI_OPT_MODE].info.enum_string.values = option_strings; return SQUASH_OK; } extern "C" SquashStatus squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl) { const char* name = squash_codec_get_name (codec); if (strcmp ("brotli", name) == 0) { impl->options = squash_brotli_options; impl->get_max_compressed_size = squash_brotli_get_max_compressed_size; impl->create_stream = squash_brotli_create_stream; impl->process_stream = squash_brotli_process_stream; impl->decompress_buffer = squash_brotli_decompress_buffer; impl->compress_buffer = squash_brotli_compress_buffer; } else { return squash_error (SQUASH_UNABLE_TO_LOAD); } return SQUASH_OK; } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2018 Scott Moreau * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <core.hpp> #include <view.hpp> #include <plugin.hpp> #include <output.hpp> #include "view-transform.hpp" #include "workspace-manager.hpp" #include <nonstd/make_unique.hpp> class wayfire_alpha : public wayfire_plugin_t { axis_callback axis_cb; public: void init(wayfire_config *config) { grab_interface->name = "alpha"; grab_interface->abilities_mask = WF_ABILITY_CONTROL_WM; axis_cb = [=] (wlr_event_pointer_axis* ev) { if (!output->activate_plugin(grab_interface)) return; output->deactivate_plugin(grab_interface); auto focus = core->get_cursor_focus(); if (!focus) return; auto view = core->find_view(focus->get_main_surface()); auto layer = output->workspace->get_view_layer(view); if (layer == WF_LAYER_BACKGROUND) return; if (ev->orientation == WLR_AXIS_ORIENTATION_VERTICAL) update_alpha_target(view, ev->delta); }; auto section = config->get_section("alpha"); auto modifier = section->get_option("modifier", "<alt>"); output->add_axis(modifier, &axis_cb); } void update_alpha_target(wayfire_view view, float delta) { wf_2D_view *transformer; float alpha; if (!view->get_transformer("alpha")) view->add_transformer(nonstd::make_unique<wf_2D_view> (view), "alpha"); transformer = dynamic_cast<wf_2D_view*> (view->get_transformer("alpha").get()); alpha = transformer->alpha; alpha -= delta * 0.003; if (alpha > 1.0) alpha = 1.0; if (alpha == 1.0) return view->pop_transformer("alpha"); if (alpha < 0) alpha = 0; if (transformer->alpha != alpha) { transformer->alpha = alpha; view->damage(); } } void fini() { output->rem_axis(&axis_cb); } }; extern "C" { wayfire_plugin_t *newInstance() { return new wayfire_alpha(); } } <commit_msg>alpha: Remove newline whitespace<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2018 Scott Moreau * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <core.hpp> #include <view.hpp> #include <plugin.hpp> #include <output.hpp> #include "view-transform.hpp" #include "workspace-manager.hpp" #include <nonstd/make_unique.hpp> class wayfire_alpha : public wayfire_plugin_t { axis_callback axis_cb; public: void init(wayfire_config *config) { grab_interface->name = "alpha"; grab_interface->abilities_mask = WF_ABILITY_CONTROL_WM; axis_cb = [=] (wlr_event_pointer_axis* ev) { if (!output->activate_plugin(grab_interface)) return; output->deactivate_plugin(grab_interface); auto focus = core->get_cursor_focus(); if (!focus) return; auto view = core->find_view(focus->get_main_surface()); auto layer = output->workspace->get_view_layer(view); if (layer == WF_LAYER_BACKGROUND) return; if (ev->orientation == WLR_AXIS_ORIENTATION_VERTICAL) update_alpha_target(view, ev->delta); }; auto section = config->get_section("alpha"); auto modifier = section->get_option("modifier", "<alt>"); output->add_axis(modifier, &axis_cb); } void update_alpha_target(wayfire_view view, float delta) { wf_2D_view *transformer; float alpha; if (!view->get_transformer("alpha")) view->add_transformer(nonstd::make_unique<wf_2D_view> (view), "alpha"); transformer = dynamic_cast<wf_2D_view*> (view->get_transformer("alpha").get()); alpha = transformer->alpha; alpha -= delta * 0.003; if (alpha > 1.0) alpha = 1.0; if (alpha == 1.0) return view->pop_transformer("alpha"); if (alpha < 0) alpha = 0; if (transformer->alpha != alpha) { transformer->alpha = alpha; view->damage(); } } void fini() { output->rem_axis(&axis_cb); } }; extern "C" { wayfire_plugin_t *newInstance() { return new wayfire_alpha(); } } <|endoftext|>
<commit_before>// System Dependencies #include <sys/time.h> // Local Dependencies #include "../include/datetime.h" #include "../include/exception.h" /** Divisors: The number of milliseconds per item. */ #define DAY_DIVISOR 86400000 #define HOUR_DIVISOR 3600000 #define MINUTE_DIVISOR 60000 #define SECOND_DIVISOR 1000 namespace native { DateTime::DateTime() { struct timeval tv; struct timezone tz; ::gettimeofday(&tv, &tz); _offset = short(-tz.tz_minuteswest); _value = (int64_t(tv.tv_sec) * 1000) + (tv.tv_usec / 1000) + (_offset * MINUTE_DIVISOR); } DateTime::DateTime(int year, int month, int day) { throw NotImplementedException(); } DateTime::DateTime(const DateTime& other) : _value(other._value), _offset(other._offset) { } void DateTime::addDays(int days) { _value += int64_t(days) * DAY_DIVISOR; } void DateTime::addHours(int hours) { _value += int64_t(hours) * HOUR_DIVISOR; } void DateTime::addMinutes(int minutes) { _value += int64_t(minutes) * MINUTE_DIVISOR; } void DateTime::addSeconds(int seconds) { _value += int64_t(seconds) * SECOND_DIVISOR; } void DateTime::addMilliSeconds(int milliseconds) { _value += milliseconds; } short DateTime::getDay() const { throw NotImplementedException(); } WeekDay DateTime::getWeekDay() const { throw NotImplementedException(); } Month DateTime::getMonth() const { throw NotImplementedException(); } int DateTime::getYear() const { throw NotImplementedException(); } short DateTime::getHour() const { throw NotImplementedException(); } short DateTime::getMinute() const { throw NotImplementedException(); } short DateTime::getSecond() const { throw NotImplementedException(); } short DateTime::getMilliSecond() const { throw NotImplementedException(); } String DateTime::toString() const { const wchar_t* format; if (getTimeZoneOffset() == 0) format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}Z"; else format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}+{7:02}:{8:02}"; return String::format(format, getYear(), getMonth(), getDay(), getHour(), getMinute(), getSecond(), getMilliSecond(), getTimeZoneOffset() / 60, getTimeZoneOffset() % 60); } } <commit_msg>Stash changes for a sec...<commit_after>// System Dependencies #include <sys/time.h> // Local Dependencies #include "../include/datetime.h" #include "../include/exception.h" /** Divisors: The number of milliseconds per item. */ #define DAY_DIVISOR 86400000 #define HOUR_DIVISOR 3600000 #define MINUTE_DIVISOR 60000 #define SECOND_DIVISOR 1000 namespace native { DateTime::DateTime() { struct timeval tv; struct timezone tz; ::gettimeofday(&tv, &tz); _offset = short(-tz.tz_minuteswest); _value = (int64_t(tv.tv_sec) * 1000) + (tv.tv_usec / 1000) + (_offset * MINUTE_DIVISOR); } DateTime::DateTime(int year, int month, int day) { throw NotImplementedException(); } DateTime::DateTime(const DateTime& other) : _value(other._value), _offset(other._offset) { } void DateTime::addDays(int days) { _value += int64_t(days) * DAY_DIVISOR; } void DateTime::addHours(int hours) { _value += int64_t(hours) * HOUR_DIVISOR; } void DateTime::addMinutes(int minutes) { _value += int64_t(minutes) * MINUTE_DIVISOR; } void DateTime::addSeconds(int seconds) { _value += int64_t(seconds) * SECOND_DIVISOR; } void DateTime::addMilliSeconds(int milliseconds) { _value += milliseconds; } short DateTime::getDay() const { throw NotImplementedException(); } WeekDay DateTime::getWeekDay() const { throw NotImplementedException(); } Month DateTime::getMonth() const { throw NotImplementedException(); } int DateTime::getYear() const { throw NotImplementedException(); } short DateTime::getHour() const { throw NotImplementedException(); } short DateTime::getMinute() const { throw NotImplementedException(); } short DateTime::getSecond() const { throw NotImplementedException(); } short DateTime::getMilliSecond() const { return _value % 1000; } String DateTime::toString() const { const wchar_t* format; if (getTimeZoneOffset() == 0) format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}Z"; else format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}+{7:02}:{8:02}"; return String::format(format, getYear(), getMonth(), getDay(), getHour(), getMinute(), getSecond(), getMilliSecond(), getTimeZoneOffset() / 60, getTimeZoneOffset() % 60); } } <|endoftext|>
<commit_before>/** Based on https://gist.github.com/jvranish/4441299 */ #include "stacktrace.hpp" #include "log.hpp" #include <iostream> #ifdef STACKTRACE #include <sstream> #include <cstdio> #ifdef WIN #include <windows.h> #include <imagehlp.h> #else #include <signal.h> #include <execinfo.h> #endif namespace core { namespace util { namespace { void set_signal_handler(); std::string EXE_NAME; std::string demangleStacktraceEntry(void* t) { FILE *fp; char var[40]; std::stringstream buffer; #ifdef __APPLE__ buffer<<"atos -o "<<t<<" \""<<EXE_NAME<<"\""; #else buffer<<"addr2line -C -s -f -p "<<t<<" -e \""<<EXE_NAME<<"\""; #endif std::string command = buffer.str(); fp = popen(command.c_str(), "r"); buffer.str(std::string()); while (fgets(var, sizeof(var), fp) != NULL) buffer<<var; pclose(fp); return buffer.str(); } void printStackTrace(std::string error) { CRASH_REPORT("\n"<<error); } } bool is_stacktrace_available() { return !EXE_NAME.empty(); } #ifdef _WIN32 namespace { typedef void ( * RtlCaptureContextFunc ) ( CONTEXT * ContextRecord ); RtlCaptureContextFunc rtlCaptureContext; } void init_stacktrace(std::string exeName) { EXE_NAME = exeName; HINSTANCE kernel32 = LoadLibrary("Kernel32.dll"); rtlCaptureContext = (RtlCaptureContextFunc) GetProcAddress( kernel32, "RtlCaptureContext" ); set_signal_handler(); INFO("Startet from "<<exeName); } namespace { std::string windows_print_stacktrace(CONTEXT* context) { std::stringstream ret; SymInitialize(GetCurrentProcess(), 0, TRUE); DWORD MachineType; bool first = true; /* setup initial stack frame */ #ifdef _M_IX86 MachineType = IMAGE_FILE_MACHINE_I386; STACKFRAME frame; frame.AddrPC.Offset = context->Eip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->Ebp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context->Esp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_X64 MachineType = IMAGE_FILE_MACHINE_AMD64; STACKFRAME64 frame; frame.AddrPC.Offset = context->Rip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->Rbp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context->Rsp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_IA64 MachineType = IMAGE_FILE_MACHINE_IA64; STACKFRAME64 frame; frame.AddrPC.Offset = context->StIIP; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->IntSp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrBStore.Offset= context->RsBSP; frame.AddrBStore.Mode = AddrModeFlat; frame.AddrStack.Offset = context->IntSp; frame.AddrStack.Mode = AddrModeFlat; #else #error "Unsupported platform" #endif memset(&frame, 0, sizeof(frame)); #ifdef _M_IX86 while (StackWalk( MachineType , GetCurrentProcess(), GetCurrentThread(), &frame, context, 0, SymFunctionTableAccess, SymGetModuleBase, 0 ) ) { if(first) first=false; else ret<<"Called From "; ret<<demangleStacktraceEntry((void*)frame.AddrPC.Offset)<<std::endl; } #else while (StackWalk64( MachineType , GetCurrentProcess(), GetCurrentThread(), &frame, context, 0, SymFunctionTableAccess64, SymGetModuleBase64, 0 ) ) { if(first) first=false; else ret<<"Called From "; ret<<demangleStacktraceEntry((void*)frame.AddrPC.Offset)<<std::endl; } #endif SymCleanup( GetCurrentProcess() ); return ret.str(); } LONG WINAPI windows_exception_handler(EXCEPTION_POINTERS * ExceptionInfo) { switch(ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: std::cerr<<"Error: EXCEPTION_ACCESS_VIOLATION"; break; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: std::cerr<<"Error: EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; break; case EXCEPTION_BREAKPOINT: std::cerr<<"Error: EXCEPTION_BREAKPOINT"; break; case EXCEPTION_DATATYPE_MISALIGNMENT: std::cerr<<"Error: EXCEPTION_DATATYPE_MISALIGNMENT"; break; case EXCEPTION_FLT_DENORMAL_OPERAND: std::cerr<<"Error: EXCEPTION_FLT_DENORMAL_OPERAND"; break; case EXCEPTION_FLT_DIVIDE_BY_ZERO: std::cerr<<"Error: EXCEPTION_FLT_DIVIDE_BY_ZERO"; break; case EXCEPTION_FLT_INEXACT_RESULT: std::cerr<<"Error: EXCEPTION_FLT_INEXACT_RESULT"; break; case EXCEPTION_FLT_INVALID_OPERATION: std::cerr<<"Error: EXCEPTION_FLT_INVALID_OPERATION"; break; case EXCEPTION_FLT_OVERFLOW: std::cerr<<"Error: EXCEPTION_FLT_OVERFLOW"; break; case EXCEPTION_FLT_STACK_CHECK: std::cerr<<"Error: EXCEPTION_FLT_STACK_CHECK"; break; case EXCEPTION_FLT_UNDERFLOW: std::cerr<<"Error: EXCEPTION_FLT_UNDERFLOW"; break; case EXCEPTION_ILLEGAL_INSTRUCTION: std::cerr<<"Error: EXCEPTION_ILLEGAL_INSTRUCTION"; break; case EXCEPTION_IN_PAGE_ERROR: std::cerr<<"Error: EXCEPTION_IN_PAGE_ERROR"; break; case EXCEPTION_INT_DIVIDE_BY_ZERO: std::cerr<<"Error: EXCEPTION_INT_DIVIDE_BY_ZERO"; break; case EXCEPTION_INT_OVERFLOW: std::cerr<<"Error: EXCEPTION_INT_OVERFLOW"; break; case EXCEPTION_INVALID_DISPOSITION: std::cerr<<"Error: EXCEPTION_INVALID_DISPOSITION"; break; case EXCEPTION_NONCONTINUABLE_EXCEPTION: std::cerr<<"Error: EXCEPTION_NONCONTINUABLE_EXCEPTION"; break; case EXCEPTION_PRIV_INSTRUCTION: std::cerr<<"Error: EXCEPTION_PRIV_INSTRUCTION"; break; case EXCEPTION_SINGLE_STEP: std::cerr<<"Error: EXCEPTION_SINGLE_STEP"; break; case EXCEPTION_STACK_OVERFLOW: std::cerr<<"Error: EXCEPTION_STACK_OVERFLOW"; break; default: std::cerr<<"Error: Unrecognized Exception"; break; } std::cerr<<" at "; /* If this is a stack overflow then we can't walk the stack, so just show where the error happened */ if (EXCEPTION_STACK_OVERFLOW != ExceptionInfo->ExceptionRecord->ExceptionCode) std::cerr<<windows_print_stacktrace(ExceptionInfo->ContextRecord)<<std::endl; else #ifdef _M_IX86 std::cerr<<demangleStacktraceEntry((void*)ExceptionInfo->ContextRecord->Eip)<<"; Sorry, no stacktrace for windows here :-(\n Please upgrade to Linux"<<std::endl; #else std::cerr<<demangleStacktraceEntry((void*)ExceptionInfo->ContextRecord->Rip)<<"; Sorry, no stacktrace for windows here :-(\n Please upgrade to Linux"<<std::endl; #endif return EXCEPTION_EXECUTE_HANDLER; } void set_signal_handler() { SetUnhandledExceptionFilter(windows_exception_handler); } } std::string gen_stacktrace(int framesToSkip) { std::stringstream ret; CONTEXT context; memset(&context, 0, sizeof(context)); context.ContextFlags = CONTEXT_CONTROL; // Capture the thread context rtlCaptureContext( & context ); ret<<windows_print_stacktrace(&context)<<std::endl; return ret.str(); } #else void init_stacktrace(std::string exeName) { EXE_NAME = exeName; set_signal_handler(); INFO("Startet from "<<exeName); } namespace { void posix_signal_handler(int sig, siginfo_t *siginfo, void *context) { (void)context; switch(sig) { case SIGSEGV: printStackTrace("Caught SIGSEGV: Segmentation Fault"); break; case SIGINT: printStackTrace("Caught SIGINT: Interactive attention signal, (usually ctrl+c)"); break; case SIGFPE: switch(siginfo->si_code) { case FPE_INTDIV: printStackTrace("Caught SIGFPE: (integer divide by zero)"); break; case FPE_INTOVF: printStackTrace("Caught SIGFPE: (integer overflow)"); break; case FPE_FLTDIV: printStackTrace("Caught SIGFPE: (floating-point divide by zero)"); break; case FPE_FLTOVF: printStackTrace("Caught SIGFPE: (floating-point overflow)"); break; case FPE_FLTUND: printStackTrace("Caught SIGFPE: (floating-point underflow)"); break; case FPE_FLTRES: printStackTrace("Caught SIGFPE: (floating-point inexact result)"); break; case FPE_FLTINV: printStackTrace("Caught SIGFPE: (floating-point invalid operation)"); break; case FPE_FLTSUB: printStackTrace("Caught SIGFPE: (subscript out of range)"); break; default: printStackTrace("Caught SIGFPE: Arithmetic Exception"); break; } case SIGILL: switch(siginfo->si_code) { case ILL_ILLOPC: printStackTrace("Caught SIGILL: (illegal opcode)"); break; case ILL_ILLOPN: printStackTrace("Caught SIGILL: (illegal operand)"); break; case ILL_ILLADR: printStackTrace("Caught SIGILL: (illegal addressing mode)"); break; case ILL_ILLTRP: printStackTrace("Caught SIGILL: (illegal trap)"); break; case ILL_PRVOPC: printStackTrace("Caught SIGILL: (privileged opcode)"); break; case ILL_PRVREG: printStackTrace("Caught SIGILL: (privileged register)"); break; case ILL_COPROC: printStackTrace("Caught SIGILL: (coprocessor error)"); break; case ILL_BADSTK: printStackTrace("Caught SIGILL: (internal stack error)"); break; default: printStackTrace("Caught SIGILL: Illegal Instruction"); break; } break; case SIGTERM: printStackTrace("Caught SIGTERM: a termination request was sent to the program"); break; case SIGABRT: printStackTrace("Caught SIGABRT: usually caused by an abort() or assert()"); break; default: break; } _Exit(1); } char alternate_stack[SIGSTKSZ*2]; void set_signal_handler() { /* setup alternate stack */ { stack_t ss; /* malloc is usually used here, I'm not 100% sure my static allocation is valid but it seems to work just fine. */ ss.ss_sp = (void*)alternate_stack; ss.ss_size = sizeof(alternate_stack); ss.ss_flags = 0; if (sigaltstack(&ss, NULL) != 0) std::cerr<<"failed to create alternate stack for handlers!"<<std::endl; } /* register our signal handlers */ { struct sigaction sig_action; sig_action.sa_sigaction = posix_signal_handler; sigemptyset(&sig_action.sa_mask); #ifdef __APPLE__ /* for some reason we backtrace() doesn't work on osx when we use an alternate stack */ sig_action.sa_flags = SA_SIGINFO; #else sig_action.sa_flags = SA_SIGINFO | SA_ONSTACK; #endif if (sigaction(SIGSEGV, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGSEGV!"); if (sigaction(SIGFPE, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGFPE!"); if (sigaction(SIGINT, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGINT!"); if (sigaction(SIGILL, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGILL!"); if (sigaction(SIGTERM, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGTERM!"); if (sigaction(SIGABRT, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGABRT!"); } } } std::string gen_stacktrace(int framesToSkip) { std::stringstream ret; void *trace[32]; auto trace_size = backtrace(trace, 32); char** messages = backtrace_symbols(trace, trace_size); /* skip first stack frame (points here) */ bool first=true; for (auto i=1+framesToSkip; i<trace_size; ++i) { if(first) first=false; else ret<<"Called From "; ret<<messages[i]<<std::endl<<" "<<demangleStacktraceEntry(trace[i])<<std::endl; } return ret.str(); } #endif } } #else namespace core { namespace util { void init_stacktrace(std::string exeName) { } std::string gen_stacktrace(int stacksToSkip) { return ""; } bool is_stacktrace_available() { return false; } } } #endif <commit_msg>tilemap renderer some fixes<commit_after>/** Based on https://gist.github.com/jvranish/4441299 */ #include "stacktrace.hpp" #include "log.hpp" #include <iostream> #ifdef STACKTRACE #include <sstream> #include <cstdio> #ifdef WIN #include <windows.h> #include <imagehlp.h> #else #include <signal.h> #include <execinfo.h> #endif namespace core { namespace util { namespace { void set_signal_handler(); std::string EXE_NAME; std::string demangleStacktraceEntry(void* t) { FILE *fp; char var[40]; std::stringstream buffer; #ifdef __APPLE__ buffer<<"atos -o "<<t<<" \""<<EXE_NAME<<"\""; #else buffer<<"addr2line -C -s -f -p "<<t<<" -e \""<<EXE_NAME<<"\""; #endif std::string command = buffer.str(); fp = popen(command.c_str(), "r"); buffer.str(std::string()); while (fgets(var, sizeof(var), fp) != NULL) buffer<<var; pclose(fp); return buffer.str(); } /*void printStackTrace(std::string error) { CRASH_REPORT("\n"<<error); }*/ } bool is_stacktrace_available() { return !EXE_NAME.empty(); } #ifdef _WIN32 namespace { typedef void ( * RtlCaptureContextFunc ) ( CONTEXT * ContextRecord ); RtlCaptureContextFunc rtlCaptureContext; } void init_stacktrace(std::string exeName) { EXE_NAME = exeName; HINSTANCE kernel32 = LoadLibrary("Kernel32.dll"); rtlCaptureContext = (RtlCaptureContextFunc) GetProcAddress( kernel32, "RtlCaptureContext" ); set_signal_handler(); INFO("Startet from "<<exeName); } namespace { std::string windows_print_stacktrace(CONTEXT* context) { std::stringstream ret; SymInitialize(GetCurrentProcess(), 0, TRUE); DWORD MachineType; bool first = true; /* setup initial stack frame */ #ifdef _M_IX86 MachineType = IMAGE_FILE_MACHINE_I386; STACKFRAME frame; frame.AddrPC.Offset = context->Eip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->Ebp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context->Esp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_X64 MachineType = IMAGE_FILE_MACHINE_AMD64; STACKFRAME64 frame; frame.AddrPC.Offset = context->Rip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->Rbp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context->Rsp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_IA64 MachineType = IMAGE_FILE_MACHINE_IA64; STACKFRAME64 frame; frame.AddrPC.Offset = context->StIIP; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->IntSp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrBStore.Offset= context->RsBSP; frame.AddrBStore.Mode = AddrModeFlat; frame.AddrStack.Offset = context->IntSp; frame.AddrStack.Mode = AddrModeFlat; #else #error "Unsupported platform" #endif memset(&frame, 0, sizeof(frame)); #ifdef _M_IX86 while (StackWalk( MachineType , GetCurrentProcess(), GetCurrentThread(), &frame, context, 0, SymFunctionTableAccess, SymGetModuleBase, 0 ) ) { if(first) first=false; else ret<<"Called From "; ret<<demangleStacktraceEntry((void*)frame.AddrPC.Offset)<<std::endl; } #else while (StackWalk64( MachineType , GetCurrentProcess(), GetCurrentThread(), &frame, context, 0, SymFunctionTableAccess64, SymGetModuleBase64, 0 ) ) { if(first) first=false; else ret<<"Called From "; ret<<demangleStacktraceEntry((void*)frame.AddrPC.Offset)<<std::endl; } #endif SymCleanup( GetCurrentProcess() ); return ret.str(); } LONG WINAPI windows_exception_handler(EXCEPTION_POINTERS * ExceptionInfo) { switch(ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: std::cerr<<"Error: EXCEPTION_ACCESS_VIOLATION"; break; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: std::cerr<<"Error: EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; break; case EXCEPTION_BREAKPOINT: std::cerr<<"Error: EXCEPTION_BREAKPOINT"; break; case EXCEPTION_DATATYPE_MISALIGNMENT: std::cerr<<"Error: EXCEPTION_DATATYPE_MISALIGNMENT"; break; case EXCEPTION_FLT_DENORMAL_OPERAND: std::cerr<<"Error: EXCEPTION_FLT_DENORMAL_OPERAND"; break; case EXCEPTION_FLT_DIVIDE_BY_ZERO: std::cerr<<"Error: EXCEPTION_FLT_DIVIDE_BY_ZERO"; break; case EXCEPTION_FLT_INEXACT_RESULT: std::cerr<<"Error: EXCEPTION_FLT_INEXACT_RESULT"; break; case EXCEPTION_FLT_INVALID_OPERATION: std::cerr<<"Error: EXCEPTION_FLT_INVALID_OPERATION"; break; case EXCEPTION_FLT_OVERFLOW: std::cerr<<"Error: EXCEPTION_FLT_OVERFLOW"; break; case EXCEPTION_FLT_STACK_CHECK: std::cerr<<"Error: EXCEPTION_FLT_STACK_CHECK"; break; case EXCEPTION_FLT_UNDERFLOW: std::cerr<<"Error: EXCEPTION_FLT_UNDERFLOW"; break; case EXCEPTION_ILLEGAL_INSTRUCTION: std::cerr<<"Error: EXCEPTION_ILLEGAL_INSTRUCTION"; break; case EXCEPTION_IN_PAGE_ERROR: std::cerr<<"Error: EXCEPTION_IN_PAGE_ERROR"; break; case EXCEPTION_INT_DIVIDE_BY_ZERO: std::cerr<<"Error: EXCEPTION_INT_DIVIDE_BY_ZERO"; break; case EXCEPTION_INT_OVERFLOW: std::cerr<<"Error: EXCEPTION_INT_OVERFLOW"; break; case EXCEPTION_INVALID_DISPOSITION: std::cerr<<"Error: EXCEPTION_INVALID_DISPOSITION"; break; case EXCEPTION_NONCONTINUABLE_EXCEPTION: std::cerr<<"Error: EXCEPTION_NONCONTINUABLE_EXCEPTION"; break; case EXCEPTION_PRIV_INSTRUCTION: std::cerr<<"Error: EXCEPTION_PRIV_INSTRUCTION"; break; case EXCEPTION_SINGLE_STEP: std::cerr<<"Error: EXCEPTION_SINGLE_STEP"; break; case EXCEPTION_STACK_OVERFLOW: std::cerr<<"Error: EXCEPTION_STACK_OVERFLOW"; break; default: std::cerr<<"Error: Unrecognized Exception"; break; } std::cerr<<" at "; /* If this is a stack overflow then we can't walk the stack, so just show where the error happened */ if (EXCEPTION_STACK_OVERFLOW != ExceptionInfo->ExceptionRecord->ExceptionCode) std::cerr<<windows_print_stacktrace(ExceptionInfo->ContextRecord)<<std::endl; else #ifdef _M_IX86 std::cerr<<demangleStacktraceEntry((void*)ExceptionInfo->ContextRecord->Eip)<<"; Sorry, no stacktrace for windows here :-(\n Please upgrade to Linux"<<std::endl; #else std::cerr<<demangleStacktraceEntry((void*)ExceptionInfo->ContextRecord->Rip)<<"; Sorry, no stacktrace for windows here :-(\n Please upgrade to Linux"<<std::endl; #endif return EXCEPTION_EXECUTE_HANDLER; } void set_signal_handler() { SetUnhandledExceptionFilter(windows_exception_handler); } } std::string gen_stacktrace(int framesToSkip) { std::stringstream ret; CONTEXT context; memset(&context, 0, sizeof(context)); context.ContextFlags = CONTEXT_CONTROL; // Capture the thread context rtlCaptureContext( & context ); ret<<windows_print_stacktrace(&context)<<std::endl; return ret.str(); } #else void init_stacktrace(std::string exeName) { EXE_NAME = exeName; set_signal_handler(); INFO("Startet from "<<exeName); } namespace { void posix_signal_handler(int sig, siginfo_t *siginfo, void *context) { (void)context; switch(sig) { case SIGSEGV: printStackTrace("Caught SIGSEGV: Segmentation Fault"); break; case SIGINT: printStackTrace("Caught SIGINT: Interactive attention signal, (usually ctrl+c)"); break; case SIGFPE: switch(siginfo->si_code) { case FPE_INTDIV: printStackTrace("Caught SIGFPE: (integer divide by zero)"); break; case FPE_INTOVF: printStackTrace("Caught SIGFPE: (integer overflow)"); break; case FPE_FLTDIV: printStackTrace("Caught SIGFPE: (floating-point divide by zero)"); break; case FPE_FLTOVF: printStackTrace("Caught SIGFPE: (floating-point overflow)"); break; case FPE_FLTUND: printStackTrace("Caught SIGFPE: (floating-point underflow)"); break; case FPE_FLTRES: printStackTrace("Caught SIGFPE: (floating-point inexact result)"); break; case FPE_FLTINV: printStackTrace("Caught SIGFPE: (floating-point invalid operation)"); break; case FPE_FLTSUB: printStackTrace("Caught SIGFPE: (subscript out of range)"); break; default: printStackTrace("Caught SIGFPE: Arithmetic Exception"); break; } case SIGILL: switch(siginfo->si_code) { case ILL_ILLOPC: printStackTrace("Caught SIGILL: (illegal opcode)"); break; case ILL_ILLOPN: printStackTrace("Caught SIGILL: (illegal operand)"); break; case ILL_ILLADR: printStackTrace("Caught SIGILL: (illegal addressing mode)"); break; case ILL_ILLTRP: printStackTrace("Caught SIGILL: (illegal trap)"); break; case ILL_PRVOPC: printStackTrace("Caught SIGILL: (privileged opcode)"); break; case ILL_PRVREG: printStackTrace("Caught SIGILL: (privileged register)"); break; case ILL_COPROC: printStackTrace("Caught SIGILL: (coprocessor error)"); break; case ILL_BADSTK: printStackTrace("Caught SIGILL: (internal stack error)"); break; default: printStackTrace("Caught SIGILL: Illegal Instruction"); break; } break; case SIGTERM: printStackTrace("Caught SIGTERM: a termination request was sent to the program"); break; case SIGABRT: printStackTrace("Caught SIGABRT: usually caused by an abort() or assert()"); break; default: break; } _Exit(1); } char alternate_stack[SIGSTKSZ*2]; void set_signal_handler() { /* setup alternate stack */ { stack_t ss; /* malloc is usually used here, I'm not 100% sure my static allocation is valid but it seems to work just fine. */ ss.ss_sp = (void*)alternate_stack; ss.ss_size = sizeof(alternate_stack); ss.ss_flags = 0; if (sigaltstack(&ss, NULL) != 0) std::cerr<<"failed to create alternate stack for handlers!"<<std::endl; } /* register our signal handlers */ { struct sigaction sig_action; sig_action.sa_sigaction = posix_signal_handler; sigemptyset(&sig_action.sa_mask); #ifdef __APPLE__ /* for some reason we backtrace() doesn't work on osx when we use an alternate stack */ sig_action.sa_flags = SA_SIGINFO; #else sig_action.sa_flags = SA_SIGINFO | SA_ONSTACK; #endif if (sigaction(SIGSEGV, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGSEGV!"); if (sigaction(SIGFPE, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGFPE!"); if (sigaction(SIGINT, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGINT!"); if (sigaction(SIGILL, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGILL!"); if (sigaction(SIGTERM, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGTERM!"); if (sigaction(SIGABRT, &sig_action, NULL) != 0) ERROR("failed to register handler for SIGABRT!"); } } } std::string gen_stacktrace(int framesToSkip) { std::stringstream ret; void *trace[32]; auto trace_size = backtrace(trace, 32); char** messages = backtrace_symbols(trace, trace_size); /* skip first stack frame (points here) */ bool first=true; for (auto i=1+framesToSkip; i<trace_size; ++i) { if(first) first=false; else ret<<"Called From "; ret<<messages[i]<<std::endl<<" "<<demangleStacktraceEntry(trace[i])<<std::endl; } return ret.str(); } #endif } } #else namespace core { namespace util { void init_stacktrace(std::string exeName) { } std::string gen_stacktrace(int stacksToSkip) { return ""; } bool is_stacktrace_available() { return false; } } } #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2012 Couchbase, 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 "config.h" #include <dirent.h> #include <string.h> #include "couch-kvstore/dirutils.h" namespace CouchKVStoreDirectoryUtilities { using namespace std; static string split(const string &input, bool directory) { string::size_type path = input.find_last_of("\\/"); string file; string dir; if (path == string::npos) { dir = "."; file = input; } else { dir = input.substr(0, path); if (dir.length() == 0) { dir = input.substr(0, 1); } file = input.substr(path + 1); } if (directory) { return dir; } else { return file; } } string dirname(const string &dir) { return split(dir, true); } string basename(const string &name) { return split(name, false); } vector<string> findFilesWithPrefix(const string &dir, const string &name) { vector<string> files; DIR *dp = opendir(dir.c_str()); if (dp != NULL) { struct dirent *de; while ((de = readdir(dp)) != NULL) { if (strncmp(de->d_name, name.c_str(), name.length()) == 0) { string entry = dir; entry.append("/"); entry.append(de->d_name); files.push_back(entry); } } closedir(dp); } return files; } vector<string> findFilesWithPrefix(const string &name) { return findFilesWithPrefix(dirname(name), basename(name)); } vector<string> findFilesContaining(const string &dir, const string &name) { vector<string> files; DIR *dp = opendir(dir.c_str()); if (dp != NULL) { struct dirent *de; while ((de = readdir(dp)) != NULL) { if (name.empty() || strstr(de->d_name, name.c_str()) != NULL) { string entry = dir; entry.append("/"); entry.append(de->d_name); files.push_back(entry); } } closedir(dp); } return files; } } <commit_msg>Fix directory utilities for win32<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2012 Couchbase, 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 "config.h" #ifndef _MSC_VER #include <dirent.h> #endif #include <string.h> #include "couch-kvstore/dirutils.h" namespace CouchKVStoreDirectoryUtilities { using namespace std; static string split(const string &input, bool directory) { string::size_type path = input.find_last_of("\\/"); string file; string dir; if (path == string::npos) { dir = "."; file = input; } else { dir = input.substr(0, path); if (dir.length() == 0) { dir = input.substr(0, 1); } file = input.substr(path + 1); } if (directory) { return dir; } else { return file; } } string dirname(const string &dir) { return split(dir, true); } string basename(const string &name) { return split(name, false); } #ifdef _MSC_VER vector<string> findFilesWithPrefix(const string &dir, const string &name) { vector<string> files; std::string match = dir + "\\" + name + "*"; WIN32_FIND_DATA FindFileData; HANDLE hFind = FindFirstFileEx(match.c_str(), FindExInfoStandard, &FindFileData, FindExSearchNameMatch, NULL, 0); if (hFind != INVALID_HANDLE_VALUE) { do { string entry = dir; entry.append("\\"); entry.append(FindFileData.cFileName); files.push_back(entry); } while (FindNextFile(hFind, &FindFileData)); FindClose(hFind); } return files; } #else vector<string> findFilesWithPrefix(const string &dir, const string &name) { vector<string> files; DIR *dp = opendir(dir.c_str()); if (dp != NULL) { struct dirent *de; while ((de = readdir(dp)) != NULL) { if (strncmp(de->d_name, name.c_str(), name.length()) == 0) { string entry = dir; entry.append("/"); entry.append(de->d_name); files.push_back(entry); } } closedir(dp); } return files; } #endif vector<string> findFilesWithPrefix(const string &name) { return findFilesWithPrefix(dirname(name), basename(name)); } #ifdef _MSC_VER vector<string> findFilesContaining(const string &dir, const string &name) { vector<string> files; std::string match = dir + "\\*" + name + "*"; WIN32_FIND_DATA FindFileData; HANDLE hFind = FindFirstFileEx(match.c_str(), FindExInfoStandard, &FindFileData, FindExSearchNameMatch, NULL, 0); if (hFind != INVALID_HANDLE_VALUE) { do { string entry = dir; entry.append("\\"); entry.append(FindFileData.cFileName); files.push_back(entry); } while (FindNextFile(hFind, &FindFileData)); FindClose(hFind); } return files; } #else vector<string> findFilesContaining(const string &dir, const string &name) { vector<string> files; DIR *dp = opendir(dir.c_str()); if (dp != NULL) { struct dirent *de; while ((de = readdir(dp)) != NULL) { if (name.empty() || strstr(de->d_name, name.c_str()) != NULL) { string entry = dir; entry.append("/"); entry.append(de->d_name); files.push_back(entry); } } closedir(dp); } return files; } #endif } <|endoftext|>
<commit_before>#include "dashplayer.hpp" using namespace player; DashPlayer::DashPlayer(std::string MPD, string adaptionlogic_name, int interest_lifetime) { this->adaptionlogic_name = adaptionlogic_name; this->interest_lifetime = interest_lifetime; streaming_active = false; mpd_url=MPD; mpd = NULL; base_url = ""; max_buffered_seconds=50; mbuffer = boost::shared_ptr<MultimediaBuffer>(new MultimediaBuffer(max_buffered_seconds)); //factory - to be replaced alogic = AdaptationLogicFactory::Create(adaptionlogic_name, this); //TODO downloader = boost::shared_ptr<FileDownloader>(new FileDownloader(this->interest_lifetime )); hasDownloadedAllSegments = false; isStalling=false; last_requestedRepresentation = NULL; last_requestedSegmentNr = 0; } DashPlayer::~DashPlayer() { } void DashPlayer::startStreaming () { //1fetch MPD and parse MPD std::string mpd_path("/tmp/video.mpd"); shared_ptr<itec::Buffer> mpd_data = downloader->getFile (mpd_url); if(mpd_data == NULL) { fprintf(stderr, "Error fetching MPD! Exiting..\n"); return; } writeFileToDisk(mpd_data, mpd_path); fprintf(stderr, "parsing...\n"); if(!parseMPD(mpd_path)) return; alogic->SetAvailableRepresentations (availableRepresentations); //2. start streaming (1. thread) boost::thread downloadThread(&DashPlayer::scheduleDownloadNextSegment, this); //3. start consuming (2. thread) boost::thread playbackThread(&DashPlayer::schedulePlayback, this); //wait until threads finished downloadThread.join (); playbackThread.join (); exit(0); } void DashPlayer::scheduleDownloadNextSegment () { const dash::mpd::IRepresentation* requestedRepresentation = NULL; unsigned int requestedSegmentNr = 0; dash::mpd::ISegmentURL* requestedSegmentURL = alogic->GetNextSegment(&requestedSegmentNr, &requestedRepresentation, &hasDownloadedAllSegments); if(hasDownloadedAllSegments) // we got all segmetns, exit download thread return; if(requestedSegmentURL == NULL) // IDLE e.g. buffer is full { boost::this_thread::sleep(boost::posix_time::milliseconds(500)); scheduleDownloadNextSegment(); return; } fprintf(stderr, "downloading segment = %s\n",(base_url+requestedSegmentURL->GetMediaURI()).c_str ()); last_requestedRepresentation = requestedRepresentation; last_requestedSegmentNr = requestedSegmentNr; shared_ptr<itec::Buffer> segmentData = downloader->getFile (base_url+requestedSegmentURL->GetMediaURI()); if(segmentData != NULL) { mbuffer->addToBuffer (requestedSegmentNr, requestedRepresentation); } scheduleDownloadNextSegment(); } void DashPlayer::schedulePlayback () { fprintf(stderr, "Schedule playback\n"); unsigned int buffer_level = mbuffer->getBufferedSeconds(); // did we finish streaming yet? if (buffer_level == 0 && hasDownloadedAllSegments == true) return; //finished streaming player::MultimediaBuffer::BufferRepresentationEntry entry = mbuffer->consumeFromBuffer (); double consumedSeconds = entry.segmentDuration; if ( consumedSeconds > 0) { fprintf(stderr, "Consumed Segment %d, with Rep %s for %f seconds\n",entry.segmentNumber,entry.repId.c_str(), entry.segmentDuration); if (isStalling) { boost::posix_time::ptime stallEndTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time()); boost::posix_time::time_duration stallDuration; // we had a freeze/stall, but we can continue playing now stallDuration = (stallEndTime - stallStartTime); isStalling = false; } /*m_playerTracer(this, entry.segmentNumber, entry.segmentDuration, entry.repId, entry.bitrate_bit_s, freezeTime, entry.depIds);*/ } else { // could not consume, means buffer is empty if ( isStalling == false) { isStalling = true; stallStartTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time()); } } if(consumedSeconds == 0.0) // we are stalling { //check for download abort if(last_requestedRepresentation != NULL && !hasDownloadedAllSegments && last_requestedRepresentation->GetDependencyId ().size ()>0) { if(alogic->hasMinBufferLevel (last_requestedRepresentation)) { //TODO abort download of current segment! } } boost::this_thread::sleep(boost::posix_time::milliseconds(500)); } else { boost::this_thread::sleep(boost::posix_time::milliseconds(consumedSeconds*1000)); } schedulePlayback(); } bool DashPlayer::parseMPD(std::string mpd_path) { dash::IDASHManager *manager; manager = CreateDashManager(); mpd = manager->Open((char*)mpd_path.c_str ()); // We don't need the manager anymore... manager->Delete(); manager = NULL; if (mpd == NULL) { fprintf(stderr, "MPD - Parsing Error. Exiting..\n"); return false; } // we are assuming there is only 1 period, get the first one IPeriod *currentPeriod = mpd->GetPeriods().at(0); // get base URL (we take first always) std::vector<dash::mpd::IBaseUrl*> baseUrls = mpd->GetBaseUrls (); if(baseUrls.size () < 1) { fprintf(stderr, "No BaseUrl detected!\n"); return false; } base_url = baseUrls.at (0)->GetUrl(); // Get the adaptation sets, though we are only consider the first one std::vector<IAdaptationSet *> allAdaptationSets = currentPeriod->GetAdaptationSets(); if (allAdaptationSets.size() < 1) { fprintf(stderr, "No adaptation sets found in MPD!\n"); return false; } IAdaptationSet* adaptationSet = allAdaptationSets.at(0); std::vector<IRepresentation*> reps = adaptationSet->GetRepresentation(); if(reps.size () < 1) { fprintf(stderr, "No represntations found in MPD!\n"); return false; } availableRepresentations.clear(); for (IRepresentation* rep : reps) { std::string repId = rep->GetId(); availableRepresentations[repId] = rep; } return true; } void DashPlayer::writeFileToDisk(shared_ptr<itec::Buffer> buf, string file_path) { ofstream outputStream; outputStream.open(file_path, ios::out | ios::binary); outputStream.write(buf->getData(), buf->getSize()); outputStream.close(); } // // Main entry-point // int main(int argc, char** argv) { string appName = boost::filesystem::basename(argv[0]); options_description desc("Programm Options"); desc.add_options () ("name,p", value<string>()->required (), "The name of the interest to be sent (Required)") ("adaptionlogic,a",value<string>()->required(), "The name of the adaption-logic to be used (Required)") ("lifetime,s", value<int>(), "The lifetime of the interest in milliseconds. (Default 1000ms)"); positional_options_description positionalOptions; variables_map vm; try { store(command_line_parser(argc, argv).options(desc) .positional(positionalOptions).run(), vm); // throws on error notify(vm); //notify if required parameters are not provided. } catch(boost::program_options::required_option& e) { // user forgot to provide a required option cerr << "name ... The name of the interest to be sent (Required)" << endl; cerr << "adaptionlogic ... The name of the adaption-logic to be used (Required, buffer or rate)" << endl; cerr << "lifetime ... The lifetime of the interest in milliseconds. (Default 1000ms)" << endl; cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData --adaptionlogic buffer" << endl; cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData --adaptionlogic buffer --lifetime 1000" << endl; cerr << "ERROR: " << e.what() << endl << endl; return -1; } catch(boost::program_options::error& e) { // a given parameter is faulty (e.g. given a string, asked for int) cerr << "ERROR: " << e.what() << endl << endl; return -1; } catch(exception& e) { cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << endl; return -1; } int lifetime = 1000; if(vm.count ("lifetime")) { lifetime = vm["lifetime"].as<int>(); } // create new DashPlayer instance with given parameters DashPlayer consumer(vm["name"].as<string>(),vm["adaptionlogic"].as<string>(), lifetime); try { //get MPD and start streaming consumer.startStreaming(); } catch (const exception& e) { // shit happens cerr << "ERROR: " << e.what() << endl; } return 0; } double DashPlayer::GetBufferLevel(std::string repId) { if(repId.compare ("NULL") == 0) return mbuffer->getBufferedSeconds (); else return mbuffer->getBufferedSeconds (repId); } unsigned int DashPlayer::nextSegmentNrToConsume () { return mbuffer->nextSegmentNrToBeConsumed (); } unsigned int DashPlayer::getHighestBufferedSegmentNr(std::string repId) { return mbuffer->getHighestBufferedSegmentNr (repId); } <commit_msg>added "http" replacment for baseurl.<commit_after>#include "dashplayer.hpp" using namespace player; DashPlayer::DashPlayer(std::string MPD, string adaptionlogic_name, int interest_lifetime) { this->adaptionlogic_name = adaptionlogic_name; this->interest_lifetime = interest_lifetime; streaming_active = false; mpd_url=MPD; mpd = NULL; base_url = ""; max_buffered_seconds=50; mbuffer = boost::shared_ptr<MultimediaBuffer>(new MultimediaBuffer(max_buffered_seconds)); //factory - to be replaced alogic = AdaptationLogicFactory::Create(adaptionlogic_name, this); //TODO downloader = boost::shared_ptr<FileDownloader>(new FileDownloader(this->interest_lifetime )); hasDownloadedAllSegments = false; isStalling=false; last_requestedRepresentation = NULL; last_requestedSegmentNr = 0; } DashPlayer::~DashPlayer() { } void DashPlayer::startStreaming () { //1fetch MPD and parse MPD std::string mpd_path("/tmp/video.mpd"); shared_ptr<itec::Buffer> mpd_data = downloader->getFile (mpd_url); if(mpd_data == NULL) { fprintf(stderr, "Error fetching MPD! Exiting..\n"); return; } writeFileToDisk(mpd_data, mpd_path); fprintf(stderr, "parsing...\n"); if(!parseMPD(mpd_path)) return; alogic->SetAvailableRepresentations (availableRepresentations); //2. start streaming (1. thread) boost::thread downloadThread(&DashPlayer::scheduleDownloadNextSegment, this); //3. start consuming (2. thread) boost::thread playbackThread(&DashPlayer::schedulePlayback, this); //wait until threads finished downloadThread.join (); playbackThread.join (); exit(0); } void DashPlayer::scheduleDownloadNextSegment () { const dash::mpd::IRepresentation* requestedRepresentation = NULL; unsigned int requestedSegmentNr = 0; dash::mpd::ISegmentURL* requestedSegmentURL = alogic->GetNextSegment(&requestedSegmentNr, &requestedRepresentation, &hasDownloadedAllSegments); if(hasDownloadedAllSegments) // we got all segmetns, exit download thread return; if(requestedSegmentURL == NULL) // IDLE e.g. buffer is full { boost::this_thread::sleep(boost::posix_time::milliseconds(500)); scheduleDownloadNextSegment(); return; } fprintf(stderr, "downloading segment = %s\n",(base_url+requestedSegmentURL->GetMediaURI()).c_str ()); last_requestedRepresentation = requestedRepresentation; last_requestedSegmentNr = requestedSegmentNr; shared_ptr<itec::Buffer> segmentData = downloader->getFile (base_url+requestedSegmentURL->GetMediaURI()); if(segmentData != NULL) { mbuffer->addToBuffer (requestedSegmentNr, requestedRepresentation); } scheduleDownloadNextSegment(); } void DashPlayer::schedulePlayback () { fprintf(stderr, "Schedule playback\n"); unsigned int buffer_level = mbuffer->getBufferedSeconds(); // did we finish streaming yet? if (buffer_level == 0 && hasDownloadedAllSegments == true) return; //finished streaming player::MultimediaBuffer::BufferRepresentationEntry entry = mbuffer->consumeFromBuffer (); double consumedSeconds = entry.segmentDuration; if ( consumedSeconds > 0) { fprintf(stderr, "Consumed Segment %d, with Rep %s for %f seconds\n",entry.segmentNumber,entry.repId.c_str(), entry.segmentDuration); if (isStalling) { boost::posix_time::ptime stallEndTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time()); boost::posix_time::time_duration stallDuration; // we had a freeze/stall, but we can continue playing now stallDuration = (stallEndTime - stallStartTime); isStalling = false; } /*m_playerTracer(this, entry.segmentNumber, entry.segmentDuration, entry.repId, entry.bitrate_bit_s, freezeTime, entry.depIds);*/ } else { // could not consume, means buffer is empty if ( isStalling == false) { isStalling = true; stallStartTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time()); } } if(consumedSeconds == 0.0) // we are stalling { //check for download abort if(last_requestedRepresentation != NULL && !hasDownloadedAllSegments && last_requestedRepresentation->GetDependencyId ().size ()>0) { if(alogic->hasMinBufferLevel (last_requestedRepresentation)) { //TODO abort download of current segment! } } boost::this_thread::sleep(boost::posix_time::milliseconds(500)); } else { boost::this_thread::sleep(boost::posix_time::milliseconds(consumedSeconds*1000)); } schedulePlayback(); } bool DashPlayer::parseMPD(std::string mpd_path) { dash::IDASHManager *manager; manager = CreateDashManager(); mpd = manager->Open((char*)mpd_path.c_str ()); // We don't need the manager anymore... manager->Delete(); manager = NULL; if (mpd == NULL) { fprintf(stderr, "MPD - Parsing Error. Exiting..\n"); return false; } // we are assuming there is only 1 period, get the first one IPeriod *currentPeriod = mpd->GetPeriods().at(0); // get base URL (we take first always) std::vector<dash::mpd::IBaseUrl*> baseUrls = mpd->GetBaseUrls (); if(baseUrls.size () < 1) { fprintf(stderr, "No BaseUrl detected!\n"); return false; } base_url = baseUrls.at (0)->GetUrl(); if(base_url.substr (0,7).compare ("http://") == 0) base_url = base_url.substr(6,base_url.length ()); // Get the adaptation sets, though we are only consider the first one std::vector<IAdaptationSet *> allAdaptationSets = currentPeriod->GetAdaptationSets(); if (allAdaptationSets.size() < 1) { fprintf(stderr, "No adaptation sets found in MPD!\n"); return false; } IAdaptationSet* adaptationSet = allAdaptationSets.at(0); std::vector<IRepresentation*> reps = adaptationSet->GetRepresentation(); if(reps.size () < 1) { fprintf(stderr, "No represntations found in MPD!\n"); return false; } availableRepresentations.clear(); for (IRepresentation* rep : reps) { std::string repId = rep->GetId(); availableRepresentations[repId] = rep; } return true; } void DashPlayer::writeFileToDisk(shared_ptr<itec::Buffer> buf, string file_path) { ofstream outputStream; outputStream.open(file_path, ios::out | ios::binary); outputStream.write(buf->getData(), buf->getSize()); outputStream.close(); } // // Main entry-point // int main(int argc, char** argv) { string appName = boost::filesystem::basename(argv[0]); options_description desc("Programm Options"); desc.add_options () ("name,p", value<string>()->required (), "The name of the interest to be sent (Required)") ("adaptionlogic,a",value<string>()->required(), "The name of the adaption-logic to be used (Required)") ("lifetime,s", value<int>(), "The lifetime of the interest in milliseconds. (Default 1000ms)"); positional_options_description positionalOptions; variables_map vm; try { store(command_line_parser(argc, argv).options(desc) .positional(positionalOptions).run(), vm); // throws on error notify(vm); //notify if required parameters are not provided. } catch(boost::program_options::required_option& e) { // user forgot to provide a required option cerr << "name ... The name of the interest to be sent (Required)" << endl; cerr << "adaptionlogic ... The name of the adaption-logic to be used (Required, buffer or rate)" << endl; cerr << "lifetime ... The lifetime of the interest in milliseconds. (Default 1000ms)" << endl; cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData --adaptionlogic buffer" << endl; cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData --adaptionlogic buffer --lifetime 1000" << endl; cerr << "ERROR: " << e.what() << endl << endl; return -1; } catch(boost::program_options::error& e) { // a given parameter is faulty (e.g. given a string, asked for int) cerr << "ERROR: " << e.what() << endl << endl; return -1; } catch(exception& e) { cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << endl; return -1; } int lifetime = 1000; if(vm.count ("lifetime")) { lifetime = vm["lifetime"].as<int>(); } // create new DashPlayer instance with given parameters DashPlayer consumer(vm["name"].as<string>(),vm["adaptionlogic"].as<string>(), lifetime); try { //get MPD and start streaming consumer.startStreaming(); } catch (const exception& e) { // shit happens cerr << "ERROR: " << e.what() << endl; } return 0; } double DashPlayer::GetBufferLevel(std::string repId) { if(repId.compare ("NULL") == 0) return mbuffer->getBufferedSeconds (); else return mbuffer->getBufferedSeconds (repId); } unsigned int DashPlayer::nextSegmentNrToConsume () { return mbuffer->nextSegmentNrToBeConsumed (); } unsigned int DashPlayer::getHighestBufferedSegmentNr(std::string repId) { return mbuffer->getHighestBufferedSegmentNr (repId); } <|endoftext|>
<commit_before>/** * Copyright (c) 2015, Jozef Stefan Institute, Quintelligence d.o.o. and contributors * All rights reserved. * * This source code is licensed under the FreeBSD license found in the * LICENSE file in the root directory of this source tree. */ using namespace TRegression; /////////////////////////////////////////// // Logistic Regression TLogReg::TLogReg(const double& _Lambda, const bool _IncludeIntercept, const bool _Verbose): Lambda(_Lambda), WgtV(), IncludeIntercept(_IncludeIntercept), Verbose(_Verbose), Notify(Verbose ? TNotify::StdNotify : TNotify::NullNotify) {} TLogReg::TLogReg(TSIn& SIn): Lambda(TFlt(SIn)), WgtV(SIn), IncludeIntercept(TBool(SIn)), Verbose(TBool(SIn)), Notify(nullptr) { Notify = Verbose ? TNotify::StdNotify : TNotify::NullNotify; } void TLogReg::Save(TSOut& SOut) const { TFlt(Lambda).Save(SOut); WgtV.Save(SOut); TBool(IncludeIntercept).Save(SOut); TBool(Verbose).Save(SOut); } void TLogReg::Fit(const TFltVV& _X, const TFltV& y, const double& Eps) { TFltVV X(_X); if (IncludeIntercept) { // add 1s into the last row X.AddXDim(); for (int i = 0; i < X.GetCols(); i++) { X(X.GetRows()-1, i) = 1; } } const int NInst = X.GetCols(); const int Dim = X.GetRows(); const int OrigDim = IncludeIntercept ? Dim-1 : Dim; // minimize the following objective function: // L(w) = (sum(log(1 + exp(w*x_i)) - y_i*w*x_i) + lambda*beta*beta'/2) / m // using Newton-Raphson algorithm: // w <- w - H^(-1)(w)*g(w) // g(w) = (X*(s(beta*x) - y)' + lambda*beta') // H(w) = X*W*X^(-1) + lambda*I // where H is the Hessian at point w, g is the gradient of the objective function at point w // W is a diagonal matrix defined as W_ii = p_i(1 - p_i) // temporary variables TFltV ProbV(NInst, NInst); // vector of probabilities TFltV PrevProbV(NInst, NInst); // vector of probs in the previous step, used to terminate the procedure TFltV DeltaWgtV(Dim, Dim); // the step used to update the weights TFltV YMinP(NInst, NInst); TFltV GradV(Dim, Dim); // gradient TFltVV XTimesW(Dim, NInst); // temporary variable to compute (X*W)*X' TFltVV H(Dim, Dim); // Hessian TFltVV X_t(X.GetCols(), X.GetRows()); TLinAlg::Transpose(X, X_t); // the transposed instance matrix TVec<TIntFltKdV> WgtColSpVV(NInst, NInst); // weight matrix // generate weight matrix with only ones on the diagonal // so you don't recreate all the object every iteration for (int i = 0; i < NInst; i++) { WgtColSpVV[i].Add(TIntFltKd(i, 1)); } WgtV.Gen(Dim); // perform the algorithm double Diff = TFlt::NInf; double AbsDiff; int k = 1; do { if (k % 10 == 0) { Notify->OnNotifyFmt(TNotifyType::ntInfo, "Step: %d, diff: %.3f", k, Diff); } // compute the probabilities p_i = 1 / (1 + exp(-w*x_i)) and // compute the weight matrix diagonal W_ii = p_i(1 - p_i) TLinAlg::Multiply(X_t, WgtV, ProbV); for (int i = 0; i < NInst; i++) { ProbV[i] = 1 / (1 + TMath::Power(TMath::E, -ProbV[i])); WgtColSpVV[i][0].Dat = ProbV[i]*(1 - ProbV[i]); } // compute the Hessian H = X*W*X' + lambda*I // 1) compute X*W TLinAlg::Multiply(X, WgtColSpVV, XTimesW); // 2) compute H = (X*W)*X' TLinAlg::Multiply(XTimesW, X_t, H); // 3) add lambda to the diagonal of H, exclude the punishment for the intercept for (int i = 0; i < OrigDim; i++) { H(i,i) += Lambda; } // compute the gradient g(w) = X*(y - p)' + lambda * w // 1) compute (y - p) TLinAlg::LinComb(1, y, -1, ProbV, YMinP); // 2) compute X*(y - p) TLinAlg::Multiply(X, YMinP, GradV); // 3) add lambda * w, exclude the punishment for the intercept for (int i = 0; i < OrigDim; i++) { GradV[i] += Lambda*WgtV[i]; } // compute delta_w = H(w) \ (g(w)) #ifdef LAPACKE const TFlt SingEps = 1e-10; if (H.GetRows() == 1) { // fix for a bug in SVD factorization DeltaWgtV[0] = GradV[0] / H(0,0); } else { TLinAlg::SVDSolve(H, DeltaWgtV, GradV, SingEps); } #else throw TExcept::New("Should include LAPACKE!!"); #endif if (TFlt::IsNan(TLinAlg::Norm(DeltaWgtV))) { Notify->OnNotifyFmt(TNotifyType::ntInfo, "Got NaNs while fitting logistic regression! The weights could still be OK."); break; } // update the current weight vector for (int i = 0; i < Dim; i++) { WgtV[i] += DeltaWgtV[i]; } // recompute the termination criteria and store the probabilities for // the next iteration Diff = TFlt::NInf; for (int i = 0; i < NInst; i++) { AbsDiff = TFlt::Abs(PrevProbV[i] - ProbV[i]); if (AbsDiff > Diff) { Diff = AbsDiff; } PrevProbV[i] = ProbV[i]; } k++; } while (Diff > Eps); Notify->OnNotifyFmt(TNotifyType::ntInfo, "Converged. Diff: %.5f", Diff); } double TLogReg::Predict(const TFltV& x) const { if (IncludeIntercept) { TFltV x1(x); x1.Add(1); return PredictWithoutIntercept(x1); } else { return PredictWithoutIntercept(x); } } void TLogReg::GetWgtV(TFltV& _WgtV) const { _WgtV = WgtV; if (IncludeIntercept) { _WgtV.DelLast(); } } double TLogReg::PredictWithoutIntercept(const TFltV& x) const { if (!Initialized()) { return 0; } EAssertR(x.Len() == WgtV.Len(), "Dimension mismatch while predicting!"); return 1 / (1 + TMath::Power(TMath::E, -TLinAlg::DotProduct(WgtV, x))); } /////////////////////////////////////////// // Proportional Hazards model TPropHazards::TPropHazards(const double& _Lambda, const bool _Verbose): Lambda(_Lambda), WgtV(), Verbose(_Verbose), Notify(_Verbose ? TNotify::StdNotify : TNotify::NullNotify) {} TPropHazards::TPropHazards(TSIn& SIn): Lambda(TFlt(SIn)), WgtV(SIn), Verbose(TBool(SIn)) { Notify = Verbose ? TNotify::StdNotify : TNotify::NullNotify; } void TPropHazards::Save(TSOut& SOut) const { TFlt(Lambda).Save(SOut); WgtV.Save(SOut); TBool(Verbose).Save(SOut); } void TPropHazards::Fit(const TFltVV& _X, const TFltV& t, const double& Eps) { const int NInst = _X.GetCols(); const int Dim = _X.GetRows() + 1; Notify->OnNotifyFmt(TNotifyType::ntInfo, "Fitting proportional hazards model on %d instances ...", NInst); TFltVV X(_X.GetRows()+1, NInst); for (int ColN = 0; ColN < NInst; ColN++) { X(0, ColN) = 1; for (int RowN = 0; RowN < _X.GetRows(); RowN++) { X(RowN+1, ColN) = _X(RowN, ColN); } } WgtV.Gen(Dim); TFltVV X_t(X); X_t.Transpose(); // TODO slow TFltVV XTimesW(X.GetRows(), X.GetCols()); TFltVV H(Dim, Dim); TFltV TempNInstV(NInst, NInst); TFltV GradV(Dim, Dim); TFltV DeltaWgtV(Dim, Dim); TSpVV WgtColSpVV(NInst, NInst); double IntensTimesT; // generate weight matrix with only ones on the diagonal // so you don't recreate all the object every iteration for (int i = 0; i < NInst; i++) { WgtColSpVV[i].Add(TIntFltKd(i, 1)); } int k = 0; double Diff = TFlt::PInf; while (Diff > Eps) { // construct the intensity vector PredictInternal(X, TempNInstV); // I) construct the Hessian: X*W*X' + lambda*I // prepare W and t .* intens - 1 for (int i = 0; i < NInst; i++) { IntensTimesT = t[i] * TempNInstV[i]; TempNInstV[i] = IntensTimesT - 1; WgtColSpVV[i][0].Dat = IntensTimesT; } // 1) compute X*W TLinAlg::Multiply(X, WgtColSpVV, XTimesW); // 2) compute (X*W)*X' TLinAlg::Multiply(XTimesW, X_t, H); // 3) (X*W*X') + lambda*I, exclude the base hazard if (Lambda > 0) { for (int i = 1; i < Dim; i++) { H(i,i) += Lambda; } } // II) construct the gradient: (t .* intens - 1) * X' + lambda*[0, w(2:end)] // 1) (t .* intens - 1) * X' TLinAlg::Multiply(X, TempNInstV, GradV); // 2) ((t .* intens - 1) * X') + lambda*[0, w(2:end)] if (Lambda > 0) { for (int i = 1; i < Dim; i++) { GradV[i] += Lambda * WgtV[i]; } } // III) compute: delta_w = H \ grad #ifdef LAPACKE const TFlt SingEps = 1e-10; if (H.GetRows() == 1) { // fix for a bug in SVD factorization DeltaWgtV[0] = GradV[0] / H(0,0); } else { TLinAlg::SVDSolve(H, DeltaWgtV, GradV, SingEps); } #else throw TExcept::New("Should include LAPACKE!!"); #endif // IV) w <= w - delta_w for (int i = 0; i < Dim; i++) { WgtV[i] -= DeltaWgtV[i]; } Diff = TLinAlg::Norm(DeltaWgtV); EAssertR(!TFlt::IsNan(Diff), "nans in delta wgt vector!"); if (++k % 10 == 0) { Notify->OnNotifyFmt(TNotifyType::ntInfo, "Step: %d, diff: %.3f", k, Diff); } } Notify->OnNotifyFmt(TNotifyType::ntInfo, "Converged. Diff: %.5f", Diff); } double TPropHazards::Predict(const TFltV& x) const { if (WgtV.Empty()) { return 0; } double Pred = WgtV[0]; for (int i = 1; i < WgtV.Len(); i++) { Pred += x[i-1]*WgtV[i]; } return exp(Pred); } void TPropHazards::GetWgtV(TFltV& _WgtV) const { for (int i = 1; i < WgtV.Len(); i++) { _WgtV.Add(WgtV[i]); } } void TPropHazards::PredictInternal(const TFltVV& X, TFltV& IntensV) const { const int NInst = X.GetCols(); TLinAlg::MultiplyT(X, WgtV, IntensV); for (int i = 0; i < NInst; i++) { IntensV[i] = exp(IntensV[i]); } } ///////////////////////////////////////////// // Ridge Regression void TRidgeReg::Fit(const TFltVV& X, const TFltV& y) { TNumericalStuff::LeastSquares(X, y, Gamma, WgtV); } double TRidgeReg::Predict(const TFltV& x) const { EAssertR(x.Len() == WgtV.Len(), "TRegression::TRidgeReg::Predict: model and data dimension mismatch"); return TLinAlg::DotProduct(x, WgtV); } <commit_msg>added asserts that check for input consistency in logistic regression and proportional hazards model<commit_after>/** * Copyright (c) 2015, Jozef Stefan Institute, Quintelligence d.o.o. and contributors * All rights reserved. * * This source code is licensed under the FreeBSD license found in the * LICENSE file in the root directory of this source tree. */ using namespace TRegression; /////////////////////////////////////////// // Logistic Regression TLogReg::TLogReg(const double& _Lambda, const bool _IncludeIntercept, const bool _Verbose): Lambda(_Lambda), WgtV(), IncludeIntercept(_IncludeIntercept), Verbose(_Verbose), Notify(Verbose ? TNotify::StdNotify : TNotify::NullNotify) {} TLogReg::TLogReg(TSIn& SIn): Lambda(TFlt(SIn)), WgtV(SIn), IncludeIntercept(TBool(SIn)), Verbose(TBool(SIn)), Notify(nullptr) { Notify = Verbose ? TNotify::StdNotify : TNotify::NullNotify; } void TLogReg::Save(TSOut& SOut) const { TFlt(Lambda).Save(SOut); WgtV.Save(SOut); TBool(IncludeIntercept).Save(SOut); TBool(Verbose).Save(SOut); } void TLogReg::Fit(const TFltVV& _X, const TFltV& y, const double& Eps) { TFltVV X(_X); if (IncludeIntercept) { // add 1s into the last row X.AddXDim(); for (int i = 0; i < X.GetCols(); i++) { X(X.GetRows()-1, i) = 1; } } const int NInst = X.GetCols(); const int Dim = X.GetRows(); const int OrigDim = IncludeIntercept ? Dim-1 : Dim; EAssertR(NInst == y.Len(), "TLogReg::Fit the number of instances in X.GetCols() and y.Len() do not match"); // minimize the following objective function: // L(w) = (sum(log(1 + exp(w*x_i)) - y_i*w*x_i) + lambda*beta*beta'/2) / m // using Newton-Raphson algorithm: // w <- w - H^(-1)(w)*g(w) // g(w) = (X*(s(beta*x) - y)' + lambda*beta') // H(w) = X*W*X^(-1) + lambda*I // where H is the Hessian at point w, g is the gradient of the objective function at point w // W is a diagonal matrix defined as W_ii = p_i(1 - p_i) // temporary variables TFltV ProbV(NInst, NInst); // vector of probabilities TFltV PrevProbV(NInst, NInst); // vector of probs in the previous step, used to terminate the procedure TFltV DeltaWgtV(Dim, Dim); // the step used to update the weights TFltV YMinP(NInst, NInst); TFltV GradV(Dim, Dim); // gradient TFltVV XTimesW(Dim, NInst); // temporary variable to compute (X*W)*X' TFltVV H(Dim, Dim); // Hessian TFltVV X_t(X.GetCols(), X.GetRows()); TLinAlg::Transpose(X, X_t); // the transposed instance matrix TVec<TIntFltKdV> WgtColSpVV(NInst, NInst); // weight matrix // generate weight matrix with only ones on the diagonal // so you don't recreate all the object every iteration for (int i = 0; i < NInst; i++) { WgtColSpVV[i].Add(TIntFltKd(i, 1)); } WgtV.Gen(Dim); // perform the algorithm double Diff = TFlt::NInf; double AbsDiff; int k = 1; do { if (k % 10 == 0) { Notify->OnNotifyFmt(TNotifyType::ntInfo, "Step: %d, diff: %.3f", k, Diff); } // compute the probabilities p_i = 1 / (1 + exp(-w*x_i)) and // compute the weight matrix diagonal W_ii = p_i(1 - p_i) TLinAlg::Multiply(X_t, WgtV, ProbV); for (int i = 0; i < NInst; i++) { ProbV[i] = 1 / (1 + TMath::Power(TMath::E, -ProbV[i])); WgtColSpVV[i][0].Dat = ProbV[i]*(1 - ProbV[i]); } // compute the Hessian H = X*W*X' + lambda*I // 1) compute X*W TLinAlg::Multiply(X, WgtColSpVV, XTimesW); // 2) compute H = (X*W)*X' TLinAlg::Multiply(XTimesW, X_t, H); // 3) add lambda to the diagonal of H, exclude the punishment for the intercept for (int i = 0; i < OrigDim; i++) { H(i,i) += Lambda; } // compute the gradient g(w) = X*(y - p)' + lambda * w // 1) compute (y - p) TLinAlg::LinComb(1, y, -1, ProbV, YMinP); // 2) compute X*(y - p) TLinAlg::Multiply(X, YMinP, GradV); // 3) add lambda * w, exclude the punishment for the intercept for (int i = 0; i < OrigDim; i++) { GradV[i] += Lambda*WgtV[i]; } // compute delta_w = H(w) \ (g(w)) #ifdef LAPACKE const TFlt SingEps = 1e-10; if (H.GetRows() == 1) { // fix for a bug in SVD factorization DeltaWgtV[0] = GradV[0] / H(0,0); } else { TLinAlg::SVDSolve(H, DeltaWgtV, GradV, SingEps); } #else throw TExcept::New("Should include LAPACKE!!"); #endif if (TFlt::IsNan(TLinAlg::Norm(DeltaWgtV))) { Notify->OnNotifyFmt(TNotifyType::ntInfo, "Got NaNs while fitting logistic regression! The weights could still be OK."); break; } // update the current weight vector for (int i = 0; i < Dim; i++) { WgtV[i] += DeltaWgtV[i]; } // recompute the termination criteria and store the probabilities for // the next iteration Diff = TFlt::NInf; for (int i = 0; i < NInst; i++) { AbsDiff = TFlt::Abs(PrevProbV[i] - ProbV[i]); if (AbsDiff > Diff) { Diff = AbsDiff; } PrevProbV[i] = ProbV[i]; } k++; } while (Diff > Eps); Notify->OnNotifyFmt(TNotifyType::ntInfo, "Converged. Diff: %.5f", Diff); } double TLogReg::Predict(const TFltV& x) const { if (IncludeIntercept) { TFltV x1(x); x1.Add(1); return PredictWithoutIntercept(x1); } else { return PredictWithoutIntercept(x); } } void TLogReg::GetWgtV(TFltV& _WgtV) const { _WgtV = WgtV; if (IncludeIntercept) { _WgtV.DelLast(); } } double TLogReg::PredictWithoutIntercept(const TFltV& x) const { if (!Initialized()) { return 0; } EAssertR(x.Len() == WgtV.Len(), "Dimension mismatch while predicting!"); return 1 / (1 + TMath::Power(TMath::E, -TLinAlg::DotProduct(WgtV, x))); } /////////////////////////////////////////// // Proportional Hazards model TPropHazards::TPropHazards(const double& _Lambda, const bool _Verbose): Lambda(_Lambda), WgtV(), Verbose(_Verbose), Notify(_Verbose ? TNotify::StdNotify : TNotify::NullNotify) {} TPropHazards::TPropHazards(TSIn& SIn): Lambda(TFlt(SIn)), WgtV(SIn), Verbose(TBool(SIn)) { Notify = Verbose ? TNotify::StdNotify : TNotify::NullNotify; } void TPropHazards::Save(TSOut& SOut) const { TFlt(Lambda).Save(SOut); WgtV.Save(SOut); TBool(Verbose).Save(SOut); } void TPropHazards::Fit(const TFltVV& _X, const TFltV& t, const double& Eps) { const int NInst = _X.GetCols(); const int Dim = _X.GetRows() + 1; EAssertR(NInst == t.Len(), "TPropHazards::Fit the number of instances in X.GetCols() and t.Len() do not match"); Notify->OnNotifyFmt(TNotifyType::ntInfo, "Fitting proportional hazards model on %d instances ...", NInst); TFltVV X(_X.GetRows()+1, NInst); for (int ColN = 0; ColN < NInst; ColN++) { X(0, ColN) = 1; for (int RowN = 0; RowN < _X.GetRows(); RowN++) { X(RowN+1, ColN) = _X(RowN, ColN); } } WgtV.Gen(Dim); TFltVV X_t(X); X_t.Transpose(); // TODO slow TFltVV XTimesW(X.GetRows(), X.GetCols()); TFltVV H(Dim, Dim); TFltV TempNInstV(NInst, NInst); TFltV GradV(Dim, Dim); TFltV DeltaWgtV(Dim, Dim); TSpVV WgtColSpVV(NInst, NInst); double IntensTimesT; // generate weight matrix with only ones on the diagonal // so you don't recreate all the object every iteration for (int i = 0; i < NInst; i++) { WgtColSpVV[i].Add(TIntFltKd(i, 1)); } int k = 0; double Diff = TFlt::PInf; while (Diff > Eps) { // construct the intensity vector PredictInternal(X, TempNInstV); // I) construct the Hessian: X*W*X' + lambda*I // prepare W and t .* intens - 1 for (int i = 0; i < NInst; i++) { IntensTimesT = t[i] * TempNInstV[i]; TempNInstV[i] = IntensTimesT - 1; WgtColSpVV[i][0].Dat = IntensTimesT; } // 1) compute X*W TLinAlg::Multiply(X, WgtColSpVV, XTimesW); // 2) compute (X*W)*X' TLinAlg::Multiply(XTimesW, X_t, H); // 3) (X*W*X') + lambda*I, exclude the base hazard if (Lambda > 0) { for (int i = 1; i < Dim; i++) { H(i,i) += Lambda; } } // II) construct the gradient: (t .* intens - 1) * X' + lambda*[0, w(2:end)] // 1) (t .* intens - 1) * X' TLinAlg::Multiply(X, TempNInstV, GradV); // 2) ((t .* intens - 1) * X') + lambda*[0, w(2:end)] if (Lambda > 0) { for (int i = 1; i < Dim; i++) { GradV[i] += Lambda * WgtV[i]; } } // III) compute: delta_w = H \ grad #ifdef LAPACKE const TFlt SingEps = 1e-10; if (H.GetRows() == 1) { // fix for a bug in SVD factorization DeltaWgtV[0] = GradV[0] / H(0,0); } else { TLinAlg::SVDSolve(H, DeltaWgtV, GradV, SingEps); } #else throw TExcept::New("Should include LAPACKE!!"); #endif // IV) w <= w - delta_w for (int i = 0; i < Dim; i++) { WgtV[i] -= DeltaWgtV[i]; } Diff = TLinAlg::Norm(DeltaWgtV); EAssertR(!TFlt::IsNan(Diff), "nans in delta wgt vector!"); if (++k % 10 == 0) { Notify->OnNotifyFmt(TNotifyType::ntInfo, "Step: %d, diff: %.3f", k, Diff); } } Notify->OnNotifyFmt(TNotifyType::ntInfo, "Converged. Diff: %.5f", Diff); } double TPropHazards::Predict(const TFltV& x) const { if (WgtV.Empty()) { return 0; } double Pred = WgtV[0]; for (int i = 1; i < WgtV.Len(); i++) { Pred += x[i-1]*WgtV[i]; } return exp(Pred); } void TPropHazards::GetWgtV(TFltV& _WgtV) const { for (int i = 1; i < WgtV.Len(); i++) { _WgtV.Add(WgtV[i]); } } void TPropHazards::PredictInternal(const TFltVV& X, TFltV& IntensV) const { const int NInst = X.GetCols(); TLinAlg::MultiplyT(X, WgtV, IntensV); for (int i = 0; i < NInst; i++) { IntensV[i] = exp(IntensV[i]); } } ///////////////////////////////////////////// // Ridge Regression void TRidgeReg::Fit(const TFltVV& X, const TFltV& y) { TNumericalStuff::LeastSquares(X, y, Gamma, WgtV); } double TRidgeReg::Predict(const TFltV& x) const { EAssertR(x.Len() == WgtV.Len(), "TRegression::TRidgeReg::Predict: model and data dimension mismatch"); return TLinAlg::DotProduct(x, WgtV); } <|endoftext|>
<commit_before>#include <maya/MArgList.h> #include <maya/MStatus.h> #include <maya/MDGModifier.h> #include <maya/MFnMesh.h> #include <maya/MIntArray.h> #include <maya/MFloatPointArray.h> #include "assetCommand.h" #include "assetManager.h" #include "util.h" AssetCommand::AssetCommand() { cerr << "AssetCommand constructor" << endl; } AssetCommand::~AssetCommand() { cerr << "AssetCommand destructor" << endl; } void* AssetCommand::creator() { cerr << "AssetCommand creator" << endl; return new AssetCommand(); } MStatus AssetCommand::doIt(const MArgList& args) { cerr << "AssetCommand doIt" << endl; MString filePath = args.asString(0); AssetManager::createManager(filePath); } <commit_msg>Build fix on Maya plugin.<commit_after>#include <maya/MArgList.h> #include <maya/MStatus.h> #include <maya/MDGModifier.h> #include <maya/MFnMesh.h> #include <maya/MIntArray.h> #include <maya/MFloatPointArray.h> #include "assetCommand.h" #include "assetManager.h" #include "util.h" AssetCommand::AssetCommand() { cerr << "AssetCommand constructor" << endl; } AssetCommand::~AssetCommand() { cerr << "AssetCommand destructor" << endl; } void* AssetCommand::creator() { cerr << "AssetCommand creator" << endl; return new AssetCommand(); } MStatus AssetCommand::doIt(const MArgList& args) { cerr << "AssetCommand doIt" << endl; MString filePath = args.asString(0); AssetManager::createManager(filePath); return MS::MStatusCode::kSuccess; } <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info> * * 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 "jstreamsconfig.h" #include "query.h" #include "jstreamsconfig.h" #include "indexreader.h" #include <ctype.h> using namespace std; using namespace Strigi; Query::Query() { } /** * The constructor parses the query in include and exclude statements. * The following lines contain example queries. * hi * 'hi' * hi Jos * 'hi Jos' * "hi Jos" * -hi Jos * path:"hi Jos" * -path:"hi Jos" * So the syntax is something like this: * query ::= [term]* * term ::= [-][prefix]:("searchphrase"|searchphrase) **/ Query::Query(int max, int offset) { this->max = max; this->offset = offset; } QueryParser::QueryParser() { defaultFields.push_back("content"); defaultFields.push_back("artist"); defaultFields.push_back("filename"); defaultFields.push_back("album"); defaultFields.push_back("title"); } Query QueryParser::buildQuery(const string& querystring, int32_t max, int32_t offset){ const char* q = querystring.c_str(); const char* end = q + querystring.length(); const char* p = q; Query query(max, offset); Query term; Query lastterm; bool hadOr = false; while (p < end) { term.clear(); p = parseQuery(p, term); if (term.expression == "OR") { hadOr = true; Query q; addQuery(q, lastterm); } else { addQuery(query, lastterm); lastterm = term; } } addQuery(query, lastterm); return query; }/* bool operator<(const Query&a,const Query&b) { return &a < &b; }*/ void QueryParser::addQuery(Query& query, const Query& subquery) const { // if the subquery is empty, do not add it if (subquery.terms.size() == 0 && subquery.expression.size() == 0) return; // if the subquery has no field name, use the default field names if (subquery.expression.size() > 0 && subquery.fieldname.size() == 0 && defaultFields.size() > 0) { if (defaultFields.size() == 1) { Query sq = subquery; sq.fieldname = *defaultFields.begin(); query.terms.push_back(sq); } else { list<string>::const_iterator i; Query orQuery; orQuery.occurrence = subquery.occurrence; for (i = defaultFields.begin(); i != defaultFields.end(); ++i) { Query sub; sub.fieldname = *i; sub.expression = subquery.expression; sub.occurrence = Query::SHOULD; orQuery.terms.push_back(sub); } query.terms.push_back(orQuery); } } else { query.terms.push_back(subquery); } } const char* QueryParser::parseQuery(const char* s, Query& parsedterm) const { bool include = true; const char* p = s; // skip whitespace while (*p != '\0' && isspace(*p)) p++; if (*p == '\0') return p; // check for a - sign if (*p == '-') { include = false; p++; } // skip whitespace while (*p != '\0' && isspace(*p)) p++; if (*p == '\0') return p; char quote = 0; if (*p == '\'' || *p == '"') { quote = *p++; if (*p == '\0') return p; } const char* prefix = 0; const char* prefend = 0; const char* term = p; // skip until end of string or closing quote or colon or whitespace while (*p != '\0' && ((quote == 0 && !isspace(*p)) || (quote != 0 && *p != quote))) { if (quote == 0 && *p == ':') { // define the prefix prefix = term; prefend = p; ++p; if (*p == '\0') return p; if (*p == '\'' || *p == '"') { quote = *p++; if (*p == '\0') return p; } term = p; } ++p; } if (*term == '\0') return term; if (p - term > 0) { parsedterm.occurrence = (include) ?Query::MUST :Query::MUST_NOT; if (prefix != 0 && term - prefix > 1) { parsedterm.fieldname = string(prefix, prefend-prefix); } parsedterm.expression = string(term, p-term); } // skip the terminating character if (p != '\0') p++; return p; } void replaceall(string& text, const string& a, const string& b) { size_t pos = 0; pos = text.find(a); while (pos != string::npos) { text.replace(pos, a.length(), "&lt;"); pos = text.find('<'); } } void Query::clear() { terms.clear(); occurrence = MUST; fieldname = expression = ""; } string Query::highlight(const string& text) const { return text; int pre = 5, post = 5, maxlen = 100; string t = text; replaceall(t, "<", "&lt;"); replaceall(t, ">", "&gt;"); string lt = t; for (unsigned i=0; i<t.length(); ++i) { lt[i] = tolower(lt[i]); } vector<string> re; list<Query>::const_iterator i; for (i = terms.begin(); i != terms.end(); ++i) { if (i->occurrence != MUST_NOT) { string s = i->expression; for (unsigned k = 0; k < s.length(); ++k) { s[k] = tolower(s[k]); } re.push_back(s); } } string out; int pos = 0; string::size_type last1 = string::npos; //int last2 = string::npos; //int last3 = string::npos; string::size_type last4 = string::npos; vector<string>::const_iterator k; while (pos >= 0 && (int)(out.length()+last1-last4) < maxlen) { string::size_type rep = string::npos; int len; for (k = re.begin(); k != re.end(); ++k) { unsigned p = lt.find(*k, pos); if (p > 0 && (rep == string::npos || p < rep)) { rep = p; len = k->length(); } } if (rep != string::npos) { string::size_type p1 = t.find(" ", rep-pre); if (p1 == string::npos) p1 = rep-pre; string::size_type p4 = t.find(" ", rep+len+post); if (p4 == string::npos) p4 = t.length(); out += t.substr(p1, rep-p1); out += "<b>"; out += t.substr(rep, len); out += "</b>"; out += t.substr(rep+len, p4-(rep+len)); out += " ... "; /* if (lasts == string::npos) { lasts = s; } else if (s > laste) { if (out.length() == 0 && lasts > 0) out += "... "; out += t.substr(lasts, laste - lasts) + " ... "; lasts = s; } laste = e;*/ pos = rep+1; } else { pos = rep; } } /* if (lasts != string::npos) { if (out.length() == 0 && lasts > 0) out += "... "; out += t.substr(lasts, laste - lasts) + " ... "; } for (k = re.begin(); k != re.end(); ++k) { replaceall(out, *k, "<b>great</b>"); }*/ if (out.length() == 0) { out = t.substr(0, 100); } return out; } <commit_msg>don't compare pointers to char (CID 3143)<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info> * * 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 "jstreamsconfig.h" #include "query.h" #include "jstreamsconfig.h" #include "indexreader.h" #include <ctype.h> using namespace std; using namespace Strigi; Query::Query() { } /** * The constructor parses the query in include and exclude statements. * The following lines contain example queries. * hi * 'hi' * hi Jos * 'hi Jos' * "hi Jos" * -hi Jos * path:"hi Jos" * -path:"hi Jos" * So the syntax is something like this: * query ::= [term]* * term ::= [-][prefix]:("searchphrase"|searchphrase) **/ Query::Query(int max, int offset) { this->max = max; this->offset = offset; } QueryParser::QueryParser() { defaultFields.push_back("content"); defaultFields.push_back("artist"); defaultFields.push_back("filename"); defaultFields.push_back("album"); defaultFields.push_back("title"); } Query QueryParser::buildQuery(const string& querystring, int32_t max, int32_t offset){ const char* q = querystring.c_str(); const char* end = q + querystring.length(); const char* p = q; Query query(max, offset); Query term; Query lastterm; bool hadOr = false; while (p < end) { term.clear(); p = parseQuery(p, term); if (term.expression == "OR") { hadOr = true; Query q; addQuery(q, lastterm); } else { addQuery(query, lastterm); lastterm = term; } } addQuery(query, lastterm); return query; }/* bool operator<(const Query&a,const Query&b) { return &a < &b; }*/ void QueryParser::addQuery(Query& query, const Query& subquery) const { // if the subquery is empty, do not add it if (subquery.terms.size() == 0 && subquery.expression.size() == 0) return; // if the subquery has no field name, use the default field names if (subquery.expression.size() > 0 && subquery.fieldname.size() == 0 && defaultFields.size() > 0) { if (defaultFields.size() == 1) { Query sq = subquery; sq.fieldname = *defaultFields.begin(); query.terms.push_back(sq); } else { list<string>::const_iterator i; Query orQuery; orQuery.occurrence = subquery.occurrence; for (i = defaultFields.begin(); i != defaultFields.end(); ++i) { Query sub; sub.fieldname = *i; sub.expression = subquery.expression; sub.occurrence = Query::SHOULD; orQuery.terms.push_back(sub); } query.terms.push_back(orQuery); } } else { query.terms.push_back(subquery); } } const char* QueryParser::parseQuery(const char* s, Query& parsedterm) const { bool include = true; const char* p = s; // skip whitespace while (*p != '\0' && isspace(*p)) p++; if (*p == '\0') return p; // check for a - sign if (*p == '-') { include = false; p++; } // skip whitespace while (*p != '\0' && isspace(*p)) p++; if (*p == '\0') return p; char quote = 0; if (*p == '\'' || *p == '"') { quote = *p++; if (*p == '\0') return p; } const char* prefix = 0; const char* prefend = 0; const char* term = p; // skip until end of string or closing quote or colon or whitespace while (*p != '\0' && ((quote == 0 && !isspace(*p)) || (quote != 0 && *p != quote))) { if (quote == 0 && *p == ':') { // define the prefix prefix = term; prefend = p; ++p; if (*p == '\0') return p; if (*p == '\'' || *p == '"') { quote = *p++; if (*p == '\0') return p; } term = p; } ++p; } if (*term == '\0') return term; if (p - term > 0) { parsedterm.occurrence = (include) ?Query::MUST :Query::MUST_NOT; if (prefix != 0 && term - prefix > 1) { parsedterm.fieldname = string(prefix, prefend-prefix); } parsedterm.expression = string(term, p-term); } // skip the terminating character if (*p != '\0') p++; return p; } void replaceall(string& text, const string& a, const string& b) { size_t pos = 0; pos = text.find(a); while (pos != string::npos) { text.replace(pos, a.length(), "&lt;"); pos = text.find('<'); } } void Query::clear() { terms.clear(); occurrence = MUST; fieldname = expression = ""; } string Query::highlight(const string& text) const { return text; int pre = 5, post = 5, maxlen = 100; string t = text; replaceall(t, "<", "&lt;"); replaceall(t, ">", "&gt;"); string lt = t; for (unsigned i=0; i<t.length(); ++i) { lt[i] = tolower(lt[i]); } vector<string> re; list<Query>::const_iterator i; for (i = terms.begin(); i != terms.end(); ++i) { if (i->occurrence != MUST_NOT) { string s = i->expression; for (unsigned k = 0; k < s.length(); ++k) { s[k] = tolower(s[k]); } re.push_back(s); } } string out; int pos = 0; string::size_type last1 = string::npos; //int last2 = string::npos; //int last3 = string::npos; string::size_type last4 = string::npos; vector<string>::const_iterator k; while (pos >= 0 && (int)(out.length()+last1-last4) < maxlen) { string::size_type rep = string::npos; int len; for (k = re.begin(); k != re.end(); ++k) { unsigned p = lt.find(*k, pos); if (p > 0 && (rep == string::npos || p < rep)) { rep = p; len = k->length(); } } if (rep != string::npos) { string::size_type p1 = t.find(" ", rep-pre); if (p1 == string::npos) p1 = rep-pre; string::size_type p4 = t.find(" ", rep+len+post); if (p4 == string::npos) p4 = t.length(); out += t.substr(p1, rep-p1); out += "<b>"; out += t.substr(rep, len); out += "</b>"; out += t.substr(rep+len, p4-(rep+len)); out += " ... "; /* if (lasts == string::npos) { lasts = s; } else if (s > laste) { if (out.length() == 0 && lasts > 0) out += "... "; out += t.substr(lasts, laste - lasts) + " ... "; lasts = s; } laste = e;*/ pos = rep+1; } else { pos = rep; } } /* if (lasts != string::npos) { if (out.length() == 0 && lasts > 0) out += "... "; out += t.substr(lasts, laste - lasts) + " ... "; } for (k = re.begin(); k != re.end(); ++k) { replaceall(out, *k, "<b>great</b>"); }*/ if (out.length() == 0) { out = t.substr(0, 100); } return out; } <|endoftext|>
<commit_before>// Copyright(c) 2016 Jounayd Id Salah // Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT). #include "test_math/pch.h" #include "test/unit/coTest.h" #include "math/quaternion/coQuat_f.h" coTEST(coQuat_f, coNormalize) { coEXPECT(coNearEqual(coNormalize(coQuat(-7, 0, 0, 0)), coQuat(-1, 0, 0, 0))); coEXPECT(coNearEqual(coNormalize(coQuat(0, -7, 0, 0)), coQuat(0, -1, 0, 0))); coEXPECT(coNearEqual(coNormalize(coQuat(0, 0, -7, 0)), coQuat(0, 0, -1, 0))); coEXPECT(coNearEqual(coNormalize(coQuat(0, 0, 0, -7)), coQuat(0, 0, 0, -1))); } coTEST(coQuat_f, coConjugate) { coEXPECT(coConjugate(coQuat(0, 0, 0, 0)) == coQuat(0, 0, 0, 0)); coEXPECT(coConjugate(coQuat(7, 0, 0, 0)) == coQuat(-7, 0, 0, 0)); coEXPECT(coConjugate(coQuat(0, 7, 0, 0)) == coQuat(0, -7, 0, 0)); coEXPECT(coConjugate(coQuat(0, 0, 7, 0)) == coQuat(0, 0, -7, 0)); coEXPECT(coConjugate(coQuat(0, 0, 0, 7)) == coQuat(0, 0, 0, -7)); } coTEST(coQuat_f, coRotation) { } coTEST(coQuat_f, coRotateVector) { { const coQuat q = coRotation(coFloatx3(0, 0, 0)); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(3, 0, 0)), coFloatx3(3, 0, 0))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 3, 0)), coFloatx3(0, 3, 0))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 0, 3)), coFloatx3(0, 0, 3))); } { const coQuat q = coRotation(coFloatx3(coFloat_halfPi, 0, 0)); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(3, 0, 0)), coFloatx3(3, 0, 0))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 3, 0)), coFloatx3(0, 0, -3))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 0, 3)), coFloatx3(0, 3, 0))); } { const coQuat q = coRotation(coFloatx3(0, coFloat_halfPi, 0)); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(3, 0, 0)), coFloatx3(0, 0, 3))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 3, 0)), coFloatx3(0, 3, 0))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 0, 3)), coFloatx3(-3, 0, 0))); } } <commit_msg>testssdfsd<commit_after>// Copyright(c) 2016 Jounayd Id Salah // Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT). #include "test_math/pch.h" #include "test/unit/coTest.h" #include "math/quaternion/coQuat_f.h" coTEST(coQuat_f, coNormalize) { coEXPECT(coNearEqual(coNormalize(coQuat(-7, 0, 0, 0)), coQuat(-1, 0, 0, 0))); coEXPECT(coNearEqual(coNormalize(coQuat(0, -7, 0, 0)), coQuat(0, -1, 0, 0))); coEXPECT(coNearEqual(coNormalize(coQuat(0, 0, -7, 0)), coQuat(0, 0, -1, 0))); coEXPECT(coNearEqual(coNormalize(coQuat(0, 0, 0, -7)), coQuat(0, 0, 0, -1))); } coTEST(coQuat_f, coConjugate) { coEXPECT(coConjugate(coQuat(0, 0, 0, 0)) == coQuat(0, 0, 0, 0)); coEXPECT(coConjugate(coQuat(7, 0, 0, 0)) == coQuat(-7, 0, 0, 0)); coEXPECT(coConjugate(coQuat(0, 7, 0, 0)) == coQuat(0, -7, 0, 0)); coEXPECT(coConjugate(coQuat(0, 0, 7, 0)) == coQuat(0, 0, -7, 0)); coEXPECT(coConjugate(coQuat(0, 0, 0, 7)) == coQuat(0, 0, 0, -7)); } coTEST(coQuat_f, coRotation) { coEXPECT(coNearEqual(coRotation(coFloatx3(7, 0, 0), coFloatx3(7, 0, 0)), coRotation(coFloatx3(0, 0, 0)))); coEXPECT(coNearEqual(coRotation(coFloatx3(7, 0, 0), coFloatx3(0, 7, 0)), coRotation(coFloatx3(0, 0, coFloat_halfPi)))); coEXPECT(coNearEqual(coRotation(coFloatx3(7, 0, 0), coFloatx3(0, 0, 7)), coRotation(coFloatx3(0, coFloat_halfPi, 0)))); coEXPECT(coNearEqual(coRotation(coFloatx3(0, 0, 7), coFloatx3(0, 7, 0)), coRotation(coFloatx3(coFloat_halfPi, 0, 0)))); } coTEST(coQuat_f, coRotateVector) { { const coQuat q = coRotation(coFloatx3(0, 0, 0)); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(3, 0, 0)), coFloatx3(3, 0, 0))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 3, 0)), coFloatx3(0, 3, 0))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 0, 3)), coFloatx3(0, 0, 3))); } { const coQuat q = coRotation(coFloatx3(coFloat_halfPi, 0, 0)); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(3, 0, 0)), coFloatx3(3, 0, 0))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 3, 0)), coFloatx3(0, 0, -3))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 0, 3)), coFloatx3(0, 3, 0))); } { const coQuat q = coRotation(coFloatx3(0, coFloat_halfPi, 0)); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(3, 0, 0)), coFloatx3(0, 0, 3))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 3, 0)), coFloatx3(0, 3, 0))); coEXPECT(coNearEqual(coRotateVector(q, coFloatx3(0, 0, 3)), coFloatx3(-3, 0, 0))); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Mikhail Baranov * Copyright (c) 2015 Victor Gaydov * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <CppUTest/TestHarness.h> #include <stdio.h> #include <unistd.h> #include "roc_core/buffer_pool.h" #include "roc_core/heap_allocator.h" #include "roc_core/log.h" #include "roc_core/random.h" #include "roc_core/stddefs.h" #include "roc_core/thread.h" #include "roc_netio/transceiver.h" #include "roc_packet/address_to_str.h" #include "roc_packet/packet_pool.h" #include "roc_packet/parse_address.h" #include "roc/receiver.h" #include "roc/sender.h" namespace roc { namespace { enum { MaxBufSize = 4096 }; core::HeapAllocator allocator; packet::PacketPool packet_pool(allocator, 1); core::BufferPool<uint8_t> byte_buffer_pool(allocator, MaxBufSize, 1); class Sender : public core::Thread { public: Sender(roc_sender_config& config, packet::Address dst_source_addr, packet::Address dst_repair_addr, float* samples, size_t len, size_t frame_size) : samples_(samples) , sz_(len) , frame_size_(frame_size) { packet::Address addr; CHECK(packet::parse_address("127.0.0.1:0", addr)); sndr_ = roc_sender_new(&config); CHECK(sndr_); CHECK(roc_sender_bind(sndr_, addr.saddr()) == 0); CHECK( roc_sender_connect(sndr_, ROC_PROTO_RTP_RSM8_SOURCE, dst_source_addr.saddr()) == 0); CHECK(roc_sender_connect(sndr_, ROC_PROTO_RSM8_REPAIR, dst_repair_addr.saddr()) == 0); CHECK(roc_sender_start(sndr_) == 0); } ~Sender() { roc_sender_stop(sndr_); roc_sender_delete(sndr_); } private: virtual void run() { for (size_t off = 0; off < sz_; off += frame_size_) { if (off + frame_size_ > sz_) { off = sz_ - frame_size_; } const ssize_t ret = roc_sender_write(sndr_, samples_ + off, frame_size_); LONGS_EQUAL(frame_size_, ret); } } roc_sender* sndr_; float* samples_; const size_t sz_; const size_t frame_size_; }; class Receiver { public: Receiver(roc_receiver_config& config) { CHECK(packet::parse_address("127.0.0.1:0", source_addr_)); CHECK(packet::parse_address("127.0.0.1:0", repair_addr_)); recv_ = roc_receiver_new(&config); CHECK(recv_); CHECK(roc_receiver_bind(recv_, ROC_PROTO_RTP_RSM8_SOURCE, source_addr_.saddr()) == 0); CHECK(roc_receiver_bind(recv_, ROC_PROTO_RSM8_REPAIR, repair_addr_.saddr()) == 0); CHECK(roc_receiver_start(recv_) == 0); } ~Receiver() { roc_receiver_stop(recv_); roc_receiver_delete(recv_); } packet::Address source_addr() { return source_addr_; } packet::Address repair_addr() { return repair_addr_; } ssize_t read(float* samples, const size_t n_samples) { return roc_receiver_read(recv_, samples, n_samples); } private: roc_receiver* recv_; packet::Address source_addr_; packet::Address repair_addr_; }; class Proxy : private packet::IWriter { public: Proxy(const packet::Address& dst_source_addr, const packet::Address& dst_repair_addr, const size_t block_size) : trx_(packet_pool, byte_buffer_pool, allocator) , dst_source_addr_(dst_source_addr) , dst_repair_addr_(dst_repair_addr) , block_size_(block_size) , num_(0) { CHECK(packet::parse_address("127.0.0.1:0", send_addr_)); CHECK(packet::parse_address("127.0.0.1:0", recv_source_addr_)); CHECK(packet::parse_address("127.0.0.1:0", recv_repair_addr_)); writer_ = trx_.add_udp_sender(send_addr_); CHECK(writer_); CHECK(trx_.add_udp_receiver(recv_source_addr_, *this)); CHECK(trx_.add_udp_receiver(recv_repair_addr_, *this)); } packet::Address source_addr() { return recv_source_addr_; } packet::Address repair_addr() { return recv_repair_addr_; } void start() { trx_.start(); } void stop() { trx_.stop(); trx_.join(); } private: virtual void write(const packet::PacketPtr& ptr) { if (num_++ % block_size_ == 1) { return; } ptr->udp()->src_addr = send_addr_; if (ptr->udp()->dst_addr == recv_source_addr_) { ptr->udp()->dst_addr = dst_source_addr_; } else { ptr->udp()->dst_addr = dst_repair_addr_; } writer_->write(ptr); } netio::Transceiver trx_; packet::Address send_addr_; packet::Address recv_source_addr_; packet::Address recv_repair_addr_; packet::Address dst_source_addr_; packet::Address dst_repair_addr_; packet::IWriter* writer_; const size_t block_size_; size_t num_; }; } // namespace TEST_GROUP(sender_receiver) { static const size_t n_channels = 2; static const size_t n_source_packets = 10; static const size_t n_repair_packets = 5; static const size_t packet_len = 100; static const size_t packet_num = n_source_packets * 5; static const size_t frame_size = packet_len * 2; roc_sender_config sender_conf; roc_receiver_config receiver_conf; static const size_t total_sz = packet_len * packet_num; float s2send[total_sz]; float s2recv[total_sz]; void setup() { memset(&sender_conf, 0, sizeof(sender_conf)); sender_conf.flags |= ROC_FLAG_DISABLE_INTERLEAVER; sender_conf.flags |= ROC_FLAG_ENABLE_TIMER; sender_conf.samples_per_packet = (unsigned int)packet_len / n_channels; sender_conf.fec_scheme = ROC_FEC_RS8M; sender_conf.n_source_packets = n_source_packets; sender_conf.n_repair_packets = n_repair_packets; memset(&receiver_conf, 0, sizeof(receiver_conf)); receiver_conf.flags |= ROC_FLAG_DISABLE_RESAMPLER; receiver_conf.flags |= ROC_FLAG_ENABLE_TIMER; receiver_conf.samples_per_packet = (unsigned int)packet_len / n_channels; receiver_conf.fec_scheme = ROC_FEC_RS8M; receiver_conf.n_source_packets = n_source_packets; receiver_conf.n_repair_packets = n_repair_packets; receiver_conf.latency = packet_len * 20; receiver_conf.timeout = packet_len * 300; const float sstep = 1. / 32768.; float sval = -1 + sstep; for (size_t i = 0; i < total_sz; ++i) { s2send[i] = sval; sval += sstep; if (sval >= 1) { sval = -1 + sstep; } } } void check_sample_arrays(Receiver & recv, float* original, const size_t len) { float rx_buff[packet_len]; size_t s_first = 0; size_t inner_cntr = 0; bool seek_first = true; size_t s_last = 0; size_t ipacket = 0; while (s_last == 0) { size_t i = 0; ipacket++; LONGS_EQUAL(packet_len, recv.read(rx_buff, packet_len)); if (seek_first) { for (; i < packet_len && fabs(double(rx_buff[i])) < 1e-9; i++, s_first++) { } CHECK(s_first < len); if (i < packet_len) { seek_first = false; } } if (!seek_first) { for (; i < packet_len; i++) { if (inner_cntr >= len) { CHECK(fabs(double(rx_buff[i])) < 1e-9); s_last = inner_cntr + s_first; roc_log(LogInfo, "finish: s_first: %lu, s_last: %lu, inner_cntr: %lu", (unsigned long)s_first, (unsigned long)s_last, (unsigned long)inner_cntr); break; } else if (fabs(double(original[inner_cntr] - rx_buff[i])) > 1e-9) { char sbuff[256]; int sbuff_i = snprintf(sbuff, sizeof(sbuff), "failed comparing samples #%lu\n\npacket_num: %lu\n", (unsigned long)inner_cntr, (unsigned long)ipacket); snprintf(&sbuff[sbuff_i], sizeof(sbuff) - (size_t)sbuff_i, "original: %f,\treceived: %f\n", (double)original[inner_cntr], (double)rx_buff[i]); FAIL(sbuff); } else { inner_cntr++; } } } } } }; TEST(sender_receiver, simple) { Receiver recv(receiver_conf); Sender sndr(sender_conf, recv.source_addr(), recv.repair_addr(), s2send, total_sz, frame_size); sndr.start(); check_sample_arrays(recv, s2send, total_sz); sndr.join(); } #ifdef ROC_TARGET_OPENFEC TEST(sender_receiver, losses) { Receiver recv(receiver_conf); Proxy proxy(recv.source_addr(), recv.repair_addr(), n_source_packets + n_repair_packets); Sender sndr(sender_conf, proxy.source_addr(), proxy.repair_addr(), s2send, total_sz, frame_size); proxy.start(); sndr.start(); check_sample_arrays(recv, s2send, total_sz); sndr.join(); proxy.stop(); } #endif // ROC_TARGET_OPENFEC } // namespace roc <commit_msg>roc_lib: refactor test<commit_after>/* * Copyright (c) 2015 Mikhail Baranov * Copyright (c) 2015 Victor Gaydov * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <CppUTest/TestHarness.h> #include <stdio.h> #include <unistd.h> #include "roc_core/buffer_pool.h" #include "roc_core/heap_allocator.h" #include "roc_core/log.h" #include "roc_core/random.h" #include "roc_core/stddefs.h" #include "roc_core/thread.h" #include "roc_netio/transceiver.h" #include "roc_packet/address_to_str.h" #include "roc_packet/packet_pool.h" #include "roc_packet/parse_address.h" #include "roc/receiver.h" #include "roc/sender.h" namespace roc { namespace { enum { MaxBufSize = 4096, NumChans = 2, SourcePackets = 10, RepairPackets = 5, NumPackets = SourcePackets * 5, PacketSamples = 100, FrameSamples = PacketSamples * 2, TotalSamples = PacketSamples * NumPackets }; core::HeapAllocator allocator; packet::PacketPool packet_pool(allocator, 1); core::BufferPool<uint8_t> byte_buffer_pool(allocator, MaxBufSize, 1); class Sender : public core::Thread { public: Sender(roc_sender_config& config, packet::Address dst_source_addr, packet::Address dst_repair_addr, float* samples, size_t len, size_t frame_size) : samples_(samples) , sz_(len) , frame_size_(frame_size) { packet::Address addr; CHECK(packet::parse_address("127.0.0.1:0", addr)); sndr_ = roc_sender_new(&config); CHECK(sndr_); CHECK(roc_sender_bind(sndr_, addr.saddr()) == 0); CHECK( roc_sender_connect(sndr_, ROC_PROTO_RTP_RSM8_SOURCE, dst_source_addr.saddr()) == 0); CHECK(roc_sender_connect(sndr_, ROC_PROTO_RSM8_REPAIR, dst_repair_addr.saddr()) == 0); CHECK(roc_sender_start(sndr_) == 0); } ~Sender() { roc_sender_stop(sndr_); roc_sender_delete(sndr_); } private: virtual void run() { for (size_t off = 0; off < sz_; off += frame_size_) { if (off + frame_size_ > sz_) { off = sz_ - frame_size_; } const ssize_t ret = roc_sender_write(sndr_, samples_ + off, frame_size_); LONGS_EQUAL(frame_size_, ret); } } roc_sender* sndr_; float* samples_; const size_t sz_; const size_t frame_size_; }; class Receiver { public: Receiver(roc_receiver_config& config, const float* samples, size_t len, size_t frame_size) : samples_(samples) , sz_(len) , frame_size_(frame_size) { CHECK(packet::parse_address("127.0.0.1:0", source_addr_)); CHECK(packet::parse_address("127.0.0.1:0", repair_addr_)); recv_ = roc_receiver_new(&config); CHECK(recv_); CHECK(roc_receiver_bind(recv_, ROC_PROTO_RTP_RSM8_SOURCE, source_addr_.saddr()) == 0); CHECK(roc_receiver_bind(recv_, ROC_PROTO_RSM8_REPAIR, repair_addr_.saddr()) == 0); CHECK(roc_receiver_start(recv_) == 0); } ~Receiver() { roc_receiver_stop(recv_); roc_receiver_delete(recv_); } packet::Address source_addr() { return source_addr_; } packet::Address repair_addr() { return repair_addr_; } void run() { float rx_buff[MaxBufSize]; size_t s_first = 0; size_t inner_cntr = 0; bool seek_first = true; size_t s_last = 0; size_t ipacket = 0; while (s_last == 0) { size_t i = 0; ipacket++; LONGS_EQUAL(frame_size_, roc_receiver_read(recv_, rx_buff, frame_size_)); if (seek_first) { for (; i < frame_size_ && is_zero_(rx_buff[i]); i++, s_first++) { } CHECK(s_first < sz_); if (i < frame_size_) { seek_first = false; } } if (!seek_first) { for (; i < frame_size_; i++) { if (inner_cntr >= sz_) { CHECK(is_zero_(rx_buff[i])); s_last = inner_cntr + s_first; roc_log(LogInfo, "finish: s_first: %lu, s_last: %lu, inner_cntr: %lu", (unsigned long)s_first, (unsigned long)s_last, (unsigned long)inner_cntr); break; } else if (!is_zero_(samples_[inner_cntr] - rx_buff[i])) { char sbuff[256]; int sbuff_i = snprintf(sbuff, sizeof(sbuff), "failed comparing sample #%lu\n\npacket_num: %lu\n", (unsigned long)inner_cntr, (unsigned long)ipacket); snprintf(&sbuff[sbuff_i], sizeof(sbuff) - (size_t)sbuff_i, "original: %f,\treceived: %f\n", (double)samples_[inner_cntr], (double)rx_buff[i]); FAIL(sbuff); } else { inner_cntr++; } } } } } private: static inline bool is_zero_(float s) { return fabs(double(s)) < 1e-9; } roc_receiver* recv_; packet::Address source_addr_; packet::Address repair_addr_; const float* samples_; const size_t sz_; const size_t frame_size_; }; class Proxy : private packet::IWriter { public: Proxy(const packet::Address& dst_source_addr, const packet::Address& dst_repair_addr, const size_t block_size) : trx_(packet_pool, byte_buffer_pool, allocator) , dst_source_addr_(dst_source_addr) , dst_repair_addr_(dst_repair_addr) , block_size_(block_size) , num_(0) { CHECK(packet::parse_address("127.0.0.1:0", send_addr_)); CHECK(packet::parse_address("127.0.0.1:0", recv_source_addr_)); CHECK(packet::parse_address("127.0.0.1:0", recv_repair_addr_)); writer_ = trx_.add_udp_sender(send_addr_); CHECK(writer_); CHECK(trx_.add_udp_receiver(recv_source_addr_, *this)); CHECK(trx_.add_udp_receiver(recv_repair_addr_, *this)); } packet::Address source_addr() { return recv_source_addr_; } packet::Address repair_addr() { return recv_repair_addr_; } void start() { trx_.start(); } void stop() { trx_.stop(); trx_.join(); } private: virtual void write(const packet::PacketPtr& ptr) { if (num_++ % block_size_ == 1) { // packet loss return; } ptr->udp()->src_addr = send_addr_; if (ptr->udp()->dst_addr == recv_source_addr_) { ptr->udp()->dst_addr = dst_source_addr_; } else { ptr->udp()->dst_addr = dst_repair_addr_; } writer_->write(ptr); } netio::Transceiver trx_; packet::Address send_addr_; packet::Address recv_source_addr_; packet::Address recv_repair_addr_; packet::Address dst_source_addr_; packet::Address dst_repair_addr_; packet::IWriter* writer_; const size_t block_size_; size_t num_; }; } // namespace TEST_GROUP(sender_receiver) { roc_sender_config sender_conf; roc_receiver_config receiver_conf; float samples[TotalSamples]; void setup() { memset(&sender_conf, 0, sizeof(sender_conf)); sender_conf.flags |= ROC_FLAG_DISABLE_INTERLEAVER; sender_conf.flags |= ROC_FLAG_ENABLE_TIMER; sender_conf.samples_per_packet = (unsigned int)PacketSamples / NumChans; sender_conf.fec_scheme = ROC_FEC_RS8M; sender_conf.n_source_packets = SourcePackets; sender_conf.n_repair_packets = RepairPackets; memset(&receiver_conf, 0, sizeof(receiver_conf)); receiver_conf.flags |= ROC_FLAG_DISABLE_RESAMPLER; receiver_conf.flags |= ROC_FLAG_ENABLE_TIMER; receiver_conf.samples_per_packet = (unsigned int)PacketSamples / NumChans; receiver_conf.fec_scheme = ROC_FEC_RS8M; receiver_conf.n_source_packets = SourcePackets; receiver_conf.n_repair_packets = RepairPackets; receiver_conf.latency = PacketSamples * 20; receiver_conf.timeout = PacketSamples * 300; init_samples(); } void init_samples() { const float sstep = 1. / 32768.; float sval = -1 + sstep; for (size_t i = 0; i < TotalSamples; ++i) { samples[i] = sval; sval += sstep; if (sval >= 1) { sval = -1 + sstep; } } } }; TEST(sender_receiver, simple) { Receiver receiver(receiver_conf, samples, TotalSamples, FrameSamples); Sender sender(sender_conf, receiver.source_addr(), receiver.repair_addr(), samples, TotalSamples, FrameSamples); sender.start(); receiver.run(); sender.join(); } #ifdef ROC_TARGET_OPENFEC TEST(sender_receiver, losses) { Receiver receiver(receiver_conf, samples, TotalSamples, FrameSamples); Proxy proxy(receiver.source_addr(), receiver.repair_addr(), SourcePackets + RepairPackets); Sender sender(sender_conf, proxy.source_addr(), proxy.repair_addr(), samples, TotalSamples, FrameSamples); proxy.start(); sender.start(); receiver.run(); sender.join(); proxy.stop(); } #endif // ROC_TARGET_OPENFEC } // namespace roc <|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include "transportsocketcache.hpp" qiLogCategory("qimessaging.socketcache"); namespace qi { TransportSocketCache::~TransportSocketCache() { close(); } void TransportSocketCache::init() { boost::mutex::scoped_lock sl(_socketsMutex); _dying = false; } void TransportSocketCache::close() { { _dying = true; MachineConnectionMap socketsCopy; { // Do not hold _socketsMutex while iterating or deadlock may occurr // between disconnect() that waits for callback handler // and callback handler that tries to acquire _socketsMutex boost::mutex::scoped_lock sl(_socketsMutex); socketsCopy = _sockets; } MachineConnectionMap::iterator mcmIt; for (mcmIt = socketsCopy.begin(); mcmIt != socketsCopy.end(); ++mcmIt) { TransportSocketConnectionMap& tscm = mcmIt->second; TransportSocketConnectionMap::iterator tscmIt; for (tscmIt = tscm.begin(); tscmIt != tscm.end(); ++tscmIt) { TransportSocketConnection& tsc = tscmIt->second; tsc.socket->disconnected.disconnect(tscmIt->second.disconnectLink); tsc.socket->connected.disconnect(tscmIt->second.connectLink); //remove callback before calling disconnect. (we dont need them) if (tscmIt->second.socket->isConnected()) tscmIt->second.socket->disconnect(); tscmIt->second.promise.reset(); tscmIt->second.promise.setError("session closed"); } } } } qi::Future<qi::TransportSocketPtr> TransportSocketCache::socket(const ServiceInfo& servInfo, const std::string protocol) { qi::UrlVector endpoints; qi::UrlVector::const_iterator urlIt; bool local = servInfo.machineId() == qi::os::getMachineId(); qiLogDebug() << "local check " << servInfo.machineId() << " " << qi::os::getMachineId() << " " << local; // RFC 3330 - http://tools.ietf.org/html/rfc3330 // -> 127.0.0.0/8 is assigned to loopback address. // // This filters endpoints. If we are on the same machine, we just try to // connect on the loopback address, else we will try on all endpoints we // have that are not loopback. for (urlIt = servInfo.endpoints().begin(); urlIt != servInfo.endpoints().end(); ++urlIt) { qi::Url url = *urlIt; qiLogDebug() << "testing url " << url.str(); if (!url.isValid()) continue; if (url.host().substr(0, 4) == "127." || url.host() == "localhost") { if (local && (protocol == "" || url.protocol() == protocol)) { endpoints.push_back(url); break; } } else if (!local) { endpoints.push_back(url); } } if (endpoints.empty() && local && !servInfo.endpoints().empty()) { // We are local, but localhost is not listed in endpoints. // Just take any entry, it has to be one of our public IP addresses endpoints.push_back(servInfo.endpoints().front()); } if (endpoints.empty()) qiLogWarning() << "No more endpoints available after filtering."; { boost::mutex::scoped_lock sl(_socketsMutex); if (_dying) return qi::makeFutureError<qi::TransportSocketPtr>("TransportSocketCache is closed."); // From here, we will see if we have a pending/established connection to // machineId on one of the endpoints (they all share the same promise // anyway). If it is the case, we return its future. MachineConnectionMap::iterator mcmIt; if ((mcmIt = _sockets.find(servInfo.machineId())) != _sockets.end()) { TransportSocketConnectionMap& tscm = mcmIt->second; TransportSocketConnectionMap::iterator tscmIt; for (urlIt = endpoints.begin(); urlIt != endpoints.end(); ++urlIt) { if ((tscmIt = tscm.find((*urlIt).str())) != tscm.end()) { TransportSocketConnection& tsc = tscmIt->second; if (tsc.promise.future().hasError()) { // When we have a socket with an error, we will try to connect to // all endpoints in case the old one is completely down. continue; } qiLogVerbose() << "A connection is pending or already" << " established."; return tsc.promise.future(); } } } // Launching connections to all endpoints at the same time. They all share // the same promise. qi::Promise<qi::TransportSocketPtr> prom; if (endpoints.empty()) { prom.setError("No endpoint available."); return prom.future(); } // We will need this to report error (to know if all sockets didn't // connect). TransportSocketConnectionAttempt& tsca = _attempts[servInfo.machineId()]; tsca.promise = prom; tsca.socket_count = 0; tsca.successful = false; // This part launches all the socket connections on the same promise. The // first socket to connect is the winner. TransportSocketConnectionMap& tscm = _sockets[servInfo.machineId()]; for (urlIt = endpoints.begin(); urlIt != endpoints.end(); ++urlIt) { qi::Url url = *urlIt; if (protocol != "" && protocol != url.protocol()) { continue; } qi::TransportSocketPtr socket = makeTransportSocket(url.protocol()); TransportSocketConnection& tsc = tscm[url.str()]; qiLogVerbose() << "Attempting connection to " << url.str() << " of machine id " << servInfo.machineId(); tsc.socket = socket; tsc.promise = prom; tsc.url = url; tsc.connectLink = socket->connected.connect(boost::bind(&TransportSocketCache::onSocketConnected, this, socket, servInfo, url)); tsc.disconnectLink = socket->disconnected.connect(boost::bind(&TransportSocketCache::onSocketDisconnected, this, _1, socket, servInfo, url)); socket->connect(url).async(); tsca.socket_count++; } return prom.future(); } // ! boost::mutex::scoped_lock } void TransportSocketCache::onSocketDisconnected(std::string error, TransportSocketPtr socket, const qi::ServiceInfo& servInfo, const qi::Url& url) { { boost::mutex::scoped_lock sl(_socketsMutex); // First, we get the attempts of the machineId. It is used to know if we // have pending connections to other endpoints. MachineAttemptsMap::iterator mamIt; if ((mamIt = _attempts.find(servInfo.machineId())) == _attempts.end()) { // Unknown error. This shouldn't happen... return; } TransportSocketConnectionAttempt& tsca = mamIt->second; if (_dying) { tsca.promise.setError("TransportSocketCache is closed."); return; } tsca.socket_count--; if (tsca.socket_count != 0) { // We still have some sockets attempting to connect to the service, so // we just ignore this disconnection. return; } // No socket can be created, we just return an error. std::stringstream ss; ss << "Failed to connect to service " << servInfo.name() << " on " << "machine " << servInfo.machineId() << ". All endpoints are " << "unavailable."; tsca.promise.setError(ss.str()); } // ! boost::mutex::scoped_lock } /* * Corner case to manage (TODO): * * You are connecting to machineId foo, you are machineId bar. foo and bar are * on different sub-networks with the same netmask. They sadly got the same IP * on their subnet: 192.168.1.42. When trying to connect to foo from bar, we * will try to connect its endpoints, basically: * - tcp://1.2.3.4:1333 (public IP) * - tcp://192.168.1.42:1333 (subnet public IP) * If bar is listening on port 1333, we may connect to it instead of foo (our * real target). */ void TransportSocketCache::onSocketConnected(TransportSocketPtr socket, const qi::ServiceInfo& servInfo, const qi::Url& url) { { boost::mutex::scoped_lock sl(_socketsMutex); MachineAttemptsMap::iterator mamIt; if ((mamIt = _attempts.find(servInfo.machineId())) == _attempts.end()) { // Unknown error. This shouldn't happen... return; } TransportSocketConnectionAttempt& tsca = mamIt->second; if (_dying) { tsca.promise.setError("TransportSocketCache is closed."); return; } if (tsca.successful) { // If we are already connected to this service, disconnect this socket. socket->disconnect(); return; } // Else, we set promise to this socket. We have a winner. MachineConnectionMap::iterator mcmIt; if ((mcmIt = _sockets.find(servInfo.machineId())) != _sockets.end()) { TransportSocketConnectionMap& tscm = mcmIt->second; TransportSocketConnectionMap::iterator tscmIt; if ((tscmIt = tscm.find(url.str())) != tscm.end()) { tscmIt->second.promise.setValue(socket); tsca.successful = true; } } } // ! boost::mutex::scoped_lock } } <commit_msg>Add missing timeout on future error<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include "transportsocketcache.hpp" qiLogCategory("qimessaging.socketcache"); namespace qi { TransportSocketCache::~TransportSocketCache() { close(); } void TransportSocketCache::init() { boost::mutex::scoped_lock sl(_socketsMutex); _dying = false; } void TransportSocketCache::close() { { _dying = true; MachineConnectionMap socketsCopy; { // Do not hold _socketsMutex while iterating or deadlock may occurr // between disconnect() that waits for callback handler // and callback handler that tries to acquire _socketsMutex boost::mutex::scoped_lock sl(_socketsMutex); socketsCopy = _sockets; } MachineConnectionMap::iterator mcmIt; for (mcmIt = socketsCopy.begin(); mcmIt != socketsCopy.end(); ++mcmIt) { TransportSocketConnectionMap& tscm = mcmIt->second; TransportSocketConnectionMap::iterator tscmIt; for (tscmIt = tscm.begin(); tscmIt != tscm.end(); ++tscmIt) { TransportSocketConnection& tsc = tscmIt->second; tsc.socket->disconnected.disconnect(tscmIt->second.disconnectLink); tsc.socket->connected.disconnect(tscmIt->second.connectLink); //remove callback before calling disconnect. (we dont need them) if (tscmIt->second.socket->isConnected()) tscmIt->second.socket->disconnect(); tscmIt->second.promise.reset(); tscmIt->second.promise.setError("session closed"); } } } } qi::Future<qi::TransportSocketPtr> TransportSocketCache::socket(const ServiceInfo& servInfo, const std::string protocol) { qi::UrlVector endpoints; qi::UrlVector::const_iterator urlIt; bool local = servInfo.machineId() == qi::os::getMachineId(); qiLogDebug() << "local check " << servInfo.machineId() << " " << qi::os::getMachineId() << " " << local; // RFC 3330 - http://tools.ietf.org/html/rfc3330 // -> 127.0.0.0/8 is assigned to loopback address. // // This filters endpoints. If we are on the same machine, we just try to // connect on the loopback address, else we will try on all endpoints we // have that are not loopback. for (urlIt = servInfo.endpoints().begin(); urlIt != servInfo.endpoints().end(); ++urlIt) { qi::Url url = *urlIt; qiLogDebug() << "testing url " << url.str(); if (!url.isValid()) continue; if (url.host().substr(0, 4) == "127." || url.host() == "localhost") { if (local && (protocol == "" || url.protocol() == protocol)) { endpoints.push_back(url); break; } } else if (!local) { endpoints.push_back(url); } } if (endpoints.empty() && local && !servInfo.endpoints().empty()) { // We are local, but localhost is not listed in endpoints. // Just take any entry, it has to be one of our public IP addresses endpoints.push_back(servInfo.endpoints().front()); } if (endpoints.empty()) qiLogWarning() << "No more endpoints available after filtering."; { boost::mutex::scoped_lock sl(_socketsMutex); if (_dying) return qi::makeFutureError<qi::TransportSocketPtr>("TransportSocketCache is closed."); // From here, we will see if we have a pending/established connection to // machineId on one of the endpoints (they all share the same promise // anyway). If it is the case, we return its future. MachineConnectionMap::iterator mcmIt; if ((mcmIt = _sockets.find(servInfo.machineId())) != _sockets.end()) { TransportSocketConnectionMap& tscm = mcmIt->second; TransportSocketConnectionMap::iterator tscmIt; for (urlIt = endpoints.begin(); urlIt != endpoints.end(); ++urlIt) { if ((tscmIt = tscm.find((*urlIt).str())) != tscm.end()) { TransportSocketConnection& tsc = tscmIt->second; try { if (tsc.promise.future().isFinished() && tsc.promise.future().hasError(0)) { // When we have a socket with an error, we will try to connect to // all endpoints in case the old one is completely down. continue; } } catch (...) { continue; } qiLogVerbose() << "A connection is pending or already" << " established."; return tsc.promise.future(); } } } // Launching connections to all endpoints at the same time. They all share // the same promise. qi::Promise<qi::TransportSocketPtr> prom; if (endpoints.empty()) { prom.setError("No endpoint available."); return prom.future(); } // We will need this to report error (to know if all sockets didn't // connect). TransportSocketConnectionAttempt& tsca = _attempts[servInfo.machineId()]; tsca.promise = prom; tsca.socket_count = 0; tsca.successful = false; // This part launches all the socket connections on the same promise. The // first socket to connect is the winner. TransportSocketConnectionMap& tscm = _sockets[servInfo.machineId()]; for (urlIt = endpoints.begin(); urlIt != endpoints.end(); ++urlIt) { qi::Url url = *urlIt; if (protocol != "" && protocol != url.protocol()) { continue; } qi::TransportSocketPtr socket = makeTransportSocket(url.protocol()); TransportSocketConnection& tsc = tscm[url.str()]; qiLogVerbose() << "Attempting connection to " << url.str() << " of machine id " << servInfo.machineId(); tsc.socket = socket; tsc.promise = prom; tsc.url = url; tsc.connectLink = socket->connected.connect(boost::bind(&TransportSocketCache::onSocketConnected, this, socket, servInfo, url)); tsc.disconnectLink = socket->disconnected.connect(boost::bind(&TransportSocketCache::onSocketDisconnected, this, _1, socket, servInfo, url)); socket->connect(url).async(); tsca.socket_count++; } return prom.future(); } // ! boost::mutex::scoped_lock } void TransportSocketCache::onSocketDisconnected(std::string error, TransportSocketPtr socket, const qi::ServiceInfo& servInfo, const qi::Url& url) { { boost::mutex::scoped_lock sl(_socketsMutex); // First, we get the attempts of the machineId. It is used to know if we // have pending connections to other endpoints. MachineAttemptsMap::iterator mamIt; if ((mamIt = _attempts.find(servInfo.machineId())) == _attempts.end()) { // Unknown error. This shouldn't happen... return; } TransportSocketConnectionAttempt& tsca = mamIt->second; if (_dying) { tsca.promise.setError("TransportSocketCache is closed."); return; } tsca.socket_count--; if (tsca.socket_count != 0) { // We still have some sockets attempting to connect to the service, so // we just ignore this disconnection. return; } // No socket can be created, we just return an error. std::stringstream ss; ss << "Failed to connect to service " << servInfo.name() << " on " << "machine " << servInfo.machineId() << ". All endpoints are " << "unavailable."; tsca.promise.setError(ss.str()); } // ! boost::mutex::scoped_lock } /* * Corner case to manage (TODO): * * You are connecting to machineId foo, you are machineId bar. foo and bar are * on different sub-networks with the same netmask. They sadly got the same IP * on their subnet: 192.168.1.42. When trying to connect to foo from bar, we * will try to connect its endpoints, basically: * - tcp://1.2.3.4:1333 (public IP) * - tcp://192.168.1.42:1333 (subnet public IP) * If bar is listening on port 1333, we may connect to it instead of foo (our * real target). */ void TransportSocketCache::onSocketConnected(TransportSocketPtr socket, const qi::ServiceInfo& servInfo, const qi::Url& url) { { boost::mutex::scoped_lock sl(_socketsMutex); MachineAttemptsMap::iterator mamIt; if ((mamIt = _attempts.find(servInfo.machineId())) == _attempts.end()) { // Unknown error. This shouldn't happen... return; } TransportSocketConnectionAttempt& tsca = mamIt->second; if (_dying) { tsca.promise.setError("TransportSocketCache is closed."); return; } if (tsca.successful) { // If we are already connected to this service, disconnect this socket. socket->disconnect(); return; } // Else, we set promise to this socket. We have a winner. MachineConnectionMap::iterator mcmIt; if ((mcmIt = _sockets.find(servInfo.machineId())) != _sockets.end()) { TransportSocketConnectionMap& tscm = mcmIt->second; TransportSocketConnectionMap::iterator tscmIt; if ((tscmIt = tscm.find(url.str())) != tscm.end()) { tscmIt->second.promise.setValue(socket); tsca.successful = true; } } } // ! boost::mutex::scoped_lock } } <|endoftext|>
<commit_before>/* * */ #ifndef UNIX_CONDITION_QUEUE_HPP #define UNIX_CONDITION_QUEUE_HPP #include <condition_variable> #include <mutex> #include <optional> #include "condition-queue-detail.hpp" #include "move-queue.hpp" namespace unix { // mutex_t is either std::mutex or std::ref(std::mutex) // similar for condition_t template <typename record_t, typename mutex_t, typename condition_t> class condition_queue_t { public: condition_queue_t () = default; condition_queue_t (mutex_t mutex, condition_t condition); ~condition_queue_t () = default; void push (record_t record); template <bool wait> std::optional<record_t> pop (); template <bool lock> bool empty (); template <bool lock> void notify_one (); private: mutex_t m_mutex; condition_t m_condition; move_queue_t<record_t> m_queue; }; template <typename record_t, typename mutex_t, typename condition_t> condition_queue_t<record_t, mutex_t, condition_t>:: condition_queue_t (mutex_t mutex, condition_t condition) : m_mutex (mutex), m_condition (condition) { } template <typename record_t, typename mutex_t, typename condition_t> void condition_queue_t<record_t, mutex_t, condition_t>::push (record_t record) { // take a reference std::mutex &mutex (m_mutex); std::lock_guard lock (mutex); bool empty = m_queue.empty (); m_queue.push (std::move (record)); if (empty == true) { std::condition_variable &condition (m_condition); condition.notify_one (); } } template <typename record_t, typename mutex_t, typename condition_t> template <bool really_wait> std::optional<record_t> condition_queue_t<record_t, mutex_t, condition_t>::pop () { std::mutex &mutex (m_mutex); std::unique_lock lock (mutex); std::condition_variable &condition (m_condition); if (m_queue.empty () == true) condition_queue_detail::wait<really_wait>(lock, condition); if (m_queue.empty ()) return {}; return std::optional<record_t>(m_queue.pop ()); } template <typename record_t, typename mutex_t, typename condition_t> template <bool really_lock> bool condition_queue_t<record_t, mutex_t, condition_t>::empty () { std::mutex &mutex (m_mutex); typename condition_queue_detail::guard<really_lock>::lock lock (mutex); return m_queue.empty (); } template <typename record_t, typename mutex_t, typename condition_t> template <bool really_lock> void condition_queue_t<record_t, mutex_t, condition_t>::notify_one () { std::mutex &mutex (m_mutex); typename condition_queue_detail::unique<really_lock>::lock lock (mutex); std::condition_variable &condition (m_condition); condition.notify_one (); } } // unix #endif <commit_msg>pi: Simplify condition-queue, use if constexpr<commit_after>/* * */ #ifndef UNIX_CONDITION_QUEUE_HPP #define UNIX_CONDITION_QUEUE_HPP #include <condition_variable> #include <mutex> #include <optional> // #include "condition-queue-detail.hpp" #include "move-queue.hpp" namespace unix { // mutex_t is either std::mutex or std::ref(std::mutex) // similar for condition_t template <typename record_t, typename mutex_t, typename condition_t> class condition_queue_t { public: condition_queue_t () = default; condition_queue_t (mutex_t mutex, condition_t condition); ~condition_queue_t () = default; void push (record_t record); template <bool wait> std::optional<record_t> pop (); template <bool lock> bool empty (); template <bool lock> void notify_one (); private: mutex_t m_mutex; condition_t m_condition; move_queue_t<record_t> m_queue; }; template <typename record_t, typename mutex_t, typename condition_t> condition_queue_t<record_t, mutex_t, condition_t>:: condition_queue_t (mutex_t mutex, condition_t condition) : m_mutex (mutex), m_condition (condition) { } template <typename record_t, typename mutex_t, typename condition_t> void condition_queue_t<record_t, mutex_t, condition_t>::push (record_t record) { // take a reference std::mutex &mutex (m_mutex); std::lock_guard lock (mutex); bool empty = m_queue.empty (); m_queue.push (std::move (record)); if (empty == true) { std::condition_variable &condition (m_condition); condition.notify_one (); } } template <typename record_t, typename mutex_t, typename condition_t> template <bool really_wait> std::optional<record_t> condition_queue_t<record_t, mutex_t, condition_t>::pop () { std::mutex &mutex (m_mutex); std::unique_lock lock (mutex); std::condition_variable &condition (m_condition); if constexpr (really_wait) condition.wait (lock); // } // a; // if (m_queue.empty () == true) // condition_queue_detail::wait<really_wait>(lock, condition); if (m_queue.empty ()) return {}; return std::optional<record_t>(m_queue.pop ()); } template <typename record_t, typename mutex_t, typename condition_t> template <bool really_lock> bool condition_queue_t<record_t, mutex_t, condition_t>::empty () { // std::mutex &mutex (m_mutex); if constexpr (really_lock) std::lock_guard lock (m_mutex); // typename condition_queue_detail::guard<really_lock>::lock lock (mutex); return m_queue.empty (); } template <typename record_t, typename mutex_t, typename condition_t> template <bool really_lock> void condition_queue_t<record_t, mutex_t, condition_t>::notify_one () { // std::mutex &mutex (m_mutex); // typename condition_queue_detail::unique<really_lock>::lock lock (mutex); if constexpr (really_lock) std::lock_guard lock (m_mutex); // std::condition_variable &condition (m_condition); m_condition.notify_one (); } } // unix #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: node.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-19 23:29:34 $ * * 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 * ************************************************************************/ #include "node.hxx" #ifndef INCLUDED_SHARABLE_ANYDATA_HXX #include "anydata.hxx" #endif #ifndef INCLUDED_SHARABLE_TREEFRAGMENT_HXX #include "treefragment.hxx" #endif #ifndef CONFIGMGR_ACCESSOR_HXX #include "accessor.hxx" #endif #ifndef CONFIGMGR_UPDATEACCESSOR_HXX #include "updateaccessor.hxx" #endif #ifndef CONFIGMGR_CONFIGURATION_ATTRIBUTES_HXX_ #include "attributes.hxx" #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef INCLUDED_CSTDDEF #include <cstddef> #define INCLUDED_CSTDDEF #endif namespace configmgr { //----------------------------------------------------------------------------- namespace sharable { //----------------------------------------------------------------------------- // Name name; // Offset parent; // always counts backwards // Flags::Field flags; // Type ::Field type; // contains discriminator for union rtl::OUString NodeInfo::getName(memory::Accessor const & _aAccessor) const { return readString(_aAccessor,this->name); } //----------------------------------------------------------------------------- configmgr::node::Attributes NodeInfo::getNodeInfoAttributes() const { configmgr::node::Attributes aResult; bool help = !!(flags & Flags::readonly); aResult.setAccess( help,!!(flags & Flags::finalized) ); // aResult.setAccess( !!(flags & Flags::readonly),!!(flags & Flags::finalized) ); aResult.setNullable(!!(flags & Flags::nullable)); aResult.setLocalized(!!(flags & Flags::localized)); configmgr::node::State state = (flags & Flags::defaulted) ? configmgr::node::isDefault : (flags & Flags::defaultable) ? configmgr::node::isMerged : configmgr::node::isReplaced; aResult.setState(state); return aResult; } //----------------------------------------------------------------------------- bool NodeInfo::isDefault() const { return !!(this->flags & Flags::defaulted); } //----------------------------------------------------------------------------- bool NodeInfo::isLocalized() const { return !!(this->flags & Flags::localized); } //----------------------------------------------------------------------------- void NodeInfo::markAsDefault(bool bDefault) { if (bDefault) { OSL_ENSURE(flags & Flags::defaultable,"Marking a non-defaultable node as default"); this->flags |= Flags::defaulted; } else this->flags &= ~Flags::defaulted; } //----------------------------------------------------------------------------- bool GroupNode::hasDefaultsAvailable() const { if (this->info.isDefault()) return true; if (node(this)->getTreeFragment()->hasDefaultsAvailable()) return true; #if 0 // extended check for default state for (Node const * pChild = getFirstChild(); pChild != NULL; pChild = getNextChild(pChild)) if (! pChild->isDefault() ) return false; return true; #endif return false; } //----------------------------------------------------------------------------- Node * GroupNode::getFirstChild() { OSL_ENSURE(numDescendants, "Groups MUST have at least one child"); return node(this) + 1; } //----------------------------------------------------------------------------- Node const * GroupNode::getFirstChild() const { OSL_ENSURE(numDescendants, "Groups MUST have at least one child"); return node(this) + 1; } //----------------------------------------------------------------------------- static Offset implGetNextChildOffset(GroupNode const * _pParent, Node const * _pChild) { OSL_PRECOND(_pChild, "getNextChild: previous child must not be NULL"); OSL_PRECOND(_pChild->getParentNode() == node(_pParent), "getNextChild: not a child of this node"); OSL_ENSURE( node(_pParent) < _pChild && _pChild <= node(_pParent) + _pParent->numDescendants, "getNextChild: child out of descendants range"); // offset to child's next sibling Offset next = 1; if ( _pChild->isGroup()) { next = next + _pChild->group.numDescendants; } if (_pChild->node.info.parent + next > _pParent->numDescendants) { OSL_ENSURE(_pChild->node.info.parent + next == _pParent->numDescendants+1, "Next child candidate should match next sibling here"); return 0; } OSL_POSTCOND( (_pChild+next)->getParentNode() == node(_pParent), "getNextChild: not a child of this node"); return next; } //----------------------------------------------------------------------------- Node * GroupNode::getNextChild(Node * _pChild) { if (Offset next = implGetNextChildOffset(this, _pChild)) return _pChild + next; else return NULL; } //----------------------------------------------------------------------------- Node const * GroupNode::getNextChild(Node const * _pChild) const { if (Offset next = implGetNextChildOffset(this, _pChild)) return _pChild + next; else return NULL; } //----------------------------------------------------------------------------- bool SetNode::isLocalizedValue() const { return info.isLocalized(); } //----------------------------------------------------------------------------- // TODO: optimize this - keep a list of such structs .... struct SetNodeTemplateData { Name name; Name module; }; //----------------------------------------------------------------------------- static inline SetNodeTemplateData * readTemplateData(memory::Allocator const & _anAllocator, Address _aTemplateData) { return static_cast<SetNodeTemplateData *>( _anAllocator.access(_aTemplateData) ); } //----------------------------------------------------------------------------- static inline SetNodeTemplateData const * readTemplateData(memory::Accessor const & _anAccessor, Address _aTemplateData) { return static_cast<SetNodeTemplateData const*>( _anAccessor.access(memory::Pointer(_aTemplateData)) ); } //----------------------------------------------------------------------------- Address SetNode::allocTemplateData(memory::Allocator const & _anAllocator, NameChar const * pName, NameChar const * pModule) { rtl::OUString aName(pName), aModule(pModule); Address aData = _anAllocator.allocate(sizeof(SetNodeTemplateData)); if (aData) { SetNodeTemplateData * pData = readTemplateData(_anAllocator,aData); OSL_ENSURE(pData, "Creating template data: unexpected NULL data"); pData->name = allocName(_anAllocator,aName); pData->module = allocName(_anAllocator,aModule); } return aData; } //----------------------------------------------------------------------------- void SetNode::releaseTemplateData(memory::Allocator const & _anAllocator, Address _aTemplateData) { if (!_aTemplateData) return; SetNodeTemplateData const * pData = readTemplateData(_anAllocator,_aTemplateData); OSL_ENSURE(pData, "Freeing template data: unexpected NULL data"); freeName(_anAllocator,pData->name); freeName(_anAllocator,pData->module); _anAllocator.deallocate(_aTemplateData); } //----------------------------------------------------------------------------- NameChar const * SetNode::getTemplateDataName(memory::Accessor const & _anAccessor, Address _aTemplateData) { OSL_PRECOND(_aTemplateData, "Reading template data: unexpected NULL pointer"); SetNodeTemplateData const * pData = readTemplateData(_anAccessor,_aTemplateData); OSL_ENSURE(pData, "Reading template data: unexpected NULL data"); return accessName(_anAccessor,pData->name); } //----------------------------------------------------------------------------- NameChar const * SetNode::getTemplateDataModule(memory::Accessor const & _anAccessor, Address _aTemplateData) { OSL_PRECOND(_aTemplateData, "Reading template data: unexpected NULL pointer"); SetNodeTemplateData const * pData = readTemplateData(_anAccessor,_aTemplateData); OSL_ENSURE(pData, "Reading template data: unexpected NULL data"); return accessName(_anAccessor,pData->module); } //----------------------------------------------------------------------------- rtl::OUString SetNode::getElementTemplateName(memory::Accessor const & _anAccessor) const { SetNodeTemplateData const * pData = readTemplateData(_anAccessor,this->elementType); OSL_ENSURE(pData, "ERROR: No template data found for set"); return readName(_anAccessor,pData->name); } //----------------------------------------------------------------------------- rtl::OUString SetNode::getElementTemplateModule(memory::Accessor const & _anAccessor) const { SetNodeTemplateData const * pData = readTemplateData(_anAccessor,this->elementType); OSL_ENSURE(pData, "ERROR: No template data found for set"); return readName(_anAccessor,pData->module); } //----------------------------------------------------------------------------- static inline TreeFragment const * implGetFragmentFromList(memory::Accessor const & _anAccessor, List _aListEntry) { return static_cast<TreeFragment const *>(_anAccessor.access(memory::Pointer(_aListEntry))); } //----------------------------------------------------------------------------- TreeFragment const * SetNode::getFirstElement(memory::Accessor const & _anAccessor) const { return implGetFragmentFromList(_anAccessor, this->elements); } //----------------------------------------------------------------------------- TreeFragment const * SetNode::getNextElement(memory::Accessor const & _anAccessor, TreeFragment const * _pElement) const { OSL_PRECOND(_pElement, "getNextElement: previous element must not be NULL"); OSL_PRECOND(_pElement->header.parent == _anAccessor.address(this).value(), "getNextElement: not an element of this node"); return implGetFragmentFromList(_anAccessor, _pElement->header.next); } //----------------------------------------------------------------------------- bool ValueNode::isEmpty() const { Type::Field const empty_value_type = Type::value_any | Type::nodetype_value; return info.type == empty_value_type; } //----------------------------------------------------------------------------- bool ValueNode::isNull() const { Flags::Type availmask = (info.flags & Flags::defaulted) ? Flags::defaultAvailable : Flags::valueAvailable; return !(info.flags & availmask); } //----------------------------------------------------------------------------- bool ValueNode::hasUsableDefault() const { return (info.flags & Flags::defaultable) && (info.flags & (Flags::defaultAvailable| Flags::nullable)); } //----------------------------------------------------------------------------- uno::Type ValueNode::getValueType() const { AnyData::TypeCode aType = AnyData::TypeCode( info.type & Type::mask_valuetype ); return getUnoType(aType); } //----------------------------------------------------------------------------- uno::Any ValueNode::getValue(memory::Accessor const & _aAccessor) const { if (info.flags & Flags::defaulted) return getDefaultValue(_aAccessor); else return getUserValue(_aAccessor); } //----------------------------------------------------------------------------- uno::Any ValueNode::getUserValue(memory::Accessor const & _aAccessor) const { if (info.flags & Flags::valueAvailable) { AnyData::TypeCode aType = AnyData::TypeCode( info.type & Type::mask_valuetype ); return readData(_aAccessor,aType,this->value); } else return uno::Any(); } //----------------------------------------------------------------------------- uno::Any ValueNode::getDefaultValue(memory::Accessor const & _aAccessor) const { if (info.flags & Flags::defaultAvailable) { AnyData::TypeCode aType = AnyData::TypeCode( info.type & Type::mask_valuetype ); return readData(_aAccessor,aType,this->defaultValue); } else return uno::Any(); } //----------------------------------------------------------------------------- bool Node::isNamed(rtl::OUString const & _aName, memory::Accessor const & _aAccessor) const { return 0 == rtl_ustr_compare(_aName.getStr(),accessString(_aAccessor,node.info.name)); } //----------------------------------------------------------------------------- rtl::OUString Node::getName(memory::Accessor const & _aAccessor) const { return node.info.getName(_aAccessor); } //----------------------------------------------------------------------------- configmgr::node::Attributes Node::getAttributes() const { if(this->isFragmentRoot()) { return this->getTreeFragment()->getAttributes(); } else { return node.info.getNodeInfoAttributes(); } } //----------------------------------------------------------------------------- bool Node::isDefault() const { return node.info.isDefault(); } //----------------------------------------------------------------------------- bool Node::isLocalized() const { return node.info.isLocalized(); } //----------------------------------------------------------------------------- bool Node::isGroup() const { return (node.info.type & Type::mask_nodetype) == Type::nodetype_group; } //----------------------------------------------------------------------------- bool Node::isSet() const { return (node.info.type & Type::mask_nodetype) == Type::nodetype_set; } //----------------------------------------------------------------------------- bool Node::isValue() const { return (node.info.type & Type::mask_nodetype) == Type::nodetype_value; } //----------------------------------------------------------------------------- GroupNode * Node::groupData() { return isGroup() ? &this->group : NULL; } //----------------------------------------------------------------------------- GroupNode const * Node::groupData() const { return isGroup() ? &this->group : NULL; } //----------------------------------------------------------------------------- SetNode * Node::setData() { return isSet() ? &this->set : NULL; } //----------------------------------------------------------------------------- SetNode const * Node::setData() const { return isSet() ? &this->set : NULL; } //----------------------------------------------------------------------------- ValueNode * Node::valueData() { return isValue() ? &this->value : NULL; } //----------------------------------------------------------------------------- ValueNode const * Node::valueData() const { return isValue() ? &this->value : NULL; } //----------------------------------------------------------------------------- bool Node::isFragmentRoot() const { return ! node.info.parent; } //----------------------------------------------------------------------------- Node * Node::getParentNode() { return node.info.parent ? this - node.info.parent : NULL; } //----------------------------------------------------------------------------- Node const * Node::getParentNode() const { return node.info.parent ? this - node.info.parent : NULL; } //----------------------------------------------------------------------------- static Offset getFragmentIndex(Node const * pNode) { Offset result = 0; while (Offset step = pNode->node.info.parent) { result = result + step; pNode -= step; } return result; } //----------------------------------------------------------------------------- TreeFragment * Node::getTreeFragment() { void * pRoot = this - getFragmentIndex(this); void * pFrag = static_cast<char*>(pRoot) - offsetof(TreeFragment,nodes); return static_cast<TreeFragment *>(pFrag); } //----------------------------------------------------------------------------- TreeFragment const * Node::getTreeFragment() const { void const * pRoot = this - getFragmentIndex(this); void const * pFrag = static_cast<char const*>(pRoot) - offsetof(TreeFragment,nodes); return static_cast<TreeFragment const *>(pFrag); } //----------------------------------------------------------------------------- } // namespace sharable //----------------------------------------------------------------------------- } // namespace configmgr <commit_msg>INTEGRATION: CWS pchfix02 (1.7.18); FILE MERGED 2006/09/01 17:20:43 kaib 1.7.18.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: node.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-16 15:21:33 $ * * 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_configmgr.hxx" #include "node.hxx" #ifndef INCLUDED_SHARABLE_ANYDATA_HXX #include "anydata.hxx" #endif #ifndef INCLUDED_SHARABLE_TREEFRAGMENT_HXX #include "treefragment.hxx" #endif #ifndef CONFIGMGR_ACCESSOR_HXX #include "accessor.hxx" #endif #ifndef CONFIGMGR_UPDATEACCESSOR_HXX #include "updateaccessor.hxx" #endif #ifndef CONFIGMGR_CONFIGURATION_ATTRIBUTES_HXX_ #include "attributes.hxx" #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef INCLUDED_CSTDDEF #include <cstddef> #define INCLUDED_CSTDDEF #endif namespace configmgr { //----------------------------------------------------------------------------- namespace sharable { //----------------------------------------------------------------------------- // Name name; // Offset parent; // always counts backwards // Flags::Field flags; // Type ::Field type; // contains discriminator for union rtl::OUString NodeInfo::getName(memory::Accessor const & _aAccessor) const { return readString(_aAccessor,this->name); } //----------------------------------------------------------------------------- configmgr::node::Attributes NodeInfo::getNodeInfoAttributes() const { configmgr::node::Attributes aResult; bool help = !!(flags & Flags::readonly); aResult.setAccess( help,!!(flags & Flags::finalized) ); // aResult.setAccess( !!(flags & Flags::readonly),!!(flags & Flags::finalized) ); aResult.setNullable(!!(flags & Flags::nullable)); aResult.setLocalized(!!(flags & Flags::localized)); configmgr::node::State state = (flags & Flags::defaulted) ? configmgr::node::isDefault : (flags & Flags::defaultable) ? configmgr::node::isMerged : configmgr::node::isReplaced; aResult.setState(state); return aResult; } //----------------------------------------------------------------------------- bool NodeInfo::isDefault() const { return !!(this->flags & Flags::defaulted); } //----------------------------------------------------------------------------- bool NodeInfo::isLocalized() const { return !!(this->flags & Flags::localized); } //----------------------------------------------------------------------------- void NodeInfo::markAsDefault(bool bDefault) { if (bDefault) { OSL_ENSURE(flags & Flags::defaultable,"Marking a non-defaultable node as default"); this->flags |= Flags::defaulted; } else this->flags &= ~Flags::defaulted; } //----------------------------------------------------------------------------- bool GroupNode::hasDefaultsAvailable() const { if (this->info.isDefault()) return true; if (node(this)->getTreeFragment()->hasDefaultsAvailable()) return true; #if 0 // extended check for default state for (Node const * pChild = getFirstChild(); pChild != NULL; pChild = getNextChild(pChild)) if (! pChild->isDefault() ) return false; return true; #endif return false; } //----------------------------------------------------------------------------- Node * GroupNode::getFirstChild() { OSL_ENSURE(numDescendants, "Groups MUST have at least one child"); return node(this) + 1; } //----------------------------------------------------------------------------- Node const * GroupNode::getFirstChild() const { OSL_ENSURE(numDescendants, "Groups MUST have at least one child"); return node(this) + 1; } //----------------------------------------------------------------------------- static Offset implGetNextChildOffset(GroupNode const * _pParent, Node const * _pChild) { OSL_PRECOND(_pChild, "getNextChild: previous child must not be NULL"); OSL_PRECOND(_pChild->getParentNode() == node(_pParent), "getNextChild: not a child of this node"); OSL_ENSURE( node(_pParent) < _pChild && _pChild <= node(_pParent) + _pParent->numDescendants, "getNextChild: child out of descendants range"); // offset to child's next sibling Offset next = 1; if ( _pChild->isGroup()) { next = next + _pChild->group.numDescendants; } if (_pChild->node.info.parent + next > _pParent->numDescendants) { OSL_ENSURE(_pChild->node.info.parent + next == _pParent->numDescendants+1, "Next child candidate should match next sibling here"); return 0; } OSL_POSTCOND( (_pChild+next)->getParentNode() == node(_pParent), "getNextChild: not a child of this node"); return next; } //----------------------------------------------------------------------------- Node * GroupNode::getNextChild(Node * _pChild) { if (Offset next = implGetNextChildOffset(this, _pChild)) return _pChild + next; else return NULL; } //----------------------------------------------------------------------------- Node const * GroupNode::getNextChild(Node const * _pChild) const { if (Offset next = implGetNextChildOffset(this, _pChild)) return _pChild + next; else return NULL; } //----------------------------------------------------------------------------- bool SetNode::isLocalizedValue() const { return info.isLocalized(); } //----------------------------------------------------------------------------- // TODO: optimize this - keep a list of such structs .... struct SetNodeTemplateData { Name name; Name module; }; //----------------------------------------------------------------------------- static inline SetNodeTemplateData * readTemplateData(memory::Allocator const & _anAllocator, Address _aTemplateData) { return static_cast<SetNodeTemplateData *>( _anAllocator.access(_aTemplateData) ); } //----------------------------------------------------------------------------- static inline SetNodeTemplateData const * readTemplateData(memory::Accessor const & _anAccessor, Address _aTemplateData) { return static_cast<SetNodeTemplateData const*>( _anAccessor.access(memory::Pointer(_aTemplateData)) ); } //----------------------------------------------------------------------------- Address SetNode::allocTemplateData(memory::Allocator const & _anAllocator, NameChar const * pName, NameChar const * pModule) { rtl::OUString aName(pName), aModule(pModule); Address aData = _anAllocator.allocate(sizeof(SetNodeTemplateData)); if (aData) { SetNodeTemplateData * pData = readTemplateData(_anAllocator,aData); OSL_ENSURE(pData, "Creating template data: unexpected NULL data"); pData->name = allocName(_anAllocator,aName); pData->module = allocName(_anAllocator,aModule); } return aData; } //----------------------------------------------------------------------------- void SetNode::releaseTemplateData(memory::Allocator const & _anAllocator, Address _aTemplateData) { if (!_aTemplateData) return; SetNodeTemplateData const * pData = readTemplateData(_anAllocator,_aTemplateData); OSL_ENSURE(pData, "Freeing template data: unexpected NULL data"); freeName(_anAllocator,pData->name); freeName(_anAllocator,pData->module); _anAllocator.deallocate(_aTemplateData); } //----------------------------------------------------------------------------- NameChar const * SetNode::getTemplateDataName(memory::Accessor const & _anAccessor, Address _aTemplateData) { OSL_PRECOND(_aTemplateData, "Reading template data: unexpected NULL pointer"); SetNodeTemplateData const * pData = readTemplateData(_anAccessor,_aTemplateData); OSL_ENSURE(pData, "Reading template data: unexpected NULL data"); return accessName(_anAccessor,pData->name); } //----------------------------------------------------------------------------- NameChar const * SetNode::getTemplateDataModule(memory::Accessor const & _anAccessor, Address _aTemplateData) { OSL_PRECOND(_aTemplateData, "Reading template data: unexpected NULL pointer"); SetNodeTemplateData const * pData = readTemplateData(_anAccessor,_aTemplateData); OSL_ENSURE(pData, "Reading template data: unexpected NULL data"); return accessName(_anAccessor,pData->module); } //----------------------------------------------------------------------------- rtl::OUString SetNode::getElementTemplateName(memory::Accessor const & _anAccessor) const { SetNodeTemplateData const * pData = readTemplateData(_anAccessor,this->elementType); OSL_ENSURE(pData, "ERROR: No template data found for set"); return readName(_anAccessor,pData->name); } //----------------------------------------------------------------------------- rtl::OUString SetNode::getElementTemplateModule(memory::Accessor const & _anAccessor) const { SetNodeTemplateData const * pData = readTemplateData(_anAccessor,this->elementType); OSL_ENSURE(pData, "ERROR: No template data found for set"); return readName(_anAccessor,pData->module); } //----------------------------------------------------------------------------- static inline TreeFragment const * implGetFragmentFromList(memory::Accessor const & _anAccessor, List _aListEntry) { return static_cast<TreeFragment const *>(_anAccessor.access(memory::Pointer(_aListEntry))); } //----------------------------------------------------------------------------- TreeFragment const * SetNode::getFirstElement(memory::Accessor const & _anAccessor) const { return implGetFragmentFromList(_anAccessor, this->elements); } //----------------------------------------------------------------------------- TreeFragment const * SetNode::getNextElement(memory::Accessor const & _anAccessor, TreeFragment const * _pElement) const { OSL_PRECOND(_pElement, "getNextElement: previous element must not be NULL"); OSL_PRECOND(_pElement->header.parent == _anAccessor.address(this).value(), "getNextElement: not an element of this node"); return implGetFragmentFromList(_anAccessor, _pElement->header.next); } //----------------------------------------------------------------------------- bool ValueNode::isEmpty() const { Type::Field const empty_value_type = Type::value_any | Type::nodetype_value; return info.type == empty_value_type; } //----------------------------------------------------------------------------- bool ValueNode::isNull() const { Flags::Type availmask = (info.flags & Flags::defaulted) ? Flags::defaultAvailable : Flags::valueAvailable; return !(info.flags & availmask); } //----------------------------------------------------------------------------- bool ValueNode::hasUsableDefault() const { return (info.flags & Flags::defaultable) && (info.flags & (Flags::defaultAvailable| Flags::nullable)); } //----------------------------------------------------------------------------- uno::Type ValueNode::getValueType() const { AnyData::TypeCode aType = AnyData::TypeCode( info.type & Type::mask_valuetype ); return getUnoType(aType); } //----------------------------------------------------------------------------- uno::Any ValueNode::getValue(memory::Accessor const & _aAccessor) const { if (info.flags & Flags::defaulted) return getDefaultValue(_aAccessor); else return getUserValue(_aAccessor); } //----------------------------------------------------------------------------- uno::Any ValueNode::getUserValue(memory::Accessor const & _aAccessor) const { if (info.flags & Flags::valueAvailable) { AnyData::TypeCode aType = AnyData::TypeCode( info.type & Type::mask_valuetype ); return readData(_aAccessor,aType,this->value); } else return uno::Any(); } //----------------------------------------------------------------------------- uno::Any ValueNode::getDefaultValue(memory::Accessor const & _aAccessor) const { if (info.flags & Flags::defaultAvailable) { AnyData::TypeCode aType = AnyData::TypeCode( info.type & Type::mask_valuetype ); return readData(_aAccessor,aType,this->defaultValue); } else return uno::Any(); } //----------------------------------------------------------------------------- bool Node::isNamed(rtl::OUString const & _aName, memory::Accessor const & _aAccessor) const { return 0 == rtl_ustr_compare(_aName.getStr(),accessString(_aAccessor,node.info.name)); } //----------------------------------------------------------------------------- rtl::OUString Node::getName(memory::Accessor const & _aAccessor) const { return node.info.getName(_aAccessor); } //----------------------------------------------------------------------------- configmgr::node::Attributes Node::getAttributes() const { if(this->isFragmentRoot()) { return this->getTreeFragment()->getAttributes(); } else { return node.info.getNodeInfoAttributes(); } } //----------------------------------------------------------------------------- bool Node::isDefault() const { return node.info.isDefault(); } //----------------------------------------------------------------------------- bool Node::isLocalized() const { return node.info.isLocalized(); } //----------------------------------------------------------------------------- bool Node::isGroup() const { return (node.info.type & Type::mask_nodetype) == Type::nodetype_group; } //----------------------------------------------------------------------------- bool Node::isSet() const { return (node.info.type & Type::mask_nodetype) == Type::nodetype_set; } //----------------------------------------------------------------------------- bool Node::isValue() const { return (node.info.type & Type::mask_nodetype) == Type::nodetype_value; } //----------------------------------------------------------------------------- GroupNode * Node::groupData() { return isGroup() ? &this->group : NULL; } //----------------------------------------------------------------------------- GroupNode const * Node::groupData() const { return isGroup() ? &this->group : NULL; } //----------------------------------------------------------------------------- SetNode * Node::setData() { return isSet() ? &this->set : NULL; } //----------------------------------------------------------------------------- SetNode const * Node::setData() const { return isSet() ? &this->set : NULL; } //----------------------------------------------------------------------------- ValueNode * Node::valueData() { return isValue() ? &this->value : NULL; } //----------------------------------------------------------------------------- ValueNode const * Node::valueData() const { return isValue() ? &this->value : NULL; } //----------------------------------------------------------------------------- bool Node::isFragmentRoot() const { return ! node.info.parent; } //----------------------------------------------------------------------------- Node * Node::getParentNode() { return node.info.parent ? this - node.info.parent : NULL; } //----------------------------------------------------------------------------- Node const * Node::getParentNode() const { return node.info.parent ? this - node.info.parent : NULL; } //----------------------------------------------------------------------------- static Offset getFragmentIndex(Node const * pNode) { Offset result = 0; while (Offset step = pNode->node.info.parent) { result = result + step; pNode -= step; } return result; } //----------------------------------------------------------------------------- TreeFragment * Node::getTreeFragment() { void * pRoot = this - getFragmentIndex(this); void * pFrag = static_cast<char*>(pRoot) - offsetof(TreeFragment,nodes); return static_cast<TreeFragment *>(pFrag); } //----------------------------------------------------------------------------- TreeFragment const * Node::getTreeFragment() const { void const * pRoot = this - getFragmentIndex(this); void const * pFrag = static_cast<char const*>(pRoot) - offsetof(TreeFragment,nodes); return static_cast<TreeFragment const *>(pFrag); } //----------------------------------------------------------------------------- } // namespace sharable //----------------------------------------------------------------------------- } // namespace configmgr <|endoftext|>
<commit_before>#include "vlc_video_source.h" #include <cstdio> #include <cstdlib> #include <chrono> #include <thread> namespace gg { VideoSourceVLC::VideoSourceVLC(const std::string path) : _vlc_inst(nullptr) , _vlc_mp(nullptr) , _running(false) , _video_buffer(nullptr) , _data_length(0) , _cols(0) , _rows(0) , _sub(nullptr) , _path(path) { init_vlc(); run_vlc(); determine_full(); } VideoSourceVLC::~VideoSourceVLC() { stop_vlc(); release_vlc(); clear(); } bool VideoSourceVLC::get_frame_dimensions(int & width, int & height) { std::lock_guard<std::mutex> data_lock_guard(_data_lock); if(this->_cols == 0 || this->_rows == 0) return false; width = this->_cols; height = this->_rows; return true; } bool VideoSourceVLC::get_frame(VideoFrame & frame) { if (frame.colour() != ColourSpace::I420) return false; std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_data_length > 0) { frame.init_from_specs(_video_buffer, _data_length, _cols, _rows); return true; } else return false; // TODO #86 } double VideoSourceVLC::get_frame_rate() { return libvlc_media_player_get_fps(_vlc_mp); } void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height) { if (x >= _full.x and x + width <= _full.x + _full.width and y >= _full.y and y + height <= _full.y + _full.height) { stop_vlc(); set_crop(x, y, width, height); run_vlc(); } } void VideoSourceVLC::get_full_frame() { stop_vlc(); reset_crop(); run_vlc(); } void VideoSourceVLC::init_vlc() { // VLC global options (valid for the lifetime of the program) // see `vlc --help` for the difference between `--option` and `:option` const char * const vlc_args[] = { "-I", "dummy", // Don't use any interface "--ignore-config", // Don't use VLC's config "--file-logging", //"--verbose=2", // Be much more verbose then normal for debugging purpose "--no-audio", "--no-video-title-show" }; // We launch VLC _vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args); if (_vlc_inst == nullptr) throw VideoSourceError("Could not create VLC engine"); // create VLC media player _vlc_mp = libvlc_media_player_new(_vlc_inst); if (_vlc_mp == nullptr) throw VideoSourceError("Could not create VLC media player"); } void VideoSourceVLC::run_vlc() { libvlc_media_t * vlc_media = nullptr; // If path contains a colon (:), it will be treated as a // URL. Else, it will be considered as a local path. if (_path.find(":") == std::string::npos) vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str()); else vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str()); if (vlc_media == nullptr) throw VideoSourceError(std::string("Could not open ").append(_path)); // compose the processing pipeline description char pipeline[512]; // open transcode step sprintf(pipeline, "#transcode{"); // cropping sub-frame unsigned int croptop = 0, cropbottom = 0, cropleft = 0, cropright = 0; if (_sub != nullptr) // cropping video? { croptop = std::max(_sub->y, croptop), cropbottom = std::max(_full.height - (_sub->y + _sub->height), cropbottom), cropleft = std::max(_sub->x, cropleft), cropright = std::max(_full.width - (_sub->x + _sub->width), cropright); } sprintf(pipeline, "%svfilter=croppadd{", pipeline); sprintf(pipeline, "%scroptop=%u,", pipeline, croptop); sprintf(pipeline, "%scropbottom=%u,", pipeline, cropbottom); sprintf(pipeline, "%scropleft=%u,", pipeline, cropleft); sprintf(pipeline, "%scropright=%u", pipeline, cropright); sprintf(pipeline, "%s}", pipeline); // colour space specification sprintf(pipeline, "%s,vcodec=I420", pipeline); // close transcode step sprintf(pipeline, "%s}:", pipeline); // callbacks sprintf(pipeline, "%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}", pipeline, (long long int)(intptr_t)(void*) this, (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender, (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream ); // activate pipeline in VLC media char sout_options[1024]; sprintf(sout_options, ":sout=%s", pipeline); libvlc_media_add_option(vlc_media, sout_options); // set VLC media player's media libvlc_media_player_set_media(_vlc_mp, vlc_media); // release VLC media libvlc_media_release(vlc_media); { // artificial scope for the mutex guard below std::lock_guard<std::mutex> data_lock_guard(_data_lock); // play the media_player if (libvlc_media_player_play(_vlc_mp) != 0) throw VideoSourceError("Could not start VLC media player"); _running = true; } // empirically determined value that allows for initialisation // to succeed before any API functions are called on this object std::this_thread::sleep_for(std::chrono::milliseconds(350)); } void VideoSourceVLC::stop_vlc() { // stop playing libvlc_media_player_stop(_vlc_mp); { // artificial scope for mutex guard below std::lock_guard<std::mutex> data_lock_guard(_data_lock); _running = false; } } void VideoSourceVLC::release_vlc() { // free media player libvlc_media_player_release(_vlc_mp); // free engine libvlc_release(_vlc_inst); } void VideoSourceVLC::clear() { // free buffer std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_video_buffer != nullptr) { delete[] _video_buffer; _video_buffer = nullptr; } _data_length = 0; _cols = 0; _rows = 0; reset_crop(); } void VideoSourceVLC::determine_full() { unsigned int width, height; if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0) throw VideoSourceError("Could not get video dimensions"); _full.x = 0; _full.y = 0; _full.width = width; _full.height = height; } void VideoSourceVLC::set_crop(unsigned int x, unsigned int y, unsigned int width, unsigned int height) { if (_sub == nullptr) _sub = new FrameBox; _sub->x = x; _sub->y = y; _sub->width = width; _sub->height = height; } void VideoSourceVLC::reset_crop() { // free sub-frame if (_sub != nullptr) { delete _sub; _sub = nullptr; } } void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data, uint8_t ** pp_pixel_buffer, size_t size) { std::lock_guard<std::mutex> data_lock_guard(p_video_data->_data_lock); if (p_video_data->_running) { if (size > p_video_data->_data_length) { if (p_video_data->_data_length == 0) p_video_data->_video_buffer = reinterpret_cast<uint8_t *>( malloc(size * sizeof(uint8_t)) ); else p_video_data->_video_buffer = reinterpret_cast<uint8_t *>( realloc(p_video_data->_video_buffer, size * sizeof(uint8_t)) ); } p_video_data->_data_length = size; *pp_pixel_buffer = p_video_data->_video_buffer; } } void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data, uint8_t * p_pixel_buffer, size_t cols, size_t rows, size_t colour_depth, size_t size) { std::lock_guard<std::mutex> data_lock_guard(p_video_data->_data_lock); // TODO: explain how data should be handled (see #86) if (p_video_data->_running) { p_video_data->_cols = cols; p_video_data->_rows = rows; } } } <commit_msg>Issue #101: fixed determine_full: using get_frame_dimensions inside it<commit_after>#include "vlc_video_source.h" #include <cstdio> #include <cstdlib> #include <chrono> #include <thread> namespace gg { VideoSourceVLC::VideoSourceVLC(const std::string path) : _vlc_inst(nullptr) , _vlc_mp(nullptr) , _running(false) , _video_buffer(nullptr) , _data_length(0) , _cols(0) , _rows(0) , _sub(nullptr) , _path(path) { init_vlc(); run_vlc(); determine_full(); } VideoSourceVLC::~VideoSourceVLC() { stop_vlc(); release_vlc(); clear(); } bool VideoSourceVLC::get_frame_dimensions(int & width, int & height) { std::lock_guard<std::mutex> data_lock_guard(_data_lock); if(this->_cols == 0 || this->_rows == 0) return false; width = this->_cols; height = this->_rows; return true; } bool VideoSourceVLC::get_frame(VideoFrame & frame) { if (frame.colour() != ColourSpace::I420) return false; std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_data_length > 0) { frame.init_from_specs(_video_buffer, _data_length, _cols, _rows); return true; } else return false; // TODO #86 } double VideoSourceVLC::get_frame_rate() { return libvlc_media_player_get_fps(_vlc_mp); } void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height) { if (x >= _full.x and x + width <= _full.x + _full.width and y >= _full.y and y + height <= _full.y + _full.height) { stop_vlc(); set_crop(x, y, width, height); run_vlc(); } } void VideoSourceVLC::get_full_frame() { stop_vlc(); reset_crop(); run_vlc(); } void VideoSourceVLC::init_vlc() { // VLC global options (valid for the lifetime of the program) // see `vlc --help` for the difference between `--option` and `:option` const char * const vlc_args[] = { "-I", "dummy", // Don't use any interface "--ignore-config", // Don't use VLC's config "--file-logging", //"--verbose=2", // Be much more verbose then normal for debugging purpose "--no-audio", "--no-video-title-show" }; // We launch VLC _vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args); if (_vlc_inst == nullptr) throw VideoSourceError("Could not create VLC engine"); // create VLC media player _vlc_mp = libvlc_media_player_new(_vlc_inst); if (_vlc_mp == nullptr) throw VideoSourceError("Could not create VLC media player"); } void VideoSourceVLC::run_vlc() { libvlc_media_t * vlc_media = nullptr; // If path contains a colon (:), it will be treated as a // URL. Else, it will be considered as a local path. if (_path.find(":") == std::string::npos) vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str()); else vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str()); if (vlc_media == nullptr) throw VideoSourceError(std::string("Could not open ").append(_path)); // compose the processing pipeline description char pipeline[512]; // open transcode step sprintf(pipeline, "#transcode{"); // cropping sub-frame unsigned int croptop = 0, cropbottom = 0, cropleft = 0, cropright = 0; if (_sub != nullptr) // cropping video? { croptop = std::max(_sub->y, croptop), cropbottom = std::max(_full.height - (_sub->y + _sub->height), cropbottom), cropleft = std::max(_sub->x, cropleft), cropright = std::max(_full.width - (_sub->x + _sub->width), cropright); } sprintf(pipeline, "%svfilter=croppadd{", pipeline); sprintf(pipeline, "%scroptop=%u,", pipeline, croptop); sprintf(pipeline, "%scropbottom=%u,", pipeline, cropbottom); sprintf(pipeline, "%scropleft=%u,", pipeline, cropleft); sprintf(pipeline, "%scropright=%u", pipeline, cropright); sprintf(pipeline, "%s}", pipeline); // colour space specification sprintf(pipeline, "%s,vcodec=I420", pipeline); // close transcode step sprintf(pipeline, "%s}:", pipeline); // callbacks sprintf(pipeline, "%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}", pipeline, (long long int)(intptr_t)(void*) this, (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender, (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream ); // activate pipeline in VLC media char sout_options[1024]; sprintf(sout_options, ":sout=%s", pipeline); libvlc_media_add_option(vlc_media, sout_options); // set VLC media player's media libvlc_media_player_set_media(_vlc_mp, vlc_media); // release VLC media libvlc_media_release(vlc_media); { // artificial scope for the mutex guard below std::lock_guard<std::mutex> data_lock_guard(_data_lock); // play the media_player if (libvlc_media_player_play(_vlc_mp) != 0) throw VideoSourceError("Could not start VLC media player"); _running = true; } // empirically determined value that allows for initialisation // to succeed before any API functions are called on this object std::this_thread::sleep_for(std::chrono::milliseconds(350)); } void VideoSourceVLC::stop_vlc() { // stop playing libvlc_media_player_stop(_vlc_mp); { // artificial scope for mutex guard below std::lock_guard<std::mutex> data_lock_guard(_data_lock); _running = false; } } void VideoSourceVLC::release_vlc() { // free media player libvlc_media_player_release(_vlc_mp); // free engine libvlc_release(_vlc_inst); } void VideoSourceVLC::clear() { // free buffer std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_video_buffer != nullptr) { delete[] _video_buffer; _video_buffer = nullptr; } _data_length = 0; _cols = 0; _rows = 0; reset_crop(); } void VideoSourceVLC::determine_full() { get_frame_dimensions((int&)_full.width, (int&)_full.height); _full.x = 0; _full.y = 0; } void VideoSourceVLC::set_crop(unsigned int x, unsigned int y, unsigned int width, unsigned int height) { if (_sub == nullptr) _sub = new FrameBox; _sub->x = x; _sub->y = y; _sub->width = width; _sub->height = height; } void VideoSourceVLC::reset_crop() { // free sub-frame if (_sub != nullptr) { delete _sub; _sub = nullptr; } } void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data, uint8_t ** pp_pixel_buffer, size_t size) { std::lock_guard<std::mutex> data_lock_guard(p_video_data->_data_lock); if (p_video_data->_running) { if (size > p_video_data->_data_length) { if (p_video_data->_data_length == 0) p_video_data->_video_buffer = reinterpret_cast<uint8_t *>( malloc(size * sizeof(uint8_t)) ); else p_video_data->_video_buffer = reinterpret_cast<uint8_t *>( realloc(p_video_data->_video_buffer, size * sizeof(uint8_t)) ); } p_video_data->_data_length = size; *pp_pixel_buffer = p_video_data->_video_buffer; } } void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data, uint8_t * p_pixel_buffer, size_t cols, size_t rows, size_t colour_depth, size_t size) { std::lock_guard<std::mutex> data_lock_guard(p_video_data->_data_lock); // TODO: explain how data should be handled (see #86) if (p_video_data->_running) { p_video_data->_cols = cols; p_video_data->_rows = rows; } } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.1 2003/09/16 14:33:36 neilg * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them * */ #if !defined(PSVIHANDLER_HPP) #define PSVIHANDLER_HPP #include <xercesc/framework/psvi/PSVIElement.hpp> #include <xercesc/framework/psvi/PSVIAttribute.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * This abstract class provides the interface for the scanner to return * PSVI information to the application. * */ class XMLPARSER_EXPORT PSVIHandler { public: // ----------------------------------------------------------------------- // Constructors are hidden, just the virtual destructor is exposed // ----------------------------------------------------------------------- /** @name Destructor */ //@{ virtual ~PSVIHandler() { } //@} /** @name The PSVI handler interface */ //@{ /** Receive notification of the PSVI properties of an element. * The scanner will issue this call after the XMLDocumentHandler * endElement call. Since the scanner will issue the psviAttributes * call immediately after reading the start tag of an element, all element * content will be effectively bracketed by these two calls. * @param localName The name of the element whose end tag was just * parsed. * @param uri The namespace to which the element is bound * @param prefix The string representing the prefix name * @param elementInfo Object containing the element's PSVI properties */ virtual void handleElementPSVI ( const XMLElementDecl * localName , const XMLCh* const uri , const XMLCh* const prefix , const PSVIElement * elementInfo ) = 0; /** * Enables PSVI information about attributes to be passed back to the * application. This callback will be made on *all* * elements; on elements with no attributes, the final parameter will * be null. * @param localName The name of the element upon which start tag * these attributes were encountered. * @param uri The namespace to which the element is bound * @param prefix The string representing the prefix name * @param psviAttributes Object containing the attributes' PSVI properties * with information to identify them. */ virtual void handleAttributesPSVI ( const XMLElementDecl * localName , const XMLCh* const uri , const XMLCh* const prefix , const PSVIAttributeList * psviAttributes ) = 0; //@} protected : // ----------------------------------------------------------------------- // Hidden Constructors // ----------------------------------------------------------------------- PSVIHandler() { } private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- PSVIHandler(const PSVIHandler&); PSVIHandler& operator=(const PSVIHandler&); }; XERCES_CPP_NAMESPACE_END #endif <commit_msg>clearly the local name of an element should be a string, not an XMLElementDecl...<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.2 2003/09/22 15:03:06 neilg * clearly the local name of an element should be a string, not an XMLElementDecl... * * Revision 1.1 2003/09/16 14:33:36 neilg * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them * */ #if !defined(PSVIHANDLER_HPP) #define PSVIHANDLER_HPP #include <xercesc/framework/psvi/PSVIElement.hpp> #include <xercesc/framework/psvi/PSVIAttribute.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * This abstract class provides the interface for the scanner to return * PSVI information to the application. * */ class XMLPARSER_EXPORT PSVIHandler { public: // ----------------------------------------------------------------------- // Constructors are hidden, just the virtual destructor is exposed // ----------------------------------------------------------------------- /** @name Destructor */ //@{ virtual ~PSVIHandler() { } //@} /** @name The PSVI handler interface */ //@{ /** Receive notification of the PSVI properties of an element. * The scanner will issue this call after the XMLDocumentHandler * endElement call. Since the scanner will issue the psviAttributes * call immediately after reading the start tag of an element, all element * content will be effectively bracketed by these two calls. * @param localName The name of the element whose end tag was just * parsed. * @param uri The namespace to which the element is bound * @param prefix The string representing the prefix name * @param elementInfo Object containing the element's PSVI properties */ virtual void handleElementPSVI ( const XMLCh * localName , const XMLCh* const uri , const XMLCh* const prefix , const PSVIElement * elementInfo ) = 0; /** * Enables PSVI information about attributes to be passed back to the * application. This callback will be made on *all* * elements; on elements with no attributes, the final parameter will * be null. * @param localName The name of the element upon which start tag * these attributes were encountered. * @param uri The namespace to which the element is bound * @param prefix The string representing the prefix name * @param psviAttributes Object containing the attributes' PSVI properties * with information to identify them. */ virtual void handleAttributesPSVI ( const XMLCh * localName , const XMLCh* const uri , const XMLCh* const prefix , const PSVIAttributeList * psviAttributes ) = 0; //@} protected : // ----------------------------------------------------------------------- // Hidden Constructors // ----------------------------------------------------------------------- PSVIHandler() { } private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- PSVIHandler(const PSVIHandler&); PSVIHandler& operator=(const PSVIHandler&); }; XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used 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. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylandglcontext.h" #include "qwaylanddisplay.h" #include "qwaylandwindow.h" #include "qwaylandeglwindow.h" #include <QtPlatformSupport/private/qeglconvenience_p.h> #include <QtGui/QPlatformOpenGLContext> #include <QtGui/QSurfaceFormat> #include <QtCore/QMutex> QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QSurfaceFormat &format, QPlatformOpenGLContext *share) : QPlatformOpenGLContext() , m_eglDisplay(eglDisplay) , m_config(q_configFromGLFormat(m_eglDisplay, format, true)) , m_format(q_glFormatFromConfig(m_eglDisplay, m_config)) { EGLContext shareEGLContext = share ? static_cast<QWaylandGLContext *>(share)->eglContext() : EGL_NO_CONTEXT; eglBindAPI(EGL_OPENGL_ES_API); QVector<EGLint> eglContextAttrs; eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION); eglContextAttrs.append(2); eglContextAttrs.append(EGL_NONE); m_context = eglCreateContext(m_eglDisplay, m_config, shareEGLContext, eglContextAttrs.constData()); } QWaylandGLContext::~QWaylandGLContext() { eglDestroyContext(m_eglDisplay, m_context); } bool QWaylandGLContext::makeCurrent(QPlatformSurface *surface) { EGLSurface eglSurface = static_cast<QWaylandEglWindow *>(surface)->eglSurface(); return eglMakeCurrent(m_eglDisplay, eglSurface, eglSurface, m_context); } void QWaylandGLContext::doneCurrent() { eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } // lock to sync with QWaylandDisplay event loop ( defined in qwaylanddisplay.cpp ) extern QMutex g_waylandLock; void QWaylandGLContext::swapBuffers(QPlatformSurface *surface) { QMutexLocker l(&g_waylandLock); EGLSurface eglSurface = static_cast<QWaylandEglWindow *>(surface)->eglSurface(); eglSwapBuffers(m_eglDisplay, eglSurface); } void (*QWaylandGLContext::getProcAddress(const QByteArray &procName)) () { return eglGetProcAddress(procName.constData()); } EGLConfig QWaylandGLContext::eglConfig() const { return m_config; } <commit_msg>pick the right gl version<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used 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. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylandglcontext.h" #include "qwaylanddisplay.h" #include "qwaylandwindow.h" #include "qwaylandeglwindow.h" #include <QtPlatformSupport/private/qeglconvenience_p.h> #include <QtGui/QPlatformOpenGLContext> #include <QtGui/QSurfaceFormat> #include <QtCore/QMutex> QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QSurfaceFormat &format, QPlatformOpenGLContext *share) : QPlatformOpenGLContext() , m_eglDisplay(eglDisplay) , m_config(q_configFromGLFormat(m_eglDisplay, format, true)) , m_format(q_glFormatFromConfig(m_eglDisplay, m_config)) { EGLContext shareEGLContext = share ? static_cast<QWaylandGLContext *>(share)->eglContext() : EGL_NO_CONTEXT; eglBindAPI(EGL_OPENGL_ES_API); QVector<EGLint> eglContextAttrs; eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION); eglContextAttrs.append(format.majorVersion() == 1 ? 1 : 2); eglContextAttrs.append(EGL_NONE); m_context = eglCreateContext(m_eglDisplay, m_config, shareEGLContext, eglContextAttrs.constData()); } QWaylandGLContext::~QWaylandGLContext() { eglDestroyContext(m_eglDisplay, m_context); } bool QWaylandGLContext::makeCurrent(QPlatformSurface *surface) { EGLSurface eglSurface = static_cast<QWaylandEglWindow *>(surface)->eglSurface(); return eglMakeCurrent(m_eglDisplay, eglSurface, eglSurface, m_context); } void QWaylandGLContext::doneCurrent() { eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } // lock to sync with QWaylandDisplay event loop ( defined in qwaylanddisplay.cpp ) extern QMutex g_waylandLock; void QWaylandGLContext::swapBuffers(QPlatformSurface *surface) { QMutexLocker l(&g_waylandLock); EGLSurface eglSurface = static_cast<QWaylandEglWindow *>(surface)->eglSurface(); eglSwapBuffers(m_eglDisplay, eglSurface); } void (*QWaylandGLContext::getProcAddress(const QByteArray &procName)) () { return eglGetProcAddress(procName.constData()); } EGLConfig QWaylandGLContext::eglConfig() const { return m_config; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkTestFixture.h> #include "mitkIOUtil.h" #include <cmath> #include <mitkGIFImageDescriptionFeatures.h> class mitkGIFImageDescriptionFeaturesTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGIFImageDescriptionFeaturesTestSuite ); MITK_TEST(ImageDescription_PhantomTest); CPPUNIT_TEST_SUITE_END(); private: mitk::Image::Pointer m_IBSI_Phantom_Image_Small; mitk::Image::Pointer m_IBSI_Phantom_Image_Large; mitk::Image::Pointer m_IBSI_Phantom_Mask_Small; mitk::Image::Pointer m_IBSI_Phantom_Mask_Large; public: void setUp(void) override { m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd")); m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd")); m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd")); m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd")); } void ImageDescription_PhantomTest() { mitk::GIFImageDescriptionFeatures::Pointer featureCalculator = mitk::GIFImageDescriptionFeatures::New(); auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 22 features.", std::size_t(22), featureList.size()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension X should be 7 with Large IBSI Phantom Image", int(7), int(results["Diagnostic::Image Dimension X"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension Y should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Image Dimension Y"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension Z should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Image Dimension Z"])); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing X should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing X"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing Y should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing Y"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing Z should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing Z"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Mean intensity should be 0.6865 with Large IBSI Phantom Image", 0.686508, results["Diagnostic::Image Mean intensity"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Minimum intensity should be 0 with Large IBSI Phantom Image", 0, results["Diagnostic::Image Minimum intensity"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Maximum intensity should be 9 with Large IBSI Phantom Image", 9, results["Diagnostic::Image Maximum intensity"], 0.0001); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension X should be 7 with Large IBSI Phantom Image", int(7), int(results["Diagnostic::Mask Dimension X"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension Y should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Mask Dimension Y"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension Z should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Mask Dimension Z"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box X should be 5 with Large IBSI Phantom Image", int(5), int(results["Diagnostic::Mask bounding box X"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box Y should be 4 with Large IBSI Phantom Image", int(4), int(results["Diagnostic::Mask bounding box Y"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box Z should be 4 with Large IBSI Phantom Image", int(4), int(results["Diagnostic::Mask bounding box Z"])); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing X should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing X"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing Y should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing Y"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing Z should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing Z"], 0.0001); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Voxel Count should be 74 with Large IBSI Phantom Image", int(74), int(results["Diagnostic::Mask Voxel Count"])); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Mean intensity should be 2.14865 with Large IBSI Phantom Image", 2.14865, results["Diagnostic::Mask Mean intensity"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Minimum intensity should be 1 with Large IBSI Phantom Image", 1, results["Diagnostic::Mask Minimum intensity"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Maximum intensity should be 6 with Large IBSI Phantom Image", 6, results["Diagnostic::Mask Maximum intensity"], 0.0001); } }; MITK_TEST_SUITE_REGISTRATION(mitkGIFImageDescriptionFeatures )<commit_msg>Added a comment to clarify the origin of the values<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkTestFixture.h> #include "mitkIOUtil.h" #include <cmath> #include <mitkGIFImageDescriptionFeatures.h> class mitkGIFImageDescriptionFeaturesTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGIFImageDescriptionFeaturesTestSuite ); MITK_TEST(ImageDescription_PhantomTest); CPPUNIT_TEST_SUITE_END(); private: mitk::Image::Pointer m_IBSI_Phantom_Image_Small; mitk::Image::Pointer m_IBSI_Phantom_Image_Large; mitk::Image::Pointer m_IBSI_Phantom_Mask_Small; mitk::Image::Pointer m_IBSI_Phantom_Mask_Large; public: void setUp(void) override { m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd")); m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd")); m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd")); m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd")); } void ImageDescription_PhantomTest() { mitk::GIFImageDescriptionFeatures::Pointer featureCalculator = mitk::GIFImageDescriptionFeatures::New(); auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 22 features.", std::size_t(22), featureList.size()); // These values are calculated obtained by using this filter. Changes, especially with mean values could happen. CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension X should be 7 with Large IBSI Phantom Image", int(7), int(results["Diagnostic::Image Dimension X"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension Y should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Image Dimension Y"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Image Dimension Z should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Image Dimension Z"])); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing X should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing X"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing Y should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing Y"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Spacing Z should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Image Spacing Z"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Mean intensity should be 0.6865 with Large IBSI Phantom Image", 0.686508, results["Diagnostic::Image Mean intensity"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Minimum intensity should be 0 with Large IBSI Phantom Image", 0, results["Diagnostic::Image Minimum intensity"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Image Maximum intensity should be 9 with Large IBSI Phantom Image", 9, results["Diagnostic::Image Maximum intensity"], 0.0001); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension X should be 7 with Large IBSI Phantom Image", int(7), int(results["Diagnostic::Mask Dimension X"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension Y should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Mask Dimension Y"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Dimension Z should be 6 with Large IBSI Phantom Image", int(6), int(results["Diagnostic::Mask Dimension Z"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box X should be 5 with Large IBSI Phantom Image", int(5), int(results["Diagnostic::Mask bounding box X"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box Y should be 4 with Large IBSI Phantom Image", int(4), int(results["Diagnostic::Mask bounding box Y"])); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask bounding box Z should be 4 with Large IBSI Phantom Image", int(4), int(results["Diagnostic::Mask bounding box Z"])); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing X should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing X"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing Y should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing Y"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Spacing Z should be 2 with Large IBSI Phantom Image", 2.0, results["Diagnostic::Mask Spacing Z"], 0.0001); CPPUNIT_ASSERT_EQUAL_MESSAGE("Diagnostic::Mask Voxel Count should be 74 with Large IBSI Phantom Image", int(74), int(results["Diagnostic::Mask Voxel Count"])); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Mean intensity should be 2.14865 with Large IBSI Phantom Image", 2.14865, results["Diagnostic::Mask Mean intensity"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Minimum intensity should be 1 with Large IBSI Phantom Image", 1, results["Diagnostic::Mask Minimum intensity"], 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Diagnostic::Mask Maximum intensity should be 6 with Large IBSI Phantom Image", 6, results["Diagnostic::Mask Maximum intensity"], 0.0001); } }; MITK_TEST_SUITE_REGISTRATION(mitkGIFImageDescriptionFeatures )<|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nagoya University * 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 Autoware 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 <fstream> #include <ros/ros.h> #include <ros/console.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> static tf::StampedTransform transform; static bool output_first; static int sub_point_queue_size; static double velocity; // km/h static std::string output_file; static void write_clicked_point(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) { if (output_first) { std::ofstream ofs(output_file.c_str()); ofs << std::fixed << msg->pose.pose.position.x + transform.getOrigin().x() << "," << std::fixed << msg->pose.pose.position.y + transform.getOrigin().y() << "," << std::fixed << msg->pose.pose.position.z + transform.getOrigin().z() << std::endl; } else { std::ofstream ofs(output_file.c_str(), std::ios_base::app); ofs << std::fixed << msg->pose.pose.position.x + transform.getOrigin().x() << "," << std::fixed << msg->pose.pose.position.y + transform.getOrigin().y() << "," << std::fixed << msg->pose.pose.position.z + transform.getOrigin().z() << "," << std::fixed << velocity << std::endl; } if (output_first) output_first = false; } int main(int argc, char **argv) { ros::init(argc, argv, "waypoint_clicker"); ros::NodeHandle n; n.param<int>("/waypoint_clicker/sub_point_queue_size", sub_point_queue_size, 1); n.param<double>("/waypoint_clicker/velocity", velocity, 40); n.param<std::string>("/waypoint_clicker/output_file", output_file, "/tmp/lane_waypoint.csv"); ros::Subscriber sub_point = n.subscribe("/clicked_point", sub_point_queue_size, write_clicked_point); tf::TransformListener listener; try { ros::Time zero = ros::Time(0); listener.waitForTransform("map", "world", zero, ros::Duration(10)); listener.lookupTransform("map", "world", zero, transform); } catch (tf::TransformException &ex) { ROS_ERROR("%s", ex.what()); } output_first = true; ros::spin(); return 0; } <commit_msg>Fix subscribing topic<commit_after>/* * Copyright (c) 2015, Nagoya University * 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 Autoware 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 <fstream> #include <ros/ros.h> #include <ros/console.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> static tf::StampedTransform transform; static bool output_first; static int sub_point_queue_size; static double velocity; // km/h static std::string output_file; static void write_clicked_point(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) { if (output_first) { std::ofstream ofs(output_file.c_str()); ofs << std::fixed << msg->pose.pose.position.x + transform.getOrigin().x() << "," << std::fixed << msg->pose.pose.position.y + transform.getOrigin().y() << "," << std::fixed << msg->pose.pose.position.z + transform.getOrigin().z() << std::endl; } else { std::ofstream ofs(output_file.c_str(), std::ios_base::app); ofs << std::fixed << msg->pose.pose.position.x + transform.getOrigin().x() << "," << std::fixed << msg->pose.pose.position.y + transform.getOrigin().y() << "," << std::fixed << msg->pose.pose.position.z + transform.getOrigin().z() << "," << std::fixed << velocity << std::endl; } if (output_first) output_first = false; } int main(int argc, char **argv) { ros::init(argc, argv, "waypoint_clicker"); ros::NodeHandle n; n.param<int>("/waypoint_clicker/sub_point_queue_size", sub_point_queue_size, 1); n.param<double>("/waypoint_clicker/velocity", velocity, 40); n.param<std::string>("/waypoint_clicker/output_file", output_file, "/tmp/lane_waypoint.csv"); ros::Subscriber sub_point = n.subscribe("/initialpose", sub_point_queue_size, write_clicked_point); tf::TransformListener listener; try { ros::Time zero = ros::Time(0); listener.waitForTransform("map", "world", zero, ros::Duration(10)); listener.lookupTransform("map", "world", zero, transform); } catch (tf::TransformException &ex) { ROS_ERROR("%s", ex.what()); } output_first = true; ros::spin(); return 0; } <|endoftext|>
<commit_before>#include "config.h" // system #include <vector> // boost #include <boost/filesystem.hpp> // dune-common #include <dune/common/exceptions.hh> #include <dune/common/mpihelper.hh> #include <dune/common/timer.hh> // dune-grid-multiscale #include <dune/grid/multiscale/provider/cube.hh> // dune-fem #include <dune/fem/misc/mpimanager.hh> #include <dune/fem/misc/gridwidth.hh> // dune-stuff #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/discretefunction/norm.hh> #include <dune/stuff/function/expression.hh> // dune-detailed-solvers #include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh> #ifdef POLORDER const int polOrder = POLORDER; #else const int polOrder = 1; #endif const std::string id = "stationary.linear.elliptic.ms.semicg.ddd"; /** \brief Creates a parameter file if it does not exist. Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary keys and values. \param[in] filename (Relative) path to the file. **/ void ensureParamFile(std::string filename) { // only write param file if there is none if (!boost::filesystem::exists(filename)) { std::ofstream file; file.open(filename); file << "[" << id << "]" << std::endl; file << "exact_solution.order = 2" << std::endl; file << "exact_solution.variable = x" << std::endl; file << "exact_solution.expression.0 = -0.5*x[0]*x[0] + 0.5*x[0]" << std::endl; file << "[grid.multiscale.provider.cube]" << std::endl; file << "level = 4" << std::endl; file << "boundaryId = 7" << std::endl; // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully) file << "partitions.0 = 2" << std::endl; file << "partitions.1 = 2" << std::endl; file << "partitions.2 = 2" << std::endl; file << "filename = " << id << ".msGrid" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl; file << "diffusion.order = 0" << std::endl; file << "diffusion.variable = x" << std::endl; file << "diffusion.expression.0 = 1.0" << std::endl; file << "diffusion.expression.1 = 1.0" << std::endl; file << "diffusion.expression.2 = 1.0" << std::endl; file << "force.order = 0" << std::endl; file << "force.variable = x" << std::endl; file << "force.expression.0 = 1.0" << std::endl; file << "force.expression.1 = 1.0" << std::endl; file << "force.expression.2 = 1.0" << std::endl; file << "dirichlet.order = 0" << std::endl; file << "dirichlet.variable = x" << std::endl; file << "dirichlet.expression.0 = 0.0" << std::endl; file << "dirichlet.expression.1 = 0.0" << std::endl; file << "dirichlet.expression.2 = 0.0" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl; file << "discretization.penaltyFactor = 10.0" << std::endl; file << "solve.type = eigen.bicgstab.incompletelut" << std::endl; file << "solve.maxIter = 5000" << std::endl; file << "solve.precision = 1e-12" << std::endl; file << "visualize.filename = " << id << ".solution" << std::endl; file << "visualize.name = solution" << std::endl; file.close(); } // only write param file if there is none } // void ensureParamFile() template< class MultiscaleDiscreteFunctionType, class OutStreamType > void compute_errors(Dune::ParameterTree& paramTree, const MultiscaleDiscreteFunctionType& discreteFunction, OutStreamType& out, std::string prefix = "") { // exact solution typedef typename MultiscaleDiscreteFunctionType::LocalDiscreteFunctionType DiscreteFunctionType; typedef typename DiscreteFunctionType::RangeFieldType RangeFieldType; typedef typename DiscreteFunctionType::DomainFieldType DomainFieldType; typedef Dune::Stuff::Function::Expression< DomainFieldType, DiscreteFunctionType::dimDomain, RangeFieldType, DiscreteFunctionType::dimRange > FunctionType; const FunctionType function(paramTree); const unsigned int functionOrder = paramTree.get("order", 100); // compute norms out << prefix << " norm | exact solution | discrete solution | error (abs) | error (rel)" << std::endl; out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl; const RangeFieldType L2_reference_norm = Dune::Stuff::DiscreteFunction::Norm::L2(*(discreteFunction.msGrid().globalGridPart()), function, functionOrder); out.precision(2); out << prefix << " L2 | " << std::setw(14) << std::scientific << L2_reference_norm << " | " << std::flush; const RangeFieldType L2_discrete_norm = Dune::Stuff::DiscreteFunction::Norm::L2(discreteFunction); out << std::setw(17) << std::scientific << L2_discrete_norm << " | " << std::flush; const RangeFieldType L2_difference = Dune::Stuff::DiscreteFunction::Norm::L2_difference(function, functionOrder, discreteFunction); out << std::setw(11) << std::scientific << L2_difference << " | " << std::flush; out << std::setw(11) << std::scientific << L2_difference/L2_reference_norm << std::endl; out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl; // const RangeFieldType h1_reference_norm = Dune::Stuff::DiscreteFunction::Norm::h1(referenceSolution); // out.precision(2); // out << prefix << " h1 | " << std::setw(9) << std::scientific << h1_reference_norm << " | " << std::flush; // const RangeFieldType h1_multiscale_norm = Dune::Stuff::DiscreteFunction::Norm::h1(multiscaleSolution); // out << std::setw(10) << std::scientific << h1_multiscale_norm << " | " << std::flush; // const RangeFieldType h1_difference = Dune::Stuff::DiscreteFunction::Norm::h1_difference(referenceSolution, multiscaleSolution); // out << std::setw(11) << std::scientific << h1_difference << " | " << std::flush; // out << std::setw(11) << std::scientific << h1_difference/h1_reference_norm << std::endl; // out << prefix << "------+-----------+------------+-------------+-------------" << std::endl; } // void compute_norms(...) int main(int argc, char** argv) { try { // mpi Dune::MPIManager::initialize(argc, argv); // parameter const std::string filename = id + ".param"; ensureParamFile(filename); Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename); // logger Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO | Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); // Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info(); std::ostream& info = std::cout; Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); // timer Dune::Timer timer; info << "setting up grid: " << std::endl; debug.suspend(); typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType; paramTree.assertSub(GridProviderType::id, id); const GridProviderType gridProvider(paramTree.sub(GridProviderType::id)); typedef GridProviderType::MsGridType MsGridType; const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGridPtr(); info << " took " << timer.elapsed() << " sec (has " << gridProvider.grid().size(0) << " elements, " << msGrid->size() << " subdomain"; if (msGrid->size() > 1) info << "s"; info << " and a width of " << Dune::GridWidth::calcGridWidth(*(msGrid->globalGridPart())) << ")" << std::endl; debug.resume(); info << "visualizing grid... " << std::flush; timer.reset(); debug.suspend(); msGrid->visualize(paramTree.sub(GridProviderType::id).get("filename", id + "_msGrid")); info << "done (took " << timer.elapsed() << " sek)" << std::endl; debug.resume(); info << "setting up model... " << std::flush; debug.suspend(); timer.reset(); const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim; const unsigned int DUNE_UNUSED(dimRange) = 1; typedef GridProviderType::CoordinateType::value_type DomainFieldType; typedef DomainFieldType RangeFieldType; typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType; paramTree.assertSub(ModelType::id(), id); const Dune::shared_ptr< const ModelType > model(new ModelType(paramTree.sub(ModelType::id()))); typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType; const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType()); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); // solver info << "initializing solver"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Multiscale::SemicontinuousGalerkin::DuneDetailedDiscretizations< ModelType, MsGridType, BoundaryInfoType, polOrder > SolverType; paramTree.assertSub(SolverType::id, id); SolverType solver(model, msGrid, boundaryInfo, paramTree.sub(SolverType::id)); solver.init(" ", debug); debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; info << "solving"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); typedef SolverType::VectorBackendType VectorType; Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector(); solver.solve(*solution, paramTree.sub(SolverType::id).sub("solve"), " ", debug); debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; // info << "computing detailed reference solution... " << std::flush; // debug.suspend(); // timer.reset(); // typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations< // ModelType, // typename MsGridType::GlobalGridPartType, // BoundaryInfoType, // polOrder > // ReferenceSolverType; // ReferenceSolverType referenceSolver(model, msGrid->globalGridPart(), boundaryInfo); // referenceSolver.init(); // Dune::shared_ptr< VectorType > referenceSolution = referenceSolver.createVector(); // referenceSolver.solve(*referenceSolution, paramTree.sub(SolverType::id).sub("solve"), " ", debug); // info << "done (took " << timer.elapsed() << " sec)" << std::endl; // debug.resume(); info << "postprocessing"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); solver.visualize(*solution, paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution"), paramTree.sub(SolverType::id).sub("visualize").get("name", "solution"), " ", debug); // referenceSolver.visualize(*referenceSolution, // paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution") + "_reference", // paramTree.sub(SolverType::id).sub("visualize").get("name", "solution") + "_reference", // " ", // debug); debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; info << "computing norms:" << std::endl; Dune::shared_ptr< typename SolverType::DiscreteFunctionType > discreteSolution = solver.createDiscreteFunction(*solution, "discrete_solution"); compute_errors(paramTree.sub(id).sub("exact_solution"), *discreteSolution, info, " "); // if we came that far we can as well be happy about it return 0; } catch(Dune::Exception& e) { std::cerr << "Dune reported error: " << e.what() << std::endl; } catch(std::exception& e) { std::cerr << e.what() << std::endl; } catch( ... ) { std::cerr << "Unknown exception thrown!" << std::endl; } // try } // main <commit_msg>[examples...elliptic.multiscale...] minor id() fix<commit_after>#include "config.h" // system #include <vector> // boost #include <boost/filesystem.hpp> // dune-common #include <dune/common/exceptions.hh> #include <dune/common/mpihelper.hh> #include <dune/common/timer.hh> // dune-grid-multiscale #include <dune/grid/multiscale/provider/cube.hh> // dune-fem #include <dune/fem/misc/mpimanager.hh> #include <dune/fem/misc/gridwidth.hh> // dune-stuff #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/discretefunction/norm.hh> #include <dune/stuff/function/expression.hh> // dune-detailed-solvers #include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh> #ifdef POLORDER const int polOrder = POLORDER; #else const int polOrder = 1; #endif const std::string id = "stationary.linear.elliptic.ms.semicg.ddd"; /** \brief Creates a parameter file if it does not exist. Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary keys and values. \param[in] filename (Relative) path to the file. **/ void ensureParamFile(std::string filename) { // only write param file if there is none if (!boost::filesystem::exists(filename)) { std::ofstream file; file.open(filename); file << "[" << id << "]" << std::endl; file << "exact_solution.order = 2" << std::endl; file << "exact_solution.variable = x" << std::endl; file << "exact_solution.expression.0 = -0.5*x[0]*x[0] + 0.5*x[0]" << std::endl; file << "[grid.multiscale.provider.cube]" << std::endl; file << "level = 4" << std::endl; file << "boundaryId = 7" << std::endl; // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully) file << "partitions.0 = 2" << std::endl; file << "partitions.1 = 2" << std::endl; file << "partitions.2 = 2" << std::endl; file << "filename = " << id << ".msGrid" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl; file << "diffusion.order = 0" << std::endl; file << "diffusion.variable = x" << std::endl; file << "diffusion.expression.0 = 1.0" << std::endl; file << "diffusion.expression.1 = 1.0" << std::endl; file << "diffusion.expression.2 = 1.0" << std::endl; file << "force.order = 0" << std::endl; file << "force.variable = x" << std::endl; file << "force.expression.0 = 1.0" << std::endl; file << "force.expression.1 = 1.0" << std::endl; file << "force.expression.2 = 1.0" << std::endl; file << "dirichlet.order = 0" << std::endl; file << "dirichlet.variable = x" << std::endl; file << "dirichlet.expression.0 = 0.0" << std::endl; file << "dirichlet.expression.1 = 0.0" << std::endl; file << "dirichlet.expression.2 = 0.0" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl; file << "discretization.penaltyFactor = 10.0" << std::endl; file << "solve.type = eigen.bicgstab.incompletelut" << std::endl; file << "solve.maxIter = 5000" << std::endl; file << "solve.precision = 1e-12" << std::endl; file << "visualize.filename = " << id << ".solution" << std::endl; file << "visualize.name = solution" << std::endl; file.close(); } // only write param file if there is none } // void ensureParamFile() template< class MultiscaleDiscreteFunctionType, class OutStreamType > void compute_errors(Dune::ParameterTree& paramTree, const MultiscaleDiscreteFunctionType& discreteFunction, OutStreamType& out, std::string prefix = "") { // exact solution typedef typename MultiscaleDiscreteFunctionType::LocalDiscreteFunctionType DiscreteFunctionType; typedef typename DiscreteFunctionType::RangeFieldType RangeFieldType; typedef typename DiscreteFunctionType::DomainFieldType DomainFieldType; typedef Dune::Stuff::Function::Expression< DomainFieldType, DiscreteFunctionType::dimDomain, RangeFieldType, DiscreteFunctionType::dimRange > FunctionType; const FunctionType function(paramTree); const unsigned int functionOrder = paramTree.get("order", 100); // compute norms out << prefix << " norm | exact solution | discrete solution | error (abs) | error (rel)" << std::endl; out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl; const RangeFieldType L2_reference_norm = Dune::Stuff::DiscreteFunction::Norm::L2(*(discreteFunction.msGrid().globalGridPart()), function, functionOrder); out.precision(2); out << prefix << " L2 | " << std::setw(14) << std::scientific << L2_reference_norm << " | " << std::flush; const RangeFieldType L2_discrete_norm = Dune::Stuff::DiscreteFunction::Norm::L2(discreteFunction); out << std::setw(17) << std::scientific << L2_discrete_norm << " | " << std::flush; const RangeFieldType L2_difference = Dune::Stuff::DiscreteFunction::Norm::L2_difference(function, functionOrder, discreteFunction); out << std::setw(11) << std::scientific << L2_difference << " | " << std::flush; out << std::setw(11) << std::scientific << L2_difference/L2_reference_norm << std::endl; out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl; // const RangeFieldType h1_reference_norm = Dune::Stuff::DiscreteFunction::Norm::h1(referenceSolution); // out.precision(2); // out << prefix << " h1 | " << std::setw(9) << std::scientific << h1_reference_norm << " | " << std::flush; // const RangeFieldType h1_multiscale_norm = Dune::Stuff::DiscreteFunction::Norm::h1(multiscaleSolution); // out << std::setw(10) << std::scientific << h1_multiscale_norm << " | " << std::flush; // const RangeFieldType h1_difference = Dune::Stuff::DiscreteFunction::Norm::h1_difference(referenceSolution, multiscaleSolution); // out << std::setw(11) << std::scientific << h1_difference << " | " << std::flush; // out << std::setw(11) << std::scientific << h1_difference/h1_reference_norm << std::endl; // out << prefix << "------+-----------+------------+-------------+-------------" << std::endl; } // void compute_norms(...) int main(int argc, char** argv) { try { // mpi Dune::MPIManager::initialize(argc, argv); // parameter const std::string filename = id + ".param"; ensureParamFile(filename); Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename); // logger Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO | Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); // Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info(); std::ostream& info = std::cout; Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); // timer Dune::Timer timer; info << "setting up grid: " << std::endl; debug.suspend(); typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType; paramTree.assertSub(GridProviderType::id(), id); const GridProviderType gridProvider(paramTree.sub(GridProviderType::id())); typedef GridProviderType::MsGridType MsGridType; const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGridPtr(); info << " took " << timer.elapsed() << " sec (has " << gridProvider.grid().size(0) << " elements, " << msGrid->size() << " subdomain"; if (msGrid->size() > 1) info << "s"; info << " and a width of " << Dune::GridWidth::calcGridWidth(*(msGrid->globalGridPart())) << ")" << std::endl; debug.resume(); info << "visualizing grid... " << std::flush; timer.reset(); debug.suspend(); msGrid->visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_msGrid")); info << "done (took " << timer.elapsed() << " sek)" << std::endl; debug.resume(); info << "setting up model... " << std::flush; debug.suspend(); timer.reset(); const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim; const unsigned int DUNE_UNUSED(dimRange) = 1; typedef GridProviderType::CoordinateType::value_type DomainFieldType; typedef DomainFieldType RangeFieldType; typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType; paramTree.assertSub(ModelType::id(), id); const Dune::shared_ptr< const ModelType > model(new ModelType(paramTree.sub(ModelType::id()))); typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType; const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType()); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); // solver info << "initializing solver"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); typedef Dune::Detailed::Solvers ::Stationary ::Linear ::Elliptic ::Multiscale ::SemicontinuousGalerkin::DuneDetailedDiscretizations< ModelType, MsGridType, BoundaryInfoType, polOrder > SolverType; paramTree.assertSub(SolverType::id, id); SolverType solver(model, msGrid, boundaryInfo, paramTree.sub(SolverType::id)); solver.init(" ", debug); debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; info << "solving"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); typedef SolverType::VectorBackendType VectorType; Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector(); solver.solve(*solution, paramTree.sub(SolverType::id).sub("solve"), " ", debug); debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; // info << "computing detailed reference solution... " << std::flush; // debug.suspend(); // timer.reset(); // typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations< // ModelType, // typename MsGridType::GlobalGridPartType, // BoundaryInfoType, // polOrder > // ReferenceSolverType; // ReferenceSolverType referenceSolver(model, msGrid->globalGridPart(), boundaryInfo); // referenceSolver.init(); // Dune::shared_ptr< VectorType > referenceSolution = referenceSolver.createVector(); // referenceSolver.solve(*referenceSolution, paramTree.sub(SolverType::id).sub("solve"), " ", debug); // info << "done (took " << timer.elapsed() << " sec)" << std::endl; // debug.resume(); info << "postprocessing"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); solver.visualize(*solution, paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution"), paramTree.sub(SolverType::id).sub("visualize").get("name", "solution"), " ", debug); // referenceSolver.visualize(*referenceSolution, // paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution") + "_reference", // paramTree.sub(SolverType::id).sub("visualize").get("name", "solution") + "_reference", // " ", // debug); debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; info << "computing norms:" << std::endl; Dune::shared_ptr< typename SolverType::DiscreteFunctionType > discreteSolution = solver.createDiscreteFunction(*solution, "discrete_solution"); compute_errors(paramTree.sub(id).sub("exact_solution"), *discreteSolution, info, " "); // if we came that far we can as well be happy about it return 0; } catch(Dune::Exception& e) { std::cerr << "Dune reported error: " << e.what() << std::endl; } catch(std::exception& e) { std::cerr << e.what() << std::endl; } catch( ... ) { std::cerr << "Unknown exception thrown!" << std::endl; } // try } // main <|endoftext|>
<commit_before>#include "stdafx.h" #include "StrategyOFGPara.h" #include "MType.h" /* Global Top-k & bound */ using namespace std; void StrategyOFGPara::topKCoordinate() { // TODO: make it total asynchronous (remove rph.input(...), send if there is a recent local-k change, broadcast if global k-th changes, change INTERVAL_COORDINATE_TOP_K smaller as a buffer timer) //ostringstream oss; //auto tt = holder->getScore(); //oss << logHeadID("GTK-Coord") << tt.size() << " { "; //for(auto& v : tt) // oss << v << " "; //oss << "}"; //cout << oss.str() << endl; if(net->id() != MASTER_ID) { // On workers: send local top-k to master ++st.topkSend; net->send(MASTER_ID, MType::GGatherLocalTopK, holder->getScore()); // the rest calculattion work will be done by master // global top-k will be received later and handled by cbUpdateLowerBound() } else { // On master: initialize current local top-k globalTopKScores.update(holder->getScore(), net->id()); // then wait for workers' GGatherLocalTopK message and // process them with cbLocalTopK() rph.input(MType::GGatherLocalTopK, net->id()); // after received the GGatherLocalTopK messages from all the workers, // finish this process with topKCoordinateFinish } } void StrategyOFGPara::topKCoordinateFinish() { rph.resetTypeCondition(MType::GGatherLocalTopK); if(globalTopKScores.full()) { updateLowerBound(globalTopKScores.lowest(), true, true); // update message will not send to master, so result is not updated updateLBResult(globalBound); } // cout << logHead("LOG") + "Global top-k coordination finished, LB=" // + to_string(globalBound) << endl; } void StrategyOFGPara::topKMerge(const std::vector<double>& recv, const int source) { lock_guard<mutex> lg(mgtk); globalTopKScores.update(recv, source); } // -------------- Lower Bound Maintaince ---------------- void StrategyOFGPara::initLowerBound() { // move lb down half a unit to accept every thing at the beginning //double lb = get<1>(edges.back()) - 0.5 / pgp->size(); updateLowerBound(0.0, false, false); } void StrategyOFGPara::updateLowerBound(double newLB, bool modifyTables, bool fromLocal) { // this epsilon checking is IMPORTANT for those with equal score to the k-th. // because in float numbers: (3.0/100 - 2.0/100) > (2.0/100 - 1.0/100) // this method may loose the bound but does not lose anyone qualified //newLB -= numeric_limits<double>::epsilon(); if(newLB > globalBound) { st.progBound.emplace_back(timer.elapseMS(), newLB); globalBound = newLB; updateLBCandEdge(newLB); if(modifyTables) updateLBWaitingMotifs(newLB); // cout << logHeadID("DBG") + "LB changed to " + to_string(globalBound) // + (fromLocal ? " by local" : " by remote") << endl; if(fromLocal) { lowerBoundSend(); } else { updateLBResult(newLB); } }/* else if(fromLocal) { ostringstream oss; oss.precision(200); oss << logHeadID("XXXX") << "CMP: "<< (newLB > globalBound)<<" Diff: " << newLB - globalBound; cout << oss.str() << endl; }*/ } int StrategyOFGPara::updateLBCandEdge(double newLB) { lock_guard<mutex> lg(mce); auto it = upper_bound(edges.begin(), edges.end(), newLB, [](double th, const tuple<Edge, double, int>& p) { return th > get<1>(p); }); int num = distance(it, edges.end()); edges.erase(it, edges.end()); return num; } int StrategyOFGPara::updateLBResult(double newLB) { lock_guard<mutex> lg(mtk); return holder->updateBound(newLB); } int StrategyOFGPara::updateLBWaitingMotifs(double newLB) { int size = net->size(); int id = net->id(); int count = ltable.updateLowerBound(newLB); for(int i = 0; i < size; ++i) { if(i != id) { rtables[i].updateLowerBound(newLB); } } return count; } void StrategyOFGPara::lowerBoundSend() { ++st.boundSend; net->broadcast(MType::GLowerBound, globalBound); } <commit_msg>support dces-b option for ofg-para strategy<commit_after>#include "stdafx.h" #include "StrategyOFGPara.h" #include "MType.h" /* Global Top-k & bound */ using namespace std; void StrategyOFGPara::topKCoordinate() { // TODO: make it total asynchronous (remove rph.input(...), send if there is a recent local-k change, broadcast if global k-th changes, change INTERVAL_COORDINATE_TOP_K smaller as a buffer timer) //ostringstream oss; //auto tt = holder->getScore(); //oss << logHeadID("GTK-Coord") << tt.size() << " { "; //for(auto& v : tt) // oss << v << " "; //oss << "}"; //cout << oss.str() << endl; if(net->id() != MASTER_ID) { // On workers: send local top-k to master ++st.topkSend; net->send(MASTER_ID, MType::GGatherLocalTopK, holder->getScore()); // the rest calculattion work will be done by master // global top-k will be received later and handled by cbUpdateLowerBound() } else { // On master: initialize current local top-k globalTopKScores.update(holder->getScore(), net->id()); // then wait for workers' GGatherLocalTopK message and // process them with cbLocalTopK() rph.input(MType::GGatherLocalTopK, net->id()); // after received the GGatherLocalTopK messages from all the workers, // finish this process with topKCoordinateFinish } } void StrategyOFGPara::topKCoordinateFinish() { rph.resetTypeCondition(MType::GGatherLocalTopK); if(globalTopKScores.full()) { updateLowerBound(globalTopKScores.lowest(), true, true); // update message will not send to master, so result is not updated updateLBResult(globalBound); } // cout << logHead("LOG") + "Global top-k coordination finished, LB=" // + to_string(globalBound) << endl; } void StrategyOFGPara::topKMerge(const std::vector<double>& recv, const int source) { lock_guard<mutex> lg(mgtk); globalTopKScores.update(recv, source); } // -------------- Lower Bound Maintaince ---------------- void StrategyOFGPara::initLowerBound() { // move lb down half a unit to accept every thing at the beginning //double lb = get<1>(edges.back()) - 0.5 / pgp->size(); updateLowerBound(0.0, false, false); } void StrategyOFGPara::updateLowerBound(double newLB, bool modifyTables, bool fromLocal) { // this epsilon checking is IMPORTANT for those with equal score to the k-th. // because in float numbers: (3.0/100 - 2.0/100) > (2.0/100 - 1.0/100) // this method may loose the bound but does not lose anyone qualified //newLB -= numeric_limits<double>::epsilon(); if(newLB > globalBound) { st.progBound.emplace_back(timer.elapseMS(), newLB); globalBound = newLB; if(flagDCESBound) updateLBCandEdge(newLB); if(modifyTables) updateLBWaitingMotifs(newLB); // cout << logHeadID("DBG") + "LB changed to " + to_string(globalBound) // + (fromLocal ? " by local" : " by remote") << endl; if(fromLocal) { lowerBoundSend(); } else { updateLBResult(newLB); } }/* else if(fromLocal) { ostringstream oss; oss.precision(200); oss << logHeadID("XXXX") << "CMP: "<< (newLB > globalBound)<<" Diff: " << newLB - globalBound; cout << oss.str() << endl; }*/ } int StrategyOFGPara::updateLBCandEdge(double newLB) { lock_guard<mutex> lg(mce); auto it = upper_bound(edges.begin(), edges.end(), newLB, [](double th, const tuple<Edge, double, int>& p) { return th > get<1>(p); }); int num = distance(it, edges.end()); edges.erase(it, edges.end()); return num; } int StrategyOFGPara::updateLBResult(double newLB) { lock_guard<mutex> lg(mtk); return holder->updateBound(newLB); } int StrategyOFGPara::updateLBWaitingMotifs(double newLB) { int size = net->size(); int id = net->id(); int count = ltable.updateLowerBound(newLB); for(int i = 0; i < size; ++i) { if(i != id) { rtables[i].updateLowerBound(newLB); } } return count; } void StrategyOFGPara::lowerBoundSend() { ++st.boundSend; net->broadcast(MType::GLowerBound, globalBound); } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; ll power(ll a, ll n) { if (n == 0) { return 1; } else if (n%2 == 0) { ll x = power(a, n/2); return x * x; } else { return power(a, n-1) * a; } } ll N, A; int main () { cin >> N >> A; ll ub = sqrt(N)+1; ll lb = 2; ll ans = N; for (auto i = 2; i < 1000; ++i) { if (power(2, i) > N) break; while (ub - lb > 1) { ll t = (ub + lb)/2; if (power(t, i) > N) { ub = t; } else { lb = t; } } // cerr << "i = " << i << ", lb = " << lb << endl; for (auto j = 0; j <= i; ++j) { if (power(lb, i-j) * power(lb+1, j) >= N) { ans = min(ans, lb * (i-j) + (lb+1) * j + A * (i-1)); break; } } ub = lb; lb = 2; } cout << ans << endl; } <commit_msg>submit E.cpp to 'E - Cookies' (cf16-final-open) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; ll power(ll a, ll n) { if (n == 0) { return 1; } else if (n%2 == 0) { ll x = power(a, n/2); return x * x; } else { return power(a, n-1) * a; } } ll N, A; int main () { cin >> N >> A; ll ub = sqrt(N)+1; ll lb = 2; ll ans = N; for (auto i = 2; i < 1000; ++i) { if (power(2, i) > N) break; if (i == 2) { while (ub - lb > 1) { ll t = (ub + lb)/2; if (power(t, i) > N) { ub = t; } else { lb = t; } } } else { for (auto j = 1; j < 12000; ++j) { if (power(j, i) < N) { lb = j; } else { break; } } } // cerr << "i = " << i << ", lb = " << lb << endl; for (auto j = 0; j <= i; ++j) { if (power(lb, i-j) * power(lb+1, j) >= N) { ans = min(ans, lb * (i-j) + (lb+1) * j + A * (i-1)); break; } } ub = lb; lb = 2; } cout << ans << endl; } <|endoftext|>
<commit_before>/* JEBBase: generic algorithms and functions * Copyright 2014 Jan Erik Breimo * All rights reserved. * * This file is distributed under the BSD License. * License text is included with the source distribution. */ #ifndef JEBBASE_ALGORITHMS_SORT_HPP #define JEBBASE_ALGORITHMS_SORT_HPP #include <utility> #include "JEBBase/JEBBaseDefinitions.hpp" namespace JEBBase { namespace Algorithms { template <typename T> void sort(T& a, T& b) { if (b < a) std::swap(a, b); } template <typename T> void sort(T& a, T& b, T& c) { sort(a, b); sort(b, c); sort(a, b); } template <typename T> void sort(T& a, T& b, T& c, T& d) { sort(a, c); sort(b, d); sort(a, b); sort(c, d); sort(b, c); } template <typename T> void sort(T (&a)[2]) { sort(a[0], a[1]); } template <typename T> void sort(T (&a)[3]) { sort(a[0], a[1], a[2]); } template <typename T> void sort(T (&a)[4]) { sort(a[0], a[1], a[2], a[3]); } }} #endif <commit_msg>Minor change<commit_after>/* JEBBase: generic algorithms and functions * Copyright 2014 Jan Erik Breimo * All rights reserved. * * This file is distributed under the BSD License. * License text is included with the source distribution. */ #ifndef JEBBASE_ALGORITHMS_SORT_HPP #define JEBBASE_ALGORITHMS_SORT_HPP #include <utility> #include "JEBBase/JEBBaseDefinitions.hpp" namespace JEBBase { namespace Algorithms { template <typename T> void sort(T& a, T& b) { if (b < a) std::swap(a, b); } template <typename T> void sort(T& a, T& b, T& c) { sort(a, b); sort(b, c); sort(a, b); } template <typename T> void sort(T& a, T& b, T& c, T& d) { sort(a, b); sort(c, d); sort(a, c); sort(b, d); sort(b, c); } template <typename T> void sort(T (&a)[2]) { sort(a[0], a[1]); } template <typename T> void sort(T (&a)[3]) { sort(a[0], a[1], a[2]); } template <typename T> void sort(T (&a)[4]) { sort(a[0], a[1], a[2], a[3]); } }} #endif <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #include "../../StroikaPreComp.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #if qPlatform_Windows #include <io.h> #elif qPlatform_POSIX #include <poll.h> #include <unistd.h> #endif #include "../../Debug/AssertExternallySynchronizedLock.h" #include "../../Debug/Trace.h" #include "../../Execution/Common.h" #include "../../Execution/ErrNoException.h" #include "../../Execution/Exceptions.h" #if qPlatform_POSIX #include "ErrNoException.h" #elif qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #endif #include "../../IO/FileAccessException.h" #include "../../Streams/BufferedInputStream.h" #include "FileInputStream.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; using Execution::make_unique_lock; using Streams::InputStream; using Streams::SeekOffsetType; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; #endif // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** **************************** FileSystem::FileInputStream *********************** ******************************************************************************** */ class FileInputStream::Rep_ : public InputStream<Byte>::_IRep, private Debug::AssertExternallySynchronizedLock { public: Rep_ () = delete; Rep_ (const Rep_&) = delete; Rep_ (const String& fileName, SeekableFlag seekable) : fFD_ (-1) , fSeekable_ (seekable) { try { #if qPlatform_Windows errno_t e = ::_wsopen_s (&fFD_, fileName.c_str (), (O_RDONLY | O_BINARY), _SH_DENYNO, 0); if (e != 0) { Execution::errno_ErrorException::Throw (e); } ThrowIfFalseGetLastError (fFD_ != -1); #else Execution::ThrowErrNoIfNegative (fFD_ = ::open (fileName.AsNarrowSDKString ().c_str (), O_RDONLY)); #endif #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"opened fd: %d", fFD_); #endif } Stroika_Foundation_IO_FileAccessException_CATCH_REBIND_FILENAME_ACCCESS_HELPER(fileName, FileAccessMode::eRead); } Rep_ (FileDescriptorType fd, AdoptFDPolicy adoptFDPolicy, SeekableFlag seekable) : fFD_ (fd) , fSeekable_ (seekable) , fAdoptFDPolicy_ (adoptFDPolicy) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"attached fd: %d", fFD_); #endif } ~Rep_ () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::~Rep_"); if (fAdoptFDPolicy_ == AdoptFDPolicy::eCloseOnDestruction) { DbgTrace (L"closing %d", fFD_); } #endif if (fAdoptFDPolicy_ == AdoptFDPolicy::eCloseOnDestruction) { #if qPlatform_Windows ::_close (fFD_); #else ::close (fFD_); #endif } } nonvirtual Rep_& operator= (const Rep_&) = delete; virtual bool IsSeekable () const override { return fSeekable_ == eSeekable; } virtual size_t Read (Byte* intoStart, Byte* intoEnd) override { RequireNotNull (intoStart); RequireNotNull (intoEnd); Require (intoStart < intoEnd); size_t nRequested = intoEnd - intoStart; #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::Read"); DbgTrace (L"(nRequested: %llu)", static_cast<unsigned long long> (nRequested)); #endif lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if qPlatform_Windows return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::_read (fFD_, intoStart, Math::PinToMaxForType<unsigned int> (nRequested)))); #else return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::read (fFD_, intoStart, nRequested))); #endif } virtual Memory::Optional<size_t> ReadSome (ElementType* intoStart, ElementType* intoEnd) override { Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1); #if qPlatform_Windows && 0 int oldFileFlags = ::fcntl (fFD_, F_GETFL, 0); if(fcntl(fFD_, F_SETFL, oldFileFlags | O_NONBLOCK)) ; auto&& cleanup = Execution::Finally ([this] () noexcept { fcntl (fFD_, F_SETFL, oldFileFlags); }); #elif qPlatform_POSIX pollfd pollData { fFD_, POLLIN, 0 }; int pollResult = ThrowErrNoIfNegative (Handle_ErrNoResultInterruption ([&]() { return ::poll (&pollData, 1, 0); })); Assert (pollResult >= 0); if (pollResult == 0) { return {}; // if no data available, return {} } else { // we don't know how much is available, but at least one byte. If not actually reading, just return 1 if (intoStart == nullptr) { return 1; } else { // if there is data available, read as much as you can... return Read (intoStart, intoEnd); } } #endif WeakAssert (false); // @todo - FIX TO REALLY CHECK return {}; } virtual Streams::SeekOffsetType GetReadOffset () const override { lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, 0, SEEK_CUR))); #elif qPlatform_Linux return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, 0, SEEK_CUR))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, 0, SEEK_CUR))); #endif } virtual Streams::SeekOffsetType SeekRead (Streams::Whence whence, Streams::SignedSeekOffsetType offset) override { using namespace Streams; #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::SeekRead"); DbgTrace (L"(whence: %d, offset: %lld)", whence, static_cast<long long> (offset)); #endif lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; switch (whence) { case Whence::eFromStart: { if (offset < 0) { Execution::Throw (std::range_error ("seek")); } #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_SET))); #elif qPlatform_Linux return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_SET))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, offset, SEEK_SET))); #endif } break; case Whence::eFromCurrent: { #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_CUR))); #elif qPlatform_Linux return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_CUR))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, offset, SEEK_CUR))); #endif } break; case Whence::eFromEnd: { #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_END))); #elif qPlatform_Linux return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_END))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, offset, SEEK_END))); #endif } break; } RequireNotReached (); return 0; } private: int fFD_; SeekableFlag fSeekable_; AdoptFDPolicy fAdoptFDPolicy_{ AdoptFDPolicy::eCloseOnDestruction }; }; FileInputStream::FileInputStream (const String& fileName, SeekableFlag seekable) : inherited (make_shared<Rep_> (fileName, seekable)) { } FileInputStream::FileInputStream (FileDescriptorType fd, AdoptFDPolicy adoptFDPolicy, SeekableFlag seekable) : inherited (make_shared<Rep_> (fd, adoptFDPolicy, seekable)) { } InputStream<Byte> FileInputStream::mk (const String& fileName, SeekableFlag seekable, BufferFlag bufferFlag) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::mk"); DbgTrace (L"(fileName: %s, seekable: %d, bufferFlag: %d)", fileName.c_str (), seekable, bufferFlag); #endif InputStream<Byte> in = FileInputStream (fileName, seekable); switch (bufferFlag) { case eBuffered: return Streams::BufferedInputStream<Byte> (in); case eUnbuffered: return in; default: AssertNotReached (); return in; } } InputStream<Byte> FileInputStream::mk (FileDescriptorType fd, AdoptFDPolicy adoptFDPolicy, SeekableFlag seekable, BufferFlag bufferFlag) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::mk"); DbgTrace (L"(fd: %d, seekable: %d, bufferFlag: %d)", fd, seekable, bufferFlag); #endif InputStream<Byte> in = FileInputStream (fd, adoptFDPolicy, seekable); switch (bufferFlag) { case eBuffered: return Streams::BufferedInputStream<Byte> (in); case eUnbuffered: return in; default: AssertNotReached (); return in; } } <commit_msg>fixed problems with poll () usage<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #include "../../StroikaPreComp.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #if qPlatform_Windows #include <io.h> #elif qPlatform_POSIX #include <poll.h> #include <unistd.h> #endif #include "../../Debug/AssertExternallySynchronizedLock.h" #include "../../Debug/Trace.h" #include "../../Execution/Common.h" #include "../../Execution/ErrNoException.h" #include "../../Execution/Exceptions.h" #if qPlatform_POSIX #include "../../Execution/ErrNoException.h" #elif qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #endif #include "../../IO/FileAccessException.h" #include "../../Streams/BufferedInputStream.h" #include "FileInputStream.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; using Execution::make_unique_lock; using Streams::InputStream; using Streams::SeekOffsetType; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; #endif // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** **************************** FileSystem::FileInputStream *********************** ******************************************************************************** */ class FileInputStream::Rep_ : public InputStream<Byte>::_IRep, private Debug::AssertExternallySynchronizedLock { public: Rep_ () = delete; Rep_ (const Rep_&) = delete; Rep_ (const String& fileName, SeekableFlag seekable) : fFD_ (-1) , fSeekable_ (seekable) { try { #if qPlatform_Windows errno_t e = ::_wsopen_s (&fFD_, fileName.c_str (), (O_RDONLY | O_BINARY), _SH_DENYNO, 0); if (e != 0) { Execution::errno_ErrorException::Throw (e); } ThrowIfFalseGetLastError (fFD_ != -1); #else Execution::ThrowErrNoIfNegative (fFD_ = ::open (fileName.AsNarrowSDKString ().c_str (), O_RDONLY)); #endif #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"opened fd: %d", fFD_); #endif } Stroika_Foundation_IO_FileAccessException_CATCH_REBIND_FILENAME_ACCCESS_HELPER(fileName, FileAccessMode::eRead); } Rep_ (FileDescriptorType fd, AdoptFDPolicy adoptFDPolicy, SeekableFlag seekable) : fFD_ (fd) , fSeekable_ (seekable) , fAdoptFDPolicy_ (adoptFDPolicy) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"attached fd: %d", fFD_); #endif } ~Rep_ () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::~Rep_"); if (fAdoptFDPolicy_ == AdoptFDPolicy::eCloseOnDestruction) { DbgTrace (L"closing %d", fFD_); } #endif if (fAdoptFDPolicy_ == AdoptFDPolicy::eCloseOnDestruction) { #if qPlatform_Windows ::_close (fFD_); #else ::close (fFD_); #endif } } nonvirtual Rep_& operator= (const Rep_&) = delete; virtual bool IsSeekable () const override { return fSeekable_ == eSeekable; } virtual size_t Read (Byte* intoStart, Byte* intoEnd) override { RequireNotNull (intoStart); RequireNotNull (intoEnd); Require (intoStart < intoEnd); size_t nRequested = intoEnd - intoStart; #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::Read"); DbgTrace (L"(nRequested: %llu)", static_cast<unsigned long long> (nRequested)); #endif lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if qPlatform_Windows return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::_read (fFD_, intoStart, Math::PinToMaxForType<unsigned int> (nRequested)))); #else return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::read (fFD_, intoStart, nRequested))); #endif } virtual Memory::Optional<size_t> ReadSome (ElementType* intoStart, ElementType* intoEnd) override { Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1); #if qPlatform_Windows && 0 int oldFileFlags = ::fcntl (fFD_, F_GETFL, 0); if(fcntl(fFD_, F_SETFL, oldFileFlags | O_NONBLOCK)) ; auto&& cleanup = Execution::Finally ([this] () noexcept { fcntl (fFD_, F_SETFL, oldFileFlags); }); #elif qPlatform_POSIX pollfd pollData { fFD_, POLLIN, 0 }; int pollResult = Execution::ThrowErrNoIfNegative (Execution::Handle_ErrNoResultInterruption ([&]() { return ::poll (&pollData, 1, 0); })); Assert (pollResult >= 0); if (pollResult == 0) { return {}; // if no data available, return {} } else { // we don't know how much is available, but at least one byte. If not actually reading, just return 1 if (intoStart == nullptr) { return 1; } else { // if there is data available, read as much as you can... return Read (intoStart, intoEnd); } } #endif WeakAssert (false); // @todo - FIX TO REALLY CHECK return {}; } virtual Streams::SeekOffsetType GetReadOffset () const override { lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, 0, SEEK_CUR))); #elif qPlatform_Linux return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, 0, SEEK_CUR))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, 0, SEEK_CUR))); #endif } virtual Streams::SeekOffsetType SeekRead (Streams::Whence whence, Streams::SignedSeekOffsetType offset) override { using namespace Streams; #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::SeekRead"); DbgTrace (L"(whence: %d, offset: %lld)", whence, static_cast<long long> (offset)); #endif lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; switch (whence) { case Whence::eFromStart: { if (offset < 0) { Execution::Throw (std::range_error ("seek")); } #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_SET))); #elif qPlatform_Linux return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_SET))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, offset, SEEK_SET))); #endif } break; case Whence::eFromCurrent: { #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_CUR))); #elif qPlatform_Linux return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_CUR))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, offset, SEEK_CUR))); #endif } break; case Whence::eFromEnd: { #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_END))); #elif qPlatform_Linux return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_END))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, offset, SEEK_END))); #endif } break; } RequireNotReached (); return 0; } private: int fFD_; SeekableFlag fSeekable_; AdoptFDPolicy fAdoptFDPolicy_{ AdoptFDPolicy::eCloseOnDestruction }; }; FileInputStream::FileInputStream (const String& fileName, SeekableFlag seekable) : inherited (make_shared<Rep_> (fileName, seekable)) { } FileInputStream::FileInputStream (FileDescriptorType fd, AdoptFDPolicy adoptFDPolicy, SeekableFlag seekable) : inherited (make_shared<Rep_> (fd, adoptFDPolicy, seekable)) { } InputStream<Byte> FileInputStream::mk (const String& fileName, SeekableFlag seekable, BufferFlag bufferFlag) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::mk"); DbgTrace (L"(fileName: %s, seekable: %d, bufferFlag: %d)", fileName.c_str (), seekable, bufferFlag); #endif InputStream<Byte> in = FileInputStream (fileName, seekable); switch (bufferFlag) { case eBuffered: return Streams::BufferedInputStream<Byte> (in); case eUnbuffered: return in; default: AssertNotReached (); return in; } } InputStream<Byte> FileInputStream::mk (FileDescriptorType fd, AdoptFDPolicy adoptFDPolicy, SeekableFlag seekable, BufferFlag bufferFlag) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::mk"); DbgTrace (L"(fd: %d, seekable: %d, bufferFlag: %d)", fd, seekable, bufferFlag); #endif InputStream<Byte> in = FileInputStream (fd, adoptFDPolicy, seekable); switch (bufferFlag) { case eBuffered: return Streams::BufferedInputStream<Byte> (in); case eUnbuffered: return in; default: AssertNotReached (); return in; } } <|endoftext|>
<commit_before>/*! \file * */ #include "Layer.h" #include "../../TEMLogger.h" extern src::severity_logger< severity_level > glg; Layer::Layer() { BOOST_LOG_SEV(glg, debug) << "Creating a (generic) layer object..."; nextl= NULL; prevl= NULL; isSnow = false; isSoil = false; isRock = false; isMoss = false; isMineral = false; isOrganic = false; isFibric = false; isHumic = false; tkey = I_UNKNOWN; indl = MISSING_I; solind= MISSING_I; age = 0.; dz = MISSING_D; z = MISSING_D; rho= MISSING_D; bulkden= MISSING_D; poro= MISSING_D; tcmin= MISSING_D; tcdry= MISSING_D; tcsolid= MISSING_D; tcsatfrz= MISSING_D; tcsatunf= MISSING_D; vhcsolid= MISSING_D; albdryvis= MISSING_D; albdrynir= MISSING_D; albsatvis= MISSING_D; albsatnir= MISSING_D; maxliq = MISSING_D; maxice = MISSING_D; psisat= MISSING_D; hksat = MISSING_D; bsw = MISSING_D; // thermal status frozen = MISSING_I; frozenfrac= MISSING_D; tem = MISSING_D; tcond= MISSING_D; pce_t= MISSING_D; pce_f= MISSING_D; // hydrological status liq = MISSING_D; ice = MISSING_D; hcond= MISSING_D; // soil carbon pool rawc = MISSING_D; soma = MISSING_D; sompr= MISSING_D; somcr= MISSING_D; cfrac= MISSING_D; }; Layer::~Layer() { BOOST_LOG_SEV(glg, debug) << "Deleting a (generic) layer object..."; }; void Layer::advanceOneDay() { age+=1/365.; }; double Layer::getHeatCapacity() { // volumetric heat capacity double hcap = MISSING_D; if(isSoil) { if(frozen==-1) { hcap = getUnfVolHeatCapa(); } else if(frozen ==1) { hcap = getFrzVolHeatCapa(); } else if(frozen ==0) { hcap = getMixVolHeatCapa(); } } else if(isSnow) { hcap = getFrzVolHeatCapa(); } else if(isRock) { hcap = getFrzVolHeatCapa(); } return hcap; }; double Layer::getThermalConductivity() { double tc = MISSING_D; if(isSoil || isSnow) { if(frozen==1) { tc = getFrzThermCond(); } else { tc = getUnfThermCond(); } } else if (isRock) { tc = getFrzThermCond(); } return tc; }; double Layer::getVolWater() { double vice = getVolIce(); double vliq = getVolLiq(); return fmin((double)poro,(double)vice+vliq); }; double Layer::getEffVolWater() { double effvol = 0.; if(isSoil) { effvol = getVolWater() - minliq/DENLIQ/dz; } else if (isSnow) { effvol = getVolWater(); } if(effvol<0) { effvol =0.; } return effvol; }; double Layer::getVolIce() { if (dz != 0) { double vice = ice/DENICE/dz; // FIX THIS: divide by zero error when there is no thickness! vice = fmin((double)vice, (double)poro); return vice; } else { return 0; } }; double Layer::getVolLiq() { if (dz != 0) { double vliq = liq/DENLIQ/dz; // FIX THIS: divide by zero error when there is no thickness! vliq = fmin((double)vliq,(double)poro); return vliq; } else { return 0; } }; double Layer::getEffVolLiq() { if (dz != 0) { double evliq = (liq-minliq)/DENLIQ/dz; // FIX THIS: divide by zero error when there is no thickness! evliq = fmin((double)evliq,(double)poro); return evliq; } else { return 0; } }; <commit_msg>Fix issue with reported 'tcond'.<commit_after>/*! \file * */ #include "Layer.h" #include "../../TEMLogger.h" extern src::severity_logger< severity_level > glg; Layer::Layer() { BOOST_LOG_SEV(glg, debug) << "Creating a (generic) layer object..."; nextl= NULL; prevl= NULL; isSnow = false; isSoil = false; isRock = false; isMoss = false; isMineral = false; isOrganic = false; isFibric = false; isHumic = false; tkey = I_UNKNOWN; indl = MISSING_I; solind= MISSING_I; age = 0.; dz = MISSING_D; z = MISSING_D; rho= MISSING_D; bulkden= MISSING_D; poro= MISSING_D; tcmin= MISSING_D; tcdry= MISSING_D; tcsolid= MISSING_D; tcsatfrz= MISSING_D; tcsatunf= MISSING_D; vhcsolid= MISSING_D; albdryvis= MISSING_D; albdrynir= MISSING_D; albsatvis= MISSING_D; albsatnir= MISSING_D; maxliq = MISSING_D; maxice = MISSING_D; psisat= MISSING_D; hksat = MISSING_D; bsw = MISSING_D; // thermal status frozen = MISSING_I; frozenfrac= MISSING_D; tem = MISSING_D; tcond= MISSING_D; pce_t= MISSING_D; pce_f= MISSING_D; // hydrological status liq = MISSING_D; ice = MISSING_D; hcond= MISSING_D; // soil carbon pool rawc = MISSING_D; soma = MISSING_D; sompr= MISSING_D; somcr= MISSING_D; cfrac= MISSING_D; }; Layer::~Layer() { BOOST_LOG_SEV(glg, debug) << "Deleting a (generic) layer object..."; }; void Layer::advanceOneDay() { age+=1/365.; }; double Layer::getHeatCapacity() { // volumetric heat capacity double hcap = MISSING_D; if(isSoil) { if(frozen==-1) { hcap = getUnfVolHeatCapa(); } else if(frozen ==1) { hcap = getFrzVolHeatCapa(); } else if(frozen ==0) { hcap = getMixVolHeatCapa(); } } else if(isSnow) { hcap = getFrzVolHeatCapa(); } else if(isRock) { hcap = getFrzVolHeatCapa(); } return hcap; }; double Layer::getThermalConductivity() { double tc = MISSING_D; if(isSoil || isSnow) { if(frozen==1) { tc = getFrzThermCond(); } else { tc = getUnfThermCond(); } } else if (isRock) { tc = getFrzThermCond(); } this->tcond = tc; return tc; }; double Layer::getVolWater() { double vice = getVolIce(); double vliq = getVolLiq(); return fmin((double)poro,(double)vice+vliq); }; double Layer::getEffVolWater() { double effvol = 0.; if(isSoil) { effvol = getVolWater() - minliq/DENLIQ/dz; } else if (isSnow) { effvol = getVolWater(); } if(effvol<0) { effvol =0.; } return effvol; }; double Layer::getVolIce() { if (dz != 0) { double vice = ice/DENICE/dz; // FIX THIS: divide by zero error when there is no thickness! vice = fmin((double)vice, (double)poro); return vice; } else { return 0; } }; double Layer::getVolLiq() { if (dz != 0) { double vliq = liq/DENLIQ/dz; // FIX THIS: divide by zero error when there is no thickness! vliq = fmin((double)vliq,(double)poro); return vliq; } else { return 0; } }; double Layer::getEffVolLiq() { if (dz != 0) { double evliq = (liq-minliq)/DENLIQ/dz; // FIX THIS: divide by zero error when there is no thickness! evliq = fmin((double)evliq,(double)poro); return evliq; } else { return 0; } }; <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <fstream> #include <graphene/chain/protocol/block.hpp> namespace graphene { namespace chain { class index_entry; class block_database { public: void open( const fc::path& dbdir ); bool is_open()const; void flush(); void close(); void store( const block_id_type& id, const signed_block& b ); void remove( const block_id_type& id ); bool contains( const block_id_type& id )const; block_id_type fetch_block_id( uint32_t block_num )const; optional<signed_block> fetch_optional( const block_id_type& id )const; optional<signed_block> fetch_by_number( uint32_t block_num )const; optional<signed_block> last()const; optional<block_id_type> last_id()const; private: optional<index_entry> last_index_entry()const; fc::path _index_filename; mutable std::fstream _blocks; mutable std::fstream _block_num_to_pos; }; } } <commit_msg>fix warning: 'index_entry' defined as a struct here but previously declared as a class<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <fstream> #include <graphene/chain/protocol/block.hpp> namespace graphene { namespace chain { struct index_entry; class block_database { public: void open( const fc::path& dbdir ); bool is_open()const; void flush(); void close(); void store( const block_id_type& id, const signed_block& b ); void remove( const block_id_type& id ); bool contains( const block_id_type& id )const; block_id_type fetch_block_id( uint32_t block_num )const; optional<signed_block> fetch_optional( const block_id_type& id )const; optional<signed_block> fetch_by_number( uint32_t block_num )const; optional<signed_block> last()const; optional<block_id_type> last_id()const; private: optional<index_entry> last_index_entry()const; fc::path _index_filename; mutable std::fstream _blocks; mutable std::fstream _block_num_to_pos; }; } } <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit 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 "FramePointerValidator.h" #include <capstone/capstone.h> #include "FunctionFramePointerValidator.h" #include "OrbitBase/Logging.h" std::optional<std::vector<std::shared_ptr<Function>>> FramePointerValidator::GetFpoFunctions( const std::vector<std::shared_ptr<Function>>& functions, const std::string& file_name, bool is_64_bit) { std::vector<std::shared_ptr<Function>> result; cs_mode mode = is_64_bit ? CS_MODE_64 : CS_MODE_32; csh handle; if (cs_open(CS_ARCH_X86, mode, &handle) != CS_ERR_OK) { ERROR("Unable to open capstone."); return {}; } cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON); std::ifstream instream(file_name, std::ios::in | std::ios::binary); std::vector<uint8_t> binary((std::istreambuf_iterator<char>(instream)), std::istreambuf_iterator<char>()); for (const auto& function : functions) { uint64_t function_size = function->Size(); if (function_size == 0) { continue; } FunctionFramePointerValidator validator{ handle, binary.data() + function->Offset(), function_size}; if (!validator.Validate()) { result.push_back(function); } } return result; }<commit_msg>Fixed memory leak in FramePointerValidator<commit_after>// Copyright (c) 2020 The Orbit 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 "FramePointerValidator.h" #include <capstone/capstone.h> #include "FunctionFramePointerValidator.h" #include "OrbitBase/Logging.h" #include "OrbitBase/UniqueResource.h" std::optional<std::vector<std::shared_ptr<Function>>> FramePointerValidator::GetFpoFunctions( const std::vector<std::shared_ptr<Function>>& functions, const std::string& file_name, bool is_64_bit) { std::vector<std::shared_ptr<Function>> result; cs_mode mode = is_64_bit ? CS_MODE_64 : CS_MODE_32; csh temp_handle; if (cs_open(CS_ARCH_X86, mode, &temp_handle) != CS_ERR_OK) { ERROR("Unable to open capstone."); return {}; } OrbitBase::unique_resource handle{std::move(temp_handle), [](csh handle) { cs_close(&handle); }}; cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON); std::ifstream instream(file_name, std::ios::in | std::ios::binary); std::vector<uint8_t> binary((std::istreambuf_iterator<char>(instream)), std::istreambuf_iterator<char>()); for (const auto& function : functions) { uint64_t function_size = function->Size(); if (function_size == 0) { continue; } FunctionFramePointerValidator validator{ handle, binary.data() + function->Offset(), function_size}; if (!validator.Validate()) { result.push_back(function); } } return result; }<|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP #define STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP #include <boost/utility/enable_if.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/dot_product.hpp> #include <stan/math/prim/mat/fun/dot_self.hpp> #include <stan/math/prim/mat/meta/length.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/meta/is_constant.hpp> #include <stan/math/prim/scal/meta/is_vector_like.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <vector> namespace stan { namespace math { /** * Returns a dot product covariance matrix. A member of Stan's Gaussian Process * Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x type of std::vector of elements * @tparam T_sigma type of sigma * * @param x std::vector of elements that can be used in dot product. * This function assumes each element of x is the same size. * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is positive semi-definite * @throw std::domain_error if sigma < 0, nan, inf or * x is nan or infinite */ template <typename T_x, typename T_sigma> Eigen::Matrix<typename return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<Eigen::Matrix<T_x, Eigen::Dynamic, 1>> &x, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) { check_not_nan("gp_dot_prod_cov", "x", x[i]); check_finite("gp_dot_prod_cov", "x", x[i]); } Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < (x_size - 1); ++i) { cov(i, i) = sigma_sq + dot_self(x[i]); for (size_t j = i + 1; j < x_size; ++j) { cov(i, j) = sigma_sq + dot_product(x[i], x[j]); cov(j, i) = cov(i, j); } } cov(x_size - 1, x_size - 1) = sigma_sq + dot_self(x[x_size - 1]); return cov; } /** * Returns a dot product covariance matrix. A member of Stan's Gaussian * Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x type of std::vector of double * @tparam T_sigma type of sigma * * @param x std::vector of elements that can be used in transpose * and multiply * This function assumes each element of x is the same size. * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is positive semi-definite * @throw std::domain_error if sigma < 0, nan, inf or * x is nan or infinite */ template <typename T_x, typename T_sigma> Eigen::Matrix<typename return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<T_x> &x, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x_size = x.size(); check_not_nan("gp_dot_prod_cov", "x", x); check_finite("gp_dot_prod_cov", "x", x); Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < (x_size - 1); ++i) { cov(i, i) = sigma_sq + x[i] * x[i]; for (size_t j = i + 1; j < x_size; ++j) { cov(i, j) = sigma_sq + x[i] * x[j]; cov(j, i) = cov(i, j); } } cov(x_size - 1, x_size - 1) = sigma_sq + x[x_size - 1] * x[x_size - 1]; return cov; } /** * Returns a dot product covariance matrix of differing * x's. A member of Stan's Gaussian Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x1 type of first std::vector of elements * @tparam T_x2 type of second std::vector of elements * @tparam T_sigma type of sigma * * @param x1 std::vector of elements that can be used in dot_product * @param x2 std::vector of elements that can be used in dot_product * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is not always symmetric * @throw std::domain_error if sigma < 0, nan or inf * or if x1 or x2 are nan or inf */ template <typename T_x1, typename T_x2, typename T_sigma> Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<Eigen::Matrix<T_x1, Eigen::Dynamic, 1>> &x1, const std::vector<Eigen::Matrix<T_x2, Eigen::Dynamic, 1>> &x2, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x1_size = x1.size(); size_t x2_size = x2.size(); for (size_t i = 0; i < x1_size; ++i) { check_not_nan("gp_dot_prod_cov", "x1", x1[i]); check_finite("gp_dot_prod_cov", "x1", x1[i]); } for (size_t i = 0; i < x2_size; ++i) { check_not_nan("gp_dot_prod_cov", "x2", x2[i]); check_finite("gp_dot_prod_cov", "x2", x2[i]); } Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq + dot_product(x1[i], x2[j]); } } return cov; } /** * Returns a dot product covariance matrix of * differing x's. A member of Stan's Gaussian Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x1 type of first std::vector of double * @tparam T_x2 type of second std::vector of double * @tparam T_sigma type of sigma * * @param x1 std::vector of elements that can be used in dot_product * @param x2 std::vector of elements that can be used in dot_product * @param sigma is the constant function that can be used in stan::math::square * @return dot product covariance matrix that is not always symmetric * @throw std::domain_error if sigma < 0, nan or inf * or if x1 or x2 are nan or inf */ template <typename T_x1, typename T_x2, typename T_sigma> Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2, const T_sigma &sigma) { using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x1_size = x1.size(); size_t x2_size = x2.size(); check_not_nan("gp_dot_prod_cov", "x1", x1); check_finite("gp_dot_prod_cov", "x1", x1); check_not_nan("gp_dot_prod_cov", "x2", x2); check_finite("gp_dot_prod_cov", "x2", x2); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq + x1[i] * x2[j]; } } return cov; } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.2-svn328729-1~exp1~20180509124008.99 (branches/release_50)<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP #define STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP #include <boost/utility/enable_if.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/dot_product.hpp> #include <stan/math/prim/mat/fun/dot_self.hpp> #include <stan/math/prim/mat/meta/length.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/meta/is_constant.hpp> #include <stan/math/prim/scal/meta/is_vector_like.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <vector> namespace stan { namespace math { /** * Returns a dot product covariance matrix. A member of Stan's Gaussian Process * Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x type of std::vector of elements * @tparam T_sigma type of sigma * * @param x std::vector of elements that can be used in dot product. * This function assumes each element of x is the same size. * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is positive semi-definite * @throw std::domain_error if sigma < 0, nan, inf or * x is nan or infinite */ template <typename T_x, typename T_sigma> Eigen::Matrix<typename return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<Eigen::Matrix<T_x, Eigen::Dynamic, 1>> &x, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) { check_not_nan("gp_dot_prod_cov", "x", x[i]); check_finite("gp_dot_prod_cov", "x", x[i]); } Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < (x_size - 1); ++i) { cov(i, i) = sigma_sq + dot_self(x[i]); for (size_t j = i + 1; j < x_size; ++j) { cov(i, j) = sigma_sq + dot_product(x[i], x[j]); cov(j, i) = cov(i, j); } } cov(x_size - 1, x_size - 1) = sigma_sq + dot_self(x[x_size - 1]); return cov; } /** * Returns a dot product covariance matrix. A member of Stan's Gaussian * Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x type of std::vector of double * @tparam T_sigma type of sigma * * @param x std::vector of elements that can be used in transpose * and multiply * This function assumes each element of x is the same size. * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is positive semi-definite * @throw std::domain_error if sigma < 0, nan, inf or * x is nan or infinite */ template <typename T_x, typename T_sigma> Eigen::Matrix<typename return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<T_x> &x, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x_size = x.size(); check_not_nan("gp_dot_prod_cov", "x", x); check_finite("gp_dot_prod_cov", "x", x); Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < (x_size - 1); ++i) { cov(i, i) = sigma_sq + x[i] * x[i]; for (size_t j = i + 1; j < x_size; ++j) { cov(i, j) = sigma_sq + x[i] * x[j]; cov(j, i) = cov(i, j); } } cov(x_size - 1, x_size - 1) = sigma_sq + x[x_size - 1] * x[x_size - 1]; return cov; } /** * Returns a dot product covariance matrix of differing * x's. A member of Stan's Gaussian Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x1 type of first std::vector of elements * @tparam T_x2 type of second std::vector of elements * @tparam T_sigma type of sigma * * @param x1 std::vector of elements that can be used in dot_product * @param x2 std::vector of elements that can be used in dot_product * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is not always symmetric * @throw std::domain_error if sigma < 0, nan or inf * or if x1 or x2 are nan or inf */ template <typename T_x1, typename T_x2, typename T_sigma> Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<Eigen::Matrix<T_x1, Eigen::Dynamic, 1>> &x1, const std::vector<Eigen::Matrix<T_x2, Eigen::Dynamic, 1>> &x2, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x1_size = x1.size(); size_t x2_size = x2.size(); for (size_t i = 0; i < x1_size; ++i) { check_not_nan("gp_dot_prod_cov", "x1", x1[i]); check_finite("gp_dot_prod_cov", "x1", x1[i]); } for (size_t i = 0; i < x2_size; ++i) { check_not_nan("gp_dot_prod_cov", "x2", x2[i]); check_finite("gp_dot_prod_cov", "x2", x2[i]); } Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq + dot_product(x1[i], x2[j]); } } return cov; } /** * Returns a dot product covariance matrix of * differing x's. A member of Stan's Gaussian Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x1 type of first std::vector of double * @tparam T_x2 type of second std::vector of double * @tparam T_sigma type of sigma * * @param x1 std::vector of elements that can be used in dot_product * @param x2 std::vector of elements that can be used in dot_product * @param sigma is the constant function that can be used in stan::math::square * @return dot product covariance matrix that is not always symmetric * @throw std::domain_error if sigma < 0, nan or inf * or if x1 or x2 are nan or inf */ template <typename T_x1, typename T_x2, typename T_sigma> Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2, const T_sigma &sigma) { using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x1_size = x1.size(); size_t x2_size = x2.size(); check_not_nan("gp_dot_prod_cov", "x1", x1); check_finite("gp_dot_prod_cov", "x1", x1); check_not_nan("gp_dot_prod_cov", "x2", x2); check_finite("gp_dot_prod_cov", "x2", x2); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq + x1[i] * x2[j]; } } return cov; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>void runGlauberMCpPb(Int_t option=0,Int_t N=250000) { //load libraries gSystem->Load("libVMC"); gSystem->Load("libPhysics"); gSystem->Load("libTree"); gSystem->Load("libPWGGlauber"); //set the random seed from current time TTimeStamp time; Int_t seed = time.GetSec(); gRandom->SetSeed(seed); Int_t nevents = N; // number of events to simulate // supported systems are e.g. "p", "d", "Si", "Au", "Pb", "U" Option_t *sysA="p"; Option_t *sysB="Pb"; Double_t signn=70; // inelastic nucleon nucleon cross section //const char *fname="GlauberMC_PbPb_ntuple.root"; // name output file // run the code to produce an ntuple: // AliGlauberMC::runAndSaveNucleons(10000,"Pb","Pb",72); Double_t mind=0.4; // AliGlauberMC::RunAndSaveNtuple(nevents,sysA,sysB,signn,mind); Double_t r=6.62; Double_t a=0.546; const char *fname="glau_ppb_ntuple.root"; AliGlauberMC mcg(sysA,sysB,signn); mcg.SetMinDistance(mind); mcg.Setr(r); mcg.Seta(a); if (option==1) mcg.SetDoFluc(0.55,78.5,0.82,kTRUE); else if (option==2) mcg.SetDoFluc(1.01,72.5,0.74,kTRUE); mcg.SetDoPartProduction(kFALSE); ////////////////// mcg.SetdNdEtaType(AliGlauberMC::kNBDSV); mcg.GetdNdEtaParam()[0] = 2.49; //npp mcg.GetdNdEtaParam()[1] = 1.7; //ratioSgm2Mu mcg.GetdNdEtaParam()[2] = 0.13; //xhard ////////////////// mcg.Run(nevents); TNtuple *nt = mcg.GetNtuple(); TFile out(fname,"recreate",fname,9); if(nt) nt->Write(); printf("total cross section with a nucleon-nucleon cross section %.4f is %.4f\n\n",signn,mcg.GetTotXSect()); out.Close(); } <commit_msg>added qparts<commit_after>void runGlauberMCpPb(Int_t option=0,Int_t N=250000,Bool_t qparts=kFALSE) { //load libraries gSystem->Load("libVMC"); gSystem->Load("libPhysics"); gSystem->Load("libTree"); gSystem->Load("libPWGGlauber"); //set the random seed from current time TTimeStamp time; Int_t seed = time.GetSec(); gRandom->SetSeed(seed); Int_t nevents = N; // number of events to simulate // supported systems are e.g. "p", "d", "Si", "Au", "Pb", "U" Option_t *sysA="p"; Option_t *sysB="Pb"; Double_t signn=70; // inelastic nucleon nucleon cross section Double_t mind=0.4; const char *fname="glau_ppb_ntuple.root"; if (qparts) { signn/=9; mind=0; } AliGlauberMC mcg(sysA,sysB,signn); mcg.SetMinDistance(mind); if (qparts) { AliGlauberNucleus &na = mcg.GetNucA(); na.SetN(3*na.GetN()); AliGlauberNucleus &nb = mcg.GetNucB(); nb.SetN(3*nb.GetN()); } if (option==1) mcg.SetDoFluc(0.55,78.5,0.82,kTRUE); else if (option==2) mcg.SetDoFluc(1.01,72.5,0.74,kTRUE); mcg.SetDoPartProduction(kFALSE); ////////////////// mcg.SetdNdEtaType(AliGlauberMC::kNBDSV); mcg.GetdNdEtaParam()[0] = 2.49; //npp mcg.GetdNdEtaParam()[1] = 1.7; //ratioSgm2Mu mcg.GetdNdEtaParam()[2] = 0.13; //xhard ////////////////// mcg.Run(nevents); TNtuple *nt = mcg.GetNtuple(); TFile out(fname,"recreate",fname,9); if(nt) nt->Write(); printf("total cross section with a nucleon-nucleon cross section %.4f is %.4f\n\n",signn,mcg.GetTotXSect()); out.Close(); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <string> #include "Options.hpp" #include "Compiler.hpp" #include "Utils.hpp" #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Eddic Tests #include <boost/test/unit_test.hpp> void assertCompiles(const std::string& file){ eddic::parseOptions(0, {}); eddic::Compiler compiler; int code = compiler.compileOnly(file); BOOST_CHECK_EQUAL (code, 0); } void assertOutputEquals(const std::string& file, const std::string& output){ assertCompiles("test/cases/" + file); std::string out = eddic::execCommand("./a.out"); BOOST_CHECK_EQUAL (output, out); } /* Compiles all the samples */ BOOST_AUTO_TEST_CASE( samples_arrays ){ assertCompiles("samples/arrays.eddi"); } BOOST_AUTO_TEST_CASE( samples_asm ){ assertCompiles("samples/asm.eddi"); } BOOST_AUTO_TEST_CASE( samples_assembly ){ assertCompiles("samples/assembly.eddi"); } BOOST_AUTO_TEST_CASE( samples_const ){ assertCompiles("samples/const.eddi"); } BOOST_AUTO_TEST_CASE( samples_concat ){ assertCompiles("samples/concat.eddi"); } BOOST_AUTO_TEST_CASE( samples_functions ){ assertCompiles("samples/functions.eddi"); } BOOST_AUTO_TEST_CASE( samples_includes ){ assertCompiles("samples/includes.eddi"); } BOOST_AUTO_TEST_CASE( samples_optimize ){ assertCompiles("samples/optimize.eddi"); } BOOST_AUTO_TEST_CASE( samples_problem ){ assertCompiles("samples/problem.eddi"); } /* Specific tests */ BOOST_AUTO_TEST_CASE( if_ ){ assertOutputEquals("if.eddi", "Cool"); } BOOST_AUTO_TEST_CASE( while_ ){ assertOutputEquals("while.eddi", "01234"); } BOOST_AUTO_TEST_CASE( for_ ){ assertOutputEquals("for.eddi", "01234"); } BOOST_AUTO_TEST_CASE( foreach_ ){ assertOutputEquals("foreach.eddi", "012345"); } BOOST_AUTO_TEST_CASE( globals_ ){ assertOutputEquals("globals.eddi", "1000a2000aa"); } BOOST_AUTO_TEST_CASE( void_functions ){ assertOutputEquals("void.eddi", "4445"); } BOOST_AUTO_TEST_CASE( string_functions ){ assertOutputEquals("return_string.eddi", "abcdef"); } BOOST_AUTO_TEST_CASE( int_functions ){ assertOutputEquals("return_int.eddi", "484"); } BOOST_AUTO_TEST_CASE( recursive_functions ){ assertOutputEquals("recursive.eddi", "362880"); } <commit_msg>Add the new sample to the integration tests<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <string> #include "Options.hpp" #include "Compiler.hpp" #include "Utils.hpp" #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Eddic Tests #include <boost/test/unit_test.hpp> void assertCompiles(const std::string& file){ eddic::parseOptions(0, {}); eddic::Compiler compiler; int code = compiler.compileOnly(file); BOOST_CHECK_EQUAL (code, 0); } void assertOutputEquals(const std::string& file, const std::string& output){ assertCompiles("test/cases/" + file); std::string out = eddic::execCommand("./a.out"); BOOST_CHECK_EQUAL (output, out); } /* Compiles all the samples */ BOOST_AUTO_TEST_CASE( samples_arrays ){ assertCompiles("samples/arrays.eddi"); } BOOST_AUTO_TEST_CASE( samples_asm ){ assertCompiles("samples/asm.eddi"); } BOOST_AUTO_TEST_CASE( samples_assembly ){ assertCompiles("samples/assembly.eddi"); } BOOST_AUTO_TEST_CASE( samples_const ){ assertCompiles("samples/const.eddi"); } BOOST_AUTO_TEST_CASE( samples_concat ){ assertCompiles("samples/concat.eddi"); } BOOST_AUTO_TEST_CASE( samples_functions ){ assertCompiles("samples/functions.eddi"); } BOOST_AUTO_TEST_CASE( samples_includes ){ assertCompiles("samples/includes.eddi"); } BOOST_AUTO_TEST_CASE( samples_optimize ){ assertCompiles("samples/optimize.eddi"); } BOOST_AUTO_TEST_CASE( samples_problem ){ assertCompiles("samples/problem.eddi"); } BOOST_AUTO_TEST_CASE( samples_sort ){ assertCompiles("samples/sort.eddi"); } /* Specific tests */ BOOST_AUTO_TEST_CASE( if_ ){ assertOutputEquals("if.eddi", "Cool"); } BOOST_AUTO_TEST_CASE( while_ ){ assertOutputEquals("while.eddi", "01234"); } BOOST_AUTO_TEST_CASE( for_ ){ assertOutputEquals("for.eddi", "01234"); } BOOST_AUTO_TEST_CASE( foreach_ ){ assertOutputEquals("foreach.eddi", "012345"); } BOOST_AUTO_TEST_CASE( globals_ ){ assertOutputEquals("globals.eddi", "1000a2000aa"); } BOOST_AUTO_TEST_CASE( void_functions ){ assertOutputEquals("void.eddi", "4445"); } BOOST_AUTO_TEST_CASE( string_functions ){ assertOutputEquals("return_string.eddi", "abcdef"); } BOOST_AUTO_TEST_CASE( int_functions ){ assertOutputEquals("return_int.eddi", "484"); } BOOST_AUTO_TEST_CASE( recursive_functions ){ assertOutputEquals("recursive.eddi", "362880"); } <|endoftext|>
<commit_before>/** * This is the macro to include the Forward multiplicity in a train. * * @ingroup pwg2_forward_analysis_scripts */ AliAnalysisTask* AddTaskFMD(Int_t nCutBins=1, Float_t correctionCut=0.1) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskFMD", "No analysis manager to connect to."); return NULL; } AliForwardMultiplicity* task = new AliForwardMultiplicity("FMD"); task->GetHistCollector().SetNCutBins(nCutBins); task->GetHistCollector().SetCorrectionCut(correctionCut); task->SetLowFluxCut(1000); mgr->AddTask(task); AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance(); AliMCEventHandler* mcHandler = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler()); Info("AddTaskFMD", "MC handler %p", mcHandler); if(mcHandler) { pars->SetRealData(kFALSE); pars->SetProcessPrimary(kTRUE); pars->SetProcessHits(kFALSE); } else { pars->SetRealData(kTRUE); pars->SetProcessPrimary(kFALSE); pars->SetProcessHits(kFALSE); } pars->Init(); TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += Form(":%s",pars->GetDndetaAnalysisName()); AliAnalysisDataContainer* histOut = mgr->CreateContainer("Forward", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, histOut); return task; } <commit_msg>Show examples of all parameters that can be tuned More documentation.<commit_after>/** * This is the macro to include the Forward multiplicity in a train. * * @ingroup pwg2_forward_analysis_scripts */ AliAnalysisTask* AddTaskFMD(Int_t nCutBins=1, Float_t correctionCut=0.1) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskFMD", "No analysis manager to connect to."); return NULL; } // --- Make the task and add it to the manager --------------------- AliForwardMultiplicity* task = new AliForwardMultiplicity("FMD"); mgr->AddTask(task); // --- Set parameters on the algorithms ---------------------------- // Set the number of SPD tracklets for which we consider the event a // low flux event task->GetEventInspector().SetLowFluxCut(1000); // Set the maximum error on v_z [cm] task->GetEventInspector().SetMaxVzErr(0.2); // Set the eta axis to use - note, this overrides whatever is used // by the rest of the algorithms - but only for the energy fitter // algorithm. task->GetEnergyFitter().SetEtaAxis(200, -4, 6); // Set the low cut used for energy task->GetEnergyFitter().SetLowCut(0.4); // Set the number of bins to subtract from maximum of distributions // to get the lower bound of the fit range task->GetEnergyFitter().SetBinsToSubtract(4); // Set the maximum number of landaus to try to fit (max 5) task->GetEnergyFitter().SetNLandau(5); // Set the minimum number of entries in the distribution before // trying to fit to the data task->GetEnergyFitter().SetMinEntries(1000); // Set maximum energy loss to consider task->GetEnergyFitter().SetMaxE(10); // Set number of energy loss bins task->GetEnergyFitter().SetNEbins(300); // Set whether to use increasing bin sizes task->GetEnergyFitter().SetUseIncreasingBins(true); // Set the low cut used for sharing task->GetSharingFilter().SetLowCut(0.3); // Set the number of extra bins (beyond the secondary map border) task->GetHistCollector().SetNCutBins(nCutBins); // Set the correction cut, that is, when bins in the secondary map // is smaller than this, they are considered empty task->GetHistCollector().SetCorrectionCut(correctionCut); // Set the overall debug level (1: some output, 3: a lot of output) task->SetDebug(0); // Set the debug level of a single algorithm task->GetEnergyFitter().SetDebug(3); // --- Set up the parameer manager --------------------------------- AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance(); AliMCEventHandler* mcHandler = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler()); Info("AddTaskFMD", "MC handler %p", mcHandler); if(mcHandler) { pars->SetRealData(kFALSE); pars->SetProcessPrimary(kTRUE); pars->SetProcessHits(kFALSE); } else { pars->SetRealData(kTRUE); pars->SetProcessPrimary(kFALSE); pars->SetProcessHits(kFALSE); } pars->Init(); // --- Makek the output container and connect it ------------------- TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += Form(":%s",pars->GetDndetaAnalysisName()); AliAnalysisDataContainer* histOut = mgr->CreateContainer("Forward", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, histOut); return task; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP #define STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/rev/mat/fun/dot_product.hpp> #include <vector> namespace stan { namespace math { /** * Returns a dot product covariance matrix. A member of Stan's Gaussian Process * Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x type of std::vector of elements * @tparam T_sigma type of sigma * * @param x std::vector of elements that can be used in dot product. * This function assumes each element of x is the same size. * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is positive semi-definite * @throw std::domain_error if sigma < 0, nan, inf or * x is nan or infinite */ template <typename T_x, typename T_sigma> inline typename Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<T_x> &x, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) check_not_nan("gp_dot_prod_cov", "x", x[i]); check_finite("gp_dot_prod_cov", "x", x); Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < (x_size - 1); ++i) { cov(i, i) = sigma_sq + dot_self(x[i]); for (size_t j = i + 1; j < x_size; ++j) { cov(i, j) = sigma_sq + dot_product(x[i], x[j]); cov(j, i) = cov(i, j); } } cov(x_size - 1, x_size - 1) = sigma_sq + dot_self(x[x_size - 1]); return cov; } /** * Returns a dot product covariance matrix. A member of Stan's Gaussian * Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x type of std::vector of double * @tparam T_sigma type of sigma * * @param x std::vector of elements that can be used in transpose * and multiply * This function assumes each element of x is the same size. * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is positive semi-definite * @throw std::domain_error if sigma < 0, nan, inf or * x is nan or infinite */ template <typename T_sigma> inline typename Eigen::Matrix<typename stan::return_type<double, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<double> &x, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) check_not_nan("gp_dot_prod_cov", "x", x[i]); check_finite("gp_dot_prod_cov", "x", x); Eigen::Matrix<typename stan::return_type<double, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < (x_size - 1); ++i) { cov(i, i) = sigma_sq + x[i] * x[i]; for (size_t j = i + 1; j < x_size; ++j) { cov(i, j) = sigma_sq + x[i] * x[j]; cov(j, i) = cov(i, j); } } cov(x_size - 1, x_size - 1) = sigma_sq + x[x_size - 1] * x[x_size - 1]; return cov; } /** * Returns a dot product covariance matrix of differing * x's. A member of Stan's Gaussian Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x1 type of first std::vector of elements * @tparam T_x2 type of second std::vector of elements * @tparam T_sigma type of sigma * * @param x1 std::vector of elements that can be used in dot_product * @param x2 std::vector of elements that can be used in dot_product * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is not always symmetric * @throw std::domain_error if sigma < 0, nan or inf * or if x1 or x2 are nan or inf */ template <typename T_x1, typename T_x2, typename T_sigma> inline typename Eigen::Matrix< typename stan::return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x1_size = x1.size(); size_t x2_size = x2.size(); for (size_t i = 0; i < x1_size; ++i) check_not_nan("gp_dot_prod_cov", "x1", x1[i]); check_finite("gp_dot_prod_cov", "x1", x1); for (size_t i = 0; i < x2_size; ++i) check_not_nan("gp_dot_prod_cov", "x2", x2[i]); check_finite("gp_dot_prod_cov", "x2", x2); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq + dot_product(x1[i], x2[j]); } } return cov; } /** * Returns a dot product covariance matrix of * differing x's. A member of Stan's Gaussian Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x1 type of first std::vector of double * @tparam T_x2 type of second std::vector of double * @tparam T_sigma type of sigma * * @param x1 std::vector of elements that can be used in dot_product * @param x2 std::vector of elements that can be used in dot_product * @param sigma is the constant function that can be used in stan::math::square * @return dot product covariance matrix that is not always symmetric * @throw std::domain_error if sigma < 0, nan or inf * or if x1 or x2 are nan or inf */ template <typename T_sigma> inline typename Eigen::Matrix<typename stan::return_type<double, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<double> &x1, const std::vector<double> &x2, const T_sigma &sigma) { using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x1_size = x1.size(); size_t x2_size = x2.size(); for (size_t i = 0; i < x1_size; ++i) check_not_nan("gp_dot_prod_cov", "x1", x1[i]); check_finite("gp_dot_prod_cov", "x1", x1); for (size_t i = 0; i < x2_size; ++i) check_not_nan("gp_dot_prod_cov", "x2", x2[i]); check_finite("gp_dot_prod_cov", "x2", x2); Eigen::Matrix<typename stan::return_type<double, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq + x1[i] * x2[j]; } } return cov; } } // namespace math } // namespace stan #endif <commit_msg>change rev inclue to prim include<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP #define STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/mat/fun/dot_product.hpp> #include <vector> namespace stan { namespace math { /** * Returns a dot product covariance matrix. A member of Stan's Gaussian Process * Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x type of std::vector of elements * @tparam T_sigma type of sigma * * @param x std::vector of elements that can be used in dot product. * This function assumes each element of x is the same size. * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is positive semi-definite * @throw std::domain_error if sigma < 0, nan, inf or * x is nan or infinite */ template <typename T_x, typename T_sigma> inline typename Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<T_x> &x, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) check_not_nan("gp_dot_prod_cov", "x", x[i]); check_finite("gp_dot_prod_cov", "x", x); Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < (x_size - 1); ++i) { cov(i, i) = sigma_sq + dot_self(x[i]); for (size_t j = i + 1; j < x_size; ++j) { cov(i, j) = sigma_sq + dot_product(x[i], x[j]); cov(j, i) = cov(i, j); } } cov(x_size - 1, x_size - 1) = sigma_sq + dot_self(x[x_size - 1]); return cov; } /** * Returns a dot product covariance matrix. A member of Stan's Gaussian * Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x type of std::vector of double * @tparam T_sigma type of sigma * * @param x std::vector of elements that can be used in transpose * and multiply * This function assumes each element of x is the same size. * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is positive semi-definite * @throw std::domain_error if sigma < 0, nan, inf or * x is nan or infinite */ template <typename T_sigma> inline typename Eigen::Matrix<typename stan::return_type<double, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<double> &x, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) check_not_nan("gp_dot_prod_cov", "x", x[i]); check_finite("gp_dot_prod_cov", "x", x); Eigen::Matrix<typename stan::return_type<double, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < (x_size - 1); ++i) { cov(i, i) = sigma_sq + x[i] * x[i]; for (size_t j = i + 1; j < x_size; ++j) { cov(i, j) = sigma_sq + x[i] * x[j]; cov(j, i) = cov(i, j); } } cov(x_size - 1, x_size - 1) = sigma_sq + x[x_size - 1] * x[x_size - 1]; return cov; } /** * Returns a dot product covariance matrix of differing * x's. A member of Stan's Gaussian Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x1 type of first std::vector of elements * @tparam T_x2 type of second std::vector of elements * @tparam T_sigma type of sigma * * @param x1 std::vector of elements that can be used in dot_product * @param x2 std::vector of elements that can be used in dot_product * @param sigma constant function that can be used in stan::math::square * @return dot product covariance matrix that is not always symmetric * @throw std::domain_error if sigma < 0, nan or inf * or if x1 or x2 are nan or inf */ template <typename T_x1, typename T_x2, typename T_sigma> inline typename Eigen::Matrix< typename stan::return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2, const T_sigma &sigma) { using stan::math::dot_product; using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x1_size = x1.size(); size_t x2_size = x2.size(); for (size_t i = 0; i < x1_size; ++i) check_not_nan("gp_dot_prod_cov", "x1", x1[i]); check_finite("gp_dot_prod_cov", "x1", x1); for (size_t i = 0; i < x2_size; ++i) check_not_nan("gp_dot_prod_cov", "x2", x2[i]); check_finite("gp_dot_prod_cov", "x2", x2); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq + dot_product(x1[i], x2[j]); } } return cov; } /** * Returns a dot product covariance matrix of * differing x's. A member of Stan's Gaussian Process Library. * * \f$k(x,x') = \sigma^2 + x \cdot x'\f$ * * A dot product covariance matrix is the same covariance matrix * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and * Williams et al 2006, Chapter 4. * * @tparam T_x1 type of first std::vector of double * @tparam T_x2 type of second std::vector of double * @tparam T_sigma type of sigma * * @param x1 std::vector of elements that can be used in dot_product * @param x2 std::vector of elements that can be used in dot_product * @param sigma is the constant function that can be used in stan::math::square * @return dot product covariance matrix that is not always symmetric * @throw std::domain_error if sigma < 0, nan or inf * or if x1 or x2 are nan or inf */ template <typename T_sigma> inline typename Eigen::Matrix<typename stan::return_type<double, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> gp_dot_prod_cov(const std::vector<double> &x1, const std::vector<double> &x2, const T_sigma &sigma) { using stan::math::square; check_not_nan("gp_dot_prod_cov", "sigma", sigma); check_nonnegative("gp_dot_prod_cov", "sigma", sigma); check_finite("gp_dot_prod_cov", "sigma", sigma); size_t x1_size = x1.size(); size_t x2_size = x2.size(); for (size_t i = 0; i < x1_size; ++i) check_not_nan("gp_dot_prod_cov", "x1", x1[i]); check_finite("gp_dot_prod_cov", "x1", x1); for (size_t i = 0; i < x2_size; ++i) check_not_nan("gp_dot_prod_cov", "x2", x2[i]); check_finite("gp_dot_prod_cov", "x2", x2); Eigen::Matrix<typename stan::return_type<double, T_sigma>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; T_sigma sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq + x1[i] * x2[j]; } } return cov; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>Bool_t kSimulation = kFALSE; TString fDataType = "AOD"; Int_t kYears = 2011; TString kCollisions = "PbPb"; TString fTrigger = "EMCGA"; Bool_t kEventTriggerAtTaskSE = kFALSE; Float_t fMinCen = -1; Float_t fMaxCen = -1; TString fAnaMesonType = "Pi0"; Bool_t kAnaPhotonCorr = kTRUE; Bool_t kAnaMesonCorr = kFALSE; Bool_t kTimeCut = kFALSE; Bool_t kDistBC = kTRUE; Bool_t kRecalClus = kTRUE; Bool_t kRecalClusE = kTRUE; Bool_t kRecalClusPos = kTRUE; Bool_t kRecalClusSSA = kTRUE; Bool_t kNonLin = kTRUE; Bool_t kTM = kFALSE; Float_t fDPhiCut = 0.03; Float_t fDEtaCut = 0.025; Bool_t kExotic = kTRUE; Float_t fExoticFraction = 0.95;///for pp:0.97, for PbPb:0.95 Bool_t kFidul = kFALSE; Bool_t kReClusterier = kFALSE; TString fName = "V2"; Float_t fMinCell = 0.1; Float_t fMinSeed = 0.3; AliAnalysisTaskEMCALCaloTrackCorr *AddTaskEmcalCaloTrackCorr( const TString data = "AOD", const TString coll = "pp", const Bool_t simulation = kFALSE, const TString trigger = "MB", const Bool_t triggerSE = kFALSE, const Float_t minCen = -1, const Float_t maxCen = -1, const Bool_t anaPhotonCorr = kTRUE, const Bool_t anaMesonCorr = kFALSE, const TString anaMesonType = "Pi0", const Bool_t timecut = kFALSE, const Bool_t tm = kFALSE, const Float_t dphicut = 0.03, const Float_t detacut = 0.025, const Bool_t exotic = kTRUE, const Float_t exoticFraction = 0.95, const Bool_t reClusterizer = kFALSE, const TString name = "V2", const Float_t minCell = 0.1, const Float_t minSeed = 0.3) { fDataType = data; kCollisions = coll; kSimulation = simulation; fTrigger = trigger; kEventTriggerAtTaskSE = triggerSE; fMinCen = minCen; fMaxCen = maxCen; fAnaMesonType = anaMesonType; kAnaPhotonCorr = anaPhotonCorr; kAnaMesonCorr = anaMesonCorr; kTimeCut = timecut; kTM = tm; fDPhiCut = dphicut; fDEtaCut = detacut; kExotic = exotic; fExoticFraction = exoticFraction; kReClusterier = reClusterizer; fName = name; fMinCell = minCell; fMinSeed = minSeed; AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTask", "No analysis manager to connect to."); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddTaskHadCorr", "This task requires an input event handler"); return NULL; } gROOT->LoadMacro("$ALICE_ROOT/PWGJE/macros/CreateTrackCutsPWGJE.C"); AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10041004); trackCuts->SetEtaRange(-0.8,0.8); AliAnalysisTaskEMCALCaloTrackCorr *task = new AliAnalysisTaskEMCALCaloTrackCorr("NeutralCorr"); task->SetMC(kSimulation); task->SetDataType(fDataType); task->SetTrackCuts(esdTrackCuts); task->SetTrackMatchedDPhiCut(fDPhiCut); task->SetTrackMatchedDEtaCut(fDEtaCut); task->SetLargeCorrTrigger(5, 50); if(kAnaPhotonCorr && !kAnaMesonCorr){ task->SwitchOnAnaPhotonCorr(); task->SwitchOffAnaMesonCorr(); task->SwitchOffFillMesonAOD(); } else if(!kAnaPhotonCorr && kAnaMesonCorr){ task->SwitchOffAnaPhotonCorr(); task->SwitchOnAnaMesonCorr(); task->SetAnaMesonType(fAnaMesonType); task->SwitchOnFillMesonAOD(); } else { task->SwitchOffAnaPhotonCorr(); task->SwitchOffAnaMesonCorr(); } task->SetCentralityClass("V0M"); task->SetCentralityBin(fMinCen,fMaxCen); task->SetEventPlaneMethod("Q"); task->SetEMCALGeometryName("EMCAL_COMPLETEV1"); mgr->AddTask(task); if(kCollisions =="pp") task->SwitchOnTrackMultBins(); if(kCollisions =="PbPb") task->SwitchOffTrackMultBins(); task->SetDeltaPhiCutRange(TMath::Pi()/2., 3*TMath::Pi()/2.); task->SetNTriggPtBins(2); Float_t fTriggerPtBins[3]={8,15,25}; task->SetTriggerBins(fTriggerPtBins); task->SetNAssocPtBins(5); Float_t fAssociatedPtBins[6]={0.5, 1, 2, 4, 6, 15}; task->SetAssociatedBins(fAssociatedPtBins); ConfigureTrigger(task); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); if(kAnaPhotonCorr && !kAnaMesonCorr) { AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("InclusivePhotonCen%.1f_%.1f",fMinCen, fMaxCen), TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root"); } else if (!kAnaPhotonCorr && kAnaMesonCorr){ AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("Inclusive%sCen%.1f_%.1f", fAnaMesonType.Data(),fMinCen, fMaxCen), TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root"); } else { AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("InclusiveNoCorrCen%.1f_%.1f", fMinCen, fMaxCen), TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root"); } mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, coutputpt1); return task; } void ConfigureTrigger(AliAnalysisTaskEMCALCaloTrackCorr *task1) { if(!kEventTriggerAtTaskSE){ task1->SwitchOffEventTriggerAtSE(); if(fTrigger=="EMC7"){ printf("CaloTrackCorr trigger EMC7\n"); task1->SetEventTriggerMask(AliVEvent::kEMC7); } else if (fTrigger=="INT7"){ printf("CaloTrackCorr trigger INT7\n"); task1->SetEventTriggerMask(AliVEvent::kINT7); } else if(fTrigger=="EMC1"){ printf("CaloTrackCorr trigger EMC1\n"); task1->SetEventTriggerMask(AliVEvent::kEMC1); } else if(fTrigger=="MB"){ printf("CaloTrackCorr trigger MB\n"); task1->SetEventTriggerMask(AliVEvent::kMB); } else if(fTrigger=="AnyINT"){ printf("CaloTrackCorr trigger AnyINT\n"); task1->SetEventTriggerMask(AliVEvent::kAnyINT); } else if(fTrigger=="EMCEGA"){ printf("CaloTrackCorr trigger EMC Gamma\n"); task1->SetEventTriggerMask(AliVEvent::kEMCEGA); } else if(fTrigger=="EMCEJE"){ printf("CaloTrackCorr trigger EMC Jet\n"); task1->SetEventTriggerMask(AliVEvent::kEMCEJE); } else if(fTrigger=="Central"){ printf("CaloTrackCorr trigger Central\n"); task1->SetEventTriggerMask(AliVEvent::kCentral); } else if(fTrigger=="SemiCentral"){ printf("CaloTrackCorr trigger SemiCentral\n"); task1->SetEventTriggerMask(AliVEvent::kSemiCentral); } else if(fTrigger=="SemiOrCentral"){ printf("CaloTrackCorr trigger SemiCentral Or Central\n"); task->SetEventTriggerMask(AliVEvent::kSemiCentral | AliVEvent::kCentral); } else{ task1->SetEventTriggerMask(AliVEvent::kAny); } } else { task1->SwitchOnEventTriggerAtSE(); if(fTrigger=="EMC7"){ printf("CaloTrackCorr trigger EMC7\n"); task1->SelectCollisionCandidates(AliVEvent::kEMC7); } else if (fTrigger=="INT7"){ printf("CaloTrackCorr trigger INT7\n"); task1->SelectCollisionCandidates(AliVEvent::kINT7); } else if(fTrigger=="EMC1"){ printf("CaloTrackCorr trigger EMC1\n"); task1->SelectCollisionCandidates(AliVEvent::kEMC1); } else if(fTrigger=="MB"){ printf("CaloTrackCorr trigger MB\n"); task1->SelectCollisionCandidates(AliVEvent::kMB); } else if(fTrigger=="AnyINT"){ printf("CaloTrackCorr trigger AnyINT\n"); task1->SelectCollisionCandidates(AliVEvent::kAnyINT); } else if(fTrigger=="EMCEGA"){ printf("CaloTrackCorr trigger EMC Gamma\n"); task1->SelectCollisionCandidates(AliVEvent::kEMCEGA); } else if(fTrigger=="EMCEJE"){ printf("CaloTrackCorr trigger EMC Jet\n"); task1->SelectCollisionCandidates(AliVEvent::kEMCEJE); } else if(fTrigger=="Central"){ printf("CaloTrackCorr trigger Central\n"); task1->SelectCollisionCandidates(AliVEvent::kCentral); } else if(fTrigger=="SemiCentral"){ printf("CaloTrackCorr trigger SemiCentral\n"); task1->SelectCollisionCandidates(AliVEvent::kSemiCentral); } else if(fTrigger=="SemiOrCentral"){ printf("CaloTrackCorr trigger SemiCentral Or Central\n"); task->SelectCollisionCandidates(AliVEvent::kSemiCentral | AliVEvent::kCentral); } else{ task1->SelectCollisionCandidates(AliVEvent::kAny); } } } <commit_msg>changes from xzhu<commit_after>Bool_t kSimulation = kFALSE; TString fDataType = "AOD"; Int_t kYears = 2011; TString kCollisions = "PbPb"; TString fTrigger = "EMCGA"; Bool_t kEventTriggerAtTaskSE = kFALSE; Float_t fMinCen = -1; Float_t fMaxCen = -1; TString fAnaMesonType = "Pi0"; Bool_t kAnaPhotonCorr = kTRUE; Bool_t kAnaMesonCorr = kFALSE; Bool_t kTimeCut = kFALSE; Bool_t kDistBC = kTRUE; Bool_t kRecalClus = kTRUE; Bool_t kRecalClusE = kTRUE; Bool_t kRecalClusPos = kTRUE; Bool_t kRecalClusSSA = kTRUE; Bool_t kNonLin = kTRUE; Bool_t kTM = kFALSE; Float_t fDPhiCut = 0.03; Float_t fDEtaCut = 0.025; Bool_t kExotic = kTRUE; Float_t fExoticFraction = 0.95;///for pp:0.97, for PbPb:0.95 Bool_t kFidul = kFALSE; Bool_t kReClusterier = kFALSE; TString fName = "V2"; Float_t fMinCell = 0.1; Float_t fMinSeed = 0.3; AliAnalysisTaskEMCALCaloTrackCorr *AddTaskEmcalCaloTrackCorr( const TString data = "AOD", const TString coll = "pp", const Bool_t simulation = kFALSE, const TString trigger = "MB", const Bool_t triggerSE = kFALSE, const Float_t minCen = -1, const Float_t maxCen = -1, const Bool_t anaPhotonCorr = kTRUE, const Bool_t anaMesonCorr = kFALSE, const TString anaMesonType = "Pi0", const Bool_t timecut = kFALSE, const Bool_t tm = kFALSE, const Float_t dphicut = 0.03, const Float_t detacut = 0.025, const Bool_t exotic = kTRUE, const Float_t exoticFraction = 0.95, const Bool_t reClusterizer = kFALSE, const TString name = "V2", const Float_t minCell = 0.1, const Float_t minSeed = 0.3) { fDataType = data; kCollisions = coll; kSimulation = simulation; fTrigger = trigger; kEventTriggerAtTaskSE = triggerSE; fMinCen = minCen; fMaxCen = maxCen; fAnaMesonType = anaMesonType; kAnaPhotonCorr = anaPhotonCorr; kAnaMesonCorr = anaMesonCorr; kTimeCut = timecut; kTM = tm; fDPhiCut = dphicut; fDEtaCut = detacut; kExotic = exotic; fExoticFraction = exoticFraction; kReClusterier = reClusterizer; fName = name; fMinCell = minCell; fMinSeed = minSeed; AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTask", "No analysis manager to connect to."); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddTaskHadCorr", "This task requires an input event handler"); return NULL; } if(fDataType == "ESD"){ gROOT->LoadMacro("$ALICE_ROOT/PWGJE/macros/CreateTrackCutsPWGJE.C"); AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10041004); esdTrackCuts->SetEtaRange(-0.8,0.8); } AliAnalysisTaskEMCALCaloTrackCorr *task = new AliAnalysisTaskEMCALCaloTrackCorr("NeutralCorr"); task->SetMC(kSimulation); task->SetDataType(fDataType); if(fDataType == "ESD")task->SetTrackCuts(esdTrackCuts); if(fDataType == "AOD") task->SwitchOnAODHybridTrackSelection(); task->SetTrackMatchedDPhiCut(fDPhiCut); task->SetTrackMatchedDEtaCut(fDEtaCut); task->SetLargeCorrTrigger(5, 50); if(kAnaPhotonCorr && !kAnaMesonCorr){ task->SwitchOnAnaPhotonCorr(); task->SwitchOffAnaMesonCorr(); task->SwitchOffFillMesonAOD(); } else if(!kAnaPhotonCorr && kAnaMesonCorr){ task->SwitchOffAnaPhotonCorr(); task->SwitchOnAnaMesonCorr(); task->SetAnaMesonType(fAnaMesonType); task->SwitchOnFillMesonAOD(); } else { task->SwitchOffAnaPhotonCorr(); task->SwitchOffAnaMesonCorr(); } task->SetCentralityClass("V0M"); task->SetCentralityBin(fMinCen,fMaxCen); task->SetEventPlaneMethod("V0"); task->SetEMCALGeometryName("EMCAL_COMPLETEV1"); mgr->AddTask(task); if(kCollisions =="pp") task->SwitchOnTrackMultBins(); if(kCollisions =="PbPb") task->SwitchOffTrackMultBins(); task->SetDeltaPhiCutRange(TMath::Pi()/2., 3*TMath::Pi()/2.); task->SetNTriggPtBins(2); Float_t fTriggerPtBins[3]={8,15,25}; task->SetTriggerBins(fTriggerPtBins); task->SetNAssocPtBins(5); Float_t fAssociatedPtBins[6]={0.5, 1, 2, 4, 6, 15}; task->SetAssociatedBins(fAssociatedPtBins); ConfigureTrigger(task); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); if(kAnaPhotonCorr && !kAnaMesonCorr) { AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("InclusivePhotonCen%.1f_%.1f",fMinCen, fMaxCen), TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root"); } else if (!kAnaPhotonCorr && kAnaMesonCorr){ AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("Inclusive%sCen%.1f_%.1f", fAnaMesonType.Data(),fMinCen, fMaxCen), TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root"); } else { AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("InclusiveNoCorrCen%.1f_%.1f", fMinCen, fMaxCen), TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root"); } mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, coutputpt1); return task; } void ConfigureTrigger(AliAnalysisTaskEMCALCaloTrackCorr *task1) { if(!kEventTriggerAtTaskSE){ task1->SwitchOffEventTriggerAtSE(); if(fTrigger=="EMC7"){ printf("CaloTrackCorr trigger EMC7\n"); task1->SetEventTriggerMask(AliVEvent::kEMC7); } else if (fTrigger=="INT7"){ printf("CaloTrackCorr trigger INT7\n"); task1->SetEventTriggerMask(AliVEvent::kINT7); } else if(fTrigger=="EMC1"){ printf("CaloTrackCorr trigger EMC1\n"); task1->SetEventTriggerMask(AliVEvent::kEMC1); } else if(fTrigger=="MB"){ printf("CaloTrackCorr trigger MB\n"); task1->SetEventTriggerMask(AliVEvent::kMB); } else if(fTrigger=="AnyINT"){ printf("CaloTrackCorr trigger AnyINT\n"); task1->SetEventTriggerMask(AliVEvent::kAnyINT); } else if(fTrigger=="EMCEGA"){ printf("CaloTrackCorr trigger EMC Gamma\n"); task1->SetEventTriggerMask(AliVEvent::kEMCEGA); } else if(fTrigger=="EMCEJE"){ printf("CaloTrackCorr trigger EMC Jet\n"); task1->SetEventTriggerMask(AliVEvent::kEMCEJE); } else if(fTrigger=="Central"){ printf("CaloTrackCorr trigger Central\n"); task1->SetEventTriggerMask(AliVEvent::kCentral); } else if(fTrigger=="SemiCentral"){ printf("CaloTrackCorr trigger SemiCentral\n"); task1->SetEventTriggerMask(AliVEvent::kSemiCentral); } else if(fTrigger=="SemiOrCentral"){ printf("CaloTrackCorr trigger SemiCentral Or Central\n"); task->SetEventTriggerMask(AliVEvent::kSemiCentral | AliVEvent::kCentral); } else{ task1->SetEventTriggerMask(AliVEvent::kAny); } } else { task1->SwitchOnEventTriggerAtSE(); if(fTrigger=="EMC7"){ printf("CaloTrackCorr trigger EMC7\n"); task1->SelectCollisionCandidates(AliVEvent::kEMC7); } else if (fTrigger=="INT7"){ printf("CaloTrackCorr trigger INT7\n"); task1->SelectCollisionCandidates(AliVEvent::kINT7); } else if(fTrigger=="EMC1"){ printf("CaloTrackCorr trigger EMC1\n"); task1->SelectCollisionCandidates(AliVEvent::kEMC1); } else if(fTrigger=="MB"){ printf("CaloTrackCorr trigger MB\n"); task1->SelectCollisionCandidates(AliVEvent::kMB); } else if(fTrigger=="AnyINT"){ printf("CaloTrackCorr trigger AnyINT\n"); task1->SelectCollisionCandidates(AliVEvent::kAnyINT); } else if(fTrigger=="EMCEGA"){ printf("CaloTrackCorr trigger EMC Gamma\n"); task1->SelectCollisionCandidates(AliVEvent::kEMCEGA); } else if(fTrigger=="EMCEJE"){ printf("CaloTrackCorr trigger EMC Jet\n"); task1->SelectCollisionCandidates(AliVEvent::kEMCEJE); } else if(fTrigger=="Central"){ printf("CaloTrackCorr trigger Central\n"); task1->SelectCollisionCandidates(AliVEvent::kCentral); } else if(fTrigger=="SemiCentral"){ printf("CaloTrackCorr trigger SemiCentral\n"); task1->SelectCollisionCandidates(AliVEvent::kSemiCentral); } else if(fTrigger=="SemiOrCentral"){ printf("CaloTrackCorr trigger SemiCentral Or Central\n"); task->SelectCollisionCandidates(AliVEvent::kSemiCentral | AliVEvent::kCentral); } else{ task1->SelectCollisionCandidates(AliVEvent::kAny); } } } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2017, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file CallableFlow.hxx * * Base class for State Flows that can be called as a subflow from a state * flow. * * @author Balazs Racz * @date 4 Feb 2017 */ #ifndef _EXECUTOR_CALLABLEFLOW_HXX_ #define _EXECUTOR_CALLABLEFLOW_HXX_ #include "executor/StateFlow.hxx" /// All callable flow request objects have to derive from this struct. struct CallableFlowRequestBase { /// Call this from all instances of reset(...). void reset_base() { resultCode = 0; } /// If high bits are zero, this is a 16-bit OpenLCB result code. Higher /// values are OpenMRN errors. int resultCode; /// Used internally by the invoke_subflow mechanism of StateFlow to notify /// the calling flow upon completion. BarrierNotifiable done; }; template<class RequestType> class CallableFlow : public StateFlow<Buffer<RequestType>, QList<1> > { public: /// Creates a callable flow. @param s defines the service we are operating /// upon. CallableFlow(Service* s) : StateFlow<Buffer<RequestType>, QList<1> >(s) {} protected: using Action = StateFlowBase::Action; /// @return the current request we are working on. RequestType* request() { return this->message()->data(); } /// Terminates the flow and returns the request buffer to the caller with /// an error code of OK (zero). Action return_ok() { return return_with_error(0); } /// Waits to be notified before moving onto the next state for termination. Action wait_and_return_ok() { return this->wait_and_call(STATE(wait_done)); } /// Terminates the flow and returns the request buffer to the caller with /// an error code of OK (zero). Action wait_done() { return return_ok(); } /// Terminates the flow and returns the request buffer to the caller with /// an specific error code. Action return_with_error(int error) { request()->resultCode = error; this->return_buffer(); return this->exit(); } }; /** Helper function for testing flow invocations. */ template<class T, typename... Args> BufferPtr<T> invoke_flow(FlowInterface<Buffer<T>>* flow, Args &&... args) { SyncNotifiable n; BufferPtr<T> b(flow->alloc()); b->data()->reset(std::forward<Args>(args)...); b->data()->done.reset(&n); flow->send(b->ref()); n.wait_for_notification(); return b; } #endif // _EXECUTOR_CALLABLEFLOW_HXX_ <commit_msg>Fixes nullptr bug in CallableFlow. (#630)<commit_after>/** \copyright * Copyright (c) 2017, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file CallableFlow.hxx * * Base class for State Flows that can be called as a subflow from a state * flow. * * @author Balazs Racz * @date 4 Feb 2017 */ #ifndef _EXECUTOR_CALLABLEFLOW_HXX_ #define _EXECUTOR_CALLABLEFLOW_HXX_ #include "executor/StateFlow.hxx" /// All callable flow request objects have to derive from this struct. struct CallableFlowRequestBase { /// Call this from all instances of reset(...). void reset_base() { resultCode = 0; } /// If high bits are zero, this is a 16-bit OpenLCB result code. Higher /// values are OpenMRN errors. int resultCode; /// Used internally by the invoke_subflow mechanism of StateFlow to notify /// the calling flow upon completion. BarrierNotifiable done; }; template<class RequestType> class CallableFlow : public StateFlow<Buffer<RequestType>, QList<1> > { public: /// Creates a callable flow. @param s defines the service we are operating /// upon. CallableFlow(Service* s) : StateFlow<Buffer<RequestType>, QList<1> >(s) {} protected: using Action = StateFlowBase::Action; /// @return the current request we are working on. RequestType* request() { return this->message() ? this->message()->data() : nullptr; } /// Terminates the flow and returns the request buffer to the caller with /// an error code of OK (zero). Action return_ok() { return return_with_error(0); } /// Waits to be notified before moving onto the next state for termination. Action wait_and_return_ok() { return this->wait_and_call(STATE(wait_done)); } /// Terminates the flow and returns the request buffer to the caller with /// an error code of OK (zero). Action wait_done() { return return_ok(); } /// Terminates the flow and returns the request buffer to the caller with /// an specific error code. Action return_with_error(int error) { request()->resultCode = error; this->return_buffer(); return this->exit(); } }; /** Helper function for testing flow invocations. */ template<class T, typename... Args> BufferPtr<T> invoke_flow(FlowInterface<Buffer<T>>* flow, Args &&... args) { SyncNotifiable n; BufferPtr<T> b(flow->alloc()); b->data()->reset(std::forward<Args>(args)...); b->data()->done.reset(&n); flow->send(b->ref()); n.wait_for_notification(); return b; } #endif // _EXECUTOR_CALLABLEFLOW_HXX_ <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP #define STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP #include <stan/math/rev/core/chainablestack.hpp> #include <tbb/task_scheduler_observer.h> #include <mutex> #include <unordered_map> #include <utility> #include <thread> #include <tuple> namespace stan { namespace math { /** * TBB observer object which is a callback hook called whenever the * TBB scheduler adds a new thread to the TBB managed threadpool. This * hook ensures that each worker thread has an initialized AD tape * ready for use. * * Refer to https://software.intel.com/en-us/node/506314 for details * on the observer concept. */ class ad_tape_observer : public tbb::task_scheduler_observer { using stack_ptr = std::unique_ptr<ChainableStack>; using ad_map = std::unordered_map<std::thread::id, stack_ptr>; public: ad_tape_observer() : tbb::task_scheduler_observer(), thread_tape_map_() { on_scheduler_entry(true); // register current process observe(true); // activates the observer } void on_scheduler_entry(bool worker) { std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_); const std::thread::id thread_id = std::this_thread::get_id(); if (thread_tape_map_.find(thread_id) == thread_tape_map_.end()) { ad_map::iterator insert_elem; bool status = false; std::tie(insert_elem, status) = thread_tape_map_.emplace(ad_map::value_type{thread_id, nullptr}); insert_elem->second = stack_ptr(new ChainableStack()); } } void on_scheduler_exit(bool worker) { std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_); auto elem = thread_tape_map_.find(std::this_thread::get_id()); if (elem != thread_tape_map_.end()) { thread_tape_map_.erase(elem); } } private: ad_map thread_tape_map_; std::mutex thread_tape_map_mutex_; }; namespace { ad_tape_observer global_observer; } // namespace } // namespace math } // namespace stan #endif <commit_msg>Fixed #1637 Merge pull request #1638 from stan-dev/bugfix/issue-1637<commit_after>#ifndef STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP #define STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP #include <stan/math/rev/core/chainablestack.hpp> #include <tbb/task_scheduler_observer.h> #include <mutex> #include <unordered_map> #include <utility> #include <thread> #include <tuple> namespace stan { namespace math { /** * TBB observer object which is a callback hook called whenever the * TBB scheduler adds a new thread to the TBB managed threadpool. This * hook ensures that each worker thread has an initialized AD tape * ready for use. * * Refer to https://software.intel.com/en-us/node/506314 for details * on the observer concept. */ class ad_tape_observer : public tbb::task_scheduler_observer { using stack_ptr = std::unique_ptr<ChainableStack>; using ad_map = std::unordered_map<std::thread::id, stack_ptr>; public: ad_tape_observer() : tbb::task_scheduler_observer(), thread_tape_map_() { on_scheduler_entry(true); // register current process observe(true); // activates the observer } ~ad_tape_observer() { observe(false); } void on_scheduler_entry(bool worker) { std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_); const std::thread::id thread_id = std::this_thread::get_id(); if (thread_tape_map_.find(thread_id) == thread_tape_map_.end()) { ad_map::iterator insert_elem; bool status = false; std::tie(insert_elem, status) = thread_tape_map_.emplace(ad_map::value_type{thread_id, nullptr}); insert_elem->second = stack_ptr(new ChainableStack()); } } void on_scheduler_exit(bool worker) { std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_); auto elem = thread_tape_map_.find(std::this_thread::get_id()); if (elem != thread_tape_map_.end()) { thread_tape_map_.erase(elem); } } private: ad_map thread_tape_map_; std::mutex thread_tape_map_mutex_; }; namespace { ad_tape_observer global_observer; } // namespace } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "gm.h" namespace skiagm { /** Create a bitmap image suitable for testing SkBitmap::scrollRect(). * * @param quarterWidth bitmap will be 4x this many pixels wide * @param quarterHeight bitmap will be 4x this many pixels tall * @param bitmap the bitmap data is written into this object */ static void make_bitmap(int quarterWidth, int quarterHeight, SkBitmap *bitmap) { SkPaint pRed, pWhite, pGreen, pBlue, pLine; pRed.setColor(0xFFFF9999); pWhite.setColor(0xFFFFFFFF); pGreen.setColor(0xFF99FF99); pBlue.setColor(0xFF9999FF); pLine.setColor(0xFF000000); pLine.setStyle(SkPaint::kStroke_Style); // Prepare bitmap, and a canvas that draws into it. bitmap->reset(); bitmap->setConfig(SkBitmap::kARGB_8888_Config, quarterWidth*4, quarterHeight*4); bitmap->allocPixels(); SkCanvas canvas(*bitmap); SkScalar w = SkIntToScalar(quarterWidth); SkScalar h = SkIntToScalar(quarterHeight); canvas.drawRectCoords( 0, 0, w*2, h*2, pRed); canvas.drawRectCoords(w*2, 0, w*4, h*2, pGreen); canvas.drawRectCoords( 0, h*2, w*2, h*4, pBlue); canvas.drawRectCoords(w*2, h*2, w*4, h*4, pWhite); canvas.drawLine(w*2, 0, w*2, h*4, pLine); canvas.drawLine( 0, h*2, w*4, h*2, pLine); canvas.drawRectCoords(w, h, w*3, h*3, pLine); } class BitmapScrollGM : public GM { public: BitmapScrollGM() { // Create the original bitmap. make_bitmap(quarterWidth, quarterHeight, &origBitmap); } protected: virtual SkString onShortName() { return SkString("bitmapscroll"); } virtual SkISize onISize() { return make_isize(800, 600); } virtual void onDraw(SkCanvas* canvas) { SkIRect scrollCenterRegion = SkIRect::MakeXYWH( quarterWidth, quarterHeight, quarterWidth*2, quarterHeight*2); int x = quarterWidth; int y = quarterHeight; int xSpacing = quarterWidth * 20; int ySpacing = quarterHeight * 16; // Draw background and left-hand text labels. canvas->drawColor(0xFFDDDDDD); drawLabel(canvas, "scroll entire bitmap", x, y, x, y + ySpacing); drawLabel(canvas, "scroll part of bitmap", x, y + ySpacing, x, y + ySpacing*2); x += 30; // Draw various permutations of scrolled bitmaps, scrolling a bit // further each time. draw9(canvas, x, y, NULL, quarterWidth*1/2, quarterHeight*1/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*1/2, quarterHeight*1/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*3/2, quarterHeight*3/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*3/2, quarterHeight*3/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*5/2, quarterHeight*5/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*5/2, quarterHeight*5/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*9/2, quarterHeight*9/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*9/2, quarterHeight*9/2); } void drawLabel(SkCanvas* canvas, const char *text, int startX, int startY, int endX, int endY) { SkPaint paint; paint.setColor(0xFF000000); SkPath path; path.moveTo(SkIntToScalar(startX), SkIntToScalar(startY)); path.lineTo(SkIntToScalar(endX), SkIntToScalar(endY)); canvas->drawTextOnPath(text, strlen(text), path, NULL, paint); } /** Stamp out 9 copies of origBitmap, scrolled in each direction (and * not scrolled at all). */ void draw9(SkCanvas* canvas, int x, int y, SkIRect* subset, int scrollX, int scrollY) { for (int yMult=-1; yMult<=1; yMult++) { for (int xMult=-1; xMult<=1; xMult++) { // Figure out the (x,y) to draw this copy at SkScalar bitmapX = SkIntToScalar( x + quarterWidth * 5 * (xMult+1)); SkScalar bitmapY = SkIntToScalar( y + quarterHeight * 5 * (yMult+1)); // Scroll a new copy of the bitmap, and then draw it. // scrollRect() should always return true, even if it's a no-op SkBitmap scrolledBitmap; SkASSERT(origBitmap.copyTo( &scrolledBitmap, origBitmap.config())); SkASSERT(scrolledBitmap.scrollRect( subset, scrollX * xMult, scrollY * yMult)); canvas->drawBitmap(scrolledBitmap, bitmapX, bitmapY); } } } private: typedef GM INHERITED; static const int quarterWidth = 10; static const int quarterHeight = 14; SkBitmap origBitmap; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BitmapScrollGM; } static GMRegistry reg(MyFactory); } <commit_msg>Slightly improve visuals of bitmapscroll test in gm<commit_after>#include "gm.h" namespace skiagm { /** Create a bitmap image suitable for testing SkBitmap::scrollRect(). * * @param quarterWidth bitmap will be 4x this many pixels wide * @param quarterHeight bitmap will be 4x this many pixels tall * @param bitmap the bitmap data is written into this object */ static void make_bitmap(int quarterWidth, int quarterHeight, SkBitmap *bitmap) { SkPaint pRed, pWhite, pGreen, pBlue, pLine, pAlphaGray; pRed.setColor(0xFFFF9999); pWhite.setColor(0xFFFFFFFF); pGreen.setColor(0xFF99FF99); pBlue.setColor(0xFF9999FF); pLine.setColor(0xFF000000); pLine.setStyle(SkPaint::kStroke_Style); pAlphaGray.setColor(0x66888888); // Prepare bitmap, and a canvas that draws into it. bitmap->reset(); bitmap->setConfig(SkBitmap::kARGB_8888_Config, quarterWidth*4, quarterHeight*4); bitmap->allocPixels(); SkCanvas canvas(*bitmap); SkScalar w = SkIntToScalar(quarterWidth); SkScalar h = SkIntToScalar(quarterHeight); canvas.drawRectCoords( 0, 0, w*2, h*2, pRed); canvas.drawRectCoords(w*2, 0, w*4, h*2, pGreen); canvas.drawRectCoords( 0, h*2, w*2, h*4, pBlue); canvas.drawRectCoords(w*2, h*2, w*4, h*4, pWhite); canvas.drawRectCoords(w, h, w*3, h*3, pAlphaGray); canvas.drawLine(w*2, 0, w*2, h*4, pLine); canvas.drawLine( 0, h*2, w*4, h*2, pLine); canvas.drawRectCoords(w, h, w*3, h*3, pLine); } class BitmapScrollGM : public GM { public: BitmapScrollGM() { // Create the original bitmap. make_bitmap(quarterWidth, quarterHeight, &origBitmap); } protected: virtual SkString onShortName() { return SkString("bitmapscroll"); } virtual SkISize onISize() { return make_isize(800, 600); } virtual void onDraw(SkCanvas* canvas) { SkIRect scrollCenterRegion = SkIRect::MakeXYWH( quarterWidth, quarterHeight, quarterWidth*2+1, quarterHeight*2+1); int x = quarterWidth; int y = quarterHeight; int xSpacing = quarterWidth * 20; int ySpacing = quarterHeight * 16; // Draw background and left-hand text labels. canvas->drawColor(0xFFDDDDDD); drawLabel(canvas, "scroll entire bitmap", x, y, x, y + ySpacing); drawLabel(canvas, "scroll part of bitmap", x, y + ySpacing, x, y + ySpacing*2); x += 30; // Draw various permutations of scrolled bitmaps, scrolling a bit // further each time. draw9(canvas, x, y, NULL, quarterWidth*1/2, quarterHeight*1/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*1/2, quarterHeight*1/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*3/2, quarterHeight*3/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*3/2, quarterHeight*3/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*5/2, quarterHeight*5/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*5/2, quarterHeight*5/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*9/2, quarterHeight*9/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*9/2, quarterHeight*9/2); } void drawLabel(SkCanvas* canvas, const char *text, int startX, int startY, int endX, int endY) { SkPaint paint; paint.setColor(0xFF000000); SkPath path; path.moveTo(SkIntToScalar(startX), SkIntToScalar(startY)); path.lineTo(SkIntToScalar(endX), SkIntToScalar(endY)); canvas->drawTextOnPath(text, strlen(text), path, NULL, paint); } /** Stamp out 9 copies of origBitmap, scrolled in each direction (and * not scrolled at all). */ void draw9(SkCanvas* canvas, int x, int y, SkIRect* subset, int scrollX, int scrollY) { for (int yMult=-1; yMult<=1; yMult++) { for (int xMult=-1; xMult<=1; xMult++) { // Figure out the (x,y) to draw this copy at SkScalar bitmapX = SkIntToScalar( x + quarterWidth * 5 * (xMult+1)); SkScalar bitmapY = SkIntToScalar( y + quarterHeight * 5 * (yMult+1)); // Scroll a new copy of the bitmap, and then draw it. // scrollRect() should always return true, even if it's a no-op SkBitmap scrolledBitmap; SkASSERT(origBitmap.copyTo( &scrolledBitmap, origBitmap.config())); SkASSERT(scrolledBitmap.scrollRect( subset, scrollX * xMult, scrollY * yMult)); canvas->drawBitmap(scrolledBitmap, bitmapX, bitmapY); } } } private: typedef GM INHERITED; static const int quarterWidth = 10; static const int quarterHeight = 14; SkBitmap origBitmap; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BitmapScrollGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_MAT_FUNCTOR_KINSOL_SOLVE_HPP #define STAN_MATH_REV_MAT_FUNCTOR_KINSOL_SOLVE_HPP #include <stan/math/prim/mat/fun/to_array_1d.hpp> #include <stan/math/prim/mat/fun/to_vector.hpp> #include <stan/math/rev/mat/functor/kinsol_data.hpp> #include <stan/math/rev/mat/functor/algebra_system.hpp> #include <stan/math/prim/mat/err/check_flag_sundials.hpp> #include <kinsol/kinsol.h> #include <sunmatrix/sunmatrix_dense.h> #include <sunlinsol/sunlinsol_dense.h> #include <nvector/nvector_serial.h> #include <vector> namespace stan { namespace math { /** * Return the solution to the specified algebraic system, * given an initial guess. Invokes the Kinsol solver from Sundials. * * @tparam F type of equation system function. * @tparam T type of initial guess vector. * @param[in] f Functor that evaluated the system of equations. * @param[in] x Vector of starting values. * @param[in] y Parameter vector for the equation system. The function * is overloaded to treat y as a vector of doubles or of a * a template type T. * @param[in] dat Continuous data vector for the equation system. * @param[in] dat_int Integer data vector for the equation system. * @param[in, out] msgs The print stream for warning messages. * @param[in] scaling_step_tol Scaled-step stopping tolerance. If * a Newton step is smaller than the scaling step * tolerance, the code breaks, assuming the solver is no * longer making significant progress (i.e. is stuck) * @param[in] function_tolerance determines whether roots are acceptable. * @param[in] max_num_steps Maximum number of function evaluations. * @param[in] custom_jacobian If 0, use Kinsol's default to compute the * jacobian for the Newton step, namely Quotient Difference * (finite difference). If 1, use reverse-mode AD, unless * the user specifies their own method. * @param[in] J_f A functor that computes the Jacobian for the Newton step. * Defaults to reverse-mode AD. * @param[in] steps_eval_jacobian Maximum number of steps before the * Jacobian gets recomputed. Note that Kinsol's default is 10. * If equal to 1, the algorithm computes exact Newton steps. * @param[in] global_line_search does the solver use a global line search? * If equal to KIN_NONE, no, if KIN_LINESEARCH, yes. * @return x_solution Vector of solutions to the system of equations. * @throw <code>std::invalid_argument</code> if Kinsol returns a negative * flag when setting up the solver. * @throw <code>boost::math::evaluation_error</code> if Kinsol returns a * negative flag after attempting to solve the equation. */ template <typename F1, typename F2 = kinsol_J_f> Eigen::VectorXd kinsol_solve( const F1& f, const Eigen::VectorXd& x, const Eigen::VectorXd& y, const std::vector<double>& dat, const std::vector<int>& dat_int, std::ostream* msgs = nullptr, double scaling_step_tol = 1e-3, double function_tolerance = 1e-6, long int max_num_steps = 200, // NOLINT(runtime/int) bool custom_jacobian = 1, const F2& J_f = kinsol_J_f(), int steps_eval_jacobian = 10, int global_line_search = KIN_LINESEARCH) { int N = x.size(); typedef kinsol_system_data<F1, F2> system_data; system_data kinsol_data(f, J_f, x, y, dat, dat_int, msgs); check_flag_sundials( KINInit(kinsol_data.kinsol_memory_, &system_data::kinsol_f_system, kinsol_data.nv_x_), "KINInit"); N_Vector scaling = N_VNew_Serial(N); N_VConst_Serial(1.0, scaling); // no scaling check_flag_sundials(KINSetNumMaxIters(kinsol_data.kinsol_memory_, max_num_steps), "KINSetNumMaxIters"); check_flag_sundials(KINSetFuncNormTol(kinsol_data.kinsol_memory_, function_tolerance), "KINSetFuncNormTol"); check_flag_sundials(KINSetScaledStepTol(kinsol_data.kinsol_memory_, scaling_step_tol), "KINSetScaledStepTol"); check_flag_sundials(KINSetMaxSetupCalls(kinsol_data.kinsol_memory_, steps_eval_jacobian), "KINSetMaxSetupCalls"); // CHECK // The default value is 1000 * ||u_0||_D where ||u_0|| is the initial guess. // So we run into issues if ||u_0|| = 0. // If the norm is non-zero, use kinsol's default (accessed with 0), // else use the dimension of x -- CHECK - find optimal length. double max_newton_step = (x.norm() == 0) ? x.size() : 0; check_flag_sundials(KINSetMaxNewtonStep(kinsol_data.kinsol_memory_, max_newton_step), "KINSetMaxNewtonStep"); check_flag_sundials( KINSetUserData(kinsol_data.kinsol_memory_, static_cast<void*>(&kinsol_data)), "KINSetUserData"); // construct Linear solver check_flag_sundials( KINSetLinearSolver(kinsol_data.kinsol_memory_, kinsol_data.LS_, kinsol_data.J_), "KINSetLinearSolver"); if (custom_jacobian) check_flag_sundials( KINSetJacFn(kinsol_data.kinsol_memory_, &system_data::kinsol_jacobian), "KINSetJacFn"); N_Vector nv_x = N_VNew_Serial(N); for (int i = 0; i < N; i++) NV_Ith_S(nv_x, i) = x(i); check_flag_kinsol( KINSol(kinsol_data.kinsol_memory_, nv_x, global_line_search, scaling, scaling), max_num_steps); Eigen::VectorXd x_solution(N); for (int i = 0; i < N; i++) x_solution(i) = NV_Ith_S(nv_x, i); N_VDestroy(nv_x); N_VDestroy(scaling); return x_solution; } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#ifndef STAN_MATH_REV_MAT_FUNCTOR_KINSOL_SOLVE_HPP #define STAN_MATH_REV_MAT_FUNCTOR_KINSOL_SOLVE_HPP #include <stan/math/prim/mat/fun/to_array_1d.hpp> #include <stan/math/prim/mat/fun/to_vector.hpp> #include <stan/math/rev/mat/functor/kinsol_data.hpp> #include <stan/math/rev/mat/functor/algebra_system.hpp> #include <stan/math/prim/mat/err/check_flag_sundials.hpp> #include <kinsol/kinsol.h> #include <sunmatrix/sunmatrix_dense.h> #include <sunlinsol/sunlinsol_dense.h> #include <nvector/nvector_serial.h> #include <vector> namespace stan { namespace math { /** * Return the solution to the specified algebraic system, * given an initial guess. Invokes the Kinsol solver from Sundials. * * @tparam F type of equation system function. * @tparam T type of initial guess vector. * @param[in] f Functor that evaluated the system of equations. * @param[in] x Vector of starting values. * @param[in] y Parameter vector for the equation system. The function * is overloaded to treat y as a vector of doubles or of a * a template type T. * @param[in] dat Continuous data vector for the equation system. * @param[in] dat_int Integer data vector for the equation system. * @param[in, out] msgs The print stream for warning messages. * @param[in] scaling_step_tol Scaled-step stopping tolerance. If * a Newton step is smaller than the scaling step * tolerance, the code breaks, assuming the solver is no * longer making significant progress (i.e. is stuck) * @param[in] function_tolerance determines whether roots are acceptable. * @param[in] max_num_steps Maximum number of function evaluations. * @param[in] custom_jacobian If 0, use Kinsol's default to compute the * jacobian for the Newton step, namely Quotient Difference * (finite difference). If 1, use reverse-mode AD, unless * the user specifies their own method. * @param[in] J_f A functor that computes the Jacobian for the Newton step. * Defaults to reverse-mode AD. * @param[in] steps_eval_jacobian Maximum number of steps before the * Jacobian gets recomputed. Note that Kinsol's default is 10. * If equal to 1, the algorithm computes exact Newton steps. * @param[in] global_line_search does the solver use a global line search? * If equal to KIN_NONE, no, if KIN_LINESEARCH, yes. * @return x_solution Vector of solutions to the system of equations. * @throw <code>std::invalid_argument</code> if Kinsol returns a negative * flag when setting up the solver. * @throw <code>boost::math::evaluation_error</code> if Kinsol returns a * negative flag after attempting to solve the equation. */ template <typename F1, typename F2 = kinsol_J_f> Eigen::VectorXd kinsol_solve( const F1& f, const Eigen::VectorXd& x, const Eigen::VectorXd& y, const std::vector<double>& dat, const std::vector<int>& dat_int, std::ostream* msgs = nullptr, double scaling_step_tol = 1e-3, double function_tolerance = 1e-6, long int max_num_steps = 200, // NOLINT(runtime/int) bool custom_jacobian = 1, const F2& J_f = kinsol_J_f(), int steps_eval_jacobian = 10, int global_line_search = KIN_LINESEARCH) { int N = x.size(); typedef kinsol_system_data<F1, F2> system_data; system_data kinsol_data(f, J_f, x, y, dat, dat_int, msgs); check_flag_sundials(KINInit(kinsol_data.kinsol_memory_, &system_data::kinsol_f_system, kinsol_data.nv_x_), "KINInit"); N_Vector scaling = N_VNew_Serial(N); N_VConst_Serial(1.0, scaling); // no scaling check_flag_sundials( KINSetNumMaxIters(kinsol_data.kinsol_memory_, max_num_steps), "KINSetNumMaxIters"); check_flag_sundials( KINSetFuncNormTol(kinsol_data.kinsol_memory_, function_tolerance), "KINSetFuncNormTol"); check_flag_sundials( KINSetScaledStepTol(kinsol_data.kinsol_memory_, scaling_step_tol), "KINSetScaledStepTol"); check_flag_sundials( KINSetMaxSetupCalls(kinsol_data.kinsol_memory_, steps_eval_jacobian), "KINSetMaxSetupCalls"); // CHECK // The default value is 1000 * ||u_0||_D where ||u_0|| is the initial guess. // So we run into issues if ||u_0|| = 0. // If the norm is non-zero, use kinsol's default (accessed with 0), // else use the dimension of x -- CHECK - find optimal length. double max_newton_step = (x.norm() == 0) ? x.size() : 0; check_flag_sundials( KINSetMaxNewtonStep(kinsol_data.kinsol_memory_, max_newton_step), "KINSetMaxNewtonStep"); check_flag_sundials(KINSetUserData(kinsol_data.kinsol_memory_, static_cast<void*>(&kinsol_data)), "KINSetUserData"); // construct Linear solver check_flag_sundials(KINSetLinearSolver(kinsol_data.kinsol_memory_, kinsol_data.LS_, kinsol_data.J_), "KINSetLinearSolver"); if (custom_jacobian) check_flag_sundials( KINSetJacFn(kinsol_data.kinsol_memory_, &system_data::kinsol_jacobian), "KINSetJacFn"); N_Vector nv_x = N_VNew_Serial(N); for (int i = 0; i < N; i++) NV_Ith_S(nv_x, i) = x(i); check_flag_kinsol(KINSol(kinsol_data.kinsol_memory_, nv_x, global_line_search, scaling, scaling), max_num_steps); Eigen::VectorXd x_solution(N); for (int i = 0; i < N; i++) x_solution(i) = NV_Ith_S(nv_x, i); N_VDestroy(nv_x); N_VDestroy(scaling); return x_solution; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "finiteem.h" #include <cmath> #include <functional> #include <algorithm> #include <iostream> #include <stdexcept> #include <cerrno> #include <cstring> #include <limits> Finiteem::Finiteem(Pileupdata p, int ploidy) : plp(p), theta(std::make_tuple(0.1,std::map::map(),1)), em(std::bind(&Finiteem::q_function, this, std::placeholders::_1), std::bind(&Finiteem::m_function,this,std::placeholders::_1), theta), ploidy(ploidy){ possible_gts = Genotype::enumerate_gts(ploidy); } Finiteem::Finiteem(Pileupdata p): Finiteem(p, 2){ } Finiteem::Finiteem(std::string samfile, std::string refname, int ploidy) : plp(samfile, refname), theta(std::make_tuple(0.1,std::map::map(),1)), em(std::bind(&Finiteem::q_function, this, std::placeholders::_1), std::bind(&Finiteem::m_function,this,std::placeholders::_1), theta), ploidy(ploidy){ possible_gts = Genotype::enumerate_gts(ploidy); } Finiteem::Finiteem(std::string samfile, std::string refname) : Finiteem(samfile, refname, 2) { } theta_t Finiteem::start(double stop){ return em.start(stop); } double Finiteem::q_function(theta_t theta){ double likelihood = 0.0; for (std::vector<Genotype>::iterator g = possible_gts.begin(); g != possible_gts.end(); ++g){ likelihood += log(g.p_finite_alleles('A',0,std::get<0>(theta),std::get<1>(theta))); } return likelihood; } theta_t Finiteem::m_function(theta_t theta){ pileupdata_t plpdata = plp.get_data(); GT_Matrix<ploidy> n(); for (pileupdata_t::iterator tid = plpdata.begin(); tid != plpdata.end(); ++tid){ for(std::vector<pileuptuple_t>::iterator pos = tid->begin(); pos != tid->end(); ++pos){ const std::vector<char> &x = std::get<0>(*pos); const char &ref = std::get<3>(*pos); for (std::vector<Genotype>::iterator g = possible_gts.begin(); g != possible_gts.end(); ++g){ std::vector<double> site_s = calc_s(x,*g,theta); double pg_x = pg_x_given_theta(*g,x,theta); for(size_t i = 0; i < s.size(); ++i){ s[i] += pg_x * site_s[i]; } t[ref][*g] += pg_x; } } } // scale to prevent underflow // double smallest = smallest_nonzero(s); // if (smallest != 0){ //there SHOULD always be an s > 0. // std::transform(s.begin(),s.end(),s.begin(),[smallest](double d){ return d / smallest; }); // } //quadratic formula double a = 3.0 * (s[0] + s[1] + s[2]); double b = - (3.0/2 * s[0] + s[1] + 5.0/2 * s[2]); double c = s[2] / 2; double epsilon_minus = (-b - sqrt(std::pow(b,2) - 4 * a * c))/(2 * a); // double epsilon_plus = (-b + sqrt(std::pow(b,2) - 4 * a * c))/(2 * a); double epsilon; if (epsilon_minus < 0){ epsilon = 0; } else{ epsilon = epsilon_minus; } return std::make_tuple(epsilon); } //TODO:Make this work for pi void Finiteem::optimize_q(GT_Matrix<2> m){ std::get<0>(theta) = meep_math::nr_root(dq_dtheta,ddq_dtheta,std::get<0>(theta)); std::get<2>(theta) = meep_math::nr_root(dq_dw,ddq_dw,std::get<2>(theta)); } double Finiteem::dq_dtheta(double th){ std::map<char,double> pi = std::get<1>(theta); double refweight = std::get<2>(theta); double dq = 0.0; int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles; ++i){ //for each reference base for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; for (int k = 0; k < it->second; ++k){ //add pi/(alpha + 0) twice for het; pi/(alpha + 1) for homozygote dq += m[i][j] * (pi[allele]/(allele_alpha(allele,Genotype::alleles[i],refweight,th,pi) + k)) } } for (l = 0; l < ploidy; ++l){ //subtract alpha, alpha + 1 dq -= m[i][j] * (1.0 / ref_alpha(refweight, th) + l); } } } return dq; } double Finiteem::ddq_dtheta(double th){ double ddq = 0.0; std::map<char,double> pi = std::get<1>(theta); double refweight = std::get<2>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles; ++i){ //for each reference base for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (l = 0; l < ploidy; ++l){ //add 1/alpha, 1/(alpha + 1) dq += m[i][j] * (1.0 / (ref_alpha(refweight, theta) + l)^2); } for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; for (int k = 0; k < it->second; ++k){ //add pi/(alpha + 0) twice for het; pi/(alpha + 1) for homozygote ddq -= m[i][j] * ((pi[allele]^2)/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)^2) } } } } return ddq; } double Finiteem::dq_dw(double w){ double dq = 0.0; double th = std::get<0>(theta); std::map<char,double> pi = std::get<1>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles; ++i){ //for each reference base for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; if (allele == Genotype::alleles[i]){ for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote dq += m[i][j] * (1.0/(allele_alpha(allele,Genotype::alleles[i],w,theta,pi) + k)) } } } } } return dq; } double Finiteem::ddq_dw(double w){ double ddq = 0.0; double th = std::get<0>(theta); std::map<char,double> pi = std::get<1>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles; ++i){ //for each reference base for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; if (allele == Genotype::alleles[i]){ for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote ddq -= m[i][j] * (1.0/(allele_alpha(allele,Genotype::alleles[i],w,theta,pi) + k)^2) } } } } } return ddq; } double dq_dpi(char a, double pi){ double dq = 0.0; double th = std::get<0>(theta); double refweight = std::get<2>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles - 1; ++i){ //for each reference base except one for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; if (allele == a){ for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote dq += m[i][j] * ((theta)/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)) } } } } } return dq; } double ddq_dpi(char a, double pi){ double ddq = 0.0; double th = std::get<0>(theta); double refweight = std::get<2>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles - 1; ++i){ //for each reference base except one for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; if (allele == a){ for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote ddq -= m[i][j] * ((theta)^2/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)^2) } } } } } return ddq; } std::vector<double> Finiteem::calc_s(std::vector<char> x, Genotype g, theta_t theta){ //TODO: make this generic std::vector<double> s(3,0.0); for (std::vector<char>::iterator i = x.begin(); i != x.end(); ++i){ int numgt = g.numbase(*i); if (numgt == 2){ s[0]++; } else if (numgt == 1){ s[1]++; } else if (numgt == 0){ s[2]++; } } return s; } //RESULT NOT IN LOG SPACE double Finiteem::pg_x_given_theta(const Genotype g,const std::vector<char> x,const theta_t theta){ double px = px_given_gtheta(x,g,theta); return exp(px + pg(g)); } //may be faster if we represent x as a map w/ char and counts, like gt?? we support this in plpdata double Finiteem::px_given_gtheta(const std::vector<char> x,const Genotype g,const theta_t theta){ double px = 0.0; std::map<char, int> counts; for (std::vector<char>::const_iterator i = x.begin(); i != x.end(); ++i){ counts[*i] += 1; } for (std::map<char,int>::iterator i = counts.begin(); i!= counts.end(); ++i){ double pn = pn_given_gtheta(i->first,g,theta); if (pn == -std::numeric_limits<double>::infinity()){ return -std::numeric_limits<double>::infinity(); } else{ px += i->second * pn; // px -= std::lgamma(i->second + 1); } } // px += std::lgamma(x.size()+1); return px; } //LOG SPACE double Finiteem::pn_given_gtheta(char n, Genotype g, theta_t theta){ double epsilon = std::get<0>(theta); double p; // p = ((double)g.numbase(n))/g.getploidy()*(1.0-3.0*epsilon) + ((double)g.numnotbase(n))/g.getploidy()*epsilon; int numgt = g.numbase(n); if (numgt == 2){ p = (1.0 - 3.0 * epsilon); } else if (numgt == 1){ p = (0.5 - epsilon); } else{ p = epsilon; } if (p == 0){ return -std::numeric_limits<double>::infinity(); } else if (p < 0){ std::clog << "N=" << n << "\tGT=" << g << "\tPloidy=" << g.getploidy() << "\t#N=" << g.numbase(n) << "\t#!N=" << g.numnotbase(n) << "\tP1=" << ((double)g.numbase(n))/g.getploidy()*(1-3*epsilon) << "\tP2=" << ((double)g.numnotbase(n))/g.getploidy()*epsilon << "\tP=" << p << "\tTheta=" << theta << std::endl; throw std::runtime_error("p < 0 detected"); } else{ return log(p); } } double Finiteem::pg(Genotype g){ return log(1.0/possible_gts.size()); } double Finiteem::smallest_nonzero(std::vector<double> v){ std::vector<double> sorted_v(v); std::sort(sorted_v.begin(),sorted_v.end()); double smallest = 0; for (std::vector<double>::iterator i = sorted_v.begin(); i != sorted_v.end(); ++i){ if(*i > smallest){ return *i; } } return 0; } double Finiteem::allele_alpha(char allele, char ref, double ref_weight, double theta, std::map<char,double> pi){ double w = (ref == allele ? ref_weight : 0); return theta * pi[allele] + w; } double Finiteem::allele_alpha(char allele, char ref, double ref_weight, double theta, double pi){ double w = (ref == allele ? ref_weight : 0); return theta * pi + w; } double Finiteem::ref_alpha(double ref_weight, double theta){ return ref_weight + theta; } <commit_msg>make functions work<commit_after>#include "finiteem.h" #include <cmath> #include <functional> #include <algorithm> #include <iostream> #include <stdexcept> #include <cerrno> #include <cstring> #include <limits> Finiteem::Finiteem(Pileupdata p, int ploidy) : plp(p), theta(std::make_tuple(0.1,std::map::map(),1)), em(std::bind(&Finiteem::q_function, this, std::placeholders::_1), std::bind(&Finiteem::m_function,this,std::placeholders::_1), theta), ploidy(ploidy){ possible_gts = Genotype::enumerate_gts(ploidy); m = load_matrix(); } Finiteem::Finiteem(Pileupdata p): Finiteem(p, 2){ } Finiteem::Finiteem(std::string samfile, std::string refname, int ploidy) : plp(samfile, refname), theta(std::make_tuple(0.1,std::map::map(),1)), em(std::bind(&Finiteem::q_function, this, std::placeholders::_1), std::bind(&Finiteem::m_function,this,std::placeholders::_1), theta), ploidy(ploidy){ possible_gts = Genotype::enumerate_gts(ploidy); m = load_matrix(); } Finiteem::Finiteem(std::string samfile, std::string refname) : Finiteem(samfile, refname, 2) { } theta_t Finiteem::start(double stop){ return em.start(stop); } double Finiteem::q_function(theta_t theta){ double likelihood = 0.0; for (int i = 0; i < Genotype::alleles.size(); ++i){ for (int j = 0; j < possible_gts.size(); ++j){ Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ char allele = it->first; for (int k = 0; k < it->second; ++k){ likelihood += m[i][j] * log(allele_alpha(allele,Genotype::alleles[i],std::get<2>(theta),std::get<0>(theta),std::get<1>(theta)) + k); } } for (l = 0; l < ploidy; ++l){ likelihood -= m[i][j] * log(ref)alpha(std::get<2>(theta), std::get<0>(theta) + l); } } } return likelihood; } theta_t Finiteem::m_function(theta_t theta){ double th = meep_math::nr_root(dq_dtheta,ddq_dtheta,std::get<0>(theta)); double w = meep_math::nr_root(dq_dw,ddq_dw,std::get<2>(theta)); std::map<char,double> pi = std::get<1>(theta); double p = 0.0; for (int i = 0; i < Genotype::alleles.size()-1; ++i){ a = Genotype::alleles[i]; auto qprime = std::bind(dq_dpi,a,_1); auto qprimeprime = std::bind(ddq_dpi,a,_1); double optimum = meep_math::nr_root(qprime,qprimeprime,pi[a]); pi[a] = optimum; p += optimum; } pi[Genotype::alleles.back()] = 1 - p; return std::make_tuple(th,pi,w); } //todo: figure out what to do with this function GT_Matrix<ploidy> Finiteem::load_matrix(){ for (pileupdata_t::iterator tid = plpdata.begin(); tid != plpdata.end(); ++tid){ for(std::vector<pileuptuple_t>::iterator pos = tid->begin(); pos != tid->end(); ++pos){ const std::vector<char> &x = std::get<0>(*pos); const char &ref = std::get<3>(*pos); // for (std::vector<Genotype>::iterator g = possible_gts.begin(); g != possible_gts.end(); ++g){ // std::vector<double> site_s = calc_s(x,*g,theta); // double pg_x = pg_x_given_theta(*g,x,theta); // for(size_t i = 0; i < s.size(); ++i){ // s[i] += pg_x * site_s[i]; // } // t[ref][*g] += pg_x; // } } } } theta_t Finiteem::optimize_q(theta_t theta){ } double Finiteem::dq_dtheta(double th){ std::map<char,double> pi = std::get<1>(theta); double refweight = std::get<2>(theta); double dq = 0.0; int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles; ++i){ //for each reference base for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; for (int k = 0; k < it->second; ++k){ //add pi/(alpha + 0) twice for het; pi/(alpha + 1) for homozygote dq += m[i][j] * (pi[allele]/(allele_alpha(allele,Genotype::alleles[i],refweight,th,pi) + k)) } } for (l = 0; l < ploidy; ++l){ //subtract alpha, alpha + 1 dq -= m[i][j] * (1.0 / ref_alpha(refweight, th) + l); } } } return dq; } double Finiteem::ddq_dtheta(double th){ double ddq = 0.0; std::map<char,double> pi = std::get<1>(theta); double refweight = std::get<2>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles; ++i){ //for each reference base for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (l = 0; l < ploidy; ++l){ //add 1/alpha, 1/(alpha + 1) dq += m[i][j] * (1.0 / (ref_alpha(refweight, theta) + l)^2); } for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; for (int k = 0; k < it->second; ++k){ //add pi/(alpha + 0) twice for het; pi/(alpha + 1) for homozygote ddq -= m[i][j] * ((pi[allele]^2)/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)^2) } } } } return ddq; } double Finiteem::dq_dw(double w){ double dq = 0.0; double th = std::get<0>(theta); std::map<char,double> pi = std::get<1>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles; ++i){ //for each reference base for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; if (allele == Genotype::alleles[i]){ for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote dq += m[i][j] * (1.0/(allele_alpha(allele,Genotype::alleles[i],w,theta,pi) + k)) } } } } } return dq; } double Finiteem::ddq_dw(double w){ double ddq = 0.0; double th = std::get<0>(theta); std::map<char,double> pi = std::get<1>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles; ++i){ //for each reference base for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; if (allele == Genotype::alleles[i]){ for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote ddq -= m[i][j] * (1.0/(allele_alpha(allele,Genotype::alleles[i],w,theta,pi) + k)^2) } } } } } return ddq; } double dq_dpi(char a, double pi){ double dq = 0.0; double th = std::get<0>(theta); double refweight = std::get<2>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles - 1; ++i){ //for each reference base except one for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; if (allele == a){ for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote dq += m[i][j] * ((theta)/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)) } } } } } return dq; } double ddq_dpi(char a, double pi){ double ddq = 0.0; double th = std::get<0>(theta); double refweight = std::get<2>(theta); int numalleles = Genotype::alleles.size(); int numgts = possible_gts.size(); for (int i = 0; i < numalleles - 1; ++i){ //for each reference base except one for (int j = 0; i < numgts; ++j){ //for each genotype Genotype g = possible_gts[j]; for (auto it = g.gt.begin(); it != g.gt.end(); ++it){ //for each base in genotype char allele = it -> first; if (allele == a){ for (int k = 0; k < it->second; ++k){ //add 1/(alpha + 0) or +0 and +1 for homozygote ddq -= m[i][j] * ((theta)^2/(allele_alpha(allele,Genotype::alleles[i],refweight,theta,pi) + k)^2) } } } } } return ddq; } double Finiteem::allele_alpha(char allele, char ref, double ref_weight, double theta, std::map<char,double> pi){ double w = (ref == allele ? ref_weight : 0); return theta * pi[allele] + w; } double Finiteem::allele_alpha(char allele, char ref, double ref_weight, double theta, double pi){ double w = (ref == allele ? ref_weight : 0); return theta * pi + w; } double Finiteem::ref_alpha(double ref_weight, double theta){ return ref_weight + theta; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "../src/scene/SceneManager.h" #include "../src/scene/Ionosphere.h" #include "../src/tracer/Ray.h" #include "../src/math/Vector3d.h" #include "../src/math/Line3d.h" #include "../src/core/Config.h" #include "../src/core/Application.h" namespace { using namespace raytracer::scene; using namespace raytracer::math; class SceneManagerTest : public ::testing::Test { protected: void SetUp() { conf = Config("config/scenario_test.json"); Application::getInstance().setCelestialConfig(conf); appConf = Config("config/config.json"); Application::getInstance().setApplicationConfig(conf); sm = SceneManager(); io = Ionosphere(); Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 100e3, 0)); mesh.size = 1e3; io.setMesh(mesh); sm.addToScene(&io); } SceneManager sm; Ionosphere io; Config conf, appConf; }; TEST_F(SceneManagerTest, MeshIsSet) { for (Geometry* g : sm.getScene()) { ASSERT_EQ(100e3, g->getMesh().centerpoint.x); ASSERT_EQ(3390e3 + 100e3, g->getMesh().centerpoint.y); ASSERT_EQ(0, g->getMesh().centerpoint.z); ASSERT_EQ(0, g->getMesh().normal.x); ASSERT_EQ(1, g->getMesh().normal.y); ASSERT_EQ(GeometryType::ionosphere, g->type); } } TEST_F(SceneManagerTest, Intersection) { raytracer::tracer::Ray r = raytracer::tracer::Ray(); r.o = Vector3d(0, 0, 0); Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 101e3, 0)); Intersection is = sm.intersect(r, rayLine); Plane3d mesh = is.g.mesh3d; ASSERT_NE(GeometryType::none, is.o); ASSERT_NEAR((mesh.centerpoint.y / rayLine.destination.y) * mesh.centerpoint.x, is.pos.x, 10); ASSERT_EQ(3390e3 + 100e3, is.pos.y); ASSERT_NEAR(100e3, mesh.centerpoint.x, 10); ASSERT_NEAR(3390e3 + 100e3, mesh.centerpoint.y, 10); ASSERT_NEAR(0, mesh.centerpoint.z, 10); } TEST_F(SceneManagerTest, SortScene) { SceneManager scm2 = SceneManager(); Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 10, 0)); Geometry g1 = Geometry(mesh); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 13, 0)); Geometry g2 = Geometry(mesh); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 14, 0)); Geometry g3 = Geometry(mesh); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 12, 0)); Geometry g4 = Geometry(mesh); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 11, 0)); Geometry g5 = Geometry(mesh); scm2.addToScene(&g1); scm2.addToScene(&g2); scm2.addToScene(&g3); scm2.addToScene(&g4); scm2.addToScene(&g5); scm2.sortScene(); double lastAlt = 0; for (Geometry* g : scm2.getScene()) { ASSERT_GT(g->altitude, 0); ASSERT_GT(g->altitude, lastAlt); lastAlt = g->altitude; ASSERT_GT(lastAlt, 0); } } TEST_F(SceneManagerTest, IntersectionOutOfBounds) { raytracer::tracer::Ray r = raytracer::tracer::Ray(); r.o = Vector3d(0, 0, 0); Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 99e3, 0)); Intersection is = sm.intersect(r, rayLine); ASSERT_EQ(GeometryType::none, is.o); } TEST_F(SceneManagerTest, IntersectionAngled) { raytracer::tracer::Ray r = raytracer::tracer::Ray(); r.o = Vector3d(0, 0, 0); double angle = Constants::PI/3; double offset = 250; Line3d rayLine = Line3d(); rayLine.origin = Vector3d(100e3 - 100e3/tan(angle) - offset, 3390e3, 0); rayLine.destination.x = 100e3 / tan(angle) + 100e3 - offset; rayLine.destination.y = 200e3 + 3390e3; Intersection is = sm.intersect(r, rayLine); Plane3d mesh = is.g.mesh3d; ASSERT_NEAR((rayLine.destination.y - rayLine.origin.y) / (rayLine.destination.x - rayLine.origin.x), tan(angle), 1e-3); ASSERT_EQ(GeometryType::ionosphere, is.o); ASSERT_NEAR(100e3 - offset, is.pos.x, 10); ASSERT_EQ(3390e3 + 100e3, is.pos.y); ASSERT_NEAR(100e3, mesh.centerpoint.x, 10); ASSERT_NEAR(3390e3 + 100e3, mesh.centerpoint.y, 10); ASSERT_NEAR(0, mesh.centerpoint.z, 10); rayLine.origin.x -= 1e3; rayLine.destination.x -= 1e3; is = sm.intersect(r, rayLine); ASSERT_EQ(GeometryType::none, is.o); } TEST_F(SceneManagerTest, IntersectionMultiple) { Ionosphere io4 = Ionosphere(); Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 101e3, 0)); mesh.size = 1e3; io4.setMesh(mesh); sm.addToScene(&io4); Ionosphere io2 = Ionosphere(); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 102e3, 0)); mesh.size = 1e3; io2.setMesh(mesh); sm.addToScene(&io2); Ionosphere io3 = Ionosphere(); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 103e3, 0)); mesh.size = 1e3; io3.setMesh(mesh); sm.addToScene(&io3); raytracer::tracer::Ray r = raytracer::tracer::Ray(); r.o = Vector3d(0, 0, 0); Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 105e3, 0)); Intersection is = sm.intersect(r, rayLine); Plane3d mesh2 = is.g.mesh3d; ASSERT_NE(GeometryType::none, is.o); ASSERT_NEAR((mesh2.centerpoint.y / rayLine.destination.y) * mesh2.centerpoint.x, is.pos.x, 10); ASSERT_EQ(3390e3 + 100e3, is.pos.y); ASSERT_NEAR(100e3, mesh2.centerpoint.x, 10); ASSERT_NEAR(3390e3 + 100e3, mesh2.centerpoint.y, 10); ASSERT_NEAR(0, mesh2.centerpoint.z, 10); } } <commit_msg>Minor bugfix in test<commit_after>#include "gtest/gtest.h" #include "../src/scene/SceneManager.h" #include "../src/scene/Ionosphere.h" #include "../src/tracer/Ray.h" #include "../src/math/Vector3d.h" #include "../src/math/Line3d.h" #include "../src/core/Config.h" #include "../src/core/Application.h" namespace { using namespace raytracer::scene; using namespace raytracer::math; class SceneManagerTest : public ::testing::Test { protected: void SetUp() { conf = Config("config/scenario_test.json"); Application::getInstance().setCelestialConfig(conf); appConf = Config("config/config.json"); Application::getInstance().setApplicationConfig(conf); sm = SceneManager(); io = Ionosphere(); Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 100e3, 0)); mesh.size = 1e3; io.setMesh(mesh); sm.addToScene(&io); } SceneManager sm; Ionosphere io; Config conf, appConf; }; TEST_F(SceneManagerTest, MeshIsSet) { for (Geometry* g : sm.getScene()) { ASSERT_EQ(100e3, g->getMesh().centerpoint.x); ASSERT_EQ(3390e3 + 100e3, g->getMesh().centerpoint.y); ASSERT_EQ(0, g->getMesh().centerpoint.z); ASSERT_EQ(0, g->getMesh().normal.x); ASSERT_EQ(1, g->getMesh().normal.y); ASSERT_EQ(GeometryType::ionosphere, g->type); } } TEST_F(SceneManagerTest, Intersection) { raytracer::tracer::Ray r = raytracer::tracer::Ray(); r.o = Vector3d(0, 0, 0); Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 101e3, 0)); Intersection is = sm.intersect(r, rayLine); Plane3d mesh = is.g->mesh3d; ASSERT_NE(GeometryType::none, is.o); ASSERT_NEAR((mesh.centerpoint.y / rayLine.destination.y) * mesh.centerpoint.x, is.pos.x, 10); ASSERT_EQ(3390e3 + 100e3, is.pos.y); ASSERT_NEAR(100e3, mesh.centerpoint.x, 10); ASSERT_NEAR(3390e3 + 100e3, mesh.centerpoint.y, 10); ASSERT_NEAR(0, mesh.centerpoint.z, 10); } TEST_F(SceneManagerTest, SortScene) { SceneManager scm2 = SceneManager(); Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 10, 0)); Geometry g1 = Geometry(mesh); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 13, 0)); Geometry g2 = Geometry(mesh); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 14, 0)); Geometry g3 = Geometry(mesh); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 12, 0)); Geometry g4 = Geometry(mesh); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(0, 3390e3 + 11, 0)); Geometry g5 = Geometry(mesh); scm2.addToScene(&g1); scm2.addToScene(&g2); scm2.addToScene(&g3); scm2.addToScene(&g4); scm2.addToScene(&g5); scm2.sortScene(); double lastAlt = 0; for (Geometry* g : scm2.getScene()) { ASSERT_GT(g->altitude, 0); ASSERT_GT(g->altitude, lastAlt); lastAlt = g->altitude; ASSERT_GT(lastAlt, 0); } } TEST_F(SceneManagerTest, IntersectionOutOfBounds) { raytracer::tracer::Ray r = raytracer::tracer::Ray(); r.o = Vector3d(0, 0, 0); Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 99e3, 0)); Intersection is = sm.intersect(r, rayLine); ASSERT_EQ(GeometryType::none, is.o); } TEST_F(SceneManagerTest, IntersectionAngled) { raytracer::tracer::Ray r = raytracer::tracer::Ray(); r.o = Vector3d(0, 0, 0); double angle = Constants::PI/3; double offset = 250; Line3d rayLine = Line3d(); rayLine.origin = Vector3d(100e3 - 100e3/tan(angle) - offset, 3390e3, 0); rayLine.destination.x = 100e3 / tan(angle) + 100e3 - offset; rayLine.destination.y = 200e3 + 3390e3; Intersection is = sm.intersect(r, rayLine); Plane3d mesh = is.g->mesh3d; ASSERT_NEAR((rayLine.destination.y - rayLine.origin.y) / (rayLine.destination.x - rayLine.origin.x), tan(angle), 1e-3); ASSERT_EQ(GeometryType::ionosphere, is.o); ASSERT_NEAR(100e3 - offset, is.pos.x, 10); ASSERT_EQ(3390e3 + 100e3, is.pos.y); ASSERT_NEAR(100e3, mesh.centerpoint.x, 10); ASSERT_NEAR(3390e3 + 100e3, mesh.centerpoint.y, 10); ASSERT_NEAR(0, mesh.centerpoint.z, 10); rayLine.origin.x -= 1e3; rayLine.destination.x -= 1e3; is = sm.intersect(r, rayLine); ASSERT_EQ(GeometryType::none, is.o); } TEST_F(SceneManagerTest, IntersectionMultiple) { Ionosphere io4 = Ionosphere(); Plane3d mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 101e3, 0)); mesh.size = 1e3; io4.setMesh(mesh); sm.addToScene(&io4); Ionosphere io2 = Ionosphere(); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 102e3, 0)); mesh.size = 1e3; io2.setMesh(mesh); sm.addToScene(&io2); Ionosphere io3 = Ionosphere(); mesh = Plane3d(Vector3d(0, 1, 0), Vector3d(100e3, 3390e3 + 103e3, 0)); mesh.size = 1e3; io3.setMesh(mesh); sm.addToScene(&io3); raytracer::tracer::Ray r = raytracer::tracer::Ray(); r.o = Vector3d(0, 0, 0); Line3d rayLine = Line3d(Vector3d(0, 0, 0), Vector3d(100e3, 3390e3 + 105e3, 0)); Intersection is = sm.intersect(r, rayLine); Plane3d mesh2 = is.g->mesh3d; ASSERT_NE(GeometryType::none, is.o); ASSERT_NEAR((mesh2.centerpoint.y / rayLine.destination.y) * mesh2.centerpoint.x, is.pos.x, 10); ASSERT_EQ(3390e3 + 100e3, is.pos.y); ASSERT_NEAR(100e3, mesh2.centerpoint.x, 10); ASSERT_NEAR(3390e3 + 100e3, mesh2.centerpoint.y, 10); ASSERT_NEAR(0, mesh2.centerpoint.z, 10); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dstribut.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 17:04:09 $ * * 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 _SVX_DSTRIBUT_HXX #define _SVX_DSTRIBUT_HXX #ifndef _SVX_DLG_CTRL_HXX #include <svx/dlgctrl.hxx> #endif #ifndef _SV_GROUP_HXX #include <vcl/group.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _SVX_DSTRIBUT_ENUM_HXX #include <svx/dstribut_enum.hxx> //CHINA001 #endif /************************************************************************* |* \************************************************************************/ /* enum SvxDistributeHorizontal { SvxDistributeHorizontalNone = 0, SvxDistributeHorizontalLeft, SvxDistributeHorizontalCenter, SvxDistributeHorizontalDistance, SvxDistributeHorizontalRight }; enum SvxDistributeVertical { SvxDistributeVerticalNone = 0, SvxDistributeVerticalTop, SvxDistributeVerticalCenter, SvxDistributeVerticalDistance, SvxDistributeVerticalBottom }; */ /************************************************************************* |* \************************************************************************/ class SvxDistributePage : public SvxTabPage { SvxDistributeHorizontal meDistributeHor; SvxDistributeVertical meDistributeVer; FixedLine maFlHorizontal ; RadioButton maBtnHorNone ; RadioButton maBtnHorLeft ; RadioButton maBtnHorCenter ; RadioButton maBtnHorDistance ; RadioButton maBtnHorRight ; FixedImage maHorLow ; FixedImage maHorCenter ; FixedImage maHorDistance ; FixedImage maHorHigh ; FixedLine maFlVertical ; RadioButton maBtnVerNone ; RadioButton maBtnVerTop ; RadioButton maBtnVerCenter ; RadioButton maBtnVerDistance ; RadioButton maBtnVerBottom ; FixedImage maVerLow ; FixedImage maVerCenter ; FixedImage maVerDistance ; FixedImage maVerHigh ; public: SvxDistributePage(Window* pWindow, const SfxItemSet& rInAttrs, SvxDistributeHorizontal eHor = SvxDistributeHorizontalNone, SvxDistributeVertical eVer = SvxDistributeVerticalNone); ~SvxDistributePage(); static SfxTabPage* Create(Window*, const SfxItemSet&, SvxDistributeHorizontal eHor, SvxDistributeVertical eVer); static UINT16* GetRanges(); virtual BOOL FillItemSet(SfxItemSet&); virtual void Reset(const SfxItemSet&); virtual void PointChanged(Window* pWindow, RECT_POINT eRP); SvxDistributeHorizontal GetDistributeHor() const { return meDistributeHor; } SvxDistributeVertical GetDistributeVer() const { return meDistributeVer; } }; /************************************************************************* |* \************************************************************************/ class SvxDistributeDialog : public SfxSingleTabDialog { SvxDistributePage* mpPage; public: SvxDistributeDialog(Window* pParent, const SfxItemSet& rAttr, SvxDistributeHorizontal eHor = SvxDistributeHorizontalNone, SvxDistributeVertical eVer = SvxDistributeVerticalNone); ~SvxDistributeDialog(); SvxDistributeHorizontal GetDistributeHor() const { return mpPage->GetDistributeHor(); } SvxDistributeVertical GetDistributeVer() const { return mpPage->GetDistributeVer(); } }; #endif // _SVX_DSTRIBUT_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.5.368); FILE MERGED 2008/04/01 15:50:19 thb 1.5.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:11 thb 1.5.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:24 rt 1.5.368.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: dstribut.hxx,v $ * $Revision: 1.6 $ * * 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. * ************************************************************************/ #ifndef _SVX_DSTRIBUT_HXX #define _SVX_DSTRIBUT_HXX #include <svx/dlgctrl.hxx> #include <vcl/group.hxx> #include <vcl/fixed.hxx> #include <svx/dstribut_enum.hxx> //CHINA001 /************************************************************************* |* \************************************************************************/ /* enum SvxDistributeHorizontal { SvxDistributeHorizontalNone = 0, SvxDistributeHorizontalLeft, SvxDistributeHorizontalCenter, SvxDistributeHorizontalDistance, SvxDistributeHorizontalRight }; enum SvxDistributeVertical { SvxDistributeVerticalNone = 0, SvxDistributeVerticalTop, SvxDistributeVerticalCenter, SvxDistributeVerticalDistance, SvxDistributeVerticalBottom }; */ /************************************************************************* |* \************************************************************************/ class SvxDistributePage : public SvxTabPage { SvxDistributeHorizontal meDistributeHor; SvxDistributeVertical meDistributeVer; FixedLine maFlHorizontal ; RadioButton maBtnHorNone ; RadioButton maBtnHorLeft ; RadioButton maBtnHorCenter ; RadioButton maBtnHorDistance ; RadioButton maBtnHorRight ; FixedImage maHorLow ; FixedImage maHorCenter ; FixedImage maHorDistance ; FixedImage maHorHigh ; FixedLine maFlVertical ; RadioButton maBtnVerNone ; RadioButton maBtnVerTop ; RadioButton maBtnVerCenter ; RadioButton maBtnVerDistance ; RadioButton maBtnVerBottom ; FixedImage maVerLow ; FixedImage maVerCenter ; FixedImage maVerDistance ; FixedImage maVerHigh ; public: SvxDistributePage(Window* pWindow, const SfxItemSet& rInAttrs, SvxDistributeHorizontal eHor = SvxDistributeHorizontalNone, SvxDistributeVertical eVer = SvxDistributeVerticalNone); ~SvxDistributePage(); static SfxTabPage* Create(Window*, const SfxItemSet&, SvxDistributeHorizontal eHor, SvxDistributeVertical eVer); static UINT16* GetRanges(); virtual BOOL FillItemSet(SfxItemSet&); virtual void Reset(const SfxItemSet&); virtual void PointChanged(Window* pWindow, RECT_POINT eRP); SvxDistributeHorizontal GetDistributeHor() const { return meDistributeHor; } SvxDistributeVertical GetDistributeVer() const { return meDistributeVer; } }; /************************************************************************* |* \************************************************************************/ class SvxDistributeDialog : public SfxSingleTabDialog { SvxDistributePage* mpPage; public: SvxDistributeDialog(Window* pParent, const SfxItemSet& rAttr, SvxDistributeHorizontal eHor = SvxDistributeHorizontalNone, SvxDistributeVertical eVer = SvxDistributeVerticalNone); ~SvxDistributeDialog(); SvxDistributeHorizontal GetDistributeHor() const { return mpPage->GetDistributeHor(); } SvxDistributeVertical GetDistributeVer() const { return mpPage->GetDistributeVer(); } }; #endif // _SVX_DSTRIBUT_HXX <|endoftext|>
<commit_before>#include "databasewizard.h" #include "traycontrol.h" #include <QApplication> #include <QDebug> #include <dialogmaster.h> #include <databasecontroller.h> #include "contentdialog.h" #include "editpackageswidget.h" TrayControl::TrayControl(QObject *parent) : QObject(parent), _tray(new QSystemTrayIcon(QIcon(QStringLiteral(":/icons/tray.ico")), this)), _trayMenu(new QMenu()) { _trayMenu->addAction(QIcon::fromTheme("package-new"), tr("Change Database"), this, &TrayControl::changeDatabase); _trayMenu->addSeparator(); _trayMenu->addAction(QIcon::fromTheme("package-upgrade"), tr("Edit Packages"), this, &TrayControl::editPackages); _trayMenu->addSeparator(); _trayMenu->addAction(QIcon::fromTheme("help-about"), tr("About"), this, &TrayControl::about); _trayMenu->addAction(QIcon::fromTheme("qt-logo"), tr("About Qt"), qApp, &QApplication::aboutQt); _trayMenu->addSeparator(); _trayMenu->addAction(QIcon::fromTheme("gtk-quit"), tr("Quit"), qApp, &QApplication::quit); _tray->setContextMenu(_trayMenu); _tray->setToolTip(QApplication::applicationDisplayName()); _tray->show(); } TrayControl::~TrayControl() { _trayMenu->deleteLater(); } void TrayControl::changeDatabase() { DatabaseWizard::run(); } void TrayControl::editPackages() { auto ctr = DatabaseController::instance(); auto ok = false; auto packages = ContentDialog::execute<EditPackagesWidget, QStringList>(ctr->listPackages(), nullptr, &ok); if(ok) { ctr->updateDb(packages); ctr->sync(); } } void TrayControl::about() { DialogMaster::about(nullptr, tr("TODO"), true, QStringLiteral("https://github.com/Baum42/pacsync")); } <commit_msg>remove unused sync<commit_after>#include "databasewizard.h" #include "traycontrol.h" #include <QApplication> #include <QDebug> #include <dialogmaster.h> #include <databasecontroller.h> #include "contentdialog.h" #include "editpackageswidget.h" TrayControl::TrayControl(QObject *parent) : QObject(parent), _tray(new QSystemTrayIcon(QIcon(QStringLiteral(":/icons/tray.ico")), this)), _trayMenu(new QMenu()) { _trayMenu->addAction(QIcon::fromTheme("package-new"), tr("Change Database"), this, &TrayControl::changeDatabase); _trayMenu->addSeparator(); _trayMenu->addAction(QIcon::fromTheme("package-upgrade"), tr("Edit Packages"), this, &TrayControl::editPackages); _trayMenu->addSeparator(); _trayMenu->addAction(QIcon::fromTheme("help-about"), tr("About"), this, &TrayControl::about); _trayMenu->addAction(QIcon::fromTheme("qt-logo"), tr("About Qt"), qApp, &QApplication::aboutQt); _trayMenu->addSeparator(); _trayMenu->addAction(QIcon::fromTheme("gtk-quit"), tr("Quit"), qApp, &QApplication::quit); _tray->setContextMenu(_trayMenu); _tray->setToolTip(QApplication::applicationDisplayName()); _tray->show(); } TrayControl::~TrayControl() { _trayMenu->deleteLater(); } void TrayControl::changeDatabase() { DatabaseWizard::run(); } void TrayControl::editPackages() { auto ctr = DatabaseController::instance(); auto ok = false; auto packages = ContentDialog::execute<EditPackagesWidget, QStringList>(ctr->listPackages(), nullptr, &ok); if(ok) ctr->updateDb(packages); } void TrayControl::about() { DialogMaster::about(nullptr, tr("TODO"), true, QStringLiteral("https://github.com/Baum42/pacsync")); } <|endoftext|>
<commit_before>/************************************************************************ This file is part of Freekick. Freekick 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. Freekick 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 Freekick. If not, see <http://www.gnu.org/licenses/>. Copyright Antti Salonen, 2008 This file was generated on So Okt 26 2008 at 12:09:20 **************************************************************************/ #include "Pitch.h" namespace freekick { namespace soccer { Pitch::Pitch (float w, float l) : width(w), length(l) { float half_width = width / 2.0f; float goal_area_left = half_width - (goal_width / 2.0f) - goal_area_width; float goal_area_right = half_width + (goal_width / 2.0f) + goal_area_width; float goal_area_up = goal_area_length; float goal_area_down = length - goal_area_length; goal_area_points[0] = addutil::Vector3(goal_area_left, 0.0f, 0.0f); goal_area_points[1] = addutil::Vector3(goal_area_right, 0.0f, goal_area_up); goal_area_points[2] = addutil::Vector3(goal_area_left, 0.0f, goal_area_down); goal_area_points[3] = addutil::Vector3(goal_area_right, 0.0f, length); float penalty_box_area_left = half_width - penalty_box_area_width / 2.0f; float penalty_box_area_right = half_width + penalty_box_area_width / 2.0f; float penalty_box_area_up = penalty_box_area_length; float penalty_box_area_down = length - penalty_box_area_length; penalty_box_area_points[0] = addutil::Vector3(penalty_box_area_left, 0.0f, 0.0f); penalty_box_area_points[1] = addutil::Vector3(penalty_box_area_right, 0.0f, penalty_box_area_up); penalty_box_area_points[2] = addutil::Vector3(penalty_box_area_left, 0.0f, penalty_box_area_down); penalty_box_area_points[3] = addutil::Vector3(penalty_box_area_right, 0.0f, length); } float Pitch::getWidth() const { return width; } float Pitch::getLength() const { return length; } bool Pitch::onPitch(float x, float y) const { if(x < 0.0f || y < 0.0f || x > width || y > length) return false; return true; } bool Pitch::onSide(bool top, float x, float y) const { if(!onPitch(x, y)) return false; bool ontopside = (y < (length / 2.0f)); if(top) return ontopside; return !ontopside; } bool Pitch::inFirstGoal(const addutil::Vector3& v) const { if(!maybeInGoal(v.x, v.y, v.z)) return false; return (v.z < 0.0f); } bool Pitch::inSecondGoal(const addutil::Vector3& v) const { if(!maybeInGoal(v.x, v.y, v.z)) return false; return (v.z > length); } bool Pitch::inFirstGoal(float x, float y, float z) const { return inFirstGoal(addutil::Vector3(x, y, z)); } bool Pitch::inSecondGoal(float x, float y, float z) const { return inSecondGoal(addutil::Vector3(x, y, z)); } bool Pitch::maybeInGoal(float x, float y, float z) const { if(onPitch(x, z)) return false; if(abs((width / 2.0f) - x) > goal_width) return false; if(y < 0.0f || y > goal_height) return false; return true; } GoalQuery Pitch::inGoalArea(const addutil::Vector3& v) const { if(addutil::inArea(goal_area_points[0], goal_area_points[1], v)) return HomeGoal; if(addutil::inArea(goal_area_points[2], goal_area_points[3], v)) return AwayGoal; return NoGoal; } GoalQuery Pitch::inPenaltyBoxArea(const addutil::Vector3& v) const { if(addutil::inArea(penalty_box_area_points[0], penalty_box_area_points[1], v)) return HomeGoal; if(addutil::inArea(penalty_box_area_points[2], penalty_box_area_points[3], v)) return AwayGoal; return NoGoal; } } } <commit_msg>libsoccer: fixed goal checking<commit_after>/************************************************************************ This file is part of Freekick. Freekick 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. Freekick 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 Freekick. If not, see <http://www.gnu.org/licenses/>. Copyright Antti Salonen, 2008 This file was generated on So Okt 26 2008 at 12:09:20 **************************************************************************/ #include "Pitch.h" namespace freekick { namespace soccer { Pitch::Pitch (float w, float l) : width(w), length(l) { float half_width = width / 2.0f; float goal_area_left = half_width - (goal_width / 2.0f) - goal_area_width; float goal_area_right = half_width + (goal_width / 2.0f) + goal_area_width; float goal_area_up = goal_area_length; float goal_area_down = length - goal_area_length; goal_area_points[0] = addutil::Vector3(goal_area_left, 0.0f, 0.0f); goal_area_points[1] = addutil::Vector3(goal_area_right, 0.0f, goal_area_up); goal_area_points[2] = addutil::Vector3(goal_area_left, 0.0f, goal_area_down); goal_area_points[3] = addutil::Vector3(goal_area_right, 0.0f, length); float penalty_box_area_left = half_width - penalty_box_area_width / 2.0f; float penalty_box_area_right = half_width + penalty_box_area_width / 2.0f; float penalty_box_area_up = penalty_box_area_length; float penalty_box_area_down = length - penalty_box_area_length; penalty_box_area_points[0] = addutil::Vector3(penalty_box_area_left, 0.0f, 0.0f); penalty_box_area_points[1] = addutil::Vector3(penalty_box_area_right, 0.0f, penalty_box_area_up); penalty_box_area_points[2] = addutil::Vector3(penalty_box_area_left, 0.0f, penalty_box_area_down); penalty_box_area_points[3] = addutil::Vector3(penalty_box_area_right, 0.0f, length); } float Pitch::getWidth() const { return width; } float Pitch::getLength() const { return length; } bool Pitch::onPitch(float x, float y) const { if(x < 0.0f || y < 0.0f || x > width || y > length) return false; return true; } bool Pitch::onSide(bool top, float x, float y) const { if(!onPitch(x, y)) return false; bool ontopside = (y < (length / 2.0f)); if(top) return ontopside; return !ontopside; } bool Pitch::inFirstGoal(const addutil::Vector3& v) const { if(!maybeInGoal(v.x, v.y, v.z)) return false; return (v.z < 0.0f); } bool Pitch::inSecondGoal(const addutil::Vector3& v) const { if(!maybeInGoal(v.x, v.y, v.z)) return false; return (v.z > length); } bool Pitch::inFirstGoal(float x, float y, float z) const { return inFirstGoal(addutil::Vector3(x, y, z)); } bool Pitch::inSecondGoal(float x, float y, float z) const { return inSecondGoal(addutil::Vector3(x, y, z)); } bool Pitch::maybeInGoal(float x, float y, float z) const { if(onPitch(x, z)) return false; if(abs((width * 0.5f) - x) > goal_width * 0.5f) return false; if(y < 0.0f || y > goal_height) return false; return true; } GoalQuery Pitch::inGoalArea(const addutil::Vector3& v) const { if(addutil::inArea(goal_area_points[0], goal_area_points[1], v)) return HomeGoal; if(addutil::inArea(goal_area_points[2], goal_area_points[3], v)) return AwayGoal; return NoGoal; } GoalQuery Pitch::inPenaltyBoxArea(const addutil::Vector3& v) const { if(addutil::inArea(penalty_box_area_points[0], penalty_box_area_points[1], v)) return HomeGoal; if(addutil::inArea(penalty_box_area_points[2], penalty_box_area_points[3], v)) return AwayGoal; return NoGoal; } } } <|endoftext|>
<commit_before>/* * kwallet.cpp: KWallet provider for SVN_AUTH_CRED_* * * ==================================================================== * 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. * ==================================================================== */ /* ==================================================================== */ /*** Includes. ***/ #include <stdlib.h> #include <string.h> #include <unistd.h> #include <apr_pools.h> #include <apr_strings.h> #include "svn_auth.h" #include "svn_config.h" #include "svn_error.h" #include "svn_io.h" #include "svn_pools.h" #include "svn_string.h" #include "svn_version.h" #include "private/svn_auth_private.h" #include "svn_private_config.h" #include <dbus/dbus.h> #include <QtCore/QCoreApplication> #include <QtCore/QString> #include <kaboutdata.h> #include <kcmdlineargs.h> #include <kcomponentdata.h> #include <klocalizedstring.h> #include <kwallet.h> /*-----------------------------------------------------------------------*/ /* KWallet simple provider, puts passwords in KWallet */ /*-----------------------------------------------------------------------*/ static const char * get_application_name(apr_hash_t *parameters, apr_pool_t *pool) { svn_config_t *config = static_cast<svn_config_t *> (apr_hash_get(parameters, SVN_AUTH_PARAM_CONFIG_CATEGORY_CONFIG, APR_HASH_KEY_STRING)); svn_boolean_t svn_application_name_with_pid; svn_config_get_bool(config, &svn_application_name_with_pid, SVN_CONFIG_SECTION_AUTH, SVN_CONFIG_OPTION_KWALLET_SVN_APPLICATION_NAME_WITH_PID, FALSE); const char *svn_application_name; if (svn_application_name_with_pid) { svn_application_name = apr_psprintf(pool, "Subversion [%ld]", long(getpid())); } else { svn_application_name = "Subversion"; } return svn_application_name; } static QString get_wallet_name(apr_hash_t *parameters) { svn_config_t *config = static_cast<svn_config_t *> (apr_hash_get(parameters, SVN_AUTH_PARAM_CONFIG_CATEGORY_CONFIG, APR_HASH_KEY_STRING)); const char *wallet_name; svn_config_get(config, &wallet_name, SVN_CONFIG_SECTION_AUTH, SVN_CONFIG_OPTION_KWALLET_WALLET, ""); if (strcmp(wallet_name, "") == 0) { return KWallet::Wallet::NetworkWallet(); } else { return QString::fromUtf8(wallet_name); } } static WId get_wid(void) { WId wid = 1; const char *wid_env_string = getenv("WINDOWID"); if (wid_env_string) { apr_int64_t wid_env; svn_error_t *err; err = svn_cstring_atoi64(&wid_env, wid_env_string); if (err) svn_error_clear(err); else wid = (WId)wid_env; } return wid; } static KWallet::Wallet * get_wallet(QString wallet_name, apr_hash_t *parameters) { KWallet::Wallet *wallet = static_cast<KWallet::Wallet *> (apr_hash_get(parameters, "kwallet-wallet", APR_HASH_KEY_STRING)); if (! wallet && ! apr_hash_get(parameters, "kwallet-opening-failed", APR_HASH_KEY_STRING)) { wallet = KWallet::Wallet::openWallet(wallet_name, get_wid(), KWallet::Wallet::Synchronous); } if (wallet) { apr_hash_set(parameters, "kwallet-wallet", APR_HASH_KEY_STRING, wallet); } else { apr_hash_set(parameters, "kwallet-opening-failed", APR_HASH_KEY_STRING, ""); } return wallet; } static apr_status_t kwallet_terminate(void *data) { apr_hash_t *parameters = static_cast<apr_hash_t *> (data); if (apr_hash_get(parameters, "kwallet-initialized", APR_HASH_KEY_STRING)) { KWallet::Wallet *wallet = get_wallet(NULL, parameters); delete wallet; apr_hash_set(parameters, "kwallet-initialized", APR_HASH_KEY_STRING, NULL); } return APR_SUCCESS; } /* Implementation of svn_auth__password_get_t that retrieves the password from KWallet. */ static svn_boolean_t kwallet_password_get(const char **password, apr_hash_t *creds, const char *realmstring, const char *username, apr_hash_t *parameters, svn_boolean_t non_interactive, apr_pool_t *pool) { if (non_interactive) { return FALSE; } if (! dbus_bus_get(DBUS_BUS_SESSION, NULL)) { return FALSE; } QCoreApplication *app; if (! qApp) { int argc = 1; app = new QCoreApplication(argc, (char *[1]) {(char *) "svn"}); } KCmdLineArgs::init(1, (char *[1]) {(char *) "svn"}, get_application_name(parameters, pool), "subversion", ki18n(get_application_name(parameters, pool)), SVN_VER_NUMBER, ki18n("Version control system"), KCmdLineArgs::CmdLineArgKDE); KComponentData component_data(KCmdLineArgs::aboutData()); svn_boolean_t ret = FALSE; QString wallet_name = get_wallet_name(parameters); QString folder = QString::fromUtf8("Subversion"); QString key = QString::fromUtf8(username) + "@" + QString::fromUtf8(realmstring); if (! KWallet::Wallet::keyDoesNotExist(wallet_name, folder, key)) { KWallet::Wallet *wallet = get_wallet(wallet_name, parameters); if (wallet) { apr_hash_set(parameters, "kwallet-initialized", APR_HASH_KEY_STRING, ""); if (wallet->setFolder(folder)) { QString q_password; if (wallet->readPassword(key, q_password) == 0) { *password = apr_pstrmemdup(pool, q_password.toUtf8().data(), q_password.size()); ret = TRUE; } } } } apr_pool_cleanup_register(pool, parameters, kwallet_terminate, NULL); return ret; } /* Implementation of svn_auth__password_set_t that stores the password in KWallet. */ static svn_boolean_t kwallet_password_set(apr_hash_t *creds, const char *realmstring, const char *username, const char *password, apr_hash_t *parameters, svn_boolean_t non_interactive, apr_pool_t *pool) { if (non_interactive) { return FALSE; } if (! dbus_bus_get(DBUS_BUS_SESSION, NULL)) { return FALSE; } QCoreApplication *app; if (! qApp) { int argc = 1; app = new QCoreApplication(argc, (char *[1]) {(char *) "svn"}); } KCmdLineArgs::init(1, (char *[1]) {(char *) "svn"}, get_application_name(parameters, pool), "subversion", ki18n(get_application_name(parameters, pool)), SVN_VER_NUMBER, ki18n("Version control system"), KCmdLineArgs::CmdLineArgKDE); KComponentData component_data(KCmdLineArgs::aboutData()); svn_boolean_t ret = FALSE; QString q_password = QString::fromUtf8(password); QString wallet_name = get_wallet_name(parameters); QString folder = QString::fromUtf8("Subversion"); KWallet::Wallet *wallet = get_wallet(wallet_name, parameters); if (wallet) { apr_hash_set(parameters, "kwallet-initialized", APR_HASH_KEY_STRING, ""); if (! wallet->hasFolder(folder)) { wallet->createFolder(folder); } if (wallet->setFolder(folder)) { QString key = QString::fromUtf8(username) + "@" + QString::fromUtf8(realmstring); if (wallet->writePassword(key, q_password) == 0) { ret = TRUE; } } } apr_pool_cleanup_register(pool, parameters, kwallet_terminate, NULL); return ret; } /* Get cached encrypted credentials from the simple provider's cache. */ static svn_error_t * kwallet_simple_first_creds(void **credentials, void **iter_baton, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__simple_first_creds_helper(credentials, iter_baton, provider_baton, parameters, realmstring, kwallet_password_get, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } /* Save encrypted credentials to the simple provider's cache. */ static svn_error_t * kwallet_simple_save_creds(svn_boolean_t *saved, void *credentials, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__simple_save_creds_helper(saved, credentials, provider_baton, parameters, realmstring, kwallet_password_set, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } static const svn_auth_provider_t kwallet_simple_provider = { SVN_AUTH_CRED_SIMPLE, kwallet_simple_first_creds, NULL, kwallet_simple_save_creds }; /* Public API */ extern "C" { void svn_auth_get_kwallet_simple_provider(svn_auth_provider_object_t **provider, apr_pool_t *pool) { svn_auth_provider_object_t *po = static_cast<svn_auth_provider_object_t *> (apr_pcalloc(pool, sizeof(*po))); po->vtable = &kwallet_simple_provider; *provider = po; } } /*-----------------------------------------------------------------------*/ /* KWallet SSL client certificate passphrase provider, */ /* puts passphrases in KWallet */ /*-----------------------------------------------------------------------*/ /* Get cached encrypted credentials from the ssl client cert password provider's cache. */ static svn_error_t * kwallet_ssl_client_cert_pw_first_creds(void **credentials, void **iter_baton, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__ssl_client_cert_pw_file_first_creds_helper (credentials, iter_baton, provider_baton, parameters, realmstring, kwallet_password_get, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } /* Save encrypted credentials to the ssl client cert password provider's cache. */ static svn_error_t * kwallet_ssl_client_cert_pw_save_creds(svn_boolean_t *saved, void *credentials, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__ssl_client_cert_pw_file_save_creds_helper (saved, credentials, provider_baton, parameters, realmstring, kwallet_password_set, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } static const svn_auth_provider_t kwallet_ssl_client_cert_pw_provider = { SVN_AUTH_CRED_SSL_CLIENT_CERT_PW, kwallet_ssl_client_cert_pw_first_creds, NULL, kwallet_ssl_client_cert_pw_save_creds }; /* Public API */ void svn_auth_get_kwallet_ssl_client_cert_pw_provider (svn_auth_provider_object_t **provider, apr_pool_t *pool) { svn_auth_provider_object_t *po = static_cast<svn_auth_provider_object_t *> (apr_pcalloc(pool, sizeof(*po))); po->vtable = &kwallet_ssl_client_cert_pw_provider; *provider = po; } <commit_msg>* subversion/libsvn_auth_kwallet/kwallet.cpp (svn_auth_get_kwallet_ssl_client_cert_pw_provider): Wrap this public function in an extern "C" block, just like svn_auth_get_kwallet_simple_provider().<commit_after>/* * kwallet.cpp: KWallet provider for SVN_AUTH_CRED_* * * ==================================================================== * 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. * ==================================================================== */ /* ==================================================================== */ /*** Includes. ***/ #include <stdlib.h> #include <string.h> #include <unistd.h> #include <apr_pools.h> #include <apr_strings.h> #include "svn_auth.h" #include "svn_config.h" #include "svn_error.h" #include "svn_io.h" #include "svn_pools.h" #include "svn_string.h" #include "svn_version.h" #include "private/svn_auth_private.h" #include "svn_private_config.h" #include <dbus/dbus.h> #include <QtCore/QCoreApplication> #include <QtCore/QString> #include <kaboutdata.h> #include <kcmdlineargs.h> #include <kcomponentdata.h> #include <klocalizedstring.h> #include <kwallet.h> /*-----------------------------------------------------------------------*/ /* KWallet simple provider, puts passwords in KWallet */ /*-----------------------------------------------------------------------*/ static const char * get_application_name(apr_hash_t *parameters, apr_pool_t *pool) { svn_config_t *config = static_cast<svn_config_t *> (apr_hash_get(parameters, SVN_AUTH_PARAM_CONFIG_CATEGORY_CONFIG, APR_HASH_KEY_STRING)); svn_boolean_t svn_application_name_with_pid; svn_config_get_bool(config, &svn_application_name_with_pid, SVN_CONFIG_SECTION_AUTH, SVN_CONFIG_OPTION_KWALLET_SVN_APPLICATION_NAME_WITH_PID, FALSE); const char *svn_application_name; if (svn_application_name_with_pid) { svn_application_name = apr_psprintf(pool, "Subversion [%ld]", long(getpid())); } else { svn_application_name = "Subversion"; } return svn_application_name; } static QString get_wallet_name(apr_hash_t *parameters) { svn_config_t *config = static_cast<svn_config_t *> (apr_hash_get(parameters, SVN_AUTH_PARAM_CONFIG_CATEGORY_CONFIG, APR_HASH_KEY_STRING)); const char *wallet_name; svn_config_get(config, &wallet_name, SVN_CONFIG_SECTION_AUTH, SVN_CONFIG_OPTION_KWALLET_WALLET, ""); if (strcmp(wallet_name, "") == 0) { return KWallet::Wallet::NetworkWallet(); } else { return QString::fromUtf8(wallet_name); } } static WId get_wid(void) { WId wid = 1; const char *wid_env_string = getenv("WINDOWID"); if (wid_env_string) { apr_int64_t wid_env; svn_error_t *err; err = svn_cstring_atoi64(&wid_env, wid_env_string); if (err) svn_error_clear(err); else wid = (WId)wid_env; } return wid; } static KWallet::Wallet * get_wallet(QString wallet_name, apr_hash_t *parameters) { KWallet::Wallet *wallet = static_cast<KWallet::Wallet *> (apr_hash_get(parameters, "kwallet-wallet", APR_HASH_KEY_STRING)); if (! wallet && ! apr_hash_get(parameters, "kwallet-opening-failed", APR_HASH_KEY_STRING)) { wallet = KWallet::Wallet::openWallet(wallet_name, get_wid(), KWallet::Wallet::Synchronous); } if (wallet) { apr_hash_set(parameters, "kwallet-wallet", APR_HASH_KEY_STRING, wallet); } else { apr_hash_set(parameters, "kwallet-opening-failed", APR_HASH_KEY_STRING, ""); } return wallet; } static apr_status_t kwallet_terminate(void *data) { apr_hash_t *parameters = static_cast<apr_hash_t *> (data); if (apr_hash_get(parameters, "kwallet-initialized", APR_HASH_KEY_STRING)) { KWallet::Wallet *wallet = get_wallet(NULL, parameters); delete wallet; apr_hash_set(parameters, "kwallet-initialized", APR_HASH_KEY_STRING, NULL); } return APR_SUCCESS; } /* Implementation of svn_auth__password_get_t that retrieves the password from KWallet. */ static svn_boolean_t kwallet_password_get(const char **password, apr_hash_t *creds, const char *realmstring, const char *username, apr_hash_t *parameters, svn_boolean_t non_interactive, apr_pool_t *pool) { if (non_interactive) { return FALSE; } if (! dbus_bus_get(DBUS_BUS_SESSION, NULL)) { return FALSE; } QCoreApplication *app; if (! qApp) { int argc = 1; app = new QCoreApplication(argc, (char *[1]) {(char *) "svn"}); } KCmdLineArgs::init(1, (char *[1]) {(char *) "svn"}, get_application_name(parameters, pool), "subversion", ki18n(get_application_name(parameters, pool)), SVN_VER_NUMBER, ki18n("Version control system"), KCmdLineArgs::CmdLineArgKDE); KComponentData component_data(KCmdLineArgs::aboutData()); svn_boolean_t ret = FALSE; QString wallet_name = get_wallet_name(parameters); QString folder = QString::fromUtf8("Subversion"); QString key = QString::fromUtf8(username) + "@" + QString::fromUtf8(realmstring); if (! KWallet::Wallet::keyDoesNotExist(wallet_name, folder, key)) { KWallet::Wallet *wallet = get_wallet(wallet_name, parameters); if (wallet) { apr_hash_set(parameters, "kwallet-initialized", APR_HASH_KEY_STRING, ""); if (wallet->setFolder(folder)) { QString q_password; if (wallet->readPassword(key, q_password) == 0) { *password = apr_pstrmemdup(pool, q_password.toUtf8().data(), q_password.size()); ret = TRUE; } } } } apr_pool_cleanup_register(pool, parameters, kwallet_terminate, NULL); return ret; } /* Implementation of svn_auth__password_set_t that stores the password in KWallet. */ static svn_boolean_t kwallet_password_set(apr_hash_t *creds, const char *realmstring, const char *username, const char *password, apr_hash_t *parameters, svn_boolean_t non_interactive, apr_pool_t *pool) { if (non_interactive) { return FALSE; } if (! dbus_bus_get(DBUS_BUS_SESSION, NULL)) { return FALSE; } QCoreApplication *app; if (! qApp) { int argc = 1; app = new QCoreApplication(argc, (char *[1]) {(char *) "svn"}); } KCmdLineArgs::init(1, (char *[1]) {(char *) "svn"}, get_application_name(parameters, pool), "subversion", ki18n(get_application_name(parameters, pool)), SVN_VER_NUMBER, ki18n("Version control system"), KCmdLineArgs::CmdLineArgKDE); KComponentData component_data(KCmdLineArgs::aboutData()); svn_boolean_t ret = FALSE; QString q_password = QString::fromUtf8(password); QString wallet_name = get_wallet_name(parameters); QString folder = QString::fromUtf8("Subversion"); KWallet::Wallet *wallet = get_wallet(wallet_name, parameters); if (wallet) { apr_hash_set(parameters, "kwallet-initialized", APR_HASH_KEY_STRING, ""); if (! wallet->hasFolder(folder)) { wallet->createFolder(folder); } if (wallet->setFolder(folder)) { QString key = QString::fromUtf8(username) + "@" + QString::fromUtf8(realmstring); if (wallet->writePassword(key, q_password) == 0) { ret = TRUE; } } } apr_pool_cleanup_register(pool, parameters, kwallet_terminate, NULL); return ret; } /* Get cached encrypted credentials from the simple provider's cache. */ static svn_error_t * kwallet_simple_first_creds(void **credentials, void **iter_baton, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__simple_first_creds_helper(credentials, iter_baton, provider_baton, parameters, realmstring, kwallet_password_get, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } /* Save encrypted credentials to the simple provider's cache. */ static svn_error_t * kwallet_simple_save_creds(svn_boolean_t *saved, void *credentials, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__simple_save_creds_helper(saved, credentials, provider_baton, parameters, realmstring, kwallet_password_set, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } static const svn_auth_provider_t kwallet_simple_provider = { SVN_AUTH_CRED_SIMPLE, kwallet_simple_first_creds, NULL, kwallet_simple_save_creds }; /* Public API */ extern "C" { void svn_auth_get_kwallet_simple_provider(svn_auth_provider_object_t **provider, apr_pool_t *pool) { svn_auth_provider_object_t *po = static_cast<svn_auth_provider_object_t *> (apr_pcalloc(pool, sizeof(*po))); po->vtable = &kwallet_simple_provider; *provider = po; } } /*-----------------------------------------------------------------------*/ /* KWallet SSL client certificate passphrase provider, */ /* puts passphrases in KWallet */ /*-----------------------------------------------------------------------*/ /* Get cached encrypted credentials from the ssl client cert password provider's cache. */ static svn_error_t * kwallet_ssl_client_cert_pw_first_creds(void **credentials, void **iter_baton, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__ssl_client_cert_pw_file_first_creds_helper (credentials, iter_baton, provider_baton, parameters, realmstring, kwallet_password_get, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } /* Save encrypted credentials to the ssl client cert password provider's cache. */ static svn_error_t * kwallet_ssl_client_cert_pw_save_creds(svn_boolean_t *saved, void *credentials, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__ssl_client_cert_pw_file_save_creds_helper (saved, credentials, provider_baton, parameters, realmstring, kwallet_password_set, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } static const svn_auth_provider_t kwallet_ssl_client_cert_pw_provider = { SVN_AUTH_CRED_SSL_CLIENT_CERT_PW, kwallet_ssl_client_cert_pw_first_creds, NULL, kwallet_ssl_client_cert_pw_save_creds }; /* Public API */ extern "C" { void svn_auth_get_kwallet_ssl_client_cert_pw_provider (svn_auth_provider_object_t **provider, apr_pool_t *pool) { svn_auth_provider_object_t *po = static_cast<svn_auth_provider_object_t *> (apr_pcalloc(pool, sizeof(*po))); po->vtable = &kwallet_ssl_client_cert_pw_provider; *provider = po; } } <|endoftext|>
<commit_before>/* * Ascent MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * * This program 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 * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. * */ /* Arena and Honor Point Calculation System * Copyright (c) 2007 Burlex */ #include "StdAfx.h" #ifdef WIN32 static HANDLE m_abortEvent = INVALID_HANDLE_VALUE; #else static pthread_cond_t abortcond; static pthread_mutex_t abortmutex; #endif DayWatcherThread::DayWatcherThread() { m_running = true; m_dirty = false; } DayWatcherThread::~DayWatcherThread() { } void DayWatcherThread::terminate() { m_running = false; #ifdef WIN32 SetEvent(m_abortEvent); #else pthread_cond_signal(&abortcond); #endif } void DayWatcherThread::dupe_tm_pointer(tm * returnvalue, tm * mypointer) { memcpy(mypointer, returnvalue, sizeof(tm)); } void DayWatcherThread::update_settings() { CharacterDatabase.Execute("REPLACE INTO server_settings VALUES(\"last_honor_update_time\", %u)", last_honor_time); CharacterDatabase.Execute("REPLACE INTO server_settings VALUES(\"last_arena_update_time\", %u)", last_arena_time); } void DayWatcherThread::load_settings() { string honor_timeout = Config.MainConfig.GetStringDefault("Periods", "HonorUpdate", "daily"); string arena_timeout = Config.MainConfig.GetStringDefault("Periods", "ArenaUpdate", "weekly"); honor_period = get_timeout_from_string(honor_timeout.c_str(), DAILY); arena_period = get_timeout_from_string(arena_timeout.c_str(), WEEKLY); QueryResult * result = CharacterDatabase.Query("SELECT setting_value FROM server_settings WHERE setting_id = \"last_honor_update_time\""); if(result) { last_honor_time = result->Fetch()[0].GetUInt32(); delete result; } else last_honor_time = 0; result = CharacterDatabase.Query("SELECT setting_value FROM server_settings WHERE setting_id = \"last_arena_update_time\""); if(result) { last_arena_time = result->Fetch()[0].GetUInt32(); delete result; } else last_arena_time = 0; } void DayWatcherThread::set_tm_pointers() { dupe_tm_pointer(localtime(&last_arena_time), &local_last_arena_time); dupe_tm_pointer(localtime(&last_honor_time), &local_last_honor_time); } uint32 DayWatcherThread::get_timeout_from_string(const char * string, uint32 def) { if(!stricmp(string, "weekly")) return WEEKLY; else if(!stricmp(string, "monthly")) return MONTHLY; else if(!stricmp(string, "daily")) return DAILY; else if(!stricmp(string, "hourly")) return HOURLY; else return def; } bool DayWatcherThread::has_timeout_expired(tm * now_time, tm * last_time, uint32 timeoutval) { switch(timeoutval) { case WEEKLY: { if( (now_time->tm_mon != last_time->tm_mon) ) return true; return ( (now_time->tm_mday / 7) != (last_time->tm_mday / 7) ); } case MONTHLY: return (now_time->tm_mon != last_time->tm_mon); case HOURLY: return ((now_time->tm_hour != last_time->tm_hour) || (now_time->tm_mday != last_time->tm_mday) || (now_time->tm_mon != last_time->tm_mon)); case DAILY: return ((now_time->tm_mday != last_time->tm_mday) || (now_time->tm_mday != last_time->tm_mday)); } return false; } bool DayWatcherThread::run() { Log.Notice("DayWatcherThread", "Started."); currenttime = UNIXTIME; dupe_tm_pointer(localtime(&currenttime), &local_currenttime); load_settings(); set_tm_pointers(); m_busy = false; #ifdef WIN32 m_abortEvent = CreateEvent(NULL, NULL, FALSE, NULL); #else struct timeval now; struct timespec tv; pthread_mutex_init(&abortmutex,NULL); pthread_cond_init(&abortcond,NULL); #endif while(ThreadState != THREADSTATE_TERMINATE) { m_busy=true; currenttime = UNIXTIME; dupe_tm_pointer(localtime(&currenttime), &local_currenttime); if(has_timeout_expired(&local_currenttime, &local_last_honor_time, honor_period)) update_honor(); if(has_timeout_expired(&local_currenttime, &local_last_arena_time, arena_period)) update_arena(); if(m_dirty) update_settings(); m_busy=false; if(ThreadState == THREADSTATE_TERMINATE) break; #ifdef WIN32 WaitForSingleObject(m_abortEvent, 120000); #else gettimeofday(&now, NULL); tv.tv_sec = now.tv_sec + 120; tv.tv_nsec = now.tv_usec * 1000; pthread_mutex_lock(&abortmutex); pthread_cond_timedwait(&abortcond, &abortmutex, &tv); pthread_mutex_unlock(&abortmutex); #endif if(!m_running) break; } #ifdef WIN32 CloseHandle(m_abortEvent); #else pthread_mutex_destroy(&abortmutex); pthread_cond_destroy(&abortcond); #endif return true; } void DayWatcherThread::update_arena() { Log.Notice("DayWatcherThread", "Running Weekly Arena Point Maintenance..."); QueryResult * result = CharacterDatabase.Query("SELECT guid, arenaPoints FROM characters"); /* this one is a little more intensive. */ Player * plr; uint32 guid, arenapoints, orig_arenapoints; ArenaTeam * team; double X, Y; if(result) { do { Field * f = result->Fetch(); guid = f[0].GetUInt32(); arenapoints = f[1].GetUInt32(); orig_arenapoints = arenapoints; /* are we in any arena teams? */ for(uint32 i = 0; i < 3; ++i) // 3 arena team types { team = objmgr.GetArenaTeamByGuid(guid, i); if(team) { /* TODO: In the future we might want to do a check that says is the player active in this arena team. * Private servers are kinda smaller so this probably isn't such a good idea. * - Burlex */ /* we're in an arena team of this type! */ /* Source: http://www.wowwiki.com/Arena_point */ X = (double)team->m_stat_rating; if(X <= 510.0) // "if X<=510" continue; // no change else if(X > 510.0 && X <= 1500.0) // "if 510 < X <= 1500" { Y = (0.22 * X) + 14.0; } else // "if X > 1500" { // http://eu.wowarmory.com/arena-calculator.xml // 1511.26 // --------------------------- // -0.00412*X // 1+1639.28*2.71828 double power = ((-0.00412) * X); //if(power < 1.0) // power = 1.0; double divisor = pow(((double)(2.71828)), power); divisor *= 1639.28; divisor += 1.0; //if(divisor < 1.0) // divisor = 1.0; Y = 1511.26 / divisor; } // 2v2 teams only earn 70% (Was 60% until 13th March 07) of the arena points, 3v3 teams get 80%, while 5v5 teams get 100% of the arena points. // 2v2 - 76%, 3v3 - 88% as of patch 2.2 if(team->m_type == ARENA_TEAM_TYPE_2V2) { Y *= 0.76; Y *= sWorld.getRate(RATE_ARENAPOINTMULTIPLIER2X); } else if(team->m_type == ARENA_TEAM_TYPE_3V3) { Y *= 0.88; Y *= sWorld.getRate(RATE_ARENAPOINTMULTIPLIER3X); } else { Y *= sWorld.getRate(RATE_ARENAPOINTMULTIPLIER5X); } if(Y > 1.0) arenapoints += long2int32(double(ceil(Y))); } } if(orig_arenapoints != arenapoints) { plr = objmgr.GetPlayer(guid); if(plr) { plr->m_arenaPoints = arenapoints; /* update visible fields (must be done through an event because of no uint lock */ sEventMgr.AddEvent(plr, &Player::RecalculateHonor, EVENT_PLAYER_UPDATE, 100, 1, 0); /* send a little message :> */ sChatHandler.SystemMessage(plr->GetSession(), "Your arena points have been updated! Check your PvP tab!"); } /* update in sql */ CharacterDatabase.Execute("UPDATE characters SET arenaPoints = %u WHERE guid = %u", arenapoints, guid); } }while(result->NextRow()); delete result; } //=========================================================================== last_arena_time = UNIXTIME; dupe_tm_pointer(localtime(&last_arena_time), &local_last_arena_time); m_dirty = true; } void DayWatcherThread::update_honor() { Log.Notice("DayWatcherThread", "Running Daily Honor Maintenance..."); uint32 guid, killstoday, killsyesterday, honortoday, honoryesterday, honorpoints, points_to_add; Player * plr; QueryResult * result = CharacterDatabase.Query("SELECT guid, killsToday, killsYesterday, honorToday, honorYesterday, honorPoints, honorPointsToAdd FROM characters"); if(result) { do { Field * f = result->Fetch(); guid = f[0].GetUInt32(); killstoday = f[1].GetUInt32(); killsyesterday = f[2].GetUInt32(); honortoday = f[3].GetUInt32(); honoryesterday = f[4].GetUInt32(); honorpoints = f[5].GetUInt32(); points_to_add = f[6].GetUInt32(); /* add his "honor points to be added" */ honorpoints += points_to_add; points_to_add = 0; /* update the yesterday fields */ killsyesterday = killstoday; honoryesterday = honortoday; honortoday = killstoday = 0; /* are we online? */ plr = objmgr.GetPlayer(guid); if(plr) { /* we're online, update our fields here too */ plr->m_honorPoints = honorpoints; plr->m_honorPointsToAdd = points_to_add; plr->m_honorToday = honortoday; plr->m_honorYesterday = honoryesterday; plr->m_killsToday = killstoday; plr->m_killsYesterday = killsyesterday; /* update visible fields (must be done through an event because of no uint lock */ sEventMgr.AddEvent(plr, &Player::RecalculateHonor, EVENT_PLAYER_UPDATE, 100, 1, 0); /* send a little message :> */ sChatHandler.SystemMessage(plr->GetSession(), "Your honor points have been updated! Check your PvP tab!"); } /* update in database */ CharacterDatabase.Execute("UPDATE characters SET killsToday = %u, killsYesterday = %u, honorToday = %u, honorYesterday = %u, honorPoints = %u, honorPointsToAdd = %u WHERE guid = %u", killstoday, killsyesterday, honortoday, honoryesterday, honorpoints, points_to_add, guid); } while(result->NextRow()); delete result; } //=========================================================================== last_honor_time = UNIXTIME; dupe_tm_pointer(localtime(&last_honor_time), &local_last_honor_time); m_dirty = true; } <commit_msg>- only arena points gained from team which grants them the most is now added, instead of adding a sum of all 3 (2v2 3v3 5v5) teams points<commit_after>/* * Ascent MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * * This program 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 * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. * */ /* Arena and Honor Point Calculation System * Copyright (c) 2007 Burlex */ #include "StdAfx.h" #ifdef WIN32 static HANDLE m_abortEvent = INVALID_HANDLE_VALUE; #else static pthread_cond_t abortcond; static pthread_mutex_t abortmutex; #endif DayWatcherThread::DayWatcherThread() { m_running = true; m_dirty = false; } DayWatcherThread::~DayWatcherThread() { } void DayWatcherThread::terminate() { m_running = false; #ifdef WIN32 SetEvent(m_abortEvent); #else pthread_cond_signal(&abortcond); #endif } void DayWatcherThread::dupe_tm_pointer(tm * returnvalue, tm * mypointer) { memcpy(mypointer, returnvalue, sizeof(tm)); } void DayWatcherThread::update_settings() { CharacterDatabase.Execute("REPLACE INTO server_settings VALUES(\"last_honor_update_time\", %u)", last_honor_time); CharacterDatabase.Execute("REPLACE INTO server_settings VALUES(\"last_arena_update_time\", %u)", last_arena_time); } void DayWatcherThread::load_settings() { string honor_timeout = Config.MainConfig.GetStringDefault("Periods", "HonorUpdate", "daily"); string arena_timeout = Config.MainConfig.GetStringDefault("Periods", "ArenaUpdate", "weekly"); honor_period = get_timeout_from_string(honor_timeout.c_str(), DAILY); arena_period = get_timeout_from_string(arena_timeout.c_str(), WEEKLY); QueryResult * result = CharacterDatabase.Query("SELECT setting_value FROM server_settings WHERE setting_id = \"last_honor_update_time\""); if(result) { last_honor_time = result->Fetch()[0].GetUInt32(); delete result; } else last_honor_time = 0; result = CharacterDatabase.Query("SELECT setting_value FROM server_settings WHERE setting_id = \"last_arena_update_time\""); if(result) { last_arena_time = result->Fetch()[0].GetUInt32(); delete result; } else last_arena_time = 0; } void DayWatcherThread::set_tm_pointers() { dupe_tm_pointer(localtime(&last_arena_time), &local_last_arena_time); dupe_tm_pointer(localtime(&last_honor_time), &local_last_honor_time); } uint32 DayWatcherThread::get_timeout_from_string(const char * string, uint32 def) { if(!stricmp(string, "weekly")) return WEEKLY; else if(!stricmp(string, "monthly")) return MONTHLY; else if(!stricmp(string, "daily")) return DAILY; else if(!stricmp(string, "hourly")) return HOURLY; else return def; } bool DayWatcherThread::has_timeout_expired(tm * now_time, tm * last_time, uint32 timeoutval) { switch(timeoutval) { case WEEKLY: { if( (now_time->tm_mon != last_time->tm_mon) ) return true; return ( (now_time->tm_mday / 7) != (last_time->tm_mday / 7) ); } case MONTHLY: return (now_time->tm_mon != last_time->tm_mon); case HOURLY: return ((now_time->tm_hour != last_time->tm_hour) || (now_time->tm_mday != last_time->tm_mday) || (now_time->tm_mon != last_time->tm_mon)); case DAILY: return ((now_time->tm_mday != last_time->tm_mday) || (now_time->tm_mday != last_time->tm_mday)); } return false; } bool DayWatcherThread::run() { Log.Notice("DayWatcherThread", "Started."); currenttime = UNIXTIME; dupe_tm_pointer(localtime(&currenttime), &local_currenttime); load_settings(); set_tm_pointers(); m_busy = false; #ifdef WIN32 m_abortEvent = CreateEvent(NULL, NULL, FALSE, NULL); #else struct timeval now; struct timespec tv; pthread_mutex_init(&abortmutex,NULL); pthread_cond_init(&abortcond,NULL); #endif while(ThreadState != THREADSTATE_TERMINATE) { m_busy=true; currenttime = UNIXTIME; dupe_tm_pointer(localtime(&currenttime), &local_currenttime); if(has_timeout_expired(&local_currenttime, &local_last_honor_time, honor_period)) update_honor(); if(has_timeout_expired(&local_currenttime, &local_last_arena_time, arena_period)) update_arena(); if(m_dirty) update_settings(); m_busy=false; if(ThreadState == THREADSTATE_TERMINATE) break; #ifdef WIN32 WaitForSingleObject(m_abortEvent, 120000); #else gettimeofday(&now, NULL); tv.tv_sec = now.tv_sec + 120; tv.tv_nsec = now.tv_usec * 1000; pthread_mutex_lock(&abortmutex); pthread_cond_timedwait(&abortcond, &abortmutex, &tv); pthread_mutex_unlock(&abortmutex); #endif if(!m_running) break; } #ifdef WIN32 CloseHandle(m_abortEvent); #else pthread_mutex_destroy(&abortmutex); pthread_cond_destroy(&abortcond); #endif return true; } void DayWatcherThread::update_arena() { Log.Notice("DayWatcherThread", "Running Weekly Arena Point Maintenance..."); QueryResult * result = CharacterDatabase.Query("SELECT guid, arenaPoints FROM characters"); /* this one is a little more intensive. */ Player * plr; uint32 guid, arenapoints, orig_arenapoints; ArenaTeam * team; uint32 arenapointsPerTeam[3] = {0}; double X, Y; if(result) { do { Field * f = result->Fetch(); guid = f[0].GetUInt32(); arenapoints = f[1].GetUInt32(); orig_arenapoints = arenapoints; for(uint32 i = 0; i < 3; ++i) arenapointsPerTeam[i] = 0; /* are we in any arena teams? */ for(uint32 i = 0; i < 3; ++i) // 3 arena team types { team = objmgr.GetArenaTeamByGuid(guid, i); if(team) { /* TODO: In the future we might want to do a check that says is the player active in this arena team. * Private servers are kinda smaller so this probably isn't such a good idea. * - Burlex */ /* we're in an arena team of this type! */ /* Source: http://www.wowwiki.com/Arena_point */ X = (double)team->m_stat_rating; if(X <= 510.0) // "if X<=510" continue; // no change else if(X > 510.0 && X <= 1500.0) // "if 510 < X <= 1500" { Y = (0.22 * X) + 14.0; } else // "if X > 1500" { // http://eu.wowarmory.com/arena-calculator.xml // 1511.26 // --------------------------- // -0.00412*X // 1+1639.28*2.71828 double power = ((-0.00412) * X); //if(power < 1.0) // power = 1.0; double divisor = pow(((double)(2.71828)), power); divisor *= 1639.28; divisor += 1.0; //if(divisor < 1.0) // divisor = 1.0; Y = 1511.26 / divisor; } // 2v2 teams only earn 70% (Was 60% until 13th March 07) of the arena points, 3v3 teams get 80%, while 5v5 teams get 100% of the arena points. // 2v2 - 76%, 3v3 - 88% as of patch 2.2 if(team->m_type == ARENA_TEAM_TYPE_2V2) { Y *= 0.76; Y *= sWorld.getRate(RATE_ARENAPOINTMULTIPLIER2X); } else if(team->m_type == ARENA_TEAM_TYPE_3V3) { Y *= 0.88; Y *= sWorld.getRate(RATE_ARENAPOINTMULTIPLIER3X); } else { Y *= sWorld.getRate(RATE_ARENAPOINTMULTIPLIER5X); } if(Y > 1.0) arenapointsPerTeam[i] += long2int32(double(ceil(Y))); } } arenapointsPerTeam[0] = max(arenapointsPerTeam[0],arenapointsPerTeam[1]); arenapoints += max(arenapointsPerTeam[0],arenapointsPerTeam[2]); if(orig_arenapoints != arenapoints) { plr = objmgr.GetPlayer(guid); if(plr) { plr->m_arenaPoints = arenapoints; /* update visible fields (must be done through an event because of no uint lock */ sEventMgr.AddEvent(plr, &Player::RecalculateHonor, EVENT_PLAYER_UPDATE, 100, 1, 0); /* send a little message :> */ sChatHandler.SystemMessage(plr->GetSession(), "Your arena points have been updated! Check your PvP tab!"); } /* update in sql */ CharacterDatabase.Execute("UPDATE characters SET arenaPoints = %u WHERE guid = %u", arenapoints, guid); } }while(result->NextRow()); delete result; } //=========================================================================== last_arena_time = UNIXTIME; dupe_tm_pointer(localtime(&last_arena_time), &local_last_arena_time); m_dirty = true; } void DayWatcherThread::update_honor() { Log.Notice("DayWatcherThread", "Running Daily Honor Maintenance..."); uint32 guid, killstoday, killsyesterday, honortoday, honoryesterday, honorpoints, points_to_add; Player * plr; QueryResult * result = CharacterDatabase.Query("SELECT guid, killsToday, killsYesterday, honorToday, honorYesterday, honorPoints, honorPointsToAdd FROM characters"); if(result) { do { Field * f = result->Fetch(); guid = f[0].GetUInt32(); killstoday = f[1].GetUInt32(); killsyesterday = f[2].GetUInt32(); honortoday = f[3].GetUInt32(); honoryesterday = f[4].GetUInt32(); honorpoints = f[5].GetUInt32(); points_to_add = f[6].GetUInt32(); /* add his "honor points to be added" */ honorpoints += points_to_add; points_to_add = 0; /* update the yesterday fields */ killsyesterday = killstoday; honoryesterday = honortoday; honortoday = killstoday = 0; /* are we online? */ plr = objmgr.GetPlayer(guid); if(plr) { /* we're online, update our fields here too */ plr->m_honorPoints = honorpoints; plr->m_honorPointsToAdd = points_to_add; plr->m_honorToday = honortoday; plr->m_honorYesterday = honoryesterday; plr->m_killsToday = killstoday; plr->m_killsYesterday = killsyesterday; /* update visible fields (must be done through an event because of no uint lock */ sEventMgr.AddEvent(plr, &Player::RecalculateHonor, EVENT_PLAYER_UPDATE, 100, 1, 0); /* send a little message :> */ sChatHandler.SystemMessage(plr->GetSession(), "Your honor points have been updated! Check your PvP tab!"); } /* update in database */ CharacterDatabase.Execute("UPDATE characters SET killsToday = %u, killsYesterday = %u, honorToday = %u, honorYesterday = %u, honorPoints = %u, honorPointsToAdd = %u WHERE guid = %u", killstoday, killsyesterday, honortoday, honoryesterday, honorpoints, points_to_add, guid); } while(result->NextRow()); delete result; } //=========================================================================== last_honor_time = UNIXTIME; dupe_tm_pointer(localtime(&last_honor_time), &local_last_honor_time); m_dirty = true; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: gradtrns.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: aw $ $Date: 2001-01-16 13:48:17 $ * * 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 _GRADTRANS_HXX #define _GRADTRANS_HXX #include "xgrad.hxx" #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef _SV_VECTOR2D_HXX #include <vcl/vector2d.hxx> #endif class SdrObject; class GradTransVector { public: Point aPos1; Point aPos2; Color aCol1; Color aCol2; }; class GradTransGradient { public: XGradient aGradient; }; class GradTransformer { public: GradTransformer() {} void GradToVec(GradTransGradient& rG, GradTransVector& rV, const SdrObject* pObj); void VecToGrad(GradTransVector& rV, GradTransGradient& rG, GradTransGradient& rGOld, const SdrObject* pObj, BOOL bMoveSingle, BOOL bMoveFirst); }; #endif _GRADTRANS_HXX <commit_msg>INTEGRATION: CWS rt02 (1.2.462); FILE MERGED 2003/09/30 16:22:56 rt 1.2.462.1: #i19697# Fixed compiler warnings<commit_after>/************************************************************************* * * $RCSfile: gradtrns.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-10-06 15:32:56 $ * * 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 _GRADTRANS_HXX #define _GRADTRANS_HXX #include "xgrad.hxx" #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef _SV_VECTOR2D_HXX #include <vcl/vector2d.hxx> #endif class SdrObject; class GradTransVector { public: Point aPos1; Point aPos2; Color aCol1; Color aCol2; }; class GradTransGradient { public: XGradient aGradient; }; class GradTransformer { public: GradTransformer() {} void GradToVec(GradTransGradient& rG, GradTransVector& rV, const SdrObject* pObj); void VecToGrad(GradTransVector& rV, GradTransGradient& rG, GradTransGradient& rGOld, const SdrObject* pObj, BOOL bMoveSingle, BOOL bMoveFirst); }; #endif // _GRADTRANS_HXX <|endoftext|>
<commit_before>#include <generation/generation.h> #include <algorithm> #include <fstream> #include <queue> namespace generation { Dungeon::Dungeon(unsigned int width, unsigned int height, std::mt19937::result_type seed) : width(width), height(height), grid(width * height, 0), merged(width * height, 0), roompts(), mt(seed) {} Dungeon::Dungeon(unsigned int width, unsigned int height) : Dungeon(width, height, std::random_device()()) {} bool Dungeon::useless(const Point &p) const { const unsigned int r = p.r, c = p.c; int found1 = 0, found2 = 0; bool foundwall = false; if (c > 1 && grid[r * width + c - 1]) { if (grid[r * width + c - 1] > 0) if (!merged[r * width + c - 1]) if (found1 > 0) found2 = grid[r * width + c - 1]; else found1 = grid[r * width + c - 1]; else foundwall = true; else foundwall = true; } if (found2 == found1) found2 = 0; if (r > 1 && grid[(r - 1) * width + c]) { if (grid[(r - 1) * width + c] > 0) if (!merged[(r - 1) * width + c]) if (found1 > 0) found2 = grid[(r - 1) * width + c]; else found1 = grid[(r - 1) * width + c]; else foundwall = true; else foundwall = true; } if (found2 == found1) found2 = 0; if (c < width - 1u && grid[r * width + c + 1]) { if (grid[r * width + c + 1] > 0) if (!merged[r * width + c + 1]) if (found1 > 0) found2 = grid[r * width + c + 1]; else found1 = grid[r * width + c + 1]; else foundwall = true; else foundwall = true; } if (found2 == found1) found2 = 0; if (r < height - 1u && grid[(r + 1) * width + c]) { if (grid[(r + 1) * width + c] > 0) if (!merged[(r + 1) * width + c]) if (found1 > 0) found2 = grid[(r + 1) * width + c]; else found1 = grid[(r + 1) * width + c]; else foundwall = true; else foundwall = true; } if (found2 == found1) found2 = 0; return !(found1 && (found2 || foundwall)); } bool Dungeon::touches_merged(const Point &p) { const unsigned int r = p.r, c = p.c; if (c > 1 && merged[r * width + c - 1]) { return true; } if (r > 1 && merged[(r - 1) * width + c]) { return true; } if (c < width - 1u && merged[r * width + c + 1]) { return true; } if (r < height - 1u && merged[(r + 1) * width + c]) { return true; } return false; } bool Dungeon::touches_cleared(const Point &p) { const unsigned int r = p.r, c = p.c; if (c > 1 && grid[r * width + c - 1] == -2) { return true; } if (r > 1 && grid[(r - 1) * width + c] == -2) { return true; } if (c < width - 1u && grid[r * width + c + 1] == -2) { return true; } if (r < height - 1u && grid[(r + 1) * width + c] == -2) { return true; } return false; } void Dungeon::floodfill(const Point &q) { std::queue<Point> Q; Q.push(q); while (!Q.empty()) { const auto p = Q.front(); Q.pop(); merged[p.r * width + p.c] = true; const unsigned int r = p.r, c = p.c; // add neighbors if (c > 1 && grid[r * width + c - 1] && !merged[r * width + c - 1]) { merged[r * width + c - 1] = true; Q.emplace(Point {r, c - 1}); } if (r > 1 && grid[(r - 1) * width + c] && !merged[(r - 1) * width + c]) { merged[(r - 1) * width + c] = true; Q.emplace(Point {r - 1, c}); } if (c < width - 1u && grid[r * width + c + 1] && !merged[r * width + c + 1]) { merged[r * width + c + 1] = true; Q.emplace(Point {r, c + 1}); } if (r < height - 1u && grid[(r + 1) * width + c] && !merged[(r + 1) * width + c]) { merged[(r + 1) * width + c] = true; Q.emplace(Point {r + 1, c}); } } } void Dungeon::write(const char *fname) { // output maze std::ofstream file(fname); for (unsigned int r = 0; r < height; r++) { for (unsigned int c = 0; c < width; c++) { int v = grid[r * width + c]; char ch; if (v == 0) ch = '#'; else if (1 <= v && v <= 9) ch = v + '0'; else if (10 <= v && v <= 35) ch = v + 'A' - 10; else if (v == -1) ch = '.'; else if (v == -2) ch = ':'; else if (v == -3) ch = '!'; else ch = '?'; file << ch; } file << std::endl; } file.close(); } void Dungeon::generate(unsigned int nrooms, unsigned int ntries, double extra_door_p, double dead_end_p) { // 0 = wall, 1+ = room, -1 = corridor, -2 = door, -3 = dead end // generate rooms std::uniform_int_distribution<unsigned int> sdist(1, 5); for (unsigned int i = 0; i < ntries && roompts.size() < nrooms; i++) { while (roompts.size() < nrooms) { // generate a random rectangle unsigned int rwidth = sdist(mt) * 2 + 1; unsigned int rheight = sdist(mt) * 2 + 1; std::uniform_int_distribution<int> rpos(0, height / 2 - rheight / 2 - 1), cpos(0, width / 2 - rwidth / 2 - 1); unsigned int r = rpos(mt) * 2 + 1; unsigned int c = cpos(mt) * 2 + 1; for (unsigned int j = 0; j < rheight; j++) { for (unsigned int k = 0; k < rwidth; k++) { if (grid[(r + j) * width + c + k]) goto overlap; } } roompts.emplace_back(Point {r, c}); for (unsigned int j = 0; j < rheight; j++) { for (unsigned int k = 0; k < rwidth; k++) { grid[(r + j) * width + c + k] = roompts.size(); } } } overlap:; } // fill with corridors // pick a random spot while (true) { std::uniform_int_distribution<unsigned int> rpos(0, height / 2 - 1), cpos(0, width / 2 - 1); unsigned int r = rpos(mt) * 2 + 1, c = cpos(mt) * 2 + 1; if (!grid[r * width + c]) { grid[r * width + c] = -1; break; } } // hunt and kill while (true) { unsigned int cr = 0, cc = 0; // find an empty cell with a visited neighbor for (unsigned int r = 1; r < height - 1u; r += 2) { for (unsigned int c = 1; c < width - 1u; c += 2) { if (!grid[r * width + c]) { if (c > 1 && grid[r * width + c - 2] == -1) grid[r * width + c - 1] = -1; else if (r > 1 && grid[(r - 2) * width + c] == -1) grid[(r - 1) * width + c] = -1; else if (c < width - 2 && grid[r * width + c + 2] == -1) grid[r * width + c + 1] = -1; else if (r < height - 2 && grid[(r + 2) * width + c] == -1) grid[(r + 1) * width + c] = -1; else continue; cr = r; cc = c; goto found; } } } found:; if (cc == 0) break; // we're done; not found (cc is always odd) while (true) { // clear ourselves grid[cr * width + cc] = -1; // advance in random direction std::uniform_int_distribution<unsigned int> compass(0, 3), turn(0, 5); unsigned int sdir = compass(mt); // turn directions: 0 (same), 1 (right), 3 (left) unsigned int dirs[3]; switch (turn(mt)) { case 0: dirs[0] = (0 + sdir) & 3; dirs[1] = (1 + sdir) & 3; dirs[2] = (3 + sdir) & 3; break; case 1: dirs[0] = (0 + sdir) & 3; dirs[1] = (3 + sdir) & 3; dirs[2] = (1 + sdir) & 3; break; case 2: dirs[0] = (1 + sdir) & 3; dirs[1] = (0 + sdir) & 3; dirs[2] = (3 + sdir) & 3; break; case 3: dirs[0] = (1 + sdir) & 3; dirs[1] = (3 + sdir) & 3; dirs[2] = (0 + sdir) & 3; break; case 4: dirs[0] = (3 + sdir) & 3; dirs[1] = (0 + sdir) & 3; dirs[2] = (1 + sdir) & 3; break; case 5: dirs[0] = (3 + sdir) & 3; dirs[1] = (1 + sdir) & 3; dirs[2] = (0 + sdir) & 3; break; } bool found = false; for (unsigned int i = 0; i < 3; i++) { int dir = dirs[i]; switch (dir) { case 0: // north if (cr > 1 && !grid[(cr - 2) * width + cc]) { grid[(cr - 1) * width + cc] = -1; cr -= 2; found = true; } break; case 1: // east if (cc < width - 2 && !grid[cr * width + cc + 2]) { grid[cr * width + cc + 1] = -1; cc += 2; found = true; } break; case 2: // south if (cr < height - 2 && !grid[(cr + 2) * width + cc]) { grid[(cr + 1) * width + cc] = -1; cr += 2; found = true; } break; case 3: // west if (cc > 1 && !grid[cr * width + cc - 2]) { grid[cr * width + cc - 1] = -1; cc -= 2; found = true; } break; } if (found) break; } if (!found) break; // no neighbors } } // connect rooms together std::vector<Point> connectors; for (unsigned int r = 0; r < height; r++) { for (unsigned int c = 0; c < width; c++) { // check if it connects two rooms together if (grid[r * width + c]) continue; Point pt = {r, c}; if (!useless(pt)) connectors.push_back(pt); } } std::shuffle(connectors.begin(), connectors.end(), mt); // merge the first room { Point p = roompts[0]; floodfill(p); } // activate connectors std::bernoulli_distribution door_dist(extra_door_p); while (!connectors.empty()) { auto conn_ = std::find_if(connectors.begin(), connectors.end(), [this](const Point &p) {return touches_merged(p);}); if (conn_ == connectors.end()) { // lol; some rooms were not connected. Trying again probably works :D break; } auto conn = *conn_; connectors.erase(conn_); // probably unnecessary grid[conn.r * width + conn.c] = -2; floodfill(conn); connectors.erase(std::remove_if(connectors.begin(), connectors.end(), [this, &door_dist](const Point &p) { if (!useless(p)) return false; if (door_dist(mt) && !touches_cleared(p)) { grid[p.r * width + p.c] = -2; merged[p.r * width + p.c] = true; } return true; }), connectors.end()); } // remove some dead-ends std::bernoulli_distribution dead_end_dist(dead_end_p); bool changed = false; do { for (unsigned int r = 0; r < height; r++) { for (unsigned int c = 0; c < width; c++) { if (grid[r * width + c] != -1) continue; unsigned int count = 0; if (c > 1 && grid[r * width + c - 1]) { count++; } if (r > 1 && grid[(r - 1) * width + c]) { count++; } if (c < width - 1u && grid[r * width + c + 1]) { count++; } if (r < height - 1u && grid[(r + 1) * width + c]) { count++; } if (count <= 1) { if (dead_end_dist(mt)) { grid[r * width + c] = -3; } else { grid[r * width + c] = 0; changed = true; } } } } } while (changed); } } // remove int main(int argc, char **argv) { generation::Dungeon dun(301, 201); dun.generate(100, 500); dun.write("maze.txt"); } <commit_msg>Fix dead ends<commit_after>#include <generation/generation.h> #include <algorithm> #include <fstream> #include <queue> namespace generation { Dungeon::Dungeon(unsigned int width, unsigned int height, std::mt19937::result_type seed) : width(width), height(height), grid(width * height, 0), merged(width * height, 0), roompts(), mt(seed) {} Dungeon::Dungeon(unsigned int width, unsigned int height) : Dungeon(width, height, std::random_device()()) {} bool Dungeon::useless(const Point &p) const { const unsigned int r = p.r, c = p.c; int found1 = 0, found2 = 0; bool foundwall = false; if (c > 1 && grid[r * width + c - 1]) { if (grid[r * width + c - 1] > 0) if (!merged[r * width + c - 1]) if (found1 > 0) found2 = grid[r * width + c - 1]; else found1 = grid[r * width + c - 1]; else foundwall = true; else foundwall = true; } if (found2 == found1) found2 = 0; if (r > 1 && grid[(r - 1) * width + c]) { if (grid[(r - 1) * width + c] > 0) if (!merged[(r - 1) * width + c]) if (found1 > 0) found2 = grid[(r - 1) * width + c]; else found1 = grid[(r - 1) * width + c]; else foundwall = true; else foundwall = true; } if (found2 == found1) found2 = 0; if (c < width - 1u && grid[r * width + c + 1]) { if (grid[r * width + c + 1] > 0) if (!merged[r * width + c + 1]) if (found1 > 0) found2 = grid[r * width + c + 1]; else found1 = grid[r * width + c + 1]; else foundwall = true; else foundwall = true; } if (found2 == found1) found2 = 0; if (r < height - 1u && grid[(r + 1) * width + c]) { if (grid[(r + 1) * width + c] > 0) if (!merged[(r + 1) * width + c]) if (found1 > 0) found2 = grid[(r + 1) * width + c]; else found1 = grid[(r + 1) * width + c]; else foundwall = true; else foundwall = true; } if (found2 == found1) found2 = 0; return !(found1 && (found2 || foundwall)); } bool Dungeon::touches_merged(const Point &p) { const unsigned int r = p.r, c = p.c; if (c > 1 && merged[r * width + c - 1]) { return true; } if (r > 1 && merged[(r - 1) * width + c]) { return true; } if (c < width - 1u && merged[r * width + c + 1]) { return true; } if (r < height - 1u && merged[(r + 1) * width + c]) { return true; } return false; } bool Dungeon::touches_cleared(const Point &p) { const unsigned int r = p.r, c = p.c; if (c > 1 && grid[r * width + c - 1] == -2) { return true; } if (r > 1 && grid[(r - 1) * width + c] == -2) { return true; } if (c < width - 1u && grid[r * width + c + 1] == -2) { return true; } if (r < height - 1u && grid[(r + 1) * width + c] == -2) { return true; } return false; } void Dungeon::floodfill(const Point &q) { std::queue<Point> Q; Q.push(q); while (!Q.empty()) { const auto p = Q.front(); Q.pop(); merged[p.r * width + p.c] = true; const unsigned int r = p.r, c = p.c; // add neighbors if (c > 1 && grid[r * width + c - 1] && !merged[r * width + c - 1]) { merged[r * width + c - 1] = true; Q.emplace(Point {r, c - 1}); } if (r > 1 && grid[(r - 1) * width + c] && !merged[(r - 1) * width + c]) { merged[(r - 1) * width + c] = true; Q.emplace(Point {r - 1, c}); } if (c < width - 1u && grid[r * width + c + 1] && !merged[r * width + c + 1]) { merged[r * width + c + 1] = true; Q.emplace(Point {r, c + 1}); } if (r < height - 1u && grid[(r + 1) * width + c] && !merged[(r + 1) * width + c]) { merged[(r + 1) * width + c] = true; Q.emplace(Point {r + 1, c}); } } } void Dungeon::write(const char *fname) { // output maze std::ofstream file(fname); for (unsigned int r = 0; r < height; r++) { for (unsigned int c = 0; c < width; c++) { int v = grid[r * width + c]; char ch; if (v == 0) ch = '#'; else if (1 <= v && v <= 9) ch = v + '0'; else if (10 <= v && v <= 35) ch = v + 'A' - 10; else if (v == -1) ch = '.'; else if (v == -2) ch = ':'; else if (v == -3) ch = '!'; else ch = '?'; file << ch; } file << std::endl; } file.close(); } void Dungeon::generate(unsigned int nrooms, unsigned int ntries, double extra_door_p, double dead_end_p) { // 0 = wall, 1+ = room, -1 = corridor, -2 = door, -3 = dead end // generate rooms std::uniform_int_distribution<unsigned int> sdist(1, 5); for (unsigned int i = 0; i < ntries && roompts.size() < nrooms; i++) { while (roompts.size() < nrooms) { // generate a random rectangle unsigned int rwidth = sdist(mt) * 2 + 1; unsigned int rheight = sdist(mt) * 2 + 1; std::uniform_int_distribution<int> rpos(0, height / 2 - rheight / 2 - 1), cpos(0, width / 2 - rwidth / 2 - 1); unsigned int r = rpos(mt) * 2 + 1; unsigned int c = cpos(mt) * 2 + 1; for (unsigned int j = 0; j < rheight; j++) { for (unsigned int k = 0; k < rwidth; k++) { if (grid[(r + j) * width + c + k]) goto overlap; } } roompts.emplace_back(Point {r, c}); for (unsigned int j = 0; j < rheight; j++) { for (unsigned int k = 0; k < rwidth; k++) { grid[(r + j) * width + c + k] = roompts.size(); } } } overlap:; } // fill with corridors // pick a random spot while (true) { std::uniform_int_distribution<unsigned int> rpos(0, height / 2 - 1), cpos(0, width / 2 - 1); unsigned int r = rpos(mt) * 2 + 1, c = cpos(mt) * 2 + 1; if (!grid[r * width + c]) { grid[r * width + c] = -1; break; } } // hunt and kill while (true) { unsigned int cr = 0, cc = 0; // find an empty cell with a visited neighbor for (unsigned int r = 1; r < height - 1u; r += 2) { for (unsigned int c = 1; c < width - 1u; c += 2) { if (!grid[r * width + c]) { if (c > 1 && grid[r * width + c - 2] == -1) grid[r * width + c - 1] = -1; else if (r > 1 && grid[(r - 2) * width + c] == -1) grid[(r - 1) * width + c] = -1; else if (c < width - 2 && grid[r * width + c + 2] == -1) grid[r * width + c + 1] = -1; else if (r < height - 2 && grid[(r + 2) * width + c] == -1) grid[(r + 1) * width + c] = -1; else continue; cr = r; cc = c; goto found; } } } found:; if (cc == 0) break; // we're done; not found (cc is always odd) while (true) { // clear ourselves grid[cr * width + cc] = -1; // advance in random direction std::uniform_int_distribution<unsigned int> compass(0, 3), turn(0, 5); unsigned int sdir = compass(mt); // turn directions: 0 (same), 1 (right), 3 (left) unsigned int dirs[3]; switch (turn(mt)) { case 0: dirs[0] = (0 + sdir) & 3; dirs[1] = (1 + sdir) & 3; dirs[2] = (3 + sdir) & 3; break; case 1: dirs[0] = (0 + sdir) & 3; dirs[1] = (3 + sdir) & 3; dirs[2] = (1 + sdir) & 3; break; case 2: dirs[0] = (1 + sdir) & 3; dirs[1] = (0 + sdir) & 3; dirs[2] = (3 + sdir) & 3; break; case 3: dirs[0] = (1 + sdir) & 3; dirs[1] = (3 + sdir) & 3; dirs[2] = (0 + sdir) & 3; break; case 4: dirs[0] = (3 + sdir) & 3; dirs[1] = (0 + sdir) & 3; dirs[2] = (1 + sdir) & 3; break; case 5: dirs[0] = (3 + sdir) & 3; dirs[1] = (1 + sdir) & 3; dirs[2] = (0 + sdir) & 3; break; } bool found = false; for (unsigned int i = 0; i < 3; i++) { int dir = dirs[i]; switch (dir) { case 0: // north if (cr > 1 && !grid[(cr - 2) * width + cc]) { grid[(cr - 1) * width + cc] = -1; cr -= 2; found = true; } break; case 1: // east if (cc < width - 2 && !grid[cr * width + cc + 2]) { grid[cr * width + cc + 1] = -1; cc += 2; found = true; } break; case 2: // south if (cr < height - 2 && !grid[(cr + 2) * width + cc]) { grid[(cr + 1) * width + cc] = -1; cr += 2; found = true; } break; case 3: // west if (cc > 1 && !grid[cr * width + cc - 2]) { grid[cr * width + cc - 1] = -1; cc -= 2; found = true; } break; } if (found) break; } if (!found) break; // no neighbors } } // connect rooms together std::vector<Point> connectors; for (unsigned int r = 0; r < height; r++) { for (unsigned int c = 0; c < width; c++) { // check if it connects two rooms together if (grid[r * width + c]) continue; Point pt = {r, c}; if (!useless(pt)) connectors.push_back(pt); } } std::shuffle(connectors.begin(), connectors.end(), mt); // merge the first room { Point p = roompts[0]; floodfill(p); } // activate connectors std::bernoulli_distribution door_dist(extra_door_p); while (!connectors.empty()) { auto conn_ = std::find_if(connectors.begin(), connectors.end(), [this](const Point &p) {return touches_merged(p);}); if (conn_ == connectors.end()) { // lol; some rooms were not connected. Trying again probably works :D break; } auto conn = *conn_; connectors.erase(conn_); // probably unnecessary grid[conn.r * width + conn.c] = -2; floodfill(conn); connectors.erase(std::remove_if(connectors.begin(), connectors.end(), [this, &door_dist](const Point &p) { if (!useless(p)) return false; if (door_dist(mt) && !touches_cleared(p)) { grid[p.r * width + p.c] = -2; merged[p.r * width + p.c] = true; } return true; }), connectors.end()); } // remove some dead-ends std::bernoulli_distribution dead_end_dist(dead_end_p); bool changed = false; do { changed = false; for (unsigned int r = 0; r < height; r++) { for (unsigned int c = 0; c < width; c++) { if (grid[r * width + c] != -1) continue; unsigned int count = 0; if (c > 1 && grid[r * width + c - 1]) { count++; } if (r > 1 && grid[(r - 1) * width + c]) { count++; } if (c < width - 1u && grid[r * width + c + 1]) { count++; } if (r < height - 1u && grid[(r + 1) * width + c]) { count++; } if (count <= 1) { if (dead_end_dist(mt)) { grid[r * width + c] = -3; } else { grid[r * width + c] = 0; changed = true; } } } } } while (changed); } } // remove int main(int argc, char **argv) { generation::Dungeon dun(301, 201); dun.generate(100, 500); dun.write("maze.txt"); } <|endoftext|>