commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
7f0de36bbcde0625ef7dbdfad47eb24ae56a0624
|
ros_workspace/src/hmmwv/src/engine.cpp
|
ros_workspace/src/hmmwv/src/engine.cpp
|
#include <cassert>
#include "../include/hmmwv/engine.hpp"
Engine::Engine(GPIO *gpio, const GPIO::Pin enablePin, const GPIO::Pin directionPin,
const GPIO::PwmPin speedPin) :
_gpio(gpio),
_enablePin(enablePin),
_directionPin(directionPin),
_speedPin(speedPin),
_lastDirection(0)
{
gpio->setPin(_enablePin, 0); // Disable first to avoid epileptic motors
gpio->setPwm(_speedPin, 0.0);
gpio->setPin(_directionPin, 1);
gpio->setPin(_enablePin, 1);
}
Engine::~Engine() {}
void Engine::start(const int direction, const float speed)
{
assert(direction == -1 || direction == 0 || direction == 1);
assert(speed >= 0.0 && speed <= 1.0);
if(direction != _lastDirection) {
if(direction == -1) {
_gpio->setPin(_directionPin, 0);
}
else if(direction == 1) {
_gpio->setPin(_directionPin, direction);
}
_lastDirection = direction;
}
if(direction != 0) {
_gpio->setPwm(_speedPin, speed);
}
else {
// Ignore speed settings, we're not supposed to work anyway
_gpio->setPwm(_speedPin, 0.0);
}
}
|
#include <cassert>
#include "../include/hmmwv/engine.hpp"
Engine::Engine(GPIO *gpio, const GPIO::Pin enablePin, const GPIO::Pin directionPin,
const GPIO::PwmPin speedPin) :
_gpio(gpio),
_enablePin(enablePin),
_directionPin(directionPin),
_speedPin(speedPin),
_lastDirection(0)
{
gpio->setPin(_enablePin, 0); // Disable first to avoid epileptic motors
gpio->setPwm(_speedPin, 0.0);
gpio->setPin(_directionPin, 1);
}
Engine::~Engine() {}
void Engine::start(const int direction, const float speed)
{
assert(direction == -1 || direction == 0 || direction == 1);
assert(speed >= 0.0 && speed <= 1.0);
if(direction != _lastDirection) {
if(direction == -1) {
_gpio->setPin(_enablePin, 1);
_gpio->setPin(_directionPin, 0);
}
else if(direction == 1) {
_gpio->setPin(_enablePin, 1);
_gpio->setPin(_directionPin, direction);
}
_lastDirection = direction;
}
if(direction != 0) {
_gpio->setPwm(_speedPin, speed);
}
else {
// Ignore speed settings, we're not supposed to work anyway
_gpio->setPwm(_speedPin, 0.0);
_gpio->setPin(_enablePin, 0);
}
}
|
disable motors if speed is 0. How does that influence motor braking?
|
Engine: disable motors if speed is 0. How does that influence motor braking?
|
C++
|
mit
|
hmmwv-team/hmmwv,hmmwv-team/hmmwv,ne0h/hmmwv,hmmwv-team/hmmwv,ne0h/hmmwv
|
14647492463ad7ff4cf7a8e1afcf9b3bac40ba97
|
chrome/browser/autocomplete/autocomplete_browsertest.cc
|
chrome/browser/autocomplete/autocomplete_browsertest.cc
|
// 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 "base/format_macros.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/autocomplete_edit.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_popup_model.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/unpacked_installer.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/omnibox/location_bar.h"
#include "chrome/browser/ui/omnibox/omnibox_view.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "testing/gtest/include/gtest/gtest.h"
// Autocomplete test is flaky on ChromeOS.
// http://crbug.com/52928
#if defined(OS_CHROMEOS)
#define MAYBE_Autocomplete FLAKY_Autocomplete
#else
#define MAYBE_Autocomplete Autocomplete
#endif
namespace {
string16 AutocompleteResultAsString(const AutocompleteResult& result) {
std::string output(base::StringPrintf("{%" PRIuS "} ", result.size()));
for (size_t i = 0; i < result.size(); ++i) {
AutocompleteMatch match = result.match_at(i);
std::string provider_name = match.provider->name();
output.append(base::StringPrintf("[\"%s\" by \"%s\"] ",
UTF16ToUTF8(match.contents).c_str(),
provider_name.c_str()));
}
return UTF8ToUTF16(output);
}
} // namespace
class AutocompleteBrowserTest : public ExtensionBrowserTest {
protected:
LocationBar* GetLocationBar() const {
return browser()->window()->GetLocationBar();
}
AutocompleteController* GetAutocompleteController() const {
return GetLocationBar()->location_entry()->model()->popup_model()->
autocomplete_controller();
}
};
#if defined(OS_WIN) || defined(OS_LINUX)
#define MAYBE_Basic FLAKY_Basic
#else
#define MAYBE_Basic Basic
#endif
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Basic) {
LocationBar* location_bar = GetLocationBar();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
// TODO(phajdan.jr): check state of IsSelectAll when it's consistent across
// platforms.
location_bar->FocusLocation(true);
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
location_bar->location_entry()->SetUserText(ASCIIToUTF16("chrome"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("chrome"), location_bar->location_entry()->GetText());
EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());
location_bar->location_entry()->RevertAll();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());
location_bar->location_entry()->SetUserText(ASCIIToUTF16("chrome"));
location_bar->Revert();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());
}
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) {
// The results depend on the history backend being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
ui_test_utils::WaitForHistoryToLoad(browser());
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
{
autocomplete_controller->Start(
ASCIIToUTF16("chrome"), string16(), true, false, true,
AutocompleteInput::SYNCHRONOUS_MATCHES);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_TRUE(location_bar->location_entry()->GetText().empty());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
const AutocompleteResult& result = autocomplete_controller->result();
// We get two matches because we have a provider for extension apps and the
// Chrome Web Store is a built-in Extension app. For this test, we only care
// about the other match existing.
ASSERT_GE(result.size(), 1U) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
}
{
location_bar->Revert();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());
const AutocompleteResult& result = autocomplete_controller->result();
EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result);
}
}
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) {
// http://code.google.com/p/chromium/issues/detail?id=38385
// Make sure that tabbing away from an empty omnibar causes a revert
// and select all.
LocationBar* location_bar = GetLocationBar();
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
location_bar->location_entry()->SetUserText(string16());
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_LOAD_STOP,
content::NotificationService::AllSources());
browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),
content::PAGE_TRANSITION_START_PAGE);
observer.Wait();
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
browser()->CloseTab();
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
}
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) {
LocationBar* location_bar = GetLocationBar();
// Focus search when omnibox is blank
{
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(1U, selection_start);
EXPECT_EQ(1U, selection_end);
}
// Focus search when omnibox is _not_ alread in forced query mode.
{
location_bar->location_entry()->SetUserText(ASCIIToUTF16("foo"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("foo"), location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(1U, selection_start);
EXPECT_EQ(1U, selection_end);
}
// Focus search when omnibox _is_ already in forced query mode, but no query
// has been typed.
{
location_bar->location_entry()->SetUserText(ASCIIToUTF16("?"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(1U, selection_start);
EXPECT_EQ(1U, selection_end);
}
// Focus search when omnibox _is_ already in forced query mode, and some query
// has been typed.
{
location_bar->location_entry()->SetUserText(ASCIIToUTF16("?foo"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?foo"), location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?foo"), location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(1U, std::min(selection_start, selection_end));
EXPECT_EQ(4U, std::max(selection_start, selection_end));
}
// Focus search when omnibox is in forced query mode with leading whitespace.
{
location_bar->location_entry()->SetUserText(ASCIIToUTF16(" ?foo"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16(" ?foo"),
location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16(" ?foo"),
location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(4U, std::min(selection_start, selection_end));
EXPECT_EQ(7U, std::max(selection_start, selection_end));
}
}
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, ExtensionAppProvider) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t extension_count = service->extensions()->size();
FilePath test_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
// Load a packaged app.
extensions::UnpackedInstaller::Create(service)->Load(
test_dir.AppendASCII("extensions").AppendASCII("packaged_app"));
WaitForExtensionLoad();
// Load a hosted app.
extensions::UnpackedInstaller::Create(service)->Load(
test_dir.AppendASCII("extensions").AppendASCII("app"));
WaitForExtensionLoad();
ASSERT_EQ(extension_count + 2U, service->extensions()->size());
// The results depend on the history backend being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
ui_test_utils::WaitForHistoryToLoad(browser());
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
// Try out the packaged app.
{
autocomplete_controller->Start(
ASCIIToUTF16("Packaged App Test"), string16(), true, false, true,
AutocompleteInput::SYNCHRONOUS_MATCHES);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_TRUE(location_bar->location_entry()->GetText().empty());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
const AutocompleteResult& result = autocomplete_controller->result();
EXPECT_GT(result.size(), 1U) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(ASCIIToUTF16("Packaged App Test"), match.contents);
EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);
EXPECT_FALSE(match.deletable);
location_bar->AcceptInput();
}
browser()->NewTab();
// Try out the hosted app.
{
autocomplete_controller->Start(
ASCIIToUTF16("App Test"), string16(), true, false, true,
AutocompleteInput::SYNCHRONOUS_MATCHES);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_TRUE(location_bar->location_entry()->GetText().empty());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
const AutocompleteResult& result = autocomplete_controller->result();
// 'App test' is also a substring of extension 'Packaged App Test'.
EXPECT_GT(result.size(), 2U) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(ASCIIToUTF16("App Test"), match.contents);
EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);
EXPECT_FALSE(match.deletable);
location_bar->AcceptInput();
}
}
|
// 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 "base/format_macros.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/autocomplete_edit.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_popup_model.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/unpacked_installer.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/omnibox/location_bar.h"
#include "chrome/browser/ui/omnibox/omnibox_view.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "testing/gtest/include/gtest/gtest.h"
// Autocomplete test is flaky on ChromeOS.
// http://crbug.com/52928
#if defined(OS_CHROMEOS)
#define MAYBE_Autocomplete FLAKY_Autocomplete
#else
#define MAYBE_Autocomplete Autocomplete
#endif
namespace {
string16 AutocompleteResultAsString(const AutocompleteResult& result) {
std::string output(base::StringPrintf("{%" PRIuS "} ", result.size()));
for (size_t i = 0; i < result.size(); ++i) {
AutocompleteMatch match = result.match_at(i);
std::string provider_name = match.provider->name();
output.append(base::StringPrintf("[\"%s\" by \"%s\"] ",
UTF16ToUTF8(match.contents).c_str(),
provider_name.c_str()));
}
return UTF8ToUTF16(output);
}
} // namespace
class AutocompleteBrowserTest : public ExtensionBrowserTest {
protected:
LocationBar* GetLocationBar() const {
return browser()->window()->GetLocationBar();
}
AutocompleteController* GetAutocompleteController() const {
return GetLocationBar()->location_entry()->model()->popup_model()->
autocomplete_controller();
}
};
#if defined(OS_WIN) || defined(OS_LINUX)
#define MAYBE_Basic FLAKY_Basic
#else
#define MAYBE_Basic Basic
#endif
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Basic) {
LocationBar* location_bar = GetLocationBar();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
// TODO(phajdan.jr): check state of IsSelectAll when it's consistent across
// platforms.
location_bar->FocusLocation(true);
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
location_bar->location_entry()->SetUserText(ASCIIToUTF16("chrome"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("chrome"), location_bar->location_entry()->GetText());
EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());
location_bar->location_entry()->RevertAll();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());
location_bar->location_entry()->SetUserText(ASCIIToUTF16("chrome"));
location_bar->Revert();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());
}
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) {
// The results depend on the history backend being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
ui_test_utils::WaitForHistoryToLoad(browser());
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
{
autocomplete_controller->Start(
ASCIIToUTF16("chrome"), string16(), true, false, true,
AutocompleteInput::SYNCHRONOUS_MATCHES);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_TRUE(location_bar->location_entry()->GetText().empty());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
const AutocompleteResult& result = autocomplete_controller->result();
// We get two matches because we have a provider for extension apps and the
// Chrome Web Store is a built-in Extension app. For this test, we only care
// about the other match existing.
ASSERT_GE(result.size(), 1U) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
}
{
location_bar->Revert();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());
const AutocompleteResult& result = autocomplete_controller->result();
EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result);
}
}
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) {
// http://code.google.com/p/chromium/issues/detail?id=38385
// Make sure that tabbing away from an empty omnibar causes a revert
// and select all.
LocationBar* location_bar = GetLocationBar();
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
location_bar->location_entry()->SetUserText(string16());
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_LOAD_STOP,
content::NotificationService::AllSources());
browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),
content::PAGE_TRANSITION_START_PAGE);
observer.Wait();
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
browser()->CloseTab();
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
}
#if defined(OS_WINDOWS) || defined(OS_LINUX)
// http://crbug.com/104307
#define FocusSearch FLAKY_FocusSearch
#endif
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) {
LocationBar* location_bar = GetLocationBar();
// Focus search when omnibox is blank
{
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),
location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(1U, selection_start);
EXPECT_EQ(1U, selection_end);
}
// Focus search when omnibox is _not_ alread in forced query mode.
{
location_bar->location_entry()->SetUserText(ASCIIToUTF16("foo"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("foo"), location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(1U, selection_start);
EXPECT_EQ(1U, selection_end);
}
// Focus search when omnibox _is_ already in forced query mode, but no query
// has been typed.
{
location_bar->location_entry()->SetUserText(ASCIIToUTF16("?"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(1U, selection_start);
EXPECT_EQ(1U, selection_end);
}
// Focus search when omnibox _is_ already in forced query mode, and some query
// has been typed.
{
location_bar->location_entry()->SetUserText(ASCIIToUTF16("?foo"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?foo"), location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16("?foo"), location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(1U, std::min(selection_start, selection_end));
EXPECT_EQ(4U, std::max(selection_start, selection_end));
}
// Focus search when omnibox is in forced query mode with leading whitespace.
{
location_bar->location_entry()->SetUserText(ASCIIToUTF16(" ?foo"));
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16(" ?foo"),
location_bar->location_entry()->GetText());
location_bar->FocusSearch();
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_EQ(ASCIIToUTF16(" ?foo"),
location_bar->location_entry()->GetText());
size_t selection_start, selection_end;
location_bar->location_entry()->GetSelectionBounds(&selection_start,
&selection_end);
EXPECT_EQ(4U, std::min(selection_start, selection_end));
EXPECT_EQ(7U, std::max(selection_start, selection_end));
}
}
IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, ExtensionAppProvider) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t extension_count = service->extensions()->size();
FilePath test_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
// Load a packaged app.
extensions::UnpackedInstaller::Create(service)->Load(
test_dir.AppendASCII("extensions").AppendASCII("packaged_app"));
WaitForExtensionLoad();
// Load a hosted app.
extensions::UnpackedInstaller::Create(service)->Load(
test_dir.AppendASCII("extensions").AppendASCII("app"));
WaitForExtensionLoad();
ASSERT_EQ(extension_count + 2U, service->extensions()->size());
// The results depend on the history backend being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
ui_test_utils::WaitForHistoryToLoad(browser());
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
// Try out the packaged app.
{
autocomplete_controller->Start(
ASCIIToUTF16("Packaged App Test"), string16(), true, false, true,
AutocompleteInput::SYNCHRONOUS_MATCHES);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_TRUE(location_bar->location_entry()->GetText().empty());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
const AutocompleteResult& result = autocomplete_controller->result();
EXPECT_GT(result.size(), 1U) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(ASCIIToUTF16("Packaged App Test"), match.contents);
EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);
EXPECT_FALSE(match.deletable);
location_bar->AcceptInput();
}
browser()->NewTab();
// Try out the hosted app.
{
autocomplete_controller->Start(
ASCIIToUTF16("App Test"), string16(), true, false, true,
AutocompleteInput::SYNCHRONOUS_MATCHES);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(location_bar->GetInputString().empty());
EXPECT_TRUE(location_bar->location_entry()->GetText().empty());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
const AutocompleteResult& result = autocomplete_controller->result();
// 'App test' is also a substring of extension 'Packaged App Test'.
EXPECT_GT(result.size(), 2U) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(ASCIIToUTF16("App Test"), match.contents);
EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);
EXPECT_FALSE(match.deletable);
location_bar->AcceptInput();
}
}
|
Mark AutocompleteBrowserTest.FocusSearch flaky on Windows and Linux.
|
Mark AutocompleteBrowserTest.FocusSearch flaky on Windows and Linux.
[email protected]
BUG=104307
Review URL: http://codereview.chromium.org/8574006
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@110092 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dednal/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,rogerwang/chromium,robclark/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,rogerwang/chromium,robclark/chromium,robclark/chromium,krieger-od/nwjs_chromium.src,robclark/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,keishi/chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,keishi/chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,rogerwang/chromium,markYoungH/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,keishi/chromium,axinging/chromium-crosswalk,robclark/chromium,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,patrickm/chromium.src,patrickm/chromium.src,M4sse/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,keishi/chromium,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,mogoweb/chromium-crosswalk,Just-D/chromium-1,zcbenz/cefode-chromium,jaruba/chromium.src,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,dednal/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,ltilve/chromium,dednal/chromium.src,jaruba/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,anirudhSK/chromium,mogoweb/chromium-crosswalk,robclark/chromium,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,keishi/chromium,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,keishi/chromium,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,Chilledheart/chromium,dednal/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,rogerwang/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,littlstar/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,robclark/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,jaruba/chromium.src,rogerwang/chromium,littlstar/chromium.src,jaruba/chromium.src,ltilve/chromium,nacl-webkit/chrome_deps,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,jaruba/chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,keishi/chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,jaruba/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,timopulkkinen/BubbleFish,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,zcbenz/cefode-chromium,Chilledheart/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,robclark/chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,anirudhSK/chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,patrickm/chromium.src,Chilledheart/chromium,M4sse/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,rogerwang/chromium,Jonekee/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,axinging/chromium-crosswalk,Chilledheart/chromium,dushu1203/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,ondra-novak/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,anirudhSK/chromium,ltilve/chromium,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,hujiajie/pa-chromium,nacl-webkit/chrome_deps,Jonekee/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,keishi/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,rogerwang/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,patrickm/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,robclark/chromium,ltilve/chromium,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src
|
c8b5efc025476f765e7772480589a95be82ff7c3
|
src/loop055.cpp
|
src/loop055.cpp
|
#include "demoloop.h"
#include "graphics/3d_primitives.h"
#include "graphics/shader.h"
#include "helpers.h"
#include <array>
#include <glm/gtx/rotate_vector.hpp>
using namespace std;
using namespace demoloop;
float t = 0;
const float CYCLE_LENGTH = 10;
const float size = 3;
float cubicEaseInOut(float t,float b , float c, float d) {
t/=d/2;
if (t < 1) return c/2*t*t*t + b;
t-=2;
return c/2*(t*t*t + 2) + b;
}
Vertex parametricPlane(const float u, const float v) {
return {
(u - 0.5f) * size, (v - 0.5f) * size, 0,
1 - u, 1 - v,
255, 255, 255, 255
};
}
Vertex flatMobius(float s, float t) {
float u = s - 0.5;
float v = 2 * DEMOLOOP_M_PI * -t;
float x, y, z;
float a = size / 2 / 2;
x = cosf(v) * (a + u * cosf(v / 2));
y = sinf(v) * (a + u * cosf(v / 2));
z = u * sinf( v / 2 );
return {
x, y, z,
1 - s, (1 - t) * 1
};
}
Vertex volumetricMobius(float s, float v) {
float u = s * DEMOLOOP_M_PI;
float t = v * 2 * DEMOLOOP_M_PI;
u = u * 2;
float phi = u / 2;
float major = size / 2, a = 0.125, b = 0.65;
float x, y, z;
x = a * cosf( t ) * cosf( phi ) - b * sinf( t ) * sinf( phi );
z = a * cosf( t ) * sinf( phi ) + b * sinf( t ) * cosf( phi );
y = ( major + x ) * sinf( u );
x = ( major + x ) * cosf( u );
return {
x, y, z,
1 - s, 1 - v
};
}
Vertex parametricSphere(float s, float t) {
float u = t * DEMOLOOP_M_PI;
float v = s * DEMOLOOP_M_PI * 2;
// v *= 3.0/4.0;
float radius = size / 2;
float x = -radius * sinf(u) * sinf(v);
float y = -radius * cosf(u);
float z = radius * sinf(u) * cosf(v);
return {
x, y, z,
1 - s, 1 - t
};
}
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;
}
glm::vec3 computeNormal(const Vertex &a, const Vertex &b, const Vertex &c) {
glm::vec3 v1(a.x, a.y, a.z);
glm::vec3 v2(b.x, b.y, b.z);
glm::vec3 v3(c.x, c.y, c.z);
return normalize(cross(v2 - v1, v3 - v1));
}
Vertex mix(const Vertex& a, const Vertex& b, const float& ratio) {
const float x = mix<float>(a.x, b.x, ratio);
const float y = mix<float>(a.y, b.y, ratio);
const float z = mix<float>(a.z, b.z, ratio);
const float s = mix<float>(a.s, b.s, ratio);
const float t = mix<float>(a.t, b.t, ratio);
const uint8_t red = mix<uint8_t>(a.r, b.r, ratio);
const uint8_t green = mix<uint8_t>(a.g, b.g, ratio);
const uint8_t blue = mix<uint8_t>(a.b, b.b, ratio);
const uint8_t alpha = mix<uint8_t>(a.a, b.a, ratio);
return {x, y, z, s, t, red, green, blue, alpha};
}
const array<function<Vertex(float, float)>, 3> surfaces = {{
parametricPlane, parametricSphere, flatMobius
}};
const static std::string shaderCode = R"===(
#ifdef VERTEX
vec4 position(mat4 transform_proj, mat4 m, vec4 v_coord) {
mat4 mvp = transform_proj * m;
return mvp * v_coord;
}
#endif
#ifdef PIXEL
vec4 effect(vec4 globalColor, Image texture, vec2 st, vec2 screen_coords) {
vec2 q = abs(fract(st) - 0.5);
float d = fract((q.x + q.y) * 5.0);
if (gl_FrontFacing) {
return vec4(vec3(1, 0.2, 0.75) * d, 1.0);
} else {
return vec4(vec3(0.2, 0.75, 1) * d, 1.0);
}
}
#endif
)===";
const uint32_t stacks = 30, slices = 30;
const uint32_t numVertices = (slices + 1) * (stacks + 1);
const uint32_t numIndices = slices * stacks * 6;
class Loop055 : public Demoloop {
public:
Loop055() : Demoloop(150, 150, 150), shader({shaderCode, shaderCode}) {
// glEnable(GL_CULL_FACE);
texture = loadTexture("uv_texture.jpg");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
}
~Loop055() {
}
void Update(float dt) {
t += dt;
const float cycle = fmod(t, CYCLE_LENGTH);
const float cycle_ratio = cycle / CYCLE_LENGTH;
// const float mod_ratio = powf(sinf(cycle_ratio * DEMOLOOP_M_PI), 2);
const uint32_t surfaceIndex = fmod(floor(t / CYCLE_LENGTH), surfaces.size());
const uint32_t sliceCount = slices + 1;
uint32_t index = 0;
for (uint32_t i = 0; i <= stacks; ++i) {
const float v = static_cast<float>(i) / stacks;
for (uint32_t j = 0; j <= slices; ++j) {
const float u = static_cast<float>(j) / slices;
// vertices[index] = volumetricMobius(u, v);
// vertices[index] = mix(plane(u, v), flatMobius(u, v), mod_ratio);
vertices[index] = mix(
surfaces[surfaceIndex](u, v),
surfaces[(surfaceIndex + 1) % surfaces.size()](u, v),
cubicEaseInOut(cycle_ratio, 0, 1, 1)
);
normals[index] = glm::vec3(0, 0, 0);
index++;
}
}
index = 0;
for (uint32_t i = 0; i < stacks; ++i) {
for (uint32_t j = 0; j < slices; ++j) {
const uint32_t a = i * sliceCount + j;
const uint32_t b = i * sliceCount + j + 1;
const uint32_t c = ( i + 1 ) * sliceCount + j + 1;
const uint32_t d = ( i + 1 ) * sliceCount + j;
// faces one and two
indices[index++] = a;
indices[index++] = b;
indices[index++] = d;
glm::vec3 faceNormal1 = computeNormal(vertices[a], vertices[b], vertices[d]);
normals[a] = glm::normalize(normals[a] + faceNormal1);
normals[b] = glm::normalize(normals[b] + faceNormal1);
normals[c] = glm::normalize(normals[c] + faceNormal1);
indices[index++] = b;
indices[index++] = c;
indices[index++] = d;
glm::vec3 faceNormal2 = computeNormal(vertices[b], vertices[c], vertices[d]);
normals[b] = glm::normalize(normals[b] + faceNormal2);
normals[c] = glm::normalize(normals[c] + faceNormal2);
normals[d] = glm::normalize(normals[d] + faceNormal2);
}
}
// const glm::vec3 eye = glm::rotate(glm::vec3(0, 0, 10), static_cast<float>(cycle_ratio * DEMOLOOP_M_PI * 2), glm::vec3(0, 1, 0));
const glm::vec3 eye = glm::vec3(0, 0, 10);
const glm::vec3 target = {0, 0, 0};
const glm::vec3 up = {0, 1, 0};
glm::mat4 camera = glm::lookAt(eye, target, up);
GL::TempTransform t1(gl);
t1.get() = camera;
GL::TempProjection p1(gl);
p1.get() = glm::perspective((float)DEMOLOOP_M_PI / 4.0f, (float)width / (float)height, 0.1f, 100.0f);
shader.attach();
gl.bufferVertices(&vertices[0], numVertices);
glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x));
glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, s));
glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, r));
// uint32_t normalsLocation = shader.getAttribLocation("v_normal");
// glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer);
// glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(glm::vec3), &normals[0].x, GL_DYNAMIC_DRAW);
// glVertexAttribPointer(normalsLocation, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0);
gl.bufferIndices(&indices[0], numIndices);
// gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR | ATTRIBFLAG_TEXCOORD | (1u << normalsLocation));
gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR | ATTRIBFLAG_TEXCOORD);
{
glm::mat4 m;
m = glm::translate(m, {2.5, 0, 0});
m = glm::scale(m, {1.5, 1.5, 1.5});
m = glm::rotate(m, cycle_ratio * (float)DEMOLOOP_M_PI * 2, glm::vec3(0, 1, 0));
gl.prepareDraw(m);
gl.drawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0);
}
{
glm::mat4 m;
m = glm::translate(m, {-2.5, 0, 0});
m = glm::scale(m, {1.5, 1.5, 1.5});
m = glm::rotate(m, cycle_ratio * (float)DEMOLOOP_M_PI * 2, glm::vec3(0, 1, 0));
m = glm::rotate(m, (float)DEMOLOOP_M_PI, glm::vec3(0, 1, 0));
gl.prepareDraw(m);
gl.drawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0);
}
shader.detach();
}
private:
GLuint texture;
Shader shader;
Vertex vertices[numVertices];
glm::vec3 normals[numVertices];
uint32_t indices[numIndices];
};
int main(int, char**){
Loop055 test;
test.Run();
return 0;
}
|
#include "demoloop.h"
#include "graphics/3d_primitives.h"
#include "graphics/shader.h"
#include "helpers.h"
#include <array>
#include <glm/gtx/rotate_vector.hpp>
using namespace std;
using namespace demoloop;
float t = 0;
const float CYCLE_LENGTH = 10;
const float size = 3;
float cubicEaseInOut(float t,float b , float c, float d) {
t/=d/2;
if (t < 1) return c/2*t*t*t + b;
t-=2;
return c/2*(t*t*t + 2) + b;
}
Vertex parametricPlane(const float u, const float v) {
return {
(u - 0.5f) * size, (v - 0.5f) * size, 0,
1 - u, 1 - v,
255, 255, 255, 255
};
}
Vertex flatMobius(float s, float t) {
float u = s - 0.5;
float v = 2 * DEMOLOOP_M_PI * -t;
float x, y, z;
float a = size / 2 / 2;
x = cosf(v) * (a + u * cosf(v / 2));
y = sinf(v) * (a + u * cosf(v / 2));
z = u * sinf( v / 2 );
return {
x, y, z,
1 - s, (1 - t) * 1
};
}
Vertex volumetricMobius(float s, float v) {
float u = s * DEMOLOOP_M_PI;
float t = v * 2 * DEMOLOOP_M_PI;
u = u * 2;
float phi = u / 2;
float major = size / 2, a = 0.125, b = 0.65;
float x, y, z;
x = a * cosf( t ) * cosf( phi ) - b * sinf( t ) * sinf( phi );
z = a * cosf( t ) * sinf( phi ) + b * sinf( t ) * cosf( phi );
y = ( major + x ) * sinf( u );
x = ( major + x ) * cosf( u );
return {
x, y, z,
1 - s, 1 - v
};
}
Vertex parametricSphere(float s, float t) {
float u = t * DEMOLOOP_M_PI;
float v = s * DEMOLOOP_M_PI * 2;
// v *= 3.0/4.0;
float radius = size / 2;
float x = -radius * sinf(u) * sinf(v);
float y = -radius * cosf(u);
float z = radius * sinf(u) * cosf(v);
return {
x, y, z,
1 - s, 1 - t
};
}
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;
}
glm::vec3 computeNormal(const Vertex &a, const Vertex &b, const Vertex &c) {
glm::vec3 v1(a.x, a.y, a.z);
glm::vec3 v2(b.x, b.y, b.z);
glm::vec3 v3(c.x, c.y, c.z);
return normalize(cross(v2 - v1, v3 - v1));
}
Vertex mix(const Vertex& a, const Vertex& b, const float& ratio) {
const float x = mix<float>(a.x, b.x, ratio);
const float y = mix<float>(a.y, b.y, ratio);
const float z = mix<float>(a.z, b.z, ratio);
const float s = mix<float>(a.s, b.s, ratio);
const float t = mix<float>(a.t, b.t, ratio);
const uint8_t red = mix<uint8_t>(a.r, b.r, ratio);
const uint8_t green = mix<uint8_t>(a.g, b.g, ratio);
const uint8_t blue = mix<uint8_t>(a.b, b.b, ratio);
const uint8_t alpha = mix<uint8_t>(a.a, b.a, ratio);
return {x, y, z, s, t, red, green, blue, alpha};
}
const array<function<Vertex(float, float)>, 3> surfaces = {{
parametricPlane, parametricSphere, flatMobius
}};
const static std::string shaderCode = R"===(
#ifdef VERTEX
vec4 position(mat4 transform_proj, mat4 m, vec4 v_coord) {
mat4 mvp = transform_proj * m;
return mvp * v_coord;
}
#endif
#ifdef PIXEL
vec4 effect(vec4 globalColor, Image texture, vec2 st, vec2 screen_coords) {
vec2 q = abs(fract(st) - 0.5);
float d = fract((q.x + q.y) * 5.0);
if (gl_FrontFacing) {
return vec4(vec3(1, 0.2, 0.75) * d, 1.0);
} else {
return vec4(vec3(0.2, 0.75, 1) * d, 1.0);
}
}
#endif
)===";
const uint32_t stacks = 30, slices = 30;
const uint32_t numVertices = (slices + 1) * (stacks + 1);
const uint32_t numIndices = slices * stacks * 6;
class Loop055 : public Demoloop {
public:
Loop055() : Demoloop(150, 150, 150), shader({shaderCode, shaderCode}) {
}
~Loop055() {
}
void Update(float dt) {
t += dt;
const float cycle = fmod(t, CYCLE_LENGTH);
const float cycle_ratio = cycle / CYCLE_LENGTH;
// const float mod_ratio = powf(sinf(cycle_ratio * DEMOLOOP_M_PI), 2);
const uint32_t surfaceIndex = fmod(floor(t / CYCLE_LENGTH), surfaces.size());
const uint32_t sliceCount = slices + 1;
uint32_t index = 0;
for (uint32_t i = 0; i <= stacks; ++i) {
const float v = static_cast<float>(i) / stacks;
for (uint32_t j = 0; j <= slices; ++j) {
const float u = static_cast<float>(j) / slices;
// vertices[index] = volumetricMobius(u, v);
// vertices[index] = mix(plane(u, v), flatMobius(u, v), mod_ratio);
vertices[index] = mix(
surfaces[surfaceIndex](u, v),
surfaces[(surfaceIndex + 1) % surfaces.size()](u, v),
cubicEaseInOut(cycle_ratio, 0, 1, 1)
);
normals[index] = glm::vec3(0, 0, 0);
index++;
}
}
index = 0;
for (uint32_t i = 0; i < stacks; ++i) {
for (uint32_t j = 0; j < slices; ++j) {
const uint32_t a = i * sliceCount + j;
const uint32_t b = i * sliceCount + j + 1;
const uint32_t c = ( i + 1 ) * sliceCount + j + 1;
const uint32_t d = ( i + 1 ) * sliceCount + j;
// faces one and two
indices[index++] = a;
indices[index++] = b;
indices[index++] = d;
glm::vec3 faceNormal1 = computeNormal(vertices[a], vertices[b], vertices[d]);
normals[a] = glm::normalize(normals[a] + faceNormal1);
normals[b] = glm::normalize(normals[b] + faceNormal1);
normals[c] = glm::normalize(normals[c] + faceNormal1);
indices[index++] = b;
indices[index++] = c;
indices[index++] = d;
glm::vec3 faceNormal2 = computeNormal(vertices[b], vertices[c], vertices[d]);
normals[b] = glm::normalize(normals[b] + faceNormal2);
normals[c] = glm::normalize(normals[c] + faceNormal2);
normals[d] = glm::normalize(normals[d] + faceNormal2);
}
}
// const glm::vec3 eye = glm::rotate(glm::vec3(0, 0, 10), static_cast<float>(cycle_ratio * DEMOLOOP_M_PI * 2), glm::vec3(0, 1, 0));
const glm::vec3 eye = glm::vec3(0, 0, 10);
const glm::vec3 target = {0, 0, 0};
const glm::vec3 up = {0, 1, 0};
glm::mat4 camera = glm::lookAt(eye, target, up);
GL::TempTransform t1(gl);
t1.get() = camera;
GL::TempProjection p1(gl);
p1.get() = glm::perspective((float)DEMOLOOP_M_PI / 4.0f, (float)width / (float)height, 0.1f, 100.0f);
shader.attach();
gl.bufferVertices(&vertices[0], numVertices);
glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x));
glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, s));
glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, r));
// uint32_t normalsLocation = shader.getAttribLocation("v_normal");
// glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer);
// glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(glm::vec3), &normals[0].x, GL_DYNAMIC_DRAW);
// glVertexAttribPointer(normalsLocation, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0);
gl.bufferIndices(&indices[0], numIndices);
// gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR | ATTRIBFLAG_TEXCOORD | (1u << normalsLocation));
gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR | ATTRIBFLAG_TEXCOORD);
{
glm::mat4 m;
m = glm::translate(m, {2.5, 0, 0});
m = glm::scale(m, {1.5, 1.5, 1.5});
m = glm::rotate(m, cycle_ratio * (float)DEMOLOOP_M_PI * 2, glm::vec3(0, 1, 0));
gl.prepareDraw(m);
gl.drawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0);
}
{
glm::mat4 m;
m = glm::translate(m, {-2.5, 0, 0});
m = glm::scale(m, {1.5, 1.5, 1.5});
m = glm::rotate(m, cycle_ratio * (float)DEMOLOOP_M_PI * 2, glm::vec3(0, 1, 0));
m = glm::rotate(m, (float)DEMOLOOP_M_PI, glm::vec3(0, 1, 0));
gl.prepareDraw(m);
gl.drawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0);
}
shader.detach();
}
private:
Shader shader;
Vertex vertices[numVertices];
glm::vec3 normals[numVertices];
uint32_t indices[numIndices];
};
int main(int, char**){
Loop055 test;
test.Run();
return 0;
}
|
remove unused texture reference from loop 055
|
remove unused texture reference from loop 055
|
C++
|
mit
|
TannerRogalsky/Demoloops,TannerRogalsky/Demoloops,TannerRogalsky/Demoloops,TannerRogalsky/Demoloops
|
0e5db091e91d576bd5b05d22103115496084bd19
|
src/mem/port.hh
|
src/mem/port.hh
|
/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* Port Object Decleration. Ports are used to interface memory objects to
* each other. They will always come in pairs, and we refer to the other
* port object as the peer. These are used to make the design more
* modular so that a specific interface between every type of objcet doesn't
* have to be created.
*/
#ifndef __MEM_PORT_HH__
#define __MEM_PORT_HH__
#include <list>
#include <inttypes.h>
#include "base/misc.hh"
#include "base/range.hh"
#include "mem/packet.hh"
#include "mem/request.hh"
/** This typedef is used to clean up the parameter list of
* getDeviceAddressRanges() and getPeerAddressRanges(). It's declared
* outside the Port object since it's also used by some mem objects.
* Eventually we should move this typedef to wherever Addr is
* defined.
*/
typedef std::list<Range<Addr> > AddrRangeList;
typedef std::list<Range<Addr> >::iterator AddrRangeIter;
/**
* Ports are used to interface memory objects to
* each other. They will always come in pairs, and we refer to the other
* port object as the peer. These are used to make the design more
* modular so that a specific interface between every type of objcet doesn't
* have to be created.
*
* Recv accesor functions are being called from the peer interface.
* Send accessor functions are being called from the device the port is
* associated with, and it will call the peer recv. accessor function.
*/
class Port
{
private:
/** Descriptive name (for DPRINTF output) */
const std::string portName;
public:
/**
* Constructor.
*
* @param _name Port name for DPRINTF output. Should include name
* of memory system object to which the port belongs.
*/
Port(const std::string &_name)
: portName(_name)
{ }
/** Return port name (for DPRINTF). */
const std::string &name() const { return portName; }
virtual ~Port() {};
// mey be better to use subclasses & RTTI?
/** Holds the ports status. Currently just that a range recomputation needs
* to be done. */
enum Status {
RangeChange
};
private:
/** A pointer to the peer port. Ports always come in pairs, that way they
can use a standardized interface to communicate between different
memory objects. */
Port *peer;
public:
/** Function to set the pointer for the peer port.
@todo should be called by the configuration stuff (python).
*/
void setPeer(Port *port);
/** Function to set the pointer for the peer port.
@todo should be called by the configuration stuff (python).
*/
Port *getPeer() { return peer; }
protected:
/** These functions are protected because they should only be
* called by a peer port, never directly by any outside object. */
/** Called to recive a timing call from the peer port. */
virtual bool recvTiming(Packet *pkt) = 0;
/** Called to recive a atomic call from the peer port. */
virtual Tick recvAtomic(Packet *pkt) = 0;
/** Called to recive a functional call from the peer port. */
virtual void recvFunctional(Packet *pkt) = 0;
/** Called to recieve a status change from the peer port. */
virtual void recvStatusChange(Status status) = 0;
/** Called by a peer port if the send was unsuccesful, and had to
wait. This shouldn't be valid for response paths (IO Devices).
so it is set to panic if it isn't already defined.
*/
virtual void recvRetry() { panic("??"); }
/** Called by a peer port in order to determine the block size of the
device connected to this port. It sometimes doesn't make sense for
this function to be called, a DMA interface doesn't really have a
block size, so it is defaulted to a panic.
*/
virtual int deviceBlockSize() { panic("??"); }
/** The peer port is requesting us to reply with a list of the ranges we
are responsible for.
@param resp is a list of ranges responded to
@param snoop is a list of ranges snooped
*/
virtual void getDeviceAddressRanges(AddrRangeList &resp,
AddrRangeList &snoop)
{ panic("??"); }
public:
/** Function called by associated memory device (cache, memory, iodevice)
in order to send a timing request to the port. Simply calls the peer
port receive function.
@return This function returns if the send was succesful in it's
recieve. If it was a failure, then the port will wait for a recvRetry
at which point it can possibly issue a successful sendTiming. This is used in
case a cache has a higher priority request come in while waiting for
the bus to arbitrate.
*/
bool sendTiming(Packet *pkt) { return peer->recvTiming(pkt); }
/** Function called by the associated device to send an atomic access,
an access in which the data is moved and the state is updated in one
cycle, without interleaving with other memory accesses.
*/
Tick sendAtomic(Packet *pkt)
{ return peer->recvAtomic(pkt); }
/** Function called by the associated device to send a functional access,
an access in which the data is instantly updated everywhere in the
memory system, without affecting the current state of any block or
moving the block.
*/
void sendFunctional(Packet *pkt)
{ return peer->recvFunctional(pkt); }
/** Called by the associated device to send a status change to the device
connected to the peer interface.
*/
void sendStatusChange(Status status) {peer->recvStatusChange(status); }
/** When a timing access doesn't return a success, some time later the
Retry will be sent.
*/
void sendRetry() { return peer->recvRetry(); }
/** Called by the associated device if it wishes to find out the blocksize
of the device on attached to the peer port.
*/
int peerBlockSize() { return peer->deviceBlockSize(); }
/** Called by the associated device if it wishes to find out the address
ranges connected to the peer ports devices.
*/
void getPeerAddressRanges(AddrRangeList &resp, AddrRangeList &snoop)
{ peer->getDeviceAddressRanges(resp, snoop); }
/** This function is a wrapper around sendFunctional()
that breaks a larger, arbitrarily aligned access into
appropriate chunks. The default implementation can use
getBlockSize() to determine the block size and go from there.
*/
virtual void readBlob(Addr addr, uint8_t *p, int size);
/** This function is a wrapper around sendFunctional()
that breaks a larger, arbitrarily aligned access into
appropriate chunks. The default implementation can use
getBlockSize() to determine the block size and go from there.
*/
virtual void writeBlob(Addr addr, uint8_t *p, int size);
/** Fill size bytes starting at addr with byte value val. This
should not need to be virtual, since it can be implemented in
terms of writeBlob(). However, it shouldn't be
performance-critical either, so it could be if we wanted to.
*/
virtual void memsetBlob(Addr addr, uint8_t val, int size);
private:
/** Internal helper function for read/writeBlob().
*/
void blobHelper(Addr addr, uint8_t *p, int size, Packet::Command cmd);
};
/** A simple functional port that is only meant for one way communication to
* physical memory. It is only meant to be used to load data into memory before
* the simulation begins.
*/
class FunctionalPort : public Port
{
public:
FunctionalPort(const std::string &_name)
: Port(_name)
{}
virtual bool recvTiming(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual Tick recvAtomic(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual void recvFunctional(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual void recvStatusChange(Status status) {}
template <typename T>
inline void write(Addr addr, T d)
{
writeBlob(addr, (uint8_t*)&d, sizeof(T));
}
template <typename T>
inline T read(Addr addr)
{
T d;
readBlob(addr, (uint8_t*)&d, sizeof(T));
return d;
}
};
#endif //__MEM_PORT_HH__
|
/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* Port Object Decleration. Ports are used to interface memory objects to
* each other. They will always come in pairs, and we refer to the other
* port object as the peer. These are used to make the design more
* modular so that a specific interface between every type of objcet doesn't
* have to be created.
*/
#ifndef __MEM_PORT_HH__
#define __MEM_PORT_HH__
#include <list>
#include <inttypes.h>
#include "base/misc.hh"
#include "base/range.hh"
#include "mem/packet.hh"
#include "mem/request.hh"
/** This typedef is used to clean up the parameter list of
* getDeviceAddressRanges() and getPeerAddressRanges(). It's declared
* outside the Port object since it's also used by some mem objects.
* Eventually we should move this typedef to wherever Addr is
* defined.
*/
typedef std::list<Range<Addr> > AddrRangeList;
typedef std::list<Range<Addr> >::iterator AddrRangeIter;
/**
* Ports are used to interface memory objects to
* each other. They will always come in pairs, and we refer to the other
* port object as the peer. These are used to make the design more
* modular so that a specific interface between every type of objcet doesn't
* have to be created.
*
* Recv accesor functions are being called from the peer interface.
* Send accessor functions are being called from the device the port is
* associated with, and it will call the peer recv. accessor function.
*/
class Port
{
private:
/** Descriptive name (for DPRINTF output) */
const std::string portName;
/** A pointer to the peer port. Ports always come in pairs, that way they
can use a standardized interface to communicate between different
memory objects. */
Port *peer;
public:
/**
* Constructor.
*
* @param _name Port name for DPRINTF output. Should include name
* of memory system object to which the port belongs.
*/
Port(const std::string &_name)
: portName(_name), peer(NULL)
{ }
/** Return port name (for DPRINTF). */
const std::string &name() const { return portName; }
virtual ~Port() {};
// mey be better to use subclasses & RTTI?
/** Holds the ports status. Currently just that a range recomputation needs
* to be done. */
enum Status {
RangeChange
};
/** Function to set the pointer for the peer port.
@todo should be called by the configuration stuff (python).
*/
void setPeer(Port *port);
/** Function to set the pointer for the peer port.
@todo should be called by the configuration stuff (python).
*/
Port *getPeer() { return peer; }
protected:
/** These functions are protected because they should only be
* called by a peer port, never directly by any outside object. */
/** Called to recive a timing call from the peer port. */
virtual bool recvTiming(Packet *pkt) = 0;
/** Called to recive a atomic call from the peer port. */
virtual Tick recvAtomic(Packet *pkt) = 0;
/** Called to recive a functional call from the peer port. */
virtual void recvFunctional(Packet *pkt) = 0;
/** Called to recieve a status change from the peer port. */
virtual void recvStatusChange(Status status) = 0;
/** Called by a peer port if the send was unsuccesful, and had to
wait. This shouldn't be valid for response paths (IO Devices).
so it is set to panic if it isn't already defined.
*/
virtual void recvRetry() { panic("??"); }
/** Called by a peer port in order to determine the block size of the
device connected to this port. It sometimes doesn't make sense for
this function to be called, a DMA interface doesn't really have a
block size, so it is defaulted to a panic.
*/
virtual int deviceBlockSize() { panic("??"); }
/** The peer port is requesting us to reply with a list of the ranges we
are responsible for.
@param resp is a list of ranges responded to
@param snoop is a list of ranges snooped
*/
virtual void getDeviceAddressRanges(AddrRangeList &resp,
AddrRangeList &snoop)
{ panic("??"); }
public:
/** Function called by associated memory device (cache, memory, iodevice)
in order to send a timing request to the port. Simply calls the peer
port receive function.
@return This function returns if the send was succesful in it's
recieve. If it was a failure, then the port will wait for a recvRetry
at which point it can possibly issue a successful sendTiming. This is used in
case a cache has a higher priority request come in while waiting for
the bus to arbitrate.
*/
bool sendTiming(Packet *pkt) { return peer->recvTiming(pkt); }
/** Function called by the associated device to send an atomic access,
an access in which the data is moved and the state is updated in one
cycle, without interleaving with other memory accesses.
*/
Tick sendAtomic(Packet *pkt)
{ return peer->recvAtomic(pkt); }
/** Function called by the associated device to send a functional access,
an access in which the data is instantly updated everywhere in the
memory system, without affecting the current state of any block or
moving the block.
*/
void sendFunctional(Packet *pkt)
{ return peer->recvFunctional(pkt); }
/** Called by the associated device to send a status change to the device
connected to the peer interface.
*/
void sendStatusChange(Status status) {peer->recvStatusChange(status); }
/** When a timing access doesn't return a success, some time later the
Retry will be sent.
*/
void sendRetry() { return peer->recvRetry(); }
/** Called by the associated device if it wishes to find out the blocksize
of the device on attached to the peer port.
*/
int peerBlockSize() { return peer->deviceBlockSize(); }
/** Called by the associated device if it wishes to find out the address
ranges connected to the peer ports devices.
*/
void getPeerAddressRanges(AddrRangeList &resp, AddrRangeList &snoop)
{ peer->getDeviceAddressRanges(resp, snoop); }
/** This function is a wrapper around sendFunctional()
that breaks a larger, arbitrarily aligned access into
appropriate chunks. The default implementation can use
getBlockSize() to determine the block size and go from there.
*/
virtual void readBlob(Addr addr, uint8_t *p, int size);
/** This function is a wrapper around sendFunctional()
that breaks a larger, arbitrarily aligned access into
appropriate chunks. The default implementation can use
getBlockSize() to determine the block size and go from there.
*/
virtual void writeBlob(Addr addr, uint8_t *p, int size);
/** Fill size bytes starting at addr with byte value val. This
should not need to be virtual, since it can be implemented in
terms of writeBlob(). However, it shouldn't be
performance-critical either, so it could be if we wanted to.
*/
virtual void memsetBlob(Addr addr, uint8_t val, int size);
private:
/** Internal helper function for read/writeBlob().
*/
void blobHelper(Addr addr, uint8_t *p, int size, Packet::Command cmd);
};
/** A simple functional port that is only meant for one way communication to
* physical memory. It is only meant to be used to load data into memory before
* the simulation begins.
*/
class FunctionalPort : public Port
{
public:
FunctionalPort(const std::string &_name)
: Port(_name)
{}
virtual bool recvTiming(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual Tick recvAtomic(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual void recvFunctional(Packet *pkt) { panic("FuncPort is UniDir"); }
virtual void recvStatusChange(Status status) {}
template <typename T>
inline void write(Addr addr, T d)
{
writeBlob(addr, (uint8_t*)&d, sizeof(T));
}
template <typename T>
inline T read(Addr addr)
{
T d;
readBlob(addr, (uint8_t*)&d, sizeof(T));
return d;
}
};
#endif //__MEM_PORT_HH__
|
Fix Port pointer initialization.
|
Fix Port pointer initialization.
src/mem/port.hh:
Initialize peer port pointer to NULL.
Move private data members together.
--HG--
extra : convert_revision : dab01f81f0934758891a6b6dc2ad5328149d164b
|
C++
|
bsd-3-clause
|
rallylee/gem5,samueldotj/TeeRISC-Simulator,powerjg/gem5-ci-test,gedare/gem5,cancro7/gem5,sobercoder/gem5,gem5/gem5,briancoutinho0905/2dsampling,qizenguf/MLC-STT,markoshorro/gem5,KuroeKurose/gem5,yb-kim/gemV,aclifton/cpeg853-gem5,samueldotj/TeeRISC-Simulator,yb-kim/gemV,aclifton/cpeg853-gem5,rjschof/gem5,markoshorro/gem5,zlfben/gem5,austinharris/gem5-riscv,KuroeKurose/gem5,rallylee/gem5,Weil0ng/gem5,rallylee/gem5,rjschof/gem5,austinharris/gem5-riscv,HwisooSo/gemV-update,HwisooSo/gemV-update,rjschof/gem5,rjschof/gem5,gem5/gem5,zlfben/gem5,SanchayanMaity/gem5,qizenguf/MLC-STT,SanchayanMaity/gem5,TUD-OS/gem5-dtu,cancro7/gem5,sobercoder/gem5,zlfben/gem5,KuroeKurose/gem5,cancro7/gem5,aclifton/cpeg853-gem5,rallylee/gem5,rallylee/gem5,cancro7/gem5,joerocklin/gem5,cancro7/gem5,gem5/gem5,austinharris/gem5-riscv,SanchayanMaity/gem5,zlfben/gem5,powerjg/gem5-ci-test,cancro7/gem5,markoshorro/gem5,sobercoder/gem5,SanchayanMaity/gem5,gedare/gem5,rjschof/gem5,Weil0ng/gem5,joerocklin/gem5,TUD-OS/gem5-dtu,joerocklin/gem5,samueldotj/TeeRISC-Simulator,joerocklin/gem5,zlfben/gem5,joerocklin/gem5,samueldotj/TeeRISC-Simulator,powerjg/gem5-ci-test,joerocklin/gem5,gedare/gem5,qizenguf/MLC-STT,aclifton/cpeg853-gem5,zlfben/gem5,kaiyuanl/gem5,gem5/gem5,qizenguf/MLC-STT,austinharris/gem5-riscv,rallylee/gem5,samueldotj/TeeRISC-Simulator,kaiyuanl/gem5,markoshorro/gem5,Weil0ng/gem5,aclifton/cpeg853-gem5,joerocklin/gem5,qizenguf/MLC-STT,sobercoder/gem5,HwisooSo/gemV-update,austinharris/gem5-riscv,briancoutinho0905/2dsampling,rjschof/gem5,Weil0ng/gem5,yb-kim/gemV,austinharris/gem5-riscv,HwisooSo/gemV-update,SanchayanMaity/gem5,aclifton/cpeg853-gem5,sobercoder/gem5,rjschof/gem5,powerjg/gem5-ci-test,briancoutinho0905/2dsampling,TUD-OS/gem5-dtu,yb-kim/gemV,TUD-OS/gem5-dtu,rallylee/gem5,markoshorro/gem5,gedare/gem5,HwisooSo/gemV-update,yb-kim/gemV,aclifton/cpeg853-gem5,SanchayanMaity/gem5,yb-kim/gemV,cancro7/gem5,briancoutinho0905/2dsampling,powerjg/gem5-ci-test,briancoutinho0905/2dsampling,gedare/gem5,markoshorro/gem5,TUD-OS/gem5-dtu,KuroeKurose/gem5,qizenguf/MLC-STT,joerocklin/gem5,KuroeKurose/gem5,samueldotj/TeeRISC-Simulator,gem5/gem5,briancoutinho0905/2dsampling,zlfben/gem5,TUD-OS/gem5-dtu,qizenguf/MLC-STT,powerjg/gem5-ci-test,yb-kim/gemV,HwisooSo/gemV-update,kaiyuanl/gem5,KuroeKurose/gem5,samueldotj/TeeRISC-Simulator,kaiyuanl/gem5,Weil0ng/gem5,TUD-OS/gem5-dtu,sobercoder/gem5,SanchayanMaity/gem5,kaiyuanl/gem5,Weil0ng/gem5,kaiyuanl/gem5,Weil0ng/gem5,kaiyuanl/gem5,HwisooSo/gemV-update,markoshorro/gem5,yb-kim/gemV,gedare/gem5,austinharris/gem5-riscv,briancoutinho0905/2dsampling,sobercoder/gem5,KuroeKurose/gem5,gem5/gem5,powerjg/gem5-ci-test,gedare/gem5,gem5/gem5
|
d8e1f77c4e85bba684d3d94af7b90b74f567e961
|
plugins/robots/interpreters/trikKitInterpreterCommon/src/robotModel/twoD/parts/twoDDisplay.cpp
|
plugins/robots/interpreters/trikKitInterpreterCommon/src/robotModel/twoD/parts/twoDDisplay.cpp
|
/* Copyright 2007-2015 QReal Research Group
*
* 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 "trikKitInterpreterCommon/robotModel/twoD/parts/twoDDisplay.h"
#include <QtCore/QJsonArray>
#include <utils/canvas/textObject.h>
using namespace trik::robotModel::twoD::parts;
using namespace kitBase::robotModel;
const int realWidth = 218;
const int realHeight = 274;
const int textSize = 20;
Display::Display(const DeviceInfo &info
, const PortInfo &port
, twoDModel::engine::TwoDModelEngineInterface &engine)
: robotModel::parts::TrikDisplay(info, port)
, mEngine(engine)
, mBackground(Qt::transparent)
{
mEngine.display()->setPainter(this);
connect(this, &Display::backgroundChanged, this, [=](const QColor &color) {
emit propertyChanged("background", color);
});
connect(this, &Display::smileChanged, this, [=](bool smiles, bool happy) {
emit propertyChanged("smiles", smiles && happy);
emit propertyChanged("sadSmiles", smiles && !happy);
});
connect(this, &Display::shapesSetChanged, this, [=]() {
// This is a bit hacky, but shapes set may be modified pretty often, can be pretty large
// and its serialization to JSON may take notable time, so we don't want to do it without real need.
if (receivers(SIGNAL(propertyChanged(QString, QVariant)))) {
emit propertyChanged("objects", toJson());
}
});
}
QString Display::background() const
{
return mBackground.name();
}
bool Display::smiles() const
{
return mSmiles;
}
bool Display::sadSmiles() const
{
return mSadSmiles;
}
void Display::drawPixel(int x, int y)
{
Canvas::drawPixel(x, y);
emit shapesSetChanged();
}
void Display::drawLine(int x1, int y1, int x2, int y2)
{
Canvas::drawLine(x1, y1, x2, y2);
emit shapesSetChanged();
}
void Display::drawRect(int x, int y, int width, int height, bool filled)
{
Canvas::drawRect(x, y, width, height, filled);
emit shapesSetChanged();
}
void Display::drawEllipse(int x, int y, int width, int height, bool filled)
{
Canvas::drawEllipse(x, y, width, height, filled);
emit shapesSetChanged();
}
void Display::drawArc(int x, int y, int width, int height, int startAngle, int spanAngle)
{
Canvas::drawArc(x, y, width, height, startAngle, spanAngle);
emit shapesSetChanged();
}
void Display::drawSmile(bool sad)
{
mCurrentImage = QImage(sad ? ":/icons/sadSmile.png" : ":/icons/smile.png");
mSmiles = !sad;
mSadSmiles = sad;
mEngine.display()->repaintDisplay();
emit smileChanged(true, !sad);
}
void Display::setBackground(const QColor &color)
{
mBackground = color;
emit backgroundChanged(color);
}
void Display::printText(int x, int y, const QString &text)
{
const QPair<int, int> coords(x, y);
if (mLabelsMap.contains(coords)) {
mLabelsMap[coords]->setText(text);
} else {
utils::TextObject * const textObject = new utils::TextObject(x, y, text
, mCurrentPenColor, mCurrentPenWidth);
mObjects << textObject;
mLabelsMap[coords] = textObject;
mLabels << textObject;
}
emit shapesSetChanged();
}
void Display::clearScreen()
{
// Background color is not cleared
mCurrentImage = QImage();
mSmiles = false;
mSadSmiles = false;
mLabelsMap.clear();
Canvas::reset();
emit smileChanged(false, false);
emit shapesSetChanged();
}
void Display::setPainterColor(const QColor &color)
{
Canvas::setPainterColor(color);
}
void Display::setPainterWidth(int penWidth)
{
Canvas::setPainterWidth(penWidth);
}
void Display::paint(QPainter *painter, const QRect &outputRect)
{
Q_UNUSED(outputRect)
const QRect displayRect(0, 0, mEngine.display()->displayWidth(), mEngine.display()->displayHeight());
painter->save();
painter->setPen(mBackground);
painter->setBrush(mBackground);
painter->drawRect(displayRect);
painter->drawImage(displayRect, mCurrentImage);
painter->restore();
painter->save();
painter->setRenderHint(QPainter::HighQualityAntialiasing);
QFont font;
font.setPixelSize(textSize);
painter->setFont(font);
painter->setPen(Qt::black);
const qreal xScale = displayRect.width() / (realWidth * 1.0);
const qreal yScale = displayRect.height() / (realHeight * 1.0);
painter->scale(xScale, yScale);
Canvas::paint(painter, {0, 0, realWidth, realHeight});
painter->restore();
}
void Display::reset()
{
clearScreen();
setBackground(Qt::transparent);
redraw();
}
void Display::redraw()
{
if (mEngine.display()) {
mEngine.display()->repaintDisplay();
}
}
|
/* Copyright 2007-2015 QReal Research Group
*
* 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 "trikKitInterpreterCommon/robotModel/twoD/parts/twoDDisplay.h"
#include <QtCore/QJsonArray>
#include <utils/canvas/textObject.h>
using namespace trik::robotModel::twoD::parts;
using namespace kitBase::robotModel;
const int realWidth = 238;
const int realHeight = 278;
const int textSize = 20;
Display::Display(const DeviceInfo &info
, const PortInfo &port
, twoDModel::engine::TwoDModelEngineInterface &engine)
: robotModel::parts::TrikDisplay(info, port)
, mEngine(engine)
, mBackground(Qt::transparent)
{
mEngine.display()->setPainter(this);
connect(this, &Display::backgroundChanged, this, [=](const QColor &color) {
emit propertyChanged("background", color);
});
connect(this, &Display::smileChanged, this, [=](bool smiles, bool happy) {
emit propertyChanged("smiles", smiles && happy);
emit propertyChanged("sadSmiles", smiles && !happy);
});
connect(this, &Display::shapesSetChanged, this, [=]() {
// This is a bit hacky, but shapes set may be modified pretty often, can be pretty large
// and its serialization to JSON may take notable time, so we don't want to do it without real need.
if (receivers(SIGNAL(propertyChanged(QString, QVariant)))) {
emit propertyChanged("objects", toJson());
}
});
}
QString Display::background() const
{
return mBackground.name();
}
bool Display::smiles() const
{
return mSmiles;
}
bool Display::sadSmiles() const
{
return mSadSmiles;
}
void Display::drawPixel(int x, int y)
{
Canvas::drawPixel(x, y);
emit shapesSetChanged();
}
void Display::drawLine(int x1, int y1, int x2, int y2)
{
Canvas::drawLine(x1, y1, x2, y2);
emit shapesSetChanged();
}
void Display::drawRect(int x, int y, int width, int height, bool filled)
{
Canvas::drawRect(x, y, width, height, filled);
emit shapesSetChanged();
}
void Display::drawEllipse(int x, int y, int width, int height, bool filled)
{
Canvas::drawEllipse(x, y, width, height, filled);
emit shapesSetChanged();
}
void Display::drawArc(int x, int y, int width, int height, int startAngle, int spanAngle)
{
Canvas::drawArc(x, y, width, height, startAngle, spanAngle);
emit shapesSetChanged();
}
void Display::drawSmile(bool sad)
{
mCurrentImage = QImage(sad ? ":/icons/sadSmile.png" : ":/icons/smile.png");
mSmiles = !sad;
mSadSmiles = sad;
mEngine.display()->repaintDisplay();
emit smileChanged(true, !sad);
}
void Display::setBackground(const QColor &color)
{
mBackground = color;
emit backgroundChanged(color);
}
void Display::printText(int x, int y, const QString &text)
{
const QPair<int, int> coords(x, y);
if (mLabelsMap.contains(coords)) {
mLabelsMap[coords]->setText(text);
} else {
utils::TextObject * const textObject = new utils::TextObject(x, y, text
, mCurrentPenColor, mCurrentPenWidth);
mObjects << textObject;
mLabelsMap[coords] = textObject;
mLabels << textObject;
}
emit shapesSetChanged();
}
void Display::clearScreen()
{
// Background color is not cleared
mCurrentImage = QImage();
mSmiles = false;
mSadSmiles = false;
mLabelsMap.clear();
Canvas::reset();
emit smileChanged(false, false);
emit shapesSetChanged();
}
void Display::setPainterColor(const QColor &color)
{
Canvas::setPainterColor(color);
}
void Display::setPainterWidth(int penWidth)
{
Canvas::setPainterWidth(penWidth);
}
void Display::paint(QPainter *painter, const QRect &outputRect)
{
Q_UNUSED(outputRect)
const QRect displayRect(0, 0, mEngine.display()->displayWidth(), mEngine.display()->displayHeight());
painter->save();
painter->setPen(mBackground);
painter->setBrush(mBackground);
painter->drawRect(displayRect);
painter->drawImage(displayRect, mCurrentImage);
painter->restore();
painter->save();
painter->setRenderHint(QPainter::HighQualityAntialiasing);
QFont font;
font.setPixelSize(textSize);
painter->setFont(font);
painter->setPen(Qt::black);
const qreal xScale = displayRect.width() / (realWidth * 1.0);
const qreal yScale = displayRect.height() / (realHeight * 1.0);
painter->scale(xScale, yScale);
Canvas::paint(painter, {0, 0, realWidth, realHeight});
painter->restore();
}
void Display::reset()
{
clearScreen();
setBackground(Qt::transparent);
redraw();
}
void Display::redraw()
{
if (mEngine.display()) {
mEngine.display()->repaintDisplay();
}
}
|
fix trik displey size
|
fix trik displey size
|
C++
|
apache-2.0
|
iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal
|
c60b5453157ca181118b4bc43aa0ed858349745c
|
src/GwMaker.cc
|
src/GwMaker.cc
|
/*
The MIT License (MIT)
Copyright (C) 2017 RSK Labs Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
File: GwMaker.cc
Purpose: Poll RSK node to get new work and send it to Kafka "RawGw" topic
@author Martin Medina
@copyright RSK Labs Ltd.
@version 1.0 30/03/17
*/
#include "GwMaker.h"
#include <glog/logging.h>
#include <util.h>
#include <utilstrencodings.h>
#include "Utils.h"
GwMaker::GwMaker(const string &rskdRpcAddr, const string &rskdRpcUserpass,
const string &kafkaBrokers, uint32_t kRpcCallInterval)
: running_(true), rskdRpcAddr_(rskdRpcAddr),
rskdRpcUserpass_(rskdRpcUserpass), kRpcCallInterval_(kRpcCallInterval),
kafkaBrokers_(kafkaBrokers),
kafkaProducer_(kafkaBrokers_.c_str(), KAFKA_TOPIC_RAWGW, 0/* partition */)
{
}
GwMaker::~GwMaker() {}
bool GwMaker::init() {
map<string, string> options;
// set to 1 (0 is an illegal value here), deliver msg as soon as possible.
options["queue.buffering.max.ms"] = "1";
if (!kafkaProducer_.setup(&options)) {
LOG(ERROR) << "kafka producer setup failure";
return false;
}
// setup kafka and check if it's alive
if (!kafkaProducer_.checkAlive()) {
LOG(ERROR) << "kafka is NOT alive";
return false;
}
// TODO: check rskd is alive in a similar way as done for btcd
return true;
}
void GwMaker::stop() {
if (!running_) {
return;
}
running_ = false;
LOG(INFO) << "stop GwMaker";
}
void GwMaker::kafkaProduceMsg(const void *payload, size_t len) {
kafkaProducer_.produce(payload, len);
}
string GwMaker::constructRequest() {
return "{\"jsonrpc\": \"2.0\", \"method\": \"mnr_getWork\", \"params\": [], \"id\": 1}";
}
bool GwMaker::rskdRpcGw(string &response) {
string request = constructRequest();
bool res = bitcoindRpcCall(rskdRpcAddr_.c_str(), rskdRpcUserpass_.c_str(), request.c_str(), response);
if (!res) {
LOG(ERROR) << "rskd RPC failure";
return false;
}
return true;
}
bool GwMaker::checkFields(JsonNode &r) {
if (r["result"].type() != Utilities::JS::type::Obj ||
r["result"]["parentBlockHash"].type() != Utilities::JS::type::Str ||
r["result"]["blockHashForMergedMining"].type() != Utilities::JS::type::Str ||
r["result"]["target"].type() != Utilities::JS::type::Str ||
r["result"]["feesPaidToMiner"].type() != Utilities::JS::type::Str ||
r["result"]["notify"].type() != Utilities::JS::type::Bool) {
return false;
}
return true;
}
string GwMaker::constructRawMsg(string &gw, JsonNode &r) {
const uint256 gwHash = Hash(gw.begin(), gw.end());
LOG(INFO) << ", parent block hash: " << r["result"]["parentBlockHash"].str()
<< ", block hash for merge mining: " << r["result"]["blockHashForMergedMining"].str()
<< ", target: " << r["result"]["target"].str()
<< ", fees paid to miner: " << r["result"]["feesPaidToMiner"].str()
<< ", notify: " << r["result"]["notify"].boolean()
<< ", gwhash: " << gwHash.ToString();
return Strings::Format("{\"created_at_ts\":%u,"
"\"rskdRpcAddress\":\"%s\","
"\"rskdRpcUserPwd\":\"%s\","
"\"target\":\"%s\","
"\"parentBlockHash\":\"%s\","
"\"blockHashForMergedMining\":\"%s\","
"\"feesPaidToMiner\":\"%s\","
"\"notify\":\"%s\"}",
(uint32_t)time(nullptr),
rskdRpcAddr_.c_str(),
rskdRpcUserpass_.c_str(),
r["result"]["target"].str().c_str(),
r["result"]["parentBlockHash"].str().c_str(),
r["result"]["blockHashForMergedMining"].str().c_str(),
r["result"]["feesPaidToMiner"].str().c_str(),
r["result"]["notify"].boolean() ? "true" : "false");
}
string GwMaker::makeRawGwMsg() {
string gw;
if (!rskdRpcGw(gw)) {
return "";
}
LOG(ERROR) << "getwork return: " << gw;
JsonNode r;
if (!JsonNode::parse(gw.c_str(), gw.c_str() + gw.length(), r)) {
LOG(ERROR) << "decode gw failure: " << gw;
return "";
}
// check fields
if (!checkFields(r)) {
LOG(ERROR) << "gw check fields failure";
return "";
}
return constructRawMsg(gw, r);
}
void GwMaker::submitRawGwMsg() {
const string rawGwMsg = makeRawGwMsg();
if (rawGwMsg.length() == 0) {
LOG(ERROR) << "get rawGw failure";
return;
}
// submit to Kafka
LOG(INFO) << "submit to Kafka, msg len: " << rawGwMsg.length();
kafkaProduceMsg(rawGwMsg.c_str(), rawGwMsg.length());
}
void GwMaker::run() {
while (running_) {
sleep(kRpcCallInterval_);
submitRawGwMsg();
}
}
GwMakerEth::GwMakerEth(const string &rskdRpcAddr, const string &rskdRpcUserpass,
const string &kafkaBrokers, uint32_t kRpcCallInterval) : GwMaker(rskdRpcAddr, rskdRpcUserpass, kafkaBrokers, kRpcCallInterval)
{
}
string GwMakerEth::constructRequest()
{
return "{\"jsonrpc\": \"2.0\", \"method\": \"eth_getWork\", \"params\": [], \"id\": 1}";
}
bool GwMakerEth::checkFields(JsonNode &r) {
// Success
// {
// "jsonrpc": "2.0",
// "id": 73,
// "result": [
// "0xe4a01e87c4cf70dd9cba9e3167328f659aed36e79c34b1b0a3f3cb77cc62575f",
// "0x0000000000000000000000000000000000000000000000000000000000000000",
// "0x0000000040080100200400801002004008010020040080100200400801002004"
// ]
// }
// error
// {
// "jsonrpc": "2.0",
// "id": 73,
// "error": {
// "code": -32000,
// "message": "mining not ready: No work available yet, don't panic."
// }
// }
if (r["result"].type() != Utilities::JS::type::Obj ||
r["result"]["result"].type() != Utilities::JS::type::Array ||
r["result"]["result"].array().size() != 3) {
LOG(ERROR) << "getwork error: " << r.str();
return false;
}
return true;
}
string GwMakerEth::constructRawMsg(string &gw, JsonNode &r) {
const uint256 gwHash = Hash(gw.begin(), gw.end());
LOG(INFO) << ", getwork result: " << r["result"]["result"].str()
<< ", gwhash: " << gwHash.ToString();
auto result = r["result"]["result"].array();
return Strings::Format("{\"created_at_ts\":%u,"
"\"rskdRpcAddress\":\"%s\","
"\"rskdRpcUserPwd\":\"%s\","
"\"hHash\":\"%s\","
"\"sHash\":\"%s\","
"\"bCond\":\"%s\"\"}",
(uint32_t)time(nullptr),
rskdRpcAddr_.c_str(),
rskdRpcUserpass_.c_str(),
result[0].str().c_str(),
result[1].str().c_str(),
result[2].str().c_str());
}
|
/*
The MIT License (MIT)
Copyright (C) 2017 RSK Labs Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
File: GwMaker.cc
Purpose: Poll RSK node to get new work and send it to Kafka "RawGw" topic
@author Martin Medina
@copyright RSK Labs Ltd.
@version 1.0 30/03/17
*/
#include "GwMaker.h"
#include <glog/logging.h>
#include <util.h>
#include <utilstrencodings.h>
#include "Utils.h"
GwMaker::GwMaker(const string &rskdRpcAddr, const string &rskdRpcUserpass,
const string &kafkaBrokers, uint32_t kRpcCallInterval)
: running_(true), rskdRpcAddr_(rskdRpcAddr),
rskdRpcUserpass_(rskdRpcUserpass), kRpcCallInterval_(kRpcCallInterval),
kafkaBrokers_(kafkaBrokers),
kafkaProducer_(kafkaBrokers_.c_str(), KAFKA_TOPIC_RAWGW, 0/* partition */)
{
}
GwMaker::~GwMaker() {}
bool GwMaker::init() {
map<string, string> options;
// set to 1 (0 is an illegal value here), deliver msg as soon as possible.
options["queue.buffering.max.ms"] = "1";
if (!kafkaProducer_.setup(&options)) {
LOG(ERROR) << "kafka producer setup failure";
return false;
}
// setup kafka and check if it's alive
if (!kafkaProducer_.checkAlive()) {
LOG(ERROR) << "kafka is NOT alive";
return false;
}
// TODO: check rskd is alive in a similar way as done for btcd
return true;
}
void GwMaker::stop() {
if (!running_) {
return;
}
running_ = false;
LOG(INFO) << "stop GwMaker";
}
void GwMaker::kafkaProduceMsg(const void *payload, size_t len) {
kafkaProducer_.produce(payload, len);
}
string GwMaker::constructRequest() {
return "{\"jsonrpc\": \"2.0\", \"method\": \"mnr_getWork\", \"params\": [], \"id\": 1}";
}
bool GwMaker::rskdRpcGw(string &response) {
string request = constructRequest();
bool res = bitcoindRpcCall(rskdRpcAddr_.c_str(), rskdRpcUserpass_.c_str(), request.c_str(), response);
if (!res) {
LOG(ERROR) << "rskd RPC failure";
return false;
}
return true;
}
bool GwMaker::checkFields(JsonNode &r) {
if (r["result"].type() != Utilities::JS::type::Obj ||
r["result"]["parentBlockHash"].type() != Utilities::JS::type::Str ||
r["result"]["blockHashForMergedMining"].type() != Utilities::JS::type::Str ||
r["result"]["target"].type() != Utilities::JS::type::Str ||
r["result"]["feesPaidToMiner"].type() != Utilities::JS::type::Str ||
r["result"]["notify"].type() != Utilities::JS::type::Bool) {
return false;
}
return true;
}
string GwMaker::constructRawMsg(string &gw, JsonNode &r) {
const uint256 gwHash = Hash(gw.begin(), gw.end());
LOG(INFO) << ", parent block hash: " << r["result"]["parentBlockHash"].str()
<< ", block hash for merge mining: " << r["result"]["blockHashForMergedMining"].str()
<< ", target: " << r["result"]["target"].str()
<< ", fees paid to miner: " << r["result"]["feesPaidToMiner"].str()
<< ", notify: " << r["result"]["notify"].boolean()
<< ", gwhash: " << gwHash.ToString();
return Strings::Format("{\"created_at_ts\":%u,"
"\"rskdRpcAddress\":\"%s\","
"\"rskdRpcUserPwd\":\"%s\","
"\"target\":\"%s\","
"\"parentBlockHash\":\"%s\","
"\"blockHashForMergedMining\":\"%s\","
"\"feesPaidToMiner\":\"%s\","
"\"notify\":\"%s\"}",
(uint32_t)time(nullptr),
rskdRpcAddr_.c_str(),
rskdRpcUserpass_.c_str(),
r["result"]["target"].str().c_str(),
r["result"]["parentBlockHash"].str().c_str(),
r["result"]["blockHashForMergedMining"].str().c_str(),
r["result"]["feesPaidToMiner"].str().c_str(),
r["result"]["notify"].boolean() ? "true" : "false");
}
string GwMaker::makeRawGwMsg() {
string gw;
if (!rskdRpcGw(gw)) {
return "";
}
LOG(INFO) << "getwork return: " << gw;
JsonNode r;
if (!JsonNode::parse(gw.c_str(), gw.c_str() + gw.length(), r)) {
LOG(ERROR) << "decode gw failure: " << gw;
return "";
}
//LOG(INFO) << "result type: " << (int)r["result"].type();
//LOG(INFO) << "parse result: " << r["result"].str();
// check fields
if (!checkFields(r)) {
LOG(ERROR) << "gw check fields failure";
return "";
}
return constructRawMsg(gw, r);
}
void GwMaker::submitRawGwMsg() {
const string rawGwMsg = makeRawGwMsg();
if (rawGwMsg.length() == 0) {
LOG(ERROR) << "get rawGw failure";
return;
}
// submit to Kafka
LOG(INFO) << "submit to Kafka, msg len: " << rawGwMsg.length();
kafkaProduceMsg(rawGwMsg.c_str(), rawGwMsg.length());
}
void GwMaker::run() {
while (running_) {
sleep(kRpcCallInterval_);
submitRawGwMsg();
}
}
GwMakerEth::GwMakerEth(const string &rskdRpcAddr, const string &rskdRpcUserpass,
const string &kafkaBrokers, uint32_t kRpcCallInterval) : GwMaker(rskdRpcAddr, rskdRpcUserpass, kafkaBrokers, kRpcCallInterval)
{
}
string GwMakerEth::constructRequest()
{
return "{\"jsonrpc\": \"2.0\", \"method\": \"eth_getWork\", \"params\": [], \"id\": 1}";
}
bool GwMakerEth::checkFields(JsonNode &r) {
// Success
// {
// "jsonrpc": "2.0",
// "id": 73,
// "result": [
// "0xe4a01e87c4cf70dd9cba9e3167328f659aed36e79c34b1b0a3f3cb77cc62575f",
// "0x0000000000000000000000000000000000000000000000000000000000000000",
// "0x0000000040080100200400801002004008010020040080100200400801002004"
// ]
// }
// error
// {
// "jsonrpc": "2.0",
// "id": 73,
// "error": {
// "code": -32000,
// "message": "mining not ready: No work available yet, don't panic."
// }
// }
if (r.type() != Utilities::JS::type::Obj ||
r["result"].type() != Utilities::JS::type::Array ||
r["result"].array().size() != 3) {
LOG(ERROR) << "getwork error: " << r.str();
return false;
}
return true;
}
string GwMakerEth::constructRawMsg(string &gw, JsonNode &r) {
const uint256 gwHash = Hash(gw.begin(), gw.end());
LOG(INFO) << "gwhash: " << gwHash.ToString();
auto result = r["result"].array();
return Strings::Format("{\"created_at_ts\":%u,"
"\"rskdRpcAddress\":\"%s\","
"\"rskdRpcUserPwd\":\"%s\","
"\"hHash\":\"%s\","
"\"sHash\":\"%s\","
"\"bCond\":\"%s\"\"}",
(uint32_t)time(nullptr),
rskdRpcAddr_.c_str(),
rskdRpcUserpass_.c_str(),
result[0].str().c_str(),
result[1].str().c_str(),
result[2].str().c_str());
}
|
fix parser error
|
fix parser error
|
C++
|
mit
|
btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool
|
235876fcf38655aa57e46e66ae1429818892bdd2
|
src/natives.cpp
|
src/natives.cpp
|
#include "main.h"
#include "natives.h"
#include "CNetwork.h"
#include "CServer.h"
#include "CCallback.h"
//native TSC_Connect(user[], pass[], host[], port = 9987, serverquery_port = 10011);
AMX_DECLARE_NATIVE(Native::TSC_Connect)
{
string
login = amx_GetCppString(amx, params[1]),
pass = amx_GetCppString(amx, params[2]),
host = amx_GetCppString(amx, params[3]);
unsigned short
server_port = static_cast<unsigned short>(params[4]),
query_port = static_cast<unsigned short>(params[5]);
if (login.empty() || pass.empty() || host.empty()
|| server_port == 0 || query_port == 0)
return 0;
if (CNetwork::Get()->Connect(host, server_port, query_port))
{
while (CNetwork::Get()->IsConnected() == false)
boost::this_thread::sleep(boost::posix_time::milliseconds(20));
if (CServer::Get()->Login(login, pass))
{
while (CServer::Get()->IsLoggedIn() == false)
boost::this_thread::sleep(boost::posix_time::milliseconds(20));
return 1;
}
}
return 0;
}
//native TSC_Disconnect();
AMX_DECLARE_NATIVE(Native::TSC_Disconnect)
{
return CNetwork::Get()->Disconnect();
}
//native TSC_ChangeNickname(nickname[]);
AMX_DECLARE_NATIVE(Native::TSC_ChangeNickname)
{
return CServer::Get()->ChangeNickname(
amx_GetCppString(amx, params[1]));
}
//native TSC_SendServerMessage(msg[]);
AMX_DECLARE_NATIVE(Native::TSC_SendServerMessage)
{
return CServer::Get()->SendServerMessage(
amx_GetCppString(amx, params[1]));
}
//native TSC_QueryChannelData(channelid, TSC_CHANNEL_QUERYDATA:data, const callback[], const format[] = "", ...);
AMX_DECLARE_NATIVE(Native::TSC_QueryChannelData)
{
auto *callback = CCallbackHandler::Get()->Create(
amx_GetCppString(amx, params[3]),
amx_GetCppString(amx, params[4]),
amx,
params,
5);
if (callback == nullptr)
return 0;
return CServer::Get()->QueryChannelData(
static_cast<Channel::Id_t>(params[1]),
static_cast<Channel::QueryData>(params[2]),
callback);
}
//native TSC_QueryClientData(clientid, TSC_CLIENT_QUERYDATA:data, const callback[], const format[] = "", ...);
AMX_DECLARE_NATIVE(Native::TSC_QueryClientData)
{
auto *callback = CCallbackHandler::Get()->Create(
amx_GetCppString(amx, params[3]),
amx_GetCppString(amx, params[4]),
amx,
params,
5);
if (callback == nullptr)
return 0;
return CServer::Get()->QueryClientData(
static_cast<Client::Id_t>(params[1]),
static_cast<Client::QueryData>(params[2]),
callback);
}
//native TSC_GetQueriedData(dest[], max_len = sizeof(dest));
AMX_DECLARE_NATIVE(Native::TSC_GetQueriedData)
{
string dest;
bool ret_val = CServer::Get()->GetQueriedData(dest);
amx_SetCppString(amx, params[1], dest, params[2]);
return ret_val;
}
//native TSC_GetQueriedDataAsInt();
AMX_DECLARE_NATIVE(Native::TSC_GetQueriedDataAsInt)
{
int dest = 0;
CServer::Get()->GetQueriedData(dest);
return dest;
}
//native TSC_CreateChannel(channelname[], TSC_CHANNELTYPE:type = TEMPORARY, maxusers = -1, parentchannelid = -1, upperchannelid = -1, talkpower = 0);
AMX_DECLARE_NATIVE(Native::TSC_CreateChannel)
{
return CServer::Get()->CreateChannel(
amx_GetCppString(amx, params[1]),
static_cast<Channel::Types>(params[2]),
params[3],
static_cast<Channel::Id_t>(params[4]),
static_cast<Channel::Id_t>(params[5]),
params[6]);
}
//native TSC_DeleteChannel(channelid);
AMX_DECLARE_NATIVE(Native::TSC_DeleteChannel)
{
return CServer::Get()->DeleteChannel(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_GetChannelIdByName(channelname[]);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelIdByName)
{
return CServer::Get()->GetChannelIdByName(
amx_GetCppString(amx, params[1]));
}
//native TSC_IsValidChannel(channelid);
AMX_DECLARE_NATIVE(Native::TSC_IsValidChannel)
{
return CServer::Get()->IsValidChannel(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelName(channelid, channelname[]);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelName)
{
return CServer::Get()->SetChannelName(
static_cast<Channel::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
//native TSC_GetChannelName(channelid, dest[], maxlen = sizeof(dest));
AMX_DECLARE_NATIVE(Native::TSC_GetChannelName)
{
string channel_name = CServer::Get()->GetChannelName(static_cast<Channel::Id_t>(params[1]));
amx_SetCppString(amx, params[2], channel_name, params[3]);
return (channel_name.empty() == false);
}
//native TSC_SetChannelDescription(channelid, desc[]);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelDescription)
{
return CServer::Get()->SetChannelDescription(
static_cast<Channel::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
//native TSC_SetChannelType(channelid, type);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelType)
{
return CServer::Get()->SetChannelType(
static_cast<Channel::Id_t>(params[1]),
static_cast<Channel::Types>(params[2]));
}
//native TSC_GetChannelType(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelType)
{
return static_cast<cell>(CServer::Get()->GetChannelType(
static_cast<Channel::Id_t>(params[1])));
}
//native TSC_SetChannelPassword(channelid, password[]);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelPassword)
{
return CServer::Get()->SetChannelPassword(
static_cast<Channel::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
//native TSC_HasChannelPassword(channelid);
AMX_DECLARE_NATIVE(Native::TSC_HasChannelPassword)
{
return CServer::Get()->HasChannelPassword(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelRequiredTP(channelid, talkpower);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelRequiredTP)
{
return CServer::Get()->SetChannelRequiredTalkPower(
static_cast<Channel::Id_t>(params[1]),
params[2]);
}
//native TSC_GetChannelRequiredTP(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelRequiredTP)
{
return CServer::Get()->GetChannelRequiredTalkPower(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelUserLimit(channelid, maxusers);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelUserLimit)
{
return CServer::Get()->SetChannelUserLimit(
static_cast<Channel::Id_t>(params[1]),
params[2]);
}
//native TSC_GetChannelUserLimit(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelUserLimit)
{
return CServer::Get()->GetChannelUserLimit(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelParentId(channelid, parentchannelid);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelParentId)
{
return CServer::Get()->SetChannelParentId(
static_cast<Channel::Id_t>(params[1]),
static_cast<Channel::Id_t>(params[2]));
}
//native TSC_GetChannelParentId(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelParentId)
{
return CServer::Get()->GetChannelParentId(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelOrderId(channelid, upperchannelid);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelOrderId)
{
return CServer::Get()->SetChannelOrderId(
static_cast<Channel::Id_t>(params[1]),
static_cast<Channel::Id_t>(params[2]));
}
//native TSC_GetChannelOrderId(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelOrderId)
{
return CServer::Get()->GetChannelOrderId(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_GetDefaultChannelId();
AMX_DECLARE_NATIVE(Native::TSC_GetDefaultChannelId)
{
return CServer::Get()->GetDefaultChannelId();
}
//native TSC_GetClientIdByUid(uid[]);
AMX_DECLARE_NATIVE(Native::TSC_GetClientIdByUid)
{
return CServer::Get()->GetClientIdByUid(
amx_GetCppString(amx, params[1]));
}
//native TSC_GetClientIdByIpAddress(ip[]);
AMX_DECLARE_NATIVE(Native::TSC_GetClientIdByIpAddress)
{
return CServer::Get()->GetClientIdByUid(
amx_GetCppString(amx, params[1]));
}
//native TSC_GetClientUid(clientid, dest[], maxlen = sizeof(dest));
AMX_DECLARE_NATIVE(Native::TSC_GetClientUid)
{
string uid = CServer::Get()->GetClientUid(static_cast<Client::Id_t>(params[1]));
amx_SetCppString(amx, params[2], uid, params[3]);
return (uid.empty() == false);
}
//native TSC_GetClientDatabaseId(clientid);
AMX_DECLARE_NATIVE(Native::TSC_GetClientDatabaseId)
{
return CServer::Get()->GetClientDatabaseId(
static_cast<Client::Id_t>(params[1]));
}
//native TSC_GetClientChannelId(clientid);
AMX_DECLARE_NATIVE(Native::TSC_GetClientChannelId)
{
return CServer::Get()->GetClientChannelId(
static_cast<Client::Id_t>(params[1]));
}
//native TSC_GetClientIpAddress(clientid, dest[], maxlen = sizeof(dest));
AMX_DECLARE_NATIVE(Native::TSC_GetClientIpAddress)
{
string ip = CServer::Get()->GetClientIpAddress(static_cast<Client::Id_t>(params[1]));
amx_SetCppString(amx, params[2], ip, params[3]);
return (ip.empty() == false);
}
//native TSC_KickClient(clientid, TSC_KICKTYPE:kicktype, reasonmsg[]);
AMX_DECLARE_NATIVE(Native::TSC_KickClient)
{
return CServer::Get()->KickClient(
static_cast<Client::Id_t>(params[1]),
static_cast<Client::KickTypes>(params[2]),
amx_GetCppString(amx, params[3]));
}
//native TSC_BanClient(uid[], seconds, reasonmsg[]);
AMX_DECLARE_NATIVE(Native::TSC_BanClient)
{
return CServer::Get()->BanClient(
amx_GetCppString(amx, params[1]),
params[2],
amx_GetCppString(amx, params[3]));
}
//native TSC_MoveClient(clientid, channelid);
AMX_DECLARE_NATIVE(Native::TSC_MoveClient)
{
return CServer::Get()->MoveClient(
static_cast<Client::Id_t>(params[1]),
static_cast<Channel::Id_t>(params[2]));
}
//native TSC_SetClientChannelGroup(clientid, groupid, channelid);
AMX_DECLARE_NATIVE(Native::TSC_SetClientChannelGroup)
{
return CServer::Get()->SetClientChannelGroup(
static_cast<Client::Id_t>(params[1]),
params[2],
static_cast<Channel::Id_t>(params[3]));
}
//native TSC_AddClientToServerGroup(clientid, groupid);
AMX_DECLARE_NATIVE(Native::TSC_AddClientToServerGroup)
{
return CServer::Get()->AddClientToServerGroup(
static_cast<Client::Id_t>(params[1]),
params[2]);
}
//native TSC_RemoveClientFromServerGroup(clientid, groupid);
AMX_DECLARE_NATIVE(Native::TSC_RemoveClientFromServerGroup)
{
return CServer::Get()->RemoveClientFromServerGroup(
static_cast<Client::Id_t>(params[1]),
params[2]);
}
//native TSC_PokeClient(clientid, msg[]);
AMX_DECLARE_NATIVE(Native::TSC_PokeClient)
{
return CServer::Get()->PokeClient(
static_cast<Client::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
//native TSC_SendClientMessage(clientid, msg[]);
AMX_DECLARE_NATIVE(Native::TSC_SendClientMessage)
{
return CServer::Get()->SendClientMessage(
static_cast<Client::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
|
#include "main.h"
#include "natives.h"
#include "CNetwork.h"
#include "CServer.h"
#include "CCallback.h"
//native TSC_Connect(user[], pass[], host[], port = 9987, serverquery_port = 10011);
AMX_DECLARE_NATIVE(Native::TSC_Connect)
{
string
login = amx_GetCppString(amx, params[1]),
pass = amx_GetCppString(amx, params[2]),
host = amx_GetCppString(amx, params[3]);
unsigned short
server_port = static_cast<unsigned short>(params[4]),
query_port = static_cast<unsigned short>(params[5]);
if (login.empty() || pass.empty() || host.empty()
|| server_port == 0 || query_port == 0)
return 0;
if (CNetwork::Get()->Connect(host, server_port, query_port))
{
while (CNetwork::Get()->IsConnected() == false)
boost::this_thread::sleep(boost::posix_time::milliseconds(20));
if (CServer::Get()->Login(login, pass))
{
while (CServer::Get()->IsLoggedIn() == false)
boost::this_thread::sleep(boost::posix_time::milliseconds(20));
return 1;
}
}
return 0;
}
//native TSC_Disconnect();
AMX_DECLARE_NATIVE(Native::TSC_Disconnect)
{
return CNetwork::Get()->Disconnect();
}
//native TSC_ChangeNickname(nickname[]);
AMX_DECLARE_NATIVE(Native::TSC_ChangeNickname)
{
return CServer::Get()->ChangeNickname(
amx_GetCppString(amx, params[1]));
}
//native TSC_SendServerMessage(msg[]);
AMX_DECLARE_NATIVE(Native::TSC_SendServerMessage)
{
return CServer::Get()->SendServerMessage(
amx_GetCppString(amx, params[1]));
}
//native TSC_QueryChannelData(channelid, TSC_CHANNEL_QUERYDATA:data, const callback[], const format[] = "", ...);
AMX_DECLARE_NATIVE(Native::TSC_QueryChannelData)
{
auto *callback = CCallbackHandler::Get()->Create(
amx_GetCppString(amx, params[3]),
amx_GetCppString(amx, params[4]),
amx,
params,
5);
if (callback == nullptr)
return 0;
return CServer::Get()->QueryChannelData(
static_cast<Channel::Id_t>(params[1]),
static_cast<Channel::QueryData>(params[2]),
callback);
}
//native TSC_QueryClientData(clientid, TSC_CLIENT_QUERYDATA:data, const callback[], const format[] = "", ...);
AMX_DECLARE_NATIVE(Native::TSC_QueryClientData)
{
auto *callback = CCallbackHandler::Get()->Create(
amx_GetCppString(amx, params[3]),
amx_GetCppString(amx, params[4]),
amx,
params,
5);
if (callback == nullptr)
return 0;
return CServer::Get()->QueryClientData(
static_cast<Client::Id_t>(params[1]),
static_cast<Client::QueryData>(params[2]),
callback);
}
//native TSC_GetQueriedData(dest[], max_len = sizeof(dest));
AMX_DECLARE_NATIVE(Native::TSC_GetQueriedData)
{
string dest;
bool ret_val = CServer::Get()->GetQueriedData(dest);
amx_SetCppString(amx, params[1], dest, params[2]);
return ret_val;
}
//native TSC_GetQueriedDataAsInt();
AMX_DECLARE_NATIVE(Native::TSC_GetQueriedDataAsInt)
{
int dest = 0;
CServer::Get()->GetQueriedData(dest);
return dest;
}
//native TSC_CreateChannel(channelname[], TSC_CHANNELTYPE:type = TEMPORARY, maxusers = -1, parentchannelid = -1, upperchannelid = -1, talkpower = 0);
AMX_DECLARE_NATIVE(Native::TSC_CreateChannel)
{
return CServer::Get()->CreateChannel(
amx_GetCppString(amx, params[1]),
static_cast<Channel::Types>(params[2]),
params[3],
static_cast<Channel::Id_t>(params[4]),
static_cast<Channel::Id_t>(params[5]),
params[6]);
}
//native TSC_DeleteChannel(channelid);
AMX_DECLARE_NATIVE(Native::TSC_DeleteChannel)
{
return CServer::Get()->DeleteChannel(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_GetChannelIdByName(channelname[]);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelIdByName)
{
return CServer::Get()->GetChannelIdByName(
amx_GetCppString(amx, params[1]));
}
//native TSC_IsValidChannel(channelid);
AMX_DECLARE_NATIVE(Native::TSC_IsValidChannel)
{
return CServer::Get()->IsValidChannel(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelName(channelid, channelname[]);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelName)
{
return CServer::Get()->SetChannelName(
static_cast<Channel::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
//native TSC_GetChannelName(channelid, dest[], maxlen = sizeof(dest));
AMX_DECLARE_NATIVE(Native::TSC_GetChannelName)
{
string channel_name = CServer::Get()->GetChannelName(static_cast<Channel::Id_t>(params[1]));
amx_SetCppString(amx, params[2], channel_name, params[3]);
return (channel_name.empty() == false);
}
//native TSC_SetChannelDescription(channelid, desc[]);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelDescription)
{
return CServer::Get()->SetChannelDescription(
static_cast<Channel::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
//native TSC_SetChannelType(channelid, type);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelType)
{
return CServer::Get()->SetChannelType(
static_cast<Channel::Id_t>(params[1]),
static_cast<Channel::Types>(params[2]));
}
//native TSC_GetChannelType(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelType)
{
return static_cast<cell>(CServer::Get()->GetChannelType(
static_cast<Channel::Id_t>(params[1])));
}
//native TSC_SetChannelPassword(channelid, password[]);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelPassword)
{
return CServer::Get()->SetChannelPassword(
static_cast<Channel::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
//native TSC_HasChannelPassword(channelid);
AMX_DECLARE_NATIVE(Native::TSC_HasChannelPassword)
{
return CServer::Get()->HasChannelPassword(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelRequiredTP(channelid, talkpower);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelRequiredTP)
{
return CServer::Get()->SetChannelRequiredTalkPower(
static_cast<Channel::Id_t>(params[1]),
params[2]);
}
//native TSC_GetChannelRequiredTP(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelRequiredTP)
{
return CServer::Get()->GetChannelRequiredTalkPower(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelUserLimit(channelid, maxusers);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelUserLimit)
{
return CServer::Get()->SetChannelUserLimit(
static_cast<Channel::Id_t>(params[1]),
params[2]);
}
//native TSC_GetChannelUserLimit(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelUserLimit)
{
return CServer::Get()->GetChannelUserLimit(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelParentId(channelid, parentchannelid);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelParentId)
{
return CServer::Get()->SetChannelParentId(
static_cast<Channel::Id_t>(params[1]),
static_cast<Channel::Id_t>(params[2]));
}
//native TSC_GetChannelParentId(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelParentId)
{
return CServer::Get()->GetChannelParentId(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_SetChannelOrderId(channelid, upperchannelid);
AMX_DECLARE_NATIVE(Native::TSC_SetChannelOrderId)
{
return CServer::Get()->SetChannelOrderId(
static_cast<Channel::Id_t>(params[1]),
static_cast<Channel::Id_t>(params[2]));
}
//native TSC_GetChannelOrderId(channelid);
AMX_DECLARE_NATIVE(Native::TSC_GetChannelOrderId)
{
return CServer::Get()->GetChannelOrderId(
static_cast<Channel::Id_t>(params[1]));
}
//native TSC_GetDefaultChannelId();
AMX_DECLARE_NATIVE(Native::TSC_GetDefaultChannelId)
{
return CServer::Get()->GetDefaultChannelId();
}
//native TSC_GetClientIdByUid(uid[]);
AMX_DECLARE_NATIVE(Native::TSC_GetClientIdByUid)
{
return CServer::Get()->GetClientIdByUid(
amx_GetCppString(amx, params[1]));
}
//native TSC_GetClientIdByIpAddress(ip[]);
AMX_DECLARE_NATIVE(Native::TSC_GetClientIdByIpAddress)
{
return CServer::Get()->GetClientIdByIpAddress(
amx_GetCppString(amx, params[1]));
}
//native TSC_GetClientUid(clientid, dest[], maxlen = sizeof(dest));
AMX_DECLARE_NATIVE(Native::TSC_GetClientUid)
{
string uid = CServer::Get()->GetClientUid(static_cast<Client::Id_t>(params[1]));
amx_SetCppString(amx, params[2], uid, params[3]);
return (uid.empty() == false);
}
//native TSC_GetClientDatabaseId(clientid);
AMX_DECLARE_NATIVE(Native::TSC_GetClientDatabaseId)
{
return CServer::Get()->GetClientDatabaseId(
static_cast<Client::Id_t>(params[1]));
}
//native TSC_GetClientChannelId(clientid);
AMX_DECLARE_NATIVE(Native::TSC_GetClientChannelId)
{
return CServer::Get()->GetClientChannelId(
static_cast<Client::Id_t>(params[1]));
}
//native TSC_GetClientIpAddress(clientid, dest[], maxlen = sizeof(dest));
AMX_DECLARE_NATIVE(Native::TSC_GetClientIpAddress)
{
string ip = CServer::Get()->GetClientIpAddress(static_cast<Client::Id_t>(params[1]));
amx_SetCppString(amx, params[2], ip, params[3]);
return (ip.empty() == false);
}
//native TSC_KickClient(clientid, TSC_KICKTYPE:kicktype, reasonmsg[]);
AMX_DECLARE_NATIVE(Native::TSC_KickClient)
{
return CServer::Get()->KickClient(
static_cast<Client::Id_t>(params[1]),
static_cast<Client::KickTypes>(params[2]),
amx_GetCppString(amx, params[3]));
}
//native TSC_BanClient(uid[], seconds, reasonmsg[]);
AMX_DECLARE_NATIVE(Native::TSC_BanClient)
{
return CServer::Get()->BanClient(
amx_GetCppString(amx, params[1]),
params[2],
amx_GetCppString(amx, params[3]));
}
//native TSC_MoveClient(clientid, channelid);
AMX_DECLARE_NATIVE(Native::TSC_MoveClient)
{
return CServer::Get()->MoveClient(
static_cast<Client::Id_t>(params[1]),
static_cast<Channel::Id_t>(params[2]));
}
//native TSC_SetClientChannelGroup(clientid, groupid, channelid);
AMX_DECLARE_NATIVE(Native::TSC_SetClientChannelGroup)
{
return CServer::Get()->SetClientChannelGroup(
static_cast<Client::Id_t>(params[1]),
params[2],
static_cast<Channel::Id_t>(params[3]));
}
//native TSC_AddClientToServerGroup(clientid, groupid);
AMX_DECLARE_NATIVE(Native::TSC_AddClientToServerGroup)
{
return CServer::Get()->AddClientToServerGroup(
static_cast<Client::Id_t>(params[1]),
params[2]);
}
//native TSC_RemoveClientFromServerGroup(clientid, groupid);
AMX_DECLARE_NATIVE(Native::TSC_RemoveClientFromServerGroup)
{
return CServer::Get()->RemoveClientFromServerGroup(
static_cast<Client::Id_t>(params[1]),
params[2]);
}
//native TSC_PokeClient(clientid, msg[]);
AMX_DECLARE_NATIVE(Native::TSC_PokeClient)
{
return CServer::Get()->PokeClient(
static_cast<Client::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
//native TSC_SendClientMessage(clientid, msg[]);
AMX_DECLARE_NATIVE(Native::TSC_SendClientMessage)
{
return CServer::Get()->SendClientMessage(
static_cast<Client::Id_t>(params[1]),
amx_GetCppString(amx, params[2]));
}
|
fix a bug where TSC_GetClientIdByIpAddress called wrong function
|
fix a bug where TSC_GetClientIdByIpAddress called wrong function
|
C++
|
mit
|
maddinat0r/samp-tsconnector
|
c12ef9e92342bfc24b5917a1d8cef5e8cd51e797
|
src/Memory.cpp
|
src/Memory.cpp
|
/*
DDS, a bridge double dummy solver.
Copyright (C) 2006-2014 by Bo Haglund /
2014-2018 by Bo Haglund & Soren Hein.
See LICENSE and README.
*/
#include "Memory.h"
Memory::Memory()
{
Memory::Reset();
}
Memory::~Memory()
{
}
void Memory::Reset()
{
nThreads = 0;
}
void Memory::ResetThread(const unsigned thrId)
{
memory[thrId]->transTable->ResetMemory(TT_RESET_FREE_MEMORY);
memory[thrId]->memUsed = Memory::MemoryInUseMB(thrId);
}
void Memory::ReturnThread(const unsigned thrId)
{
memory[thrId]->transTable->ReturnAllMemory();
memory[thrId]->memUsed = Memory::MemoryInUseMB(thrId);
}
void Memory::Resize(
const unsigned n,
const TTmemory flag,
const int memDefault_MB,
const int memMaximum_MB)
{
if (nThreads == n)
return;
if (nThreads > n)
{
// Downsize.
for (unsigned i = n; i < nThreads; i++)
{
memory[i]->transTable->ReturnAllMemory();
delete memory[i]->transTable;
delete memory[i];
}
memory.resize(static_cast<unsigned>(n));
threadSizes.resize(static_cast<unsigned>(n));
}
else
{
// Upsize.
memory.resize(n);
threadSizes.resize(n);
for (unsigned i = nThreads; i < n; i++)
{
memory[i] = new ThreadData;
if (flag == DDS_TT_SMALL)
{
memory[i]->transTable = new TransTableS;
threadSizes[i] = "S";
}
else
{
memory[i]->transTable = new TransTableL;
threadSizes[i] = "L";
}
memory[i]->transTable->SetMemoryDefault(memDefault_MB);
memory[i]->transTable->SetMemoryMaximum(memMaximum_MB);
memory[i]->transTable->MakeTT();
}
}
nThreads = n;
}
int Memory::NumThreads() const
{
return static_cast<int>(nThreads);
}
ThreadData * Memory::GetPtr(const unsigned thrId)
{
if (thrId >= nThreads)
{
cout << "Memory::GetPtr: " << thrId << " vs. " << nThreads << endl;
exit(1);
}
return memory[thrId];
}
double Memory::MemoryInUseMB(const unsigned thrId) const
{
return memory[thrId]->transTable->MemoryInUse() +
8192. * sizeof(relRanksType) / static_cast<double>(1024.);
}
void Memory::ReturnAllMemory()
{
Memory::Resize(0, DDS_TT_SMALL, 0, 0);
}
string Memory::ThreadSize(const unsigned thrId) const
{
return threadSizes[thrId];
}
|
/*
DDS, a bridge double dummy solver.
Copyright (C) 2006-2014 by Bo Haglund /
2014-2018 by Bo Haglund & Soren Hein.
See LICENSE and README.
*/
#include "Memory.h"
Memory::Memory()
{
Memory::Reset();
}
Memory::~Memory()
{
}
void Memory::Reset()
{
nThreads = 0;
}
void Memory::ResetThread(const unsigned thrId)
{
memory[thrId]->transTable->ResetMemory(TT_RESET_FREE_MEMORY);
memory[thrId]->memUsed = Memory::MemoryInUseMB(thrId);
}
void Memory::ReturnThread(const unsigned thrId)
{
memory[thrId]->transTable->ReturnAllMemory();
memory[thrId]->memUsed = Memory::MemoryInUseMB(thrId);
}
void Memory::Resize(
const unsigned n,
const TTmemory flag,
const int memDefault_MB,
const int memMaximum_MB)
{
if (nThreads == n)
return;
if (nThreads > n)
{
// Downsize.
for (unsigned i = n; i < nThreads; i++)
{
memory[i]->transTable->ReturnAllMemory();
delete memory[i]->transTable;
delete memory[i];
}
memory.resize(static_cast<unsigned>(n));
threadSizes.resize(static_cast<unsigned>(n));
}
else
{
// Upsize.
memory.resize(n);
threadSizes.resize(n);
for (unsigned i = nThreads; i < n; i++)
{
memory[i] = new ThreadData();
if (flag == DDS_TT_SMALL)
{
memory[i]->transTable = new TransTableS;
threadSizes[i] = "S";
}
else
{
memory[i]->transTable = new TransTableL;
threadSizes[i] = "L";
}
memory[i]->transTable->SetMemoryDefault(memDefault_MB);
memory[i]->transTable->SetMemoryMaximum(memMaximum_MB);
memory[i]->transTable->MakeTT();
}
}
nThreads = n;
}
int Memory::NumThreads() const
{
return static_cast<int>(nThreads);
}
ThreadData * Memory::GetPtr(const unsigned thrId)
{
if (thrId >= nThreads)
{
cout << "Memory::GetPtr: " << thrId << " vs. " << nThreads << endl;
exit(1);
}
return memory[thrId];
}
double Memory::MemoryInUseMB(const unsigned thrId) const
{
return memory[thrId]->transTable->MemoryInUse() +
8192. * sizeof(relRanksType) / static_cast<double>(1024.);
}
void Memory::ReturnAllMemory()
{
Memory::Resize(0, DDS_TT_SMALL, 0, 0);
}
string Memory::ThreadSize(const unsigned thrId) const
{
return threadSizes[thrId];
}
|
Initialize thread data to zero
|
Initialize thread data to zero
|
C++
|
apache-2.0
|
dds-bridge/dds,sorenhein/dds,sorenhein/dds,dds-bridge/dds
|
8670727ea8756c3adec38bbc022a28209cae1d55
|
SQUIRREL3/squirrel/sqtable.cpp
|
SQUIRREL3/squirrel/sqtable.cpp
|
/*
see copyright notice in squirrel.h
*/
#include "sqpcheader.h"
#include "sqvm.h"
#include "sqtable.h"
#include "sqfuncproto.h"
#include "sqclosure.h"
SQTable::SQTable(SQSharedState *ss,SQInteger nInitialSize)
{
SQInteger pow2size=MINPOWER2;
while(nInitialSize>pow2size)pow2size=pow2size<<1;
AllocNodes(pow2size);
_usednodes = 0;
_delegate = NULL;
INIT_CHAIN();
ADD_TO_CHAIN(&_sharedstate->_gc_chain,this);
}
void SQTable::Remove(const SQObjectPtr &key)
{
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1));
if (n) {
n->val.Null();
n->key.Null();
_usednodes--;
Rehash(false);
}
}
void SQTable::AllocNodes(SQInteger nSize)
{
_HashNode *nodes=(_HashNode *)SQ_MALLOC(sizeof(_HashNode)*nSize);
for(SQInteger i=0;i<nSize;i++){
_HashNode &n = nodes[i];
new (&n) _HashNode;
n.next=NULL;
}
_numofnodes=nSize;
_nodes=nodes;
_firstfree=&_nodes[_numofnodes-1];
}
void SQTable::Rehash(bool force)
{
SQInteger oldsize=_numofnodes;
//prevent problems with the integer division
if(oldsize<4)oldsize=4;
_HashNode *nold=_nodes;
SQInteger nelems=CountUsed();
if (nelems >= oldsize-oldsize/4) /* using more than 3/4? */
AllocNodes(oldsize*2);
else if (nelems <= oldsize/4 && /* less than 1/4? */
oldsize > MINPOWER2)
AllocNodes(oldsize/2);
else if(force)
AllocNodes(oldsize);
else
return;
_usednodes = 0;
for (SQInteger i=0; i<oldsize; i++) {
_HashNode *old = nold+i;
if (type(old->key) != OT_NULL)
NewSlot(old->key,old->val);
}
for(SQInteger k=0;k<oldsize;k++)
nold[k].~_HashNode();
SQ_FREE(nold,oldsize*sizeof(_HashNode));
}
SQTable *SQTable::Clone()
{
SQTable *nt=Create(_opt_ss(this),_numofnodes);
#ifdef _FAST_CLONE
_HashNode *basesrc = _nodes;
_HashNode *basedst = nt->_nodes;
_HashNode *src = _nodes;
_HashNode *dst = nt->_nodes;
SQInteger n = 0;
for(n = 0; n < _numofnodes; n++) {
dst->key = src->key;
dst->val = src->val;
if(src->next) {
assert(src->next > basesrc);
dst->next = basedst + (src->next - basesrc);
assert(dst != dst->next);
}
dst++;
src++;
}
assert(_firstfree > basesrc);
assert(_firstfree != NULL);
nt->_firstfree = basedst + (_firstfree - basesrc);
nt->_usednodes = _usednodes;
#else
SQInteger ridx=0;
SQObjectPtr key,val;
while((ridx=Next(true,ridx,key,val))!=-1){
nt->NewSlot(key,val);
}
#endif
nt->SetDelegate(_delegate);
return nt;
}
bool SQTable::Get(const SQObjectPtr &key,SQObjectPtr &val)
{
if(type(key) == OT_NULL)
return false;
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1));
if (n) {
val = _realval(n->val);
return true;
}
return false;
}
bool SQTable::NewSlot(const SQObjectPtr &key,const SQObjectPtr &val)
{
assert(type(key) != OT_NULL);
SQHash h = HashObj(key) & (_numofnodes - 1);
_HashNode *n = _Get(key, h);
if (n) {
n->val = val;
return false;
}
_HashNode *mp = &_nodes[h];
n = mp;
//key not found I'll insert it
//main pos is not free
if(type(mp->key) != OT_NULL) {
n = _firstfree; /* get a free place */
SQHash mph = HashObj(mp->key) & (_numofnodes - 1);
_HashNode *othern; /* main position of colliding node */
if (mp > n && (othern = &_nodes[mph]) != mp){
/* yes; move colliding node into free position */
while (othern->next != mp){
assert(othern->next != NULL);
othern = othern->next; /* find previous */
}
othern->next = n; /* redo the chain with `n' in place of `mp' */
n->key = mp->key;
n->val = mp->val;/* copy colliding node into free pos. (mp->next also goes) */
n->next = mp->next;
mp->key.Null();
mp->val.Null();
mp->next = NULL; /* now `mp' is free */
}
else{
/* new node will go into free position */
n->next = mp->next; /* chain new position */
mp->next = n;
mp = n;
}
}
mp->key = key;
for (;;) { /* correct `firstfree' */
if (type(_firstfree->key) == OT_NULL && _firstfree->next == NULL) {
mp->val = val;
_usednodes++;
return true; /* OK; table still has a free place */
}
else if (_firstfree == _nodes) break; /* cannot decrement from here */
else (_firstfree)--;
}
Rehash(true);
return NewSlot(key, val);
}
SQInteger SQTable::Next(bool getweakrefs,const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval)
{
SQInteger idx = (SQInteger)TranslateIndex(refpos);
while (idx < _numofnodes) {
if(type(_nodes[idx].key) != OT_NULL) {
//first found
_HashNode &n = _nodes[idx];
outkey = n.key;
outval = getweakrefs?(SQObject)n.val:_realval(n.val);
//return idx for the next iteration
return ++idx;
}
++idx;
}
//nothing to iterate anymore
return -1;
}
bool SQTable::Set(const SQObjectPtr &key, const SQObjectPtr &val)
{
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1));
if (n) {
n->val = val;
return true;
}
return false;
}
void SQTable::_ClearNodes()
{
for(SQInteger i = 0;i < _numofnodes; i++) { _HashNode &n = _nodes[i]; n.key.Null(); n.val.Null(); }
}
void SQTable::Finalize()
{
_ClearNodes();
SetDelegate(NULL);
}
void SQTable::Clear()
{
_ClearNodes();
_usednodes = 0;
Rehash(true);
}
|
/*
see copyright notice in squirrel.h
*/
#include "sqpcheader.h"
#include "sqvm.h"
#include "sqtable.h"
#include "sqfuncproto.h"
#include "sqclosure.h"
SQTable::SQTable(SQSharedState *ss,SQInteger nInitialSize)
{
SQInteger pow2size=MINPOWER2;
while(nInitialSize>pow2size)pow2size=pow2size<<1;
AllocNodes(pow2size);
_usednodes = 0;
_delegate = NULL;
INIT_CHAIN();
ADD_TO_CHAIN(&_sharedstate->_gc_chain,this);
}
void SQTable::Remove(const SQObjectPtr &key)
{
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1));
if (n) {
n->val.Null();
n->key.Null();
_usednodes--;
Rehash(false);
}
}
void SQTable::AllocNodes(SQInteger nSize)
{
_HashNode *nodes=(_HashNode *)SQ_MALLOC(sizeof(_HashNode)*nSize);
for(SQInteger i=0;i<nSize;i++){
_HashNode &n = nodes[i];
new (&n) _HashNode;
n.next=NULL;
}
_numofnodes=nSize;
_nodes=nodes;
_firstfree=&_nodes[_numofnodes-1];
}
void SQTable::Rehash(bool force)
{
SQInteger oldsize=_numofnodes;
//prevent problems with the integer division
if(oldsize<4)oldsize=4;
_HashNode *nold=_nodes;
SQInteger nelems=CountUsed();
if (nelems >= oldsize-oldsize/4) /* using more than 3/4? */
AllocNodes(oldsize*2);
else if (nelems <= oldsize/4 && /* less than 1/4? */
oldsize > MINPOWER2)
AllocNodes(oldsize/2);
else if(force)
AllocNodes(oldsize);
else
return;
_usednodes = 0;
for (SQInteger i=0; i<oldsize; i++) {
_HashNode *old = nold+i;
if (type(old->key) != OT_NULL)
NewSlot(old->key,old->val);
}
for(SQInteger k=0;k<oldsize;k++)
nold[k].~_HashNode();
SQ_FREE(nold,oldsize*sizeof(_HashNode));
}
SQTable *SQTable::Clone()
{
SQTable *nt=Create(_opt_ss(this),_numofnodes);
#ifdef _FAST_CLONE
_HashNode *basesrc = _nodes;
_HashNode *basedst = nt->_nodes;
_HashNode *src = _nodes;
_HashNode *dst = nt->_nodes;
SQInteger n = 0;
for(n = 0; n < _numofnodes; n++) {
dst->key = src->key;
dst->val = src->val;
if(src->next) {
assert(src->next > basesrc);
dst->next = basedst + (src->next - basesrc);
assert(dst != dst->next);
}
dst++;
src++;
}
assert(_firstfree > basesrc);
assert(_firstfree != NULL);
nt->_firstfree = basedst + (_firstfree - basesrc);
nt->_usednodes = _usednodes;
#else
SQInteger ridx=0;
SQObjectPtr key,val;
while((ridx=Next(true,ridx,key,val))!=-1){
nt->NewSlot(key,val);
}
#endif
nt->SetDelegate(_delegate);
return nt;
}
bool SQTable::Get(const SQObjectPtr &key,SQObjectPtr &val)
{
if(type(key) == OT_NULL)
return false;
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1));
if (n) {
val = _realval(n->val);
return true;
}
return false;
}
bool SQTable::NewSlot(const SQObjectPtr &key,const SQObjectPtr &val)
{
assert(type(key) != OT_NULL);
SQHash h = HashObj(key) & (_numofnodes - 1);
_HashNode *n = _Get(key, h);
if (n) {
n->val = val;
return false;
}
_HashNode *mp = &_nodes[h];
//key not found I'll insert it
//main pos is not free
if(type(mp->key) != OT_NULL) {
n = _firstfree; /* get a free place */
SQHash mph = HashObj(mp->key) & (_numofnodes - 1);
_HashNode *othern; /* main position of colliding node */
if (mp > n && (othern = &_nodes[mph]) != mp){
/* yes; move colliding node into free position */
while (othern->next != mp){
assert(othern->next != NULL);
othern = othern->next; /* find previous */
}
othern->next = n; /* redo the chain with `n' in place of `mp' */
n->key = mp->key;
n->val = mp->val;/* copy colliding node into free pos. (mp->next also goes) */
n->next = mp->next;
mp->key.Null();
mp->val.Null();
mp->next = NULL; /* now `mp' is free */
}
else{
/* new node will go into free position */
n->next = mp->next; /* chain new position */
mp->next = n;
mp = n;
}
}
mp->key = key;
for (;;) { /* correct `firstfree' */
if (type(_firstfree->key) == OT_NULL && _firstfree->next == NULL) {
mp->val = val;
_usednodes++;
return true; /* OK; table still has a free place */
}
else if (_firstfree == _nodes) break; /* cannot decrement from here */
else (_firstfree)--;
}
Rehash(true);
return NewSlot(key, val);
}
SQInteger SQTable::Next(bool getweakrefs,const SQObjectPtr &refpos, SQObjectPtr &outkey, SQObjectPtr &outval)
{
SQInteger idx = (SQInteger)TranslateIndex(refpos);
while (idx < _numofnodes) {
if(type(_nodes[idx].key) != OT_NULL) {
//first found
_HashNode &n = _nodes[idx];
outkey = n.key;
outval = getweakrefs?(SQObject)n.val:_realval(n.val);
//return idx for the next iteration
return ++idx;
}
++idx;
}
//nothing to iterate anymore
return -1;
}
bool SQTable::Set(const SQObjectPtr &key, const SQObjectPtr &val)
{
_HashNode *n = _Get(key, HashObj(key) & (_numofnodes - 1));
if (n) {
n->val = val;
return true;
}
return false;
}
void SQTable::_ClearNodes()
{
for(SQInteger i = 0;i < _numofnodes; i++) { _HashNode &n = _nodes[i]; n.key.Null(); n.val.Null(); }
}
void SQTable::Finalize()
{
_ClearNodes();
SetDelegate(NULL);
}
void SQTable::Clear()
{
_ClearNodes();
_usednodes = 0;
Rehash(true);
}
|
Fix 'value stored to n is never read' warning.
|
Fix 'value stored to n is never read' warning.
|
C++
|
mit
|
wanderwaltz/Squirrel,wanderwaltz/Squirrel
|
f0a19d7694b9842214b2e0edcff14aab7df8bab3
|
src/Server.cpp
|
src/Server.cpp
|
#include <cstring>
#include <vector>
#include <map>
#include <sys/queue.h>
#include <evhttp.h>
#include <mecab.h>
#include "Furigana.h"
#include "Server.h"
#define PARSE_URI(request, params) { \
char const *uri = evhttp_request_uri(request); \
evhttp_parse_query(uri, ¶ms); \
}
#define PARAM_GET_STR(var, params, name, mendatory) { \
var = evhttp_find_header(¶ms_get, name); \
if (!var && mendatory) { \
http_send(request, "<err message=\"field '" name "' is mendatory\"/>\n"); \
return; \
} \
}
inline static void output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
evbuffer_add_printf(buffer, "<root>\n");
}
inline static void output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</root>\n");
}
inline static void kana_output_xml(const char *kana, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<kana><![CDATA[");
evbuffer_add_printf(buffer, "%s", kana);
evbuffer_add_printf(buffer, "]]></kana>\n");
}
inline static void parse_output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<parse>\n");
}
inline static void parse_output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</parse>\n");
}
inline static void cdata_output_xml(const char *string, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<![CDATA[%s]]>", string);
}
inline static void reading_output_xml(
std::pair<std::string,
std::string> text,
struct evbuffer *buffer
) {
evbuffer_add_printf(
buffer,
"<reading furigana=\"%s\"><![CDATA[%s]]></reading>",
text.second.c_str(),
text.first.c_str()
);
}
inline static void token_output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<token>");
}
inline static void token_output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</token>\n");
}
inline static void token_output_xml(const char *token, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<token><![CDATA[");
evbuffer_add_printf(buffer, "%s",token);
evbuffer_add_printf(buffer, "]]></token>\n");
}
/**
*
*/
static void http_send(struct evhttp_request *request, const char *fmt, ...) {
struct evbuffer *buffer = evbuffer_new();
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
va_list ap;
va_start(ap, fmt);
evbuffer_add_vprintf(buffer, fmt, ap);
va_end(ap);
evhttp_send_reply(request, HTTP_OK, "", buffer);
evbuffer_free(buffer);
}
/**** uri: *
*
*/
static void http_callback_default(struct evhttp_request *request, void *data) {
evhttp_send_error(request, HTTP_NOTFOUND, "Service not found");
}
/**** uri: /kana?str=*
*
*/
static void http_kana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
const char *kana = server->yomiTagger->parse(str);
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
std::string enforcedHiranagas = server->furigana.katakana_to_hiragana(kana);
kana_output_xml(enforcedHiranagas.c_str(), buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**** uri: /parse?str=*
*
*/
static void http_parse_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
std::vector<std::string> tokens;
const MeCab::Node* node = server->tagger->parseToNode(str);
for (; node; node = node->next) {
if (node->stat != MECAB_BOS_NODE && node->stat != MECAB_EOS_NODE) {
tokens.push_back(std::string(node->surface, node->length));
}
}
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml_header(buffer);
for (auto& oneToken : tokens) {
token_output_xml(oneToken.c_str(), buffer);
}
parse_output_xml_footer(buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
static std::string mecab_node_get_reading(const MeCab::Node *node) {
#define MECAB_FEATURE_READING_FIELD 8
size_t field = 0;
char *token, *infos = strdupa(node->feature);
token = strtok(infos, ",");
while (token != NULL) {
field++;
if (field == MECAB_FEATURE_READING_FIELD) {
return std::string(token);
}
token = strtok(NULL, ",");
}
return "";
}
/**** uri: /furigana?str=*
*
*/
static void http_furigana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into furigana => token+kana
Server* server = (Server*) data;
std::vector< std::vector<std::pair<std::string, std::string> > > tokens;
const MeCab::Node* node = server->tagger->parseToNode(str); for (; node; node = node->next) {
if (node->stat != MECAB_BOS_NODE && node->stat != MECAB_EOS_NODE) {
std::string token(node->surface, node->length);
std::string kana(mecab_node_get_reading(node));
std::vector<std::pair<std::string, std::string> > smallerTokens;
smallerTokens = server->furigana.tokenize(token, kana);
tokens.insert(
tokens.end(),
smallerTokens
);
}
}
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml_header(buffer);
for (auto& readings : tokens) {
token_output_xml_header(buffer);
for (auto& text : readings) {
if (text.second.empty()) {
cdata_output_xml(text.first.c_str(), buffer);
} else {
reading_output_xml(text, buffer);
}
}
token_output_xml_footer(buffer);
}
parse_output_xml_footer(buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**
*
*/
Server::Server(std::string address, int port) {
struct event_base *base = event_init();
struct evhttp *server = evhttp_new(base);
int res = evhttp_bind_socket(server, address.c_str(), port);
wakatiTagger = MeCab::createTagger("-Owakati");
yomiTagger = MeCab::createTagger("-Oyomi");
tagger = MeCab::createTagger("");
if (res != 0) {
std::cout << "[ERROR] Could not start http server!" << std::endl;
return;
}
evhttp_set_gencb(server, http_callback_default, this);
evhttp_set_cb(server, "/kana", http_kana_callback, this);
evhttp_set_cb(server, "/parse", http_parse_callback, this);
evhttp_set_cb(server, "/furigana", http_furigana_callback, this);
event_base_dispatch(base);
}
/**
*
*
*/
Server::~Server() {
delete wakatiTagger;
delete yomiTagger;
delete tagger;
}
|
#include <cstring>
#include <vector>
#include <map>
#include <sys/queue.h>
#include <evhttp.h>
#include <mecab.h>
#include "Furigana.h"
#include "Server.h"
#define PARSE_URI(request, params) { \
char const *uri = evhttp_request_uri(request); \
evhttp_parse_query(uri, ¶ms); \
}
#define PARAM_GET_STR(var, params, name, mendatory) { \
var = evhttp_find_header(¶ms_get, name); \
if (!var && mendatory) { \
http_send(request, "<err message=\"field '" name "' is mendatory\"/>\n"); \
return; \
} \
}
inline static void output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
evbuffer_add_printf(buffer, "<root>\n");
}
inline static void output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</root>\n");
}
inline static void kana_output_xml(const char *kana, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<kana><![CDATA[");
evbuffer_add_printf(buffer, "%s", kana);
evbuffer_add_printf(buffer, "]]></kana>\n");
}
inline static void parse_output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<parse>\n");
}
inline static void parse_output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</parse>\n");
}
inline static void cdata_output_xml(const char *string, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<![CDATA[%s]]>", string);
}
inline static void reading_output_xml(
std::pair<std::string,
std::string> text,
struct evbuffer *buffer
) {
evbuffer_add_printf(
buffer,
"<reading furigana=\"%s\"><![CDATA[%s]]></reading>",
text.second.c_str(),
text.first.c_str()
);
}
inline static void token_output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<token>");
}
inline static void token_output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</token>\n");
}
inline static void token_output_xml(const char *token, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<token><![CDATA[");
evbuffer_add_printf(buffer, "%s",token);
evbuffer_add_printf(buffer, "]]></token>\n");
}
/**
*
*/
static void http_send(struct evhttp_request *request, const char *fmt, ...) {
struct evbuffer *buffer = evbuffer_new();
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
va_list ap;
va_start(ap, fmt);
evbuffer_add_vprintf(buffer, fmt, ap);
va_end(ap);
evhttp_send_reply(request, HTTP_OK, "", buffer);
evbuffer_free(buffer);
}
/**** uri: *
*
*/
static void http_callback_default(struct evhttp_request *request, void *data) {
evhttp_send_error(request, HTTP_NOTFOUND, "Service not found");
}
/**** uri: /kana?str=*
*
*/
static void http_kana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
const char *kana = server->yomiTagger->parse(str);
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
std::string enforcedHiranagas = server->furigana.katakana_to_hiragana(kana);
kana_output_xml(enforcedHiranagas.c_str(), buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**** uri: /parse?str=*
*
*/
static void http_parse_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
std::vector<std::string> tokens;
const MeCab::Node* node = server->tagger->parseToNode(str);
for (; node; node = node->next) {
if (node->stat != MECAB_BOS_NODE && node->stat != MECAB_EOS_NODE) {
tokens.push_back(std::string(node->surface, node->length));
}
}
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml_header(buffer);
for (auto& oneToken : tokens) {
token_output_xml(oneToken.c_str(), buffer);
}
parse_output_xml_footer(buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
static std::string mecab_node_get_reading(const MeCab::Node *node) {
#define MECAB_FEATURE_READING_FIELD 8
size_t field = 0;
char *token, *infos = strdupa(node->feature);
token = strtok(infos, ",");
while (token != NULL) {
field++;
if (field == MECAB_FEATURE_READING_FIELD) {
return std::string(token);
}
token = strtok(NULL, ",");
}
return "";
}
/**** uri: /furigana?str=*
*
*/
static void http_furigana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into furigana => token+kana
Server* server = (Server*) data;
std::vector< std::vector<std::pair<std::string, std::string> > > tokens;
const MeCab::Node* node = server->tagger->parseToNode(str); for (; node; node = node->next) {
if (node->stat != MECAB_BOS_NODE && node->stat != MECAB_EOS_NODE) {
std::string token(node->surface, node->length);
std::string kana(mecab_node_get_reading(node));
std::vector<std::pair<std::string, std::string> > smallerTokens;
smallerTokens = server->furigana.tokenize(token, kana);
tokens.insert(
tokens.end(),
smallerTokens
);
}
}
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml_header(buffer);
for (auto& readings : tokens) {
token_output_xml_header(buffer);
for (auto& text : readings) {
if (text.second.empty()) {
cdata_output_xml(text.first.c_str(), buffer);
} else {
reading_output_xml(text, buffer);
}
}
token_output_xml_footer(buffer);
}
parse_output_xml_footer(buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**
*
*/
Server::Server(std::string address, int port) {
struct event_base *base = event_init();
struct evhttp *server = evhttp_new(base);
int res = evhttp_bind_socket(server, address.c_str(), port);
wakatiTagger = MeCab::createTagger("-Owakati");
yomiTagger = MeCab::createTagger("-Oyomi");
tagger = MeCab::createTagger("");
if (res != 0) {
std::cout << "[ERROR] Could not start http server!" << std::endl;
return;
}
evhttp_set_gencb(server, http_callback_default, this);
evhttp_set_cb(server, "/kana", http_kana_callback, this);
evhttp_set_cb(server, "/parse", http_parse_callback, this);
evhttp_set_cb(server, "/furigana", http_furigana_callback, this);
event_base_dispatch(base);
}
/**
*
*
*/
Server::~Server() {
delete wakatiTagger;
delete yomiTagger;
delete tagger;
}
|
Remove superfluous blank lines
|
Remove superfluous blank lines
|
C++
|
mit
|
allan-simon/nihongoparserd,allan-simon/nihongoparserd,Tatoeba/nihongoparserd,allan-simon/nihongoparserd,Tatoeba/nihongoparserd,Tatoeba/nihongoparserd
|
54e8b62b8773a67e4065f1d1397443155aaaa379
|
src/Socket.cpp
|
src/Socket.cpp
|
/*
* Copyright (C) 2004-2014 ZNC, see the NOTICE file for details.
*
* 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 <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/znc.h>
#include <signal.h>
CZNCSock::CZNCSock(int timeout) : Csock(timeout) {
#ifdef HAVE_LIBSSL
DisableSSLProtocols(EDP_SSL);
CString sCipher = CZNC::Get().GetSSLCiphers();
if (!sCipher.empty()) {
SetCipher(sCipher);
}
#endif
}
CZNCSock::CZNCSock(const CString& sHost, u_short port, int timeout) : Csock(sHost, port, timeout) {
#ifdef HAVE_LIBSSL
DisableSSLProtocols(EDP_SSL);
CString sCipher = CZNC::Get().GetSSLCiphers();
if (!sCipher.empty()) {
SetCipher(sCipher);
}
#endif
}
unsigned int CSockManager::GetAnonConnectionCount(const CString &sIP) const {
const_iterator it;
unsigned int ret = 0;
for (it = begin(); it != end(); ++it) {
Csock *pSock = *it;
// Logged in CClients have "USR::<username>" as their sockname
if (pSock->GetType() == Csock::INBOUND && pSock->GetRemoteIP() == sIP
&& pSock->GetSockName().Left(5) != "USR::") {
ret++;
}
}
DEBUG("There are [" << ret << "] clients from [" << sIP << "]");
return ret;
}
int CZNCSock::ConvertAddress(const struct sockaddr_storage * pAddr, socklen_t iAddrLen, CS_STRING & sIP, u_short * piPort) const {
int ret = Csock::ConvertAddress(pAddr, iAddrLen, sIP, piPort);
if (ret == 0)
sIP.TrimPrefix("::ffff:");
return ret;
}
#ifdef HAVE_PTHREAD
class CSockManager::CTDNSMonitorFD : public CSMonitorFD {
public:
CTDNSMonitorFD() {
Add(CThreadPool::Get().getReadFD(), ECT_Read);
}
virtual bool FDsThatTriggered(const std::map<int, short>& miiReadyFds) {
if (miiReadyFds.find(CThreadPool::Get().getReadFD())->second) {
CThreadPool::Get().handlePipeReadable();
}
return true;
}
};
#endif
#ifdef HAVE_THREADED_DNS
void CSockManager::CDNSJob::runThread() {
int iCount = 0;
while (true) {
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_ADDRCONFIG;
iRes = getaddrinfo(sHostname.c_str(), NULL, &hints, &aiResult);
if (EAGAIN != iRes) {
break;
}
iCount++;
if (iCount > 5) {
iRes = ETIMEDOUT;
break;
}
sleep(5); // wait 5 seconds before next try
}
}
void CSockManager::CDNSJob::runMain() {
if (0 != this->iRes) {
DEBUG("Error in threaded DNS: " << gai_strerror(this->iRes));
if (this->aiResult) {
DEBUG("And aiResult is not NULL...");
}
this->aiResult = NULL; // just for case. Maybe to call freeaddrinfo()?
}
pManager->SetTDNSThreadFinished(this->task, this->bBind, this->aiResult);
}
void CSockManager::StartTDNSThread(TDNSTask* task, bool bBind) {
CString sHostname = bBind ? task->sBindhost : task->sHostname;
CDNSJob* arg = new CDNSJob;
arg->sHostname = sHostname;
arg->task = task;
arg->bBind = bBind;
arg->iRes = 0;
arg->aiResult = NULL;
arg->pManager = this;
CThreadPool::Get().addJob(arg);
}
void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* aiResult) {
if (bBind) {
task->aiBind = aiResult;
task->bDoneBind = true;
} else {
task->aiTarget = aiResult;
task->bDoneTarget = true;
}
// Now that something is done, check if everything we needed is done
if (!task->bDoneBind || !task->bDoneTarget) {
return;
}
// All needed DNS is done, now collect the results
addrinfo* aiTarget = NULL;
addrinfo* aiBind = NULL;
try {
addrinfo* aiTarget4 = task->aiTarget;
addrinfo* aiBind4 = task->aiBind;
while (aiTarget4 && aiTarget4->ai_family != AF_INET) aiTarget4 = aiTarget4->ai_next;
while (aiBind4 && aiBind4->ai_family != AF_INET) aiBind4 = aiBind4->ai_next;
addrinfo* aiTarget6 = NULL;
addrinfo* aiBind6 = NULL;
#ifdef HAVE_IPV6
aiTarget6 = task->aiTarget;
aiBind6 = task->aiBind;
while (aiTarget6 && aiTarget6->ai_family != AF_INET6) aiTarget6 = aiTarget6->ai_next;
while (aiBind6 && aiBind6->ai_family != AF_INET6) aiBind6 = aiBind6->ai_next;
#endif
if (!aiTarget4 && !aiTarget6) {
throw "Can't resolve server hostname";
} else if (task->sBindhost.empty()) {
#ifdef HAVE_IPV6
aiTarget = task->aiTarget;
#else
aiTarget = aiTarget4;
#endif
} else if (!aiBind4 && !aiBind6) {
throw "Can't resolve bind hostname. Try /znc clearbindhost and /znc clearuserbindhost";
} else if (aiBind6 && aiTarget6) {
aiTarget = aiTarget6;
aiBind = aiBind6;
} else if (aiBind4 && aiTarget4) {
aiTarget = aiTarget4;
aiBind = aiBind4;
} else {
throw "Address family of bindhost doesn't match address family of server";
}
CString sBindhost;
CString sTargetHost;
if (!task->sBindhost.empty()) {
char s[INET6_ADDRSTRLEN] = {};
getnameinfo(aiBind->ai_addr, aiBind->ai_addrlen, s, sizeof(s), NULL, 0, NI_NUMERICHOST);
sBindhost = s;
}
char s[INET6_ADDRSTRLEN] = {};
getnameinfo(aiTarget->ai_addr, aiTarget->ai_addrlen, s, sizeof(s), NULL, 0, NI_NUMERICHOST);
sTargetHost = s;
DEBUG("TDNS: " << task->sSockName << ", connecting to [" << sTargetHost << "] using bindhost [" << sBindhost << "]");
FinishConnect(sTargetHost, task->iPort, task->sSockName, task->iTimeout, task->bSSL, sBindhost, task->pcSock);
} catch (const char* s) {
DEBUG(task->sSockName << ", dns resolving error: " << s);
task->pcSock->SetSockName(task->sSockName);
task->pcSock->SockError(-1, s);
delete task->pcSock;
}
if (task->aiTarget) freeaddrinfo(task->aiTarget);
if (task->aiBind) freeaddrinfo(task->aiBind);
delete task;
}
#endif /* HAVE_THREADED_DNS */
CSockManager::CSockManager() {
#ifdef HAVE_PTHREAD
MonitorFD(new CTDNSMonitorFD());
#endif
}
CSockManager::~CSockManager() {
}
void CSockManager::Connect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock) {
#ifdef HAVE_THREADED_DNS
DEBUG("TDNS: initiating resolving of [" << sHostname << "] and bindhost [" << sBindHost << "]");
TDNSTask* task = new TDNSTask;
task->sHostname = sHostname;
task->iPort = iPort;
task->sSockName = sSockName;
task->iTimeout = iTimeout;
task->bSSL = bSSL;
task->sBindhost = sBindHost;
task->pcSock = pcSock;
task->aiTarget = NULL;
task->aiBind = NULL;
task->bDoneTarget = false;
if (sBindHost.empty()) {
task->bDoneBind = true;
} else {
task->bDoneBind = false;
StartTDNSThread(task, true);
}
StartTDNSThread(task, false);
#else /* HAVE_THREADED_DNS */
// Just let Csocket handle DNS itself
FinishConnect(sHostname, iPort, sSockName, iTimeout, bSSL, sBindHost, pcSock);
#endif
}
void CSockManager::FinishConnect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock) {
CSConnection C(sHostname, iPort, iTimeout);
C.SetSockName(sSockName);
C.SetIsSSL(bSSL);
C.SetBindHost(sBindHost);
TSocketManager<CZNCSock>::Connect(C, pcSock);
}
/////////////////// CSocket ///////////////////
CSocket::CSocket(CModule* pModule) : CZNCSock() {
m_pModule = pModule;
if (m_pModule) m_pModule->AddSocket(this);
EnableReadLine();
SetMaxBufferThreshold(10240);
}
CSocket::CSocket(CModule* pModule, const CString& sHostname, unsigned short uPort, int iTimeout) : CZNCSock(sHostname, uPort, iTimeout) {
m_pModule = pModule;
if (m_pModule) m_pModule->AddSocket(this);
EnableReadLine();
SetMaxBufferThreshold(10240);
}
CSocket::~CSocket() {
CUser *pUser = NULL;
// CWebSock could cause us to have a NULL pointer here
if (m_pModule) {
pUser = m_pModule->GetUser();
m_pModule->UnlinkSocket(this);
}
if (pUser && m_pModule && (m_pModule->GetType() != CModInfo::GlobalModule)) {
pUser->AddBytesWritten(GetBytesWritten());
pUser->AddBytesRead(GetBytesRead());
} else {
CZNC::Get().AddBytesWritten(GetBytesWritten());
CZNC::Get().AddBytesRead(GetBytesRead());
}
}
void CSocket::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
if (m_pModule) m_pModule->PutModule("Some socket reached its max buffer limit and was closed!");
Close();
}
void CSocket::SockError(int iErrno, const CString& sDescription) {
DEBUG(GetSockName() << " == SockError(" << sDescription << ", " << strerror(iErrno) << ")");
if (iErrno == EMFILE) {
// We have too many open fds, this can cause a busy loop.
Close();
}
}
bool CSocket::ConnectionFrom(const CString& sHost, unsigned short uPort) {
return CZNC::Get().AllowConnectionFrom(sHost);
}
bool CSocket::Connect(const CString& sHostname, unsigned short uPort, bool bSSL, unsigned int uTimeout) {
if (!m_pModule) {
DEBUG("ERROR: CSocket::Connect called on instance without m_pModule handle!");
return false;
}
CUser* pUser = m_pModule->GetUser();
CString sSockName = "MOD::C::" + m_pModule->GetModName();
CString sBindHost;
if (pUser) {
sSockName += "::" + pUser->GetUserName();
sBindHost = pUser->GetBindHost();
CIRCNetwork* pNetwork = m_pModule->GetNetwork();
if (pNetwork) {
sSockName += "::" + pNetwork->GetName();
sBindHost = pNetwork->GetBindHost();
}
}
// Don't overwrite the socket name if one is already set
if (!GetSockName().empty()) {
sSockName = GetSockName();
}
m_pModule->GetManager()->Connect(sHostname, uPort, sSockName, uTimeout, bSSL, sBindHost, this);
return true;
}
bool CSocket::Listen(unsigned short uPort, bool bSSL, unsigned int uTimeout) {
if (!m_pModule) {
DEBUG("ERROR: CSocket::Listen called on instance without m_pModule handle!");
return false;
}
CUser* pUser = m_pModule->GetUser();
CString sSockName = "MOD::L::" + m_pModule->GetModName();
if (pUser) {
sSockName += "::" + pUser->GetUserName();
}
// Don't overwrite the socket name if one is already set
if (!GetSockName().empty()) {
sSockName = GetSockName();
}
return m_pModule->GetManager()->ListenAll(uPort, sSockName, bSSL, SOMAXCONN, this);
}
CModule* CSocket::GetModule() const { return m_pModule; }
/////////////////// !CSocket ///////////////////
|
/*
* Copyright (C) 2004-2014 ZNC, see the NOTICE file for details.
*
* 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 <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/znc.h>
#include <signal.h>
CZNCSock::CZNCSock(int timeout) : Csock(timeout) {
#ifdef HAVE_LIBSSL
DisableSSLCompression();
DisableSSLProtocols(EDP_SSL);
CString sCipher = CZNC::Get().GetSSLCiphers();
if (!sCipher.empty()) {
SetCipher(sCipher);
}
#endif
}
CZNCSock::CZNCSock(const CString& sHost, u_short port, int timeout) : Csock(sHost, port, timeout) {
#ifdef HAVE_LIBSSL
DisableSSLCompression();
DisableSSLProtocols(EDP_SSL);
CString sCipher = CZNC::Get().GetSSLCiphers();
if (!sCipher.empty()) {
SetCipher(sCipher);
}
#endif
}
unsigned int CSockManager::GetAnonConnectionCount(const CString &sIP) const {
const_iterator it;
unsigned int ret = 0;
for (it = begin(); it != end(); ++it) {
Csock *pSock = *it;
// Logged in CClients have "USR::<username>" as their sockname
if (pSock->GetType() == Csock::INBOUND && pSock->GetRemoteIP() == sIP
&& pSock->GetSockName().Left(5) != "USR::") {
ret++;
}
}
DEBUG("There are [" << ret << "] clients from [" << sIP << "]");
return ret;
}
int CZNCSock::ConvertAddress(const struct sockaddr_storage * pAddr, socklen_t iAddrLen, CS_STRING & sIP, u_short * piPort) const {
int ret = Csock::ConvertAddress(pAddr, iAddrLen, sIP, piPort);
if (ret == 0)
sIP.TrimPrefix("::ffff:");
return ret;
}
#ifdef HAVE_PTHREAD
class CSockManager::CTDNSMonitorFD : public CSMonitorFD {
public:
CTDNSMonitorFD() {
Add(CThreadPool::Get().getReadFD(), ECT_Read);
}
virtual bool FDsThatTriggered(const std::map<int, short>& miiReadyFds) {
if (miiReadyFds.find(CThreadPool::Get().getReadFD())->second) {
CThreadPool::Get().handlePipeReadable();
}
return true;
}
};
#endif
#ifdef HAVE_THREADED_DNS
void CSockManager::CDNSJob::runThread() {
int iCount = 0;
while (true) {
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_ADDRCONFIG;
iRes = getaddrinfo(sHostname.c_str(), NULL, &hints, &aiResult);
if (EAGAIN != iRes) {
break;
}
iCount++;
if (iCount > 5) {
iRes = ETIMEDOUT;
break;
}
sleep(5); // wait 5 seconds before next try
}
}
void CSockManager::CDNSJob::runMain() {
if (0 != this->iRes) {
DEBUG("Error in threaded DNS: " << gai_strerror(this->iRes));
if (this->aiResult) {
DEBUG("And aiResult is not NULL...");
}
this->aiResult = NULL; // just for case. Maybe to call freeaddrinfo()?
}
pManager->SetTDNSThreadFinished(this->task, this->bBind, this->aiResult);
}
void CSockManager::StartTDNSThread(TDNSTask* task, bool bBind) {
CString sHostname = bBind ? task->sBindhost : task->sHostname;
CDNSJob* arg = new CDNSJob;
arg->sHostname = sHostname;
arg->task = task;
arg->bBind = bBind;
arg->iRes = 0;
arg->aiResult = NULL;
arg->pManager = this;
CThreadPool::Get().addJob(arg);
}
void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* aiResult) {
if (bBind) {
task->aiBind = aiResult;
task->bDoneBind = true;
} else {
task->aiTarget = aiResult;
task->bDoneTarget = true;
}
// Now that something is done, check if everything we needed is done
if (!task->bDoneBind || !task->bDoneTarget) {
return;
}
// All needed DNS is done, now collect the results
addrinfo* aiTarget = NULL;
addrinfo* aiBind = NULL;
try {
addrinfo* aiTarget4 = task->aiTarget;
addrinfo* aiBind4 = task->aiBind;
while (aiTarget4 && aiTarget4->ai_family != AF_INET) aiTarget4 = aiTarget4->ai_next;
while (aiBind4 && aiBind4->ai_family != AF_INET) aiBind4 = aiBind4->ai_next;
addrinfo* aiTarget6 = NULL;
addrinfo* aiBind6 = NULL;
#ifdef HAVE_IPV6
aiTarget6 = task->aiTarget;
aiBind6 = task->aiBind;
while (aiTarget6 && aiTarget6->ai_family != AF_INET6) aiTarget6 = aiTarget6->ai_next;
while (aiBind6 && aiBind6->ai_family != AF_INET6) aiBind6 = aiBind6->ai_next;
#endif
if (!aiTarget4 && !aiTarget6) {
throw "Can't resolve server hostname";
} else if (task->sBindhost.empty()) {
#ifdef HAVE_IPV6
aiTarget = task->aiTarget;
#else
aiTarget = aiTarget4;
#endif
} else if (!aiBind4 && !aiBind6) {
throw "Can't resolve bind hostname. Try /znc clearbindhost and /znc clearuserbindhost";
} else if (aiBind6 && aiTarget6) {
aiTarget = aiTarget6;
aiBind = aiBind6;
} else if (aiBind4 && aiTarget4) {
aiTarget = aiTarget4;
aiBind = aiBind4;
} else {
throw "Address family of bindhost doesn't match address family of server";
}
CString sBindhost;
CString sTargetHost;
if (!task->sBindhost.empty()) {
char s[INET6_ADDRSTRLEN] = {};
getnameinfo(aiBind->ai_addr, aiBind->ai_addrlen, s, sizeof(s), NULL, 0, NI_NUMERICHOST);
sBindhost = s;
}
char s[INET6_ADDRSTRLEN] = {};
getnameinfo(aiTarget->ai_addr, aiTarget->ai_addrlen, s, sizeof(s), NULL, 0, NI_NUMERICHOST);
sTargetHost = s;
DEBUG("TDNS: " << task->sSockName << ", connecting to [" << sTargetHost << "] using bindhost [" << sBindhost << "]");
FinishConnect(sTargetHost, task->iPort, task->sSockName, task->iTimeout, task->bSSL, sBindhost, task->pcSock);
} catch (const char* s) {
DEBUG(task->sSockName << ", dns resolving error: " << s);
task->pcSock->SetSockName(task->sSockName);
task->pcSock->SockError(-1, s);
delete task->pcSock;
}
if (task->aiTarget) freeaddrinfo(task->aiTarget);
if (task->aiBind) freeaddrinfo(task->aiBind);
delete task;
}
#endif /* HAVE_THREADED_DNS */
CSockManager::CSockManager() {
#ifdef HAVE_PTHREAD
MonitorFD(new CTDNSMonitorFD());
#endif
}
CSockManager::~CSockManager() {
}
void CSockManager::Connect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock) {
#ifdef HAVE_THREADED_DNS
DEBUG("TDNS: initiating resolving of [" << sHostname << "] and bindhost [" << sBindHost << "]");
TDNSTask* task = new TDNSTask;
task->sHostname = sHostname;
task->iPort = iPort;
task->sSockName = sSockName;
task->iTimeout = iTimeout;
task->bSSL = bSSL;
task->sBindhost = sBindHost;
task->pcSock = pcSock;
task->aiTarget = NULL;
task->aiBind = NULL;
task->bDoneTarget = false;
if (sBindHost.empty()) {
task->bDoneBind = true;
} else {
task->bDoneBind = false;
StartTDNSThread(task, true);
}
StartTDNSThread(task, false);
#else /* HAVE_THREADED_DNS */
// Just let Csocket handle DNS itself
FinishConnect(sHostname, iPort, sSockName, iTimeout, bSSL, sBindHost, pcSock);
#endif
}
void CSockManager::FinishConnect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock) {
CSConnection C(sHostname, iPort, iTimeout);
C.SetSockName(sSockName);
C.SetIsSSL(bSSL);
C.SetBindHost(sBindHost);
TSocketManager<CZNCSock>::Connect(C, pcSock);
}
/////////////////// CSocket ///////////////////
CSocket::CSocket(CModule* pModule) : CZNCSock() {
m_pModule = pModule;
if (m_pModule) m_pModule->AddSocket(this);
EnableReadLine();
SetMaxBufferThreshold(10240);
}
CSocket::CSocket(CModule* pModule, const CString& sHostname, unsigned short uPort, int iTimeout) : CZNCSock(sHostname, uPort, iTimeout) {
m_pModule = pModule;
if (m_pModule) m_pModule->AddSocket(this);
EnableReadLine();
SetMaxBufferThreshold(10240);
}
CSocket::~CSocket() {
CUser *pUser = NULL;
// CWebSock could cause us to have a NULL pointer here
if (m_pModule) {
pUser = m_pModule->GetUser();
m_pModule->UnlinkSocket(this);
}
if (pUser && m_pModule && (m_pModule->GetType() != CModInfo::GlobalModule)) {
pUser->AddBytesWritten(GetBytesWritten());
pUser->AddBytesRead(GetBytesRead());
} else {
CZNC::Get().AddBytesWritten(GetBytesWritten());
CZNC::Get().AddBytesRead(GetBytesRead());
}
}
void CSocket::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
if (m_pModule) m_pModule->PutModule("Some socket reached its max buffer limit and was closed!");
Close();
}
void CSocket::SockError(int iErrno, const CString& sDescription) {
DEBUG(GetSockName() << " == SockError(" << sDescription << ", " << strerror(iErrno) << ")");
if (iErrno == EMFILE) {
// We have too many open fds, this can cause a busy loop.
Close();
}
}
bool CSocket::ConnectionFrom(const CString& sHost, unsigned short uPort) {
return CZNC::Get().AllowConnectionFrom(sHost);
}
bool CSocket::Connect(const CString& sHostname, unsigned short uPort, bool bSSL, unsigned int uTimeout) {
if (!m_pModule) {
DEBUG("ERROR: CSocket::Connect called on instance without m_pModule handle!");
return false;
}
CUser* pUser = m_pModule->GetUser();
CString sSockName = "MOD::C::" + m_pModule->GetModName();
CString sBindHost;
if (pUser) {
sSockName += "::" + pUser->GetUserName();
sBindHost = pUser->GetBindHost();
CIRCNetwork* pNetwork = m_pModule->GetNetwork();
if (pNetwork) {
sSockName += "::" + pNetwork->GetName();
sBindHost = pNetwork->GetBindHost();
}
}
// Don't overwrite the socket name if one is already set
if (!GetSockName().empty()) {
sSockName = GetSockName();
}
m_pModule->GetManager()->Connect(sHostname, uPort, sSockName, uTimeout, bSSL, sBindHost, this);
return true;
}
bool CSocket::Listen(unsigned short uPort, bool bSSL, unsigned int uTimeout) {
if (!m_pModule) {
DEBUG("ERROR: CSocket::Listen called on instance without m_pModule handle!");
return false;
}
CUser* pUser = m_pModule->GetUser();
CString sSockName = "MOD::L::" + m_pModule->GetModName();
if (pUser) {
sSockName += "::" + pUser->GetUserName();
}
// Don't overwrite the socket name if one is already set
if (!GetSockName().empty()) {
sSockName = GetSockName();
}
return m_pModule->GetManager()->ListenAll(uPort, sSockName, bSSL, SOMAXCONN, this);
}
CModule* CSocket::GetModule() const { return m_pModule; }
/////////////////// !CSocket ///////////////////
|
Fix #719: Disable SSL compression
|
Fix #719: Disable SSL compression
|
C++
|
apache-2.0
|
evilnet/znc,reedloden/znc,GLolol/znc,TuffLuck/znc,markusj/znc,DarthGandalf/znc,Phansa/znc,GLolol/znc,elyscape/znc,TuffLuck/znc,DarthGandalf/znc,dgw/znc,badloop/znc,wolfy1339/znc,elyscape/znc,elyscape/znc,dgw/znc,znc/znc,evilnet/znc,jpnurmi/znc,ollie27/znc,Kriechi/znc,jreese/znc,anthonyryan1/znc,BtbN/znc,elyscape/znc,markusj/znc,TuffLuck/znc,Zarthus/znc,aarondunlap/znc,Hasimir/znc,YourBNC/znc,ollie27/znc,markusj/znc,BtbN/znc,anthonyryan1/znc,DarthGandalf/znc,Zarthus/znc,DarthGandalf/znc,Mkaysi/znc,wolfy1339/znc,TuffLuck/znc,Mikaela/znc,KiNgMaR/znc,Phansa/znc,Mikaela/znc,reedloden/znc,badloop/znc,Zarthus/znc,wolfy1339/znc,jreese/znc,Adam-/znc,Hasimir/znc,kashike/znc,Mkaysi/znc,KielBNC/znc,psychon/znc,aarondunlap/znc,BtbN/znc,kashike/znc,jreese/znc,GLolol/znc,badloop/znc,anthonyryan1/znc,jpnurmi/znc,kashike/znc,psychon/znc,reedloden/znc,anthonyryan1/znc,DarthGandalf/znc,GLolol/znc,BtbN/znc,jpnurmi/znc,Mikaela/znc,aarondunlap/znc,znc/znc,Phansa/znc,KielBNC/znc,Kriechi/znc,Mikaela/znc,Kriechi/znc,GLolol/znc,KiNgMaR/znc,reedloden/znc,dgw/znc,aarondunlap/znc,badloop/znc,elyscape/znc,evilnet/znc,Mkaysi/znc,ollie27/znc,badloop/znc,Mikaela/znc,Mikaela/znc,YourBNC/znc,Hasimir/znc,kashike/znc,Zarthus/znc,evilnet/znc,anthonyryan1/znc,KielBNC/znc,Adam-/znc,evilnet/znc,badloop/znc,Adam-/znc,Kriechi/znc,Mikaela/znc,kashike/znc,znc/znc,Kriechi/znc,elyscape/znc,KielBNC/znc,Hasimir/znc,Kriechi/znc,Kriechi/nobnc,znc/znc,KiNgMaR/znc,KielBNC/znc,jpnurmi/znc,znc/znc,psychon/znc,Phansa/znc,Adam-/znc,YourBNC/znc,evilnet/znc,psychon/znc,markusj/znc,KiNgMaR/znc,Zarthus/znc,DarthGandalf/znc,ollie27/znc,Mkaysi/znc,Kriechi/nobnc,badloop/znc,Adam-/znc,dgw/znc,BtbN/znc,BtbN/znc,Adam-/znc,KiNgMaR/znc,aarondunlap/znc,markusj/znc,wolfy1339/znc,Mkaysi/znc,ollie27/znc,YourBNC/znc,psychon/znc,wolfy1339/znc,Mkaysi/znc,Kriechi/nobnc,jpnurmi/znc,kashike/znc,markusj/znc,Hasimir/znc,jpnurmi/znc,Phansa/znc,TuffLuck/znc,YourBNC/znc,ollie27/znc,KielBNC/znc,jpnurmi/znc,aarondunlap/znc,GLolol/znc,znc/znc,anthonyryan1/znc,TuffLuck/znc,Zarthus/znc,jreese/znc,dgw/znc,jreese/znc,Hasimir/znc,Hasimir/znc,Mkaysi/znc,reedloden/znc,wolfy1339/znc,Adam-/znc,psychon/znc,anthonyryan1/znc,dgw/znc,Phansa/znc,reedloden/znc,YourBNC/znc,KiNgMaR/znc,aarondunlap/znc,TuffLuck/znc,jreese/znc
|
acdcb262afb036bf0f70fe0ef8dc0e6516797337
|
bindings/python/src/session.cpp
|
bindings/python/src/session.cpp
|
// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to 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 <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include <boost/python.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;
extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_dht_router_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_start_lsd_doc;
extern char const* session_stop_lsd_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;
extern char const* session_set_ip_filter_doc;
namespace
{
bool listen_on(session& s, int min_, int max_, char const* interface)
{
allow_threading_guard guard;
return s.listen_on(std::make_pair(min_, max_), interface);
}
void outgoing_ports(session& s, int _min, int _max)
{
allow_threading_guard guard;
session_settings settings = s.settings();
settings.outgoing_ports = std::make_pair(_min, _max);
s.set_settings(settings);
return;
}
#ifndef TORRENT_DISABLE_DHT
void add_dht_router(session& s, std::string router_, int port_)
{
allow_threading_guard guard;
return s.add_dht_router(std::make_pair(router_, port_));
}
#endif
struct invoke_extension_factory
{
invoke_extension_factory(object const& callback)
: cb(callback)
{}
boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
{
lock_gil lock;
return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
}
object cb;
};
void add_extension(session& s, object const& e)
{
allow_threading_guard guard;
s.add_extension(invoke_extension_factory(e));
}
torrent_handle add_torrent(session& s, dict params)
{
add_torrent_params p;
if (params.has_key("ti"))
p.ti = new torrent_info(extract<torrent_info const&>(params["ti"]));
std::string url;
if (params.has_key("tracker_url"))
{
url = extract<std::string>(params["tracker_url"]);
p.tracker_url = url.c_str();
}
if (params.has_key("info_hash"))
p.info_hash = extract<sha1_hash>(params["info_hash"]);
std::string name;
if (params.has_key("name"))
{
name = extract<std::string>(params["name"]);
p.name = name.c_str();
}
p.save_path = fs::path(extract<std::string>(params["save_path"]));
std::vector<char> resume_buf;
if (params.has_key("resume_data"))
{
std::string resume = extract<std::string>(params["resume_data"]);
resume_buf.resize(resume.size());
std::memcpy(&resume_buf[0], &resume[0], resume.size());
p.resume_data = &resume_buf;
}
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
p.paused = params["paused"];
p.auto_managed = params["auto_managed"];
p.duplicate_is_error = params["duplicate_is_error"];
return s.add_torrent(p);
}
void start_natpmp(session& s)
{
allow_threading_guard guard;
s.start_natpmp();
return;
}
void start_upnp(session& s)
{
allow_threading_guard guard;
s.start_upnp();
return;
}
list get_torrents(session& s)
{
list ret;
std::vector<torrent_handle> torrents = s.get_torrents();
for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
{
ret.append(*i);
}
return ret;
}
#ifndef TORRENT_DISABLE_GEO_IP
bool load_asnum_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_asnum_db(file.c_str());
}
bool load_country_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_country_db(file.c_str());
}
#endif
} // namespace unnamed
void bind_session()
{
class_<session_status>("session_status", session_status_doc)
.def_readonly(
"has_incoming_connections", &session_status::has_incoming_connections
, session_status_has_incoming_connections_doc
)
.def_readonly(
"upload_rate", &session_status::upload_rate
, session_status_upload_rate_doc
)
.def_readonly(
"download_rate", &session_status::download_rate
, session_status_download_rate_doc
)
.def_readonly(
"payload_upload_rate", &session_status::payload_upload_rate
, session_status_payload_upload_rate_doc
)
.def_readonly(
"payload_download_rate", &session_status::payload_download_rate
, session_status_payload_download_rate_doc
)
.def_readonly(
"total_download", &session_status::total_download
, session_status_total_download_doc
)
.def_readonly(
"total_upload", &session_status::total_upload
, session_status_total_upload_doc
)
.def_readonly(
"total_payload_download", &session_status::total_payload_download
, session_status_total_payload_download_doc
)
.def_readonly(
"total_payload_upload", &session_status::total_payload_upload
, session_status_total_payload_upload_doc
)
.def_readonly(
"num_peers", &session_status::num_peers
, session_status_num_peers_doc
)
#ifndef TORRENT_DISABLE_DHT
.def_readonly(
"dht_nodes", &session_status::dht_nodes
, session_status_dht_nodes_doc
)
.def_readonly(
"dht_cache_nodes", &session_status::dht_node_cache
, session_status_cache_nodes_doc
)
.def_readonly(
"dht_torrents", &session_status::dht_torrents
, session_status_dht_torrents_doc
)
#endif
;
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_sparse", storage_mode_sparse)
.value("storage_mode_compact", storage_mode_compact)
;
enum_<session::options_t>("options_t")
.value("none", session::none)
.value("delete_files", session::delete_files)
;
class_<session, boost::noncopyable>("session", session_doc, no_init)
.def(
init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
, session_listen_on_doc
)
.def("outgoing_ports", &outgoing_ports)
.def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
.def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
.def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
, session_add_dht_router_doc
)
.def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
.def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
.def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
.def("add_torrent", &add_torrent, session_add_torrent_doc)
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
, session_remove_torrent_doc)
.def(
"set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
, session_set_download_rate_limit_doc
)
.def(
"download_rate_limit", allow_threads(&session::download_rate_limit)
, session_download_rate_limit_doc
)
.def(
"set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
, session_set_upload_rate_limit_doc
)
.def(
"upload_rate_limit", allow_threads(&session::upload_rate_limit)
, session_upload_rate_limit_doc
)
.def(
"set_max_uploads", allow_threads(&session::set_max_uploads)
, session_set_max_uploads_doc
)
.def(
"set_max_connections", allow_threads(&session::set_max_connections)
, session_set_max_connections_doc
)
.def(
"set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
, session_set_max_half_open_connections_doc
)
.def(
"num_connections", allow_threads(&session::num_connections)
, session_num_connections_doc
)
.def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
.def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>())
#ifndef TORRENT_DISABLE_ENCRYPTION
.def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
.def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
#endif
#ifndef TORRENT_DISABLE_GEO_IP
.def("load_asnum_db", &load_asnum_db)
.def("load_country_db", &load_country_db)
#endif
.def("load_state", allow_threads(&session::load_state))
.def("state", allow_threads(&session::state))
.def(
"set_severity_level", allow_threads(&session::set_severity_level)
, session_set_severity_level_doc
)
.def("set_alert_mask", allow_threads(&session::set_alert_mask))
.def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
.def("add_extension", &add_extension)
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
.def("start_upnp", &start_upnp, session_start_upnp_doc)
.def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
.def("start_lsd", allow_threads(&session::start_lsd), session_start_lsd_doc)
.def("stop_lsd", allow_threads(&session::stop_lsd), session_stop_lsd_doc)
.def("start_natpmp", &start_natpmp, session_start_natpmp_doc)
.def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
.def("set_ip_filter", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc)
.def("find_torrent", allow_threads(&session::find_torrent))
.def("get_torrents", &get_torrents)
.def("pause", allow_threads(&session::pause))
.def("resume", allow_threads(&session::resume))
.def("is_paused", allow_threads(&session::is_paused))
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
|
// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to 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 <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include <boost/python.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;
extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_dht_router_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_start_lsd_doc;
extern char const* session_stop_lsd_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;
extern char const* session_set_ip_filter_doc;
namespace
{
bool listen_on(session& s, int min_, int max_, char const* interface)
{
allow_threading_guard guard;
return s.listen_on(std::make_pair(min_, max_), interface);
}
void outgoing_ports(session& s, int _min, int _max)
{
allow_threading_guard guard;
session_settings settings = s.settings();
settings.outgoing_ports = std::make_pair(_min, _max);
s.set_settings(settings);
return;
}
#ifndef TORRENT_DISABLE_DHT
void add_dht_router(session& s, std::string router_, int port_)
{
allow_threading_guard guard;
return s.add_dht_router(std::make_pair(router_, port_));
}
#endif
struct invoke_extension_factory
{
invoke_extension_factory(object const& callback)
: cb(callback)
{}
boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
{
lock_gil lock;
return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
}
object cb;
};
void add_extension(session& s, object const& e)
{
allow_threading_guard guard;
s.add_extension(invoke_extension_factory(e));
}
torrent_handle add_torrent(session& s, dict params)
{
add_torrent_params p;
if (params.has_key("ti"))
p.ti = new torrent_info(extract<torrent_info const&>(params["ti"]));
std::string url;
if (params.has_key("tracker_url"))
{
url = extract<std::string>(params["tracker_url"]);
p.tracker_url = url.c_str();
}
if (params.has_key("info_hash"))
p.info_hash = extract<sha1_hash>(params["info_hash"]);
std::string name;
if (params.has_key("name"))
{
name = extract<std::string>(params["name"]);
p.name = name.c_str();
}
p.save_path = fs::path(extract<std::string>(params["save_path"]));
std::vector<char> resume_buf;
if (params.has_key("resume_data"))
{
std::string resume = extract<std::string>(params["resume_data"]);
resume_buf.resize(resume.size());
std::memcpy(&resume_buf[0], &resume[0], resume.size());
p.resume_data = &resume_buf;
}
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
p.paused = params["paused"];
p.auto_managed = params["auto_managed"];
p.duplicate_is_error = params["duplicate_is_error"];
return s.add_torrent(p);
}
void start_natpmp(session& s)
{
allow_threading_guard guard;
s.start_natpmp();
return;
}
void start_upnp(session& s)
{
allow_threading_guard guard;
s.start_upnp();
return;
}
list get_torrents(session& s)
{
list ret;
std::vector<torrent_handle> torrents = s.get_torrents();
for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
{
ret.append(*i);
}
return ret;
}
#ifndef TORRENT_DISABLE_GEO_IP
bool load_asnum_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_asnum_db(file.c_str());
}
bool load_country_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_country_db(file.c_str());
}
#endif
} // namespace unnamed
void bind_session()
{
class_<session_status>("session_status", session_status_doc)
.def_readonly(
"has_incoming_connections", &session_status::has_incoming_connections
, session_status_has_incoming_connections_doc
)
.def_readonly(
"upload_rate", &session_status::upload_rate
, session_status_upload_rate_doc
)
.def_readonly(
"download_rate", &session_status::download_rate
, session_status_download_rate_doc
)
.def_readonly(
"payload_upload_rate", &session_status::payload_upload_rate
, session_status_payload_upload_rate_doc
)
.def_readonly(
"payload_download_rate", &session_status::payload_download_rate
, session_status_payload_download_rate_doc
)
.def_readonly(
"total_download", &session_status::total_download
, session_status_total_download_doc
)
.def_readonly(
"total_upload", &session_status::total_upload
, session_status_total_upload_doc
)
.def_readonly(
"total_payload_download", &session_status::total_payload_download
, session_status_total_payload_download_doc
)
.def_readonly(
"total_payload_upload", &session_status::total_payload_upload
, session_status_total_payload_upload_doc
)
.def_readonly(
"num_peers", &session_status::num_peers
, session_status_num_peers_doc
)
#ifndef TORRENT_DISABLE_DHT
.def_readonly(
"dht_nodes", &session_status::dht_nodes
, session_status_dht_nodes_doc
)
.def_readonly(
"dht_cache_nodes", &session_status::dht_node_cache
, session_status_cache_nodes_doc
)
.def_readonly(
"dht_torrents", &session_status::dht_torrents
, session_status_dht_torrents_doc
)
#endif
;
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_sparse", storage_mode_sparse)
.value("storage_mode_compact", storage_mode_compact)
;
enum_<session::options_t>("options_t")
.value("none", session::none)
.value("delete_files", session::delete_files)
;
enum_<session::session_flags_t>("session_flags_t")
.value("add_default_plugins", session::add_default_plugins)
.value("start_default_features", session::start_default_features)
;
class_<session, boost::noncopyable>("session", session_doc, no_init)
.def(
init<fingerprint, int>((
arg("fingerprint")=fingerprint("LT",0,1,0,0)
, arg("flags")=session::start_default_features | session::add_default_plugins)
, session_init_doc)
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
, session_listen_on_doc
)
.def("outgoing_ports", &outgoing_ports)
.def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
.def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
.def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
, session_add_dht_router_doc
)
.def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
.def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
.def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
.def("add_torrent", &add_torrent, session_add_torrent_doc)
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
, session_remove_torrent_doc)
.def(
"set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
, session_set_download_rate_limit_doc
)
.def(
"download_rate_limit", allow_threads(&session::download_rate_limit)
, session_download_rate_limit_doc
)
.def(
"set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
, session_set_upload_rate_limit_doc
)
.def(
"upload_rate_limit", allow_threads(&session::upload_rate_limit)
, session_upload_rate_limit_doc
)
.def(
"set_max_uploads", allow_threads(&session::set_max_uploads)
, session_set_max_uploads_doc
)
.def(
"set_max_connections", allow_threads(&session::set_max_connections)
, session_set_max_connections_doc
)
.def(
"set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
, session_set_max_half_open_connections_doc
)
.def(
"num_connections", allow_threads(&session::num_connections)
, session_num_connections_doc
)
.def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
.def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>())
#ifndef TORRENT_DISABLE_ENCRYPTION
.def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
.def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
#endif
#ifndef TORRENT_DISABLE_GEO_IP
.def("load_asnum_db", &load_asnum_db)
.def("load_country_db", &load_country_db)
#endif
.def("load_state", allow_threads(&session::load_state))
.def("state", allow_threads(&session::state))
.def(
"set_severity_level", allow_threads(&session::set_severity_level)
, session_set_severity_level_doc
)
.def("set_alert_mask", allow_threads(&session::set_alert_mask))
.def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
.def("add_extension", &add_extension)
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
.def("start_upnp", &start_upnp, session_start_upnp_doc)
.def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
.def("start_lsd", allow_threads(&session::start_lsd), session_start_lsd_doc)
.def("stop_lsd", allow_threads(&session::stop_lsd), session_stop_lsd_doc)
.def("start_natpmp", &start_natpmp, session_start_natpmp_doc)
.def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
.def("set_ip_filter", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc)
.def("find_torrent", allow_threads(&session::find_torrent))
.def("get_torrents", &get_torrents)
.def("pause", allow_threads(&session::pause))
.def("resume", allow_threads(&session::resume))
.def("is_paused", allow_threads(&session::is_paused))
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
|
update session constructor in python bindings to support 'flags'
|
update session constructor in python bindings to support 'flags'
|
C++
|
bsd-3-clause
|
jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent
|
4ac96dc72cade5002f231c905f9051ab84a8aa4a
|
far/headers.hpp
|
far/headers.hpp
|
#pragma once
/*
headers.hpp
*/
/*
Copyright 1996 Eugene Roshal
Copyright 2000 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __clang__
// test only
#define _HAS_EXCEPTIONS 0
#endif
#include <array>
#include <algorithm>
#include <bitset>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <queue>
#include <map>
#include <memory>
#include <numeric>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cstdint>
#include <ctime>
#include <process.h>
#undef _W32API_OLD
#ifdef _MSC_VER
# if _MSC_VER < 1600
# error Visual C++ 2010 (or higher) required
# endif
# include <sdkddkver.h>
# if _WIN32_WINNT < 0x0601
# error Windows SDK v7.0 (or higher) required
# endif
#endif //_MSC_VER
#ifdef __GNUC__
# define GCC_VER_(gcc_major,gcc_minor,gcc_patch) (100*(gcc_major) + 10*(gcc_minor) + (gcc_patch))
# define _GCC_VER GCC_VER_(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
# if _GCC_VER < GCC_VER_(4,9,0)
# error gcc 4.9.0 (or higher) required
# endif
# include <w32api.h>
# define _W32API_VER (100*(__W32API_MAJOR_VERSION) + (__W32API_MINOR_VERSION))
# if _W32API_VER < 314
# error w32api-3.14 (or higher) required
# endif
# if _W32API_VER < 317
# define _W32API_OLD 1
# endif
# undef WINVER
# undef _WIN32_WINNT
# undef _WIN32_IE
# define WINVER 0x0601
# define _WIN32_WINNT 0x0601
# define _WIN32_IE 0x0700
#endif // __GNUC__
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1900
#pragma warning( disable: 5024 5025 5026 5027)
#endif
#ifdef __clang__
// test only
#define try if(true)
#define catch(x) if(false)
#define throw if(false)
#endif
#define WIN32_NO_STATUS //exclude ntstatus.h macros from winnt.h
#include <windows.h>
#undef WIN32_NO_STATUS
#include <winioctl.h>
#include <mmsystem.h>
#include <wininet.h>
#include <winspool.h>
#include <setupapi.h>
#include <aclapi.h>
#include <sddl.h>
#include <dbt.h>
#include <lm.h>
#define SECURITY_WIN32
#include <security.h>
#define PSAPI_VERSION 1
#include <psapi.h>
#include <shlobj.h>
#include <shellapi.h>
#ifdef _MSC_VER
# include <ntstatus.h>
# include <shobjidl.h>
# include <winternl.h>
# include <cfgmgr32.h>
# include <ntddscsi.h>
# include <virtdisk.h>
# include <RestartManager.h>
# include <lmdfs.h>
#endif // _MSC_VER
#ifdef __GNUC__
# define __NTDDK_H
struct _ADAPTER_OBJECT;
typedef struct _ADAPTER_OBJECT ADAPTER_OBJECT,*PADAPTER_OBJECT;
# ifdef _W32API_OLD
# include <ntstatus.h>
# include <cfgmgr32.h>
# include <ntddscsi.h>
# else
# include <ddk/ntstatus.h>
# include <ddk/cfgmgr32.h>
# include <ddk/ntddscsi.h>
# include <ntdef.h>
# endif
#endif // __GNUC__
#include "SDK/sdk.common.h"
#ifdef _MSC_VER
# include "SDK/sdk.vc.h"
#endif // _MSC_VER
#ifdef __GNUC__
# include "SDK/sdk.gcc.h"
#endif // __GNUC__
#include "cpp.hpp"
#include "common.hpp"
#include "farrtl.hpp"
#include "format.hpp"
#include "local.hpp"
#include "farwinapi.hpp"
#include "cvtname.hpp"
#include "plugin.hpp"
#include "global.hpp"
|
#pragma once
/*
headers.hpp
*/
/*
Copyright 1996 Eugene Roshal
Copyright 2000 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __clang__
// test only
#define _HAS_EXCEPTIONS 0
#endif
#include <array>
#include <algorithm>
#include <bitset>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <queue>
#include <map>
#include <memory>
#include <numeric>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cstdint>
#include <ctime>
#include <process.h>
#undef _W32API_OLD
#ifdef _MSC_VER
# if _MSC_VER < 1600
# error Visual C++ 2010 (or higher) required
# endif
# include <sdkddkver.h>
# if _WIN32_WINNT < 0x0601
# error Windows SDK v7.0 (or higher) required
# endif
#endif //_MSC_VER
#ifdef __GNUC__
# define GCC_VER_(gcc_major,gcc_minor,gcc_patch) (100*(gcc_major) + 10*(gcc_minor) + (gcc_patch))
# define _GCC_VER GCC_VER_(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
# if _GCC_VER < GCC_VER_(4,9,0)
# error gcc 4.9.0 (or higher) required
# endif
# include <w32api.h>
# define _W32API_VER (100*(__W32API_MAJOR_VERSION) + (__W32API_MINOR_VERSION))
# if _W32API_VER < 314
# error w32api-3.14 (or higher) required
# endif
# if _W32API_VER < 317
# define _W32API_OLD 1
# endif
# undef WINVER
# undef _WIN32_WINNT
# undef _WIN32_IE
# define WINVER 0x0601
# define _WIN32_WINNT 0x0601
# define _WIN32_IE 0x0700
#endif // __GNUC__
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1900
#pragma warning( disable: 5024 5025 5026 5027)
#endif
#ifdef __clang__
// test only
#define try if(true)
#define catch(x) if(false)
#define throw if(false)
#endif
#define WIN32_NO_STATUS //exclude ntstatus.h macros from winnt.h
#include <windows.h>
#undef WIN32_NO_STATUS
#include <winioctl.h>
#include <mmsystem.h>
#include <wininet.h>
#include <winspool.h>
#include <setupapi.h>
#include <aclapi.h>
#include <sddl.h>
#include <dbt.h>
#include <lm.h>
#define SECURITY_WIN32
#include <security.h>
#define PSAPI_VERSION 1
#include <psapi.h>
#include <shlobj.h>
#include <shellapi.h>
#ifdef _MSC_VER
# include <ntstatus.h>
# include <shobjidl.h>
# include <winternl.h>
# include <cfgmgr32.h>
# include <ntddscsi.h>
# include <virtdisk.h>
# include <RestartManager.h>
# include <lmdfs.h>
#endif // _MSC_VER
#ifdef __GNUC__
# define __NTDDK_H
struct _ADAPTER_OBJECT;
typedef struct _ADAPTER_OBJECT ADAPTER_OBJECT,*PADAPTER_OBJECT;
# ifdef _W32API_OLD
# include <ntstatus.h>
# include <cfgmgr32.h>
# include <ntddscsi.h>
# else
# include <ddk/ntstatus.h>
# include <ddk/cfgmgr32.h>
# include <ddk/ntddscsi.h>
# include <ntdef.h>
# endif
#endif // __GNUC__
#include "SDK/sdk.common.h"
#ifdef _MSC_VER
# include "SDK/sdk.vc.h"
#endif // _MSC_VER
#ifdef __GNUC__
# include "SDK/sdk.gcc.h"
#endif // __GNUC__
#include "cpp.hpp"
#include "common.hpp"
#include "farrtl.hpp"
#include "format.hpp"
#include "local.hpp"
#include "farwinapi.hpp"
#include "cvtname.hpp"
#include "plugin.hpp"
#include "global.hpp"
|
fix build
|
fix build
|
C++
|
bsd-3-clause
|
FarGroup/FarManager,johnd0e/FarManager,johnd0e/FarManager,johnd0e/FarManager,FarGroup/FarManager,FarGroup/FarManager,FarGroup/FarManager,johnd0e/FarManager,FarGroup/FarManager,johnd0e/FarManager,FarGroup/FarManager,FarGroup/FarManager,FarGroup/FarManager,johnd0e/FarManager,johnd0e/FarManager,johnd0e/FarManager
|
aa8282344e1e5d0f6c98735c82e381dfe7af9d83
|
src/binding.cc
|
src/binding.cc
|
/* -*- 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 "couchbase_impl.h"
#include "exception.h"
#include <libcouchbase/libuv_io_opts.h>
using namespace Couchnode;
Nan::Persistent<Function> CouchbaseImpl::jsonParse;
Nan::Persistent<Function> CouchbaseImpl::jsonStringify;
Nan::Persistent<String> CouchbaseImpl::valueKey;
Nan::Persistent<String> CouchbaseImpl::casKey;
Nan::Persistent<String> CouchbaseImpl::flagsKey;
Nan::Persistent<String> CouchbaseImpl::datatypeKey;
Nan::Persistent<String> CouchbaseImpl::idKey;
Nan::Persistent<String> CouchbaseImpl::keyKey;
Nan::Persistent<String> CouchbaseImpl::docKey;
Nan::Persistent<String> CouchbaseImpl::geometryKey;
Nan::Persistent<String> CouchbaseImpl::rowsKey;
Nan::Persistent<String> CouchbaseImpl::resultsKey;
Nan::Persistent<String> CouchbaseImpl::tokenKey;
Nan::Persistent<String> CouchbaseImpl::errorKey;
Nan::Persistent<String> lcbErrorKey;
extern "C" {
static NAN_MODULE_INIT(init)
{
lcbErrorKey.Reset(Nan::New<String>("lcbError").ToLocalChecked());
Error::Init();
Cas::Init();
MutationToken::Init();
CouchbaseImpl::Init(target);
}
NODE_MODULE(couchbase_impl, init)
}
Nan::Persistent<Function> Cas::casClass;
Nan::Persistent<Function> MutationToken::tokenClass;
Nan::Persistent<Function> Error::errorClass;
Nan::Persistent<String> Error::codeKey;
NAN_MODULE_INIT(CouchbaseImpl::Init)
{
Nan::HandleScope scope;
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(fnNew);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("CouchbaseImpl").ToLocalChecked());
Nan::SetPrototypeMethod(t, "shutdown", fnShutdown);
Nan::SetPrototypeMethod(t, "control", fnControl);
Nan::SetPrototypeMethod(t, "connect", fnConnect);
Nan::SetPrototypeMethod(t, "getViewNode", fnGetViewNode);
Nan::SetPrototypeMethod(t, "getMgmtNode", fnGetMgmtNode);
Nan::SetPrototypeMethod(t, "_errorTest", fnErrorTest);
Nan::SetPrototypeMethod(t, "setConnectCallback", fnSetConnectCallback);
Nan::SetPrototypeMethod(t, "setTranscoder", fnSetTranscoder);
Nan::SetPrototypeMethod(t, "lcbVersion", fnLcbVersion);
Nan::SetPrototypeMethod(t, "get", fnGet);
Nan::SetPrototypeMethod(t, "getReplica", fnGetReplica);
Nan::SetPrototypeMethod(t, "touch", fnTouch);
Nan::SetPrototypeMethod(t, "unlock", fnUnlock);
Nan::SetPrototypeMethod(t, "remove", fnRemove);
Nan::SetPrototypeMethod(t, "store", fnStore);
Nan::SetPrototypeMethod(t, "arithmetic", fnArithmetic);
Nan::SetPrototypeMethod(t, "durability", fnDurability);
Nan::SetPrototypeMethod(t, "viewQuery", fnViewQuery);
Nan::SetPrototypeMethod(t, "n1qlQuery", fnN1qlQuery);
Nan::SetPrototypeMethod(t, "ftsQuery", fnFtsQuery);
Nan::SetPrototypeMethod(t, "lookupIn", fnLookupIn);
Nan::SetPrototypeMethod(t, "mutateIn", fnMutateIn);
target->Set(
Nan::New<String>("CouchbaseImpl").ToLocalChecked(),
t->GetFunction());
target->Set(
Nan::New<String>("Constants").ToLocalChecked(),
createConstants());
Nan::SetMethod(target, "_setErrorClass", sfnSetErrorClass);
valueKey.Reset(Nan::New<String>("value").ToLocalChecked());
casKey.Reset(Nan::New<String>("cas").ToLocalChecked());
flagsKey.Reset(Nan::New<String>("flags").ToLocalChecked());
datatypeKey.Reset(Nan::New<String>("datatype").ToLocalChecked());
idKey.Reset(Nan::New<String>("id").ToLocalChecked());
keyKey.Reset(Nan::New<String>("key").ToLocalChecked());
docKey.Reset(Nan::New<String>("doc").ToLocalChecked());
geometryKey.Reset(Nan::New<String>("geometry").ToLocalChecked());
rowsKey.Reset(Nan::New<String>("rows").ToLocalChecked());
resultsKey.Reset(Nan::New<String>("results").ToLocalChecked());
tokenKey.Reset(Nan::New<String>("token").ToLocalChecked());
errorKey.Reset(Nan::New<String>("error").ToLocalChecked());
Handle<Object> jMod = Nan::GetCurrentContext()->Global()->Get(
Nan::New<String>("JSON").ToLocalChecked()).As<Object>();
assert(!jMod.IsEmpty());
jsonParse.Reset(
jMod->Get(Nan::New<String>("parse").ToLocalChecked()).As<Function>());
jsonStringify.Reset(
jMod->Get(Nan::New<String>("stringify").ToLocalChecked()).As<Function>());
assert(!jsonParse.IsEmpty());
assert(!jsonStringify.IsEmpty());
}
NAN_METHOD(CouchbaseImpl::sfnSetErrorClass)
{
Nan::HandleScope scope;
if (info.Length() != 1) {
info.GetReturnValue().Set(Error::create("invalid number of parameters passed"));
return;
}
Error::setErrorClass(info[0].As<Function>());
info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnNew)
{
//CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(args.This());
Nan::HandleScope scope;
if (info.Length() != 3) {
return Nan::ThrowError(Error::create("expected 3 parameters"));
}
lcb_error_t err;
lcb_io_opt_st *iops;
lcbuv_options_t iopsOptions;
iopsOptions.version = 0;
iopsOptions.v.v0.loop = uv_default_loop();
iopsOptions.v.v0.startsop_noop = 1;
err = lcb_create_libuv_io_opts(0, &iops, &iopsOptions);
if (err != LCB_SUCCESS) {
return Nan::ThrowError(Error::create(err));
}
lcb_create_st createOptions;
memset(&createOptions, 0, sizeof(createOptions));
createOptions.version = 3;
Nan::Utf8String *utfConnStr = NULL;
if (info[0]->BooleanValue()) {
utfConnStr = new Nan::Utf8String(info[0]);
createOptions.v.v3.connstr = **utfConnStr;
}
Nan::Utf8String *utfUsername = NULL;
if (info[1]->BooleanValue()) {
utfUsername = new Nan::Utf8String(info[1]);
createOptions.v.v3.username = **utfUsername;
}
Nan::Utf8String *utfPassword = NULL;
if (info[2]->BooleanValue()) {
utfPassword = new Nan::Utf8String(info[2]);
createOptions.v.v3.passwd = **utfPassword;
}
createOptions.v.v3.io = iops;
lcb_t instance;
err = lcb_create(&instance, &createOptions);
if (utfConnStr) {
delete utfConnStr;
}
if (utfUsername) {
delete utfUsername;
}
if (utfPassword) {
delete utfPassword;
}
if (err != LCB_SUCCESS) {
return Nan::ThrowError(Error::create(err));
}
CouchbaseImpl *hw = new CouchbaseImpl(instance);
hw->Wrap(info.This());
return info.GetReturnValue().Set(info.This());
}
NAN_METHOD(CouchbaseImpl::fnConnect)
{
CouchbaseImpl *me = Nan::ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
lcb_error_t ec = lcb_connect(me->getLcbHandle());
if (ec != LCB_SUCCESS) {
return Nan::ThrowError(Error::create(ec));
}
return info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnSetConnectCallback)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
if (info.Length() != 1) {
return info.GetReturnValue().Set(
Error::create("invalid number of parameters passed"));
}
if (me->connectCallback) {
delete me->connectCallback;
me->connectCallback = NULL;
}
if (info[0]->BooleanValue()) {
if (!info[0]->IsFunction()) {
return Nan::ThrowError(Error::create("must pass function"));
}
me->connectCallback = new Nan::Callback(info[0].As<Function>());
}
return info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnSetTranscoder)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
if (info.Length() != 2) {
return Nan::ThrowError(Error::create("invalid number of parameters passed"));
}
if (me->transEncodeFunc) {
delete me->transEncodeFunc;
me->transEncodeFunc = NULL;
}
if (me->transDecodeFunc) {
delete me->transDecodeFunc;
me->transDecodeFunc = NULL;
}
if (info[0]->BooleanValue()) {
if (!info[0]->IsFunction()) {
return Nan::ThrowError(Error::create("must pass function"));
}
me->transEncodeFunc = new Nan::Callback(info[0].As<Function>());
}
if (info[1]->BooleanValue()) {
if (!info[1]->IsFunction()) {
return Nan::ThrowError(Error::create("must pass function"));
}
me->transDecodeFunc = new Nan::Callback(info[1].As<Function>());
}
return info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnLcbVersion)
{
Nan::HandleScope scope;
return info.GetReturnValue().Set(
Nan::New<String>(lcb_get_version(NULL)).ToLocalChecked());
}
NAN_METHOD(CouchbaseImpl::fnGetViewNode)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
lcb_int32_t numNodes = lcb_get_num_nodes(me->getLcbHandle());
if (numNodes <= 0) {
return info.GetReturnValue().SetNull();
}
unsigned int nodeIdx = rand() % numNodes;
const char *viewNode =
lcb_get_node(
me->getLcbHandle(),
(lcb_GETNODETYPE)LCB_NODE_VIEWS,
nodeIdx);
return info.GetReturnValue().Set(
Nan::New<String>(viewNode).ToLocalChecked());
}
NAN_METHOD(CouchbaseImpl::fnGetMgmtNode)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
lcb_int32_t numNodes = lcb_get_num_nodes(me->getLcbHandle());
if (numNodes <= 0) {
return info.GetReturnValue().SetNull();
}
unsigned int nodeIdx = rand() % numNodes;
const char *mgmtNode =
lcb_get_node(
me->getLcbHandle(),
(lcb_GETNODETYPE)LCB_NODE_HTCONFIG,
nodeIdx);
return info.GetReturnValue().Set(
Nan::New<String>(mgmtNode).ToLocalChecked());
}
NAN_METHOD(CouchbaseImpl::fnShutdown)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
lcb_destroy_async(me->getLcbHandle(), NULL);
me->onShutdown();
return info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnErrorTest)
{
Nan::HandleScope scope;
info.GetReturnValue().Set(Error::create("test error"));
}
|
/* -*- 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 "couchbase_impl.h"
#include "exception.h"
#include <libcouchbase/libuv_io_opts.h>
#include <libcouchbase/vbucket.h>
using namespace Couchnode;
Nan::Persistent<Function> CouchbaseImpl::jsonParse;
Nan::Persistent<Function> CouchbaseImpl::jsonStringify;
Nan::Persistent<String> CouchbaseImpl::valueKey;
Nan::Persistent<String> CouchbaseImpl::casKey;
Nan::Persistent<String> CouchbaseImpl::flagsKey;
Nan::Persistent<String> CouchbaseImpl::datatypeKey;
Nan::Persistent<String> CouchbaseImpl::idKey;
Nan::Persistent<String> CouchbaseImpl::keyKey;
Nan::Persistent<String> CouchbaseImpl::docKey;
Nan::Persistent<String> CouchbaseImpl::geometryKey;
Nan::Persistent<String> CouchbaseImpl::rowsKey;
Nan::Persistent<String> CouchbaseImpl::resultsKey;
Nan::Persistent<String> CouchbaseImpl::tokenKey;
Nan::Persistent<String> CouchbaseImpl::errorKey;
Nan::Persistent<String> lcbErrorKey;
extern "C" {
static NAN_MODULE_INIT(init)
{
lcbErrorKey.Reset(Nan::New<String>("lcbError").ToLocalChecked());
Error::Init();
Cas::Init();
MutationToken::Init();
CouchbaseImpl::Init(target);
}
NODE_MODULE(couchbase_impl, init)
}
Nan::Persistent<Function> Cas::casClass;
Nan::Persistent<Function> MutationToken::tokenClass;
Nan::Persistent<Function> Error::errorClass;
Nan::Persistent<String> Error::codeKey;
NAN_MODULE_INIT(CouchbaseImpl::Init)
{
Nan::HandleScope scope;
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(fnNew);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("CouchbaseImpl").ToLocalChecked());
Nan::SetPrototypeMethod(t, "shutdown", fnShutdown);
Nan::SetPrototypeMethod(t, "control", fnControl);
Nan::SetPrototypeMethod(t, "connect", fnConnect);
Nan::SetPrototypeMethod(t, "getViewNode", fnGetViewNode);
Nan::SetPrototypeMethod(t, "getMgmtNode", fnGetMgmtNode);
Nan::SetPrototypeMethod(t, "_errorTest", fnErrorTest);
Nan::SetPrototypeMethod(t, "setConnectCallback", fnSetConnectCallback);
Nan::SetPrototypeMethod(t, "setTranscoder", fnSetTranscoder);
Nan::SetPrototypeMethod(t, "lcbVersion", fnLcbVersion);
Nan::SetPrototypeMethod(t, "get", fnGet);
Nan::SetPrototypeMethod(t, "getReplica", fnGetReplica);
Nan::SetPrototypeMethod(t, "touch", fnTouch);
Nan::SetPrototypeMethod(t, "unlock", fnUnlock);
Nan::SetPrototypeMethod(t, "remove", fnRemove);
Nan::SetPrototypeMethod(t, "store", fnStore);
Nan::SetPrototypeMethod(t, "arithmetic", fnArithmetic);
Nan::SetPrototypeMethod(t, "durability", fnDurability);
Nan::SetPrototypeMethod(t, "viewQuery", fnViewQuery);
Nan::SetPrototypeMethod(t, "n1qlQuery", fnN1qlQuery);
Nan::SetPrototypeMethod(t, "ftsQuery", fnFtsQuery);
Nan::SetPrototypeMethod(t, "lookupIn", fnLookupIn);
Nan::SetPrototypeMethod(t, "mutateIn", fnMutateIn);
target->Set(
Nan::New<String>("CouchbaseImpl").ToLocalChecked(),
t->GetFunction());
target->Set(
Nan::New<String>("Constants").ToLocalChecked(),
createConstants());
Nan::SetMethod(target, "_setErrorClass", sfnSetErrorClass);
valueKey.Reset(Nan::New<String>("value").ToLocalChecked());
casKey.Reset(Nan::New<String>("cas").ToLocalChecked());
flagsKey.Reset(Nan::New<String>("flags").ToLocalChecked());
datatypeKey.Reset(Nan::New<String>("datatype").ToLocalChecked());
idKey.Reset(Nan::New<String>("id").ToLocalChecked());
keyKey.Reset(Nan::New<String>("key").ToLocalChecked());
docKey.Reset(Nan::New<String>("doc").ToLocalChecked());
geometryKey.Reset(Nan::New<String>("geometry").ToLocalChecked());
rowsKey.Reset(Nan::New<String>("rows").ToLocalChecked());
resultsKey.Reset(Nan::New<String>("results").ToLocalChecked());
tokenKey.Reset(Nan::New<String>("token").ToLocalChecked());
errorKey.Reset(Nan::New<String>("error").ToLocalChecked());
Handle<Object> jMod = Nan::GetCurrentContext()->Global()->Get(
Nan::New<String>("JSON").ToLocalChecked()).As<Object>();
assert(!jMod.IsEmpty());
jsonParse.Reset(
jMod->Get(Nan::New<String>("parse").ToLocalChecked()).As<Function>());
jsonStringify.Reset(
jMod->Get(Nan::New<String>("stringify").ToLocalChecked()).As<Function>());
assert(!jsonParse.IsEmpty());
assert(!jsonStringify.IsEmpty());
}
NAN_METHOD(CouchbaseImpl::sfnSetErrorClass)
{
Nan::HandleScope scope;
if (info.Length() != 1) {
info.GetReturnValue().Set(Error::create("invalid number of parameters passed"));
return;
}
Error::setErrorClass(info[0].As<Function>());
info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnNew)
{
//CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(args.This());
Nan::HandleScope scope;
if (info.Length() != 3) {
return Nan::ThrowError(Error::create("expected 3 parameters"));
}
lcb_error_t err;
lcb_io_opt_st *iops;
lcbuv_options_t iopsOptions;
iopsOptions.version = 0;
iopsOptions.v.v0.loop = uv_default_loop();
iopsOptions.v.v0.startsop_noop = 1;
err = lcb_create_libuv_io_opts(0, &iops, &iopsOptions);
if (err != LCB_SUCCESS) {
return Nan::ThrowError(Error::create(err));
}
lcb_create_st createOptions;
memset(&createOptions, 0, sizeof(createOptions));
createOptions.version = 3;
Nan::Utf8String *utfConnStr = NULL;
if (info[0]->BooleanValue()) {
utfConnStr = new Nan::Utf8String(info[0]);
createOptions.v.v3.connstr = **utfConnStr;
}
Nan::Utf8String *utfUsername = NULL;
if (info[1]->BooleanValue()) {
utfUsername = new Nan::Utf8String(info[1]);
createOptions.v.v3.username = **utfUsername;
}
Nan::Utf8String *utfPassword = NULL;
if (info[2]->BooleanValue()) {
utfPassword = new Nan::Utf8String(info[2]);
createOptions.v.v3.passwd = **utfPassword;
}
createOptions.v.v3.io = iops;
lcb_t instance;
err = lcb_create(&instance, &createOptions);
if (utfConnStr) {
delete utfConnStr;
}
if (utfUsername) {
delete utfUsername;
}
if (utfPassword) {
delete utfPassword;
}
if (err != LCB_SUCCESS) {
return Nan::ThrowError(Error::create(err));
}
CouchbaseImpl *hw = new CouchbaseImpl(instance);
hw->Wrap(info.This());
return info.GetReturnValue().Set(info.This());
}
NAN_METHOD(CouchbaseImpl::fnConnect)
{
CouchbaseImpl *me = Nan::ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
lcb_error_t ec = lcb_connect(me->getLcbHandle());
if (ec != LCB_SUCCESS) {
return Nan::ThrowError(Error::create(ec));
}
return info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnSetConnectCallback)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
if (info.Length() != 1) {
return info.GetReturnValue().Set(
Error::create("invalid number of parameters passed"));
}
if (me->connectCallback) {
delete me->connectCallback;
me->connectCallback = NULL;
}
if (info[0]->BooleanValue()) {
if (!info[0]->IsFunction()) {
return Nan::ThrowError(Error::create("must pass function"));
}
me->connectCallback = new Nan::Callback(info[0].As<Function>());
}
return info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnSetTranscoder)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
if (info.Length() != 2) {
return Nan::ThrowError(Error::create("invalid number of parameters passed"));
}
if (me->transEncodeFunc) {
delete me->transEncodeFunc;
me->transEncodeFunc = NULL;
}
if (me->transDecodeFunc) {
delete me->transDecodeFunc;
me->transDecodeFunc = NULL;
}
if (info[0]->BooleanValue()) {
if (!info[0]->IsFunction()) {
return Nan::ThrowError(Error::create("must pass function"));
}
me->transEncodeFunc = new Nan::Callback(info[0].As<Function>());
}
if (info[1]->BooleanValue()) {
if (!info[1]->IsFunction()) {
return Nan::ThrowError(Error::create("must pass function"));
}
me->transDecodeFunc = new Nan::Callback(info[1].As<Function>());
}
return info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnLcbVersion)
{
Nan::HandleScope scope;
return info.GetReturnValue().Set(
Nan::New<String>(lcb_get_version(NULL)).ToLocalChecked());
}
NAN_METHOD(CouchbaseImpl::fnGetViewNode)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
lcbvb_CONFIG *cfg;
lcb_cntl(me->getLcbHandle(), LCB_CNTL_GET, LCB_CNTL_VBCONFIG, &cfg);
int nodeIdx =
lcbvb_get_randhost(cfg, LCBVB_SVCTYPE_VIEWS, LCBVB_SVCMODE_PLAIN);
const char *viewNode =
lcb_get_node(
me->getLcbHandle(),
(lcb_GETNODETYPE)LCB_NODE_VIEWS,
nodeIdx);
return info.GetReturnValue().Set(
Nan::New<String>(viewNode).ToLocalChecked());
}
NAN_METHOD(CouchbaseImpl::fnGetMgmtNode)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
lcbvb_CONFIG *cfg;
lcb_cntl(me->getLcbHandle(), LCB_CNTL_GET, LCB_CNTL_VBCONFIG, &cfg);
int nodeIdx =
lcbvb_get_randhost(cfg, LCBVB_SVCTYPE_MGMT, LCBVB_SVCMODE_PLAIN);
const char *mgmtNode =
lcb_get_node(
me->getLcbHandle(),
(lcb_GETNODETYPE)LCB_NODE_HTCONFIG,
nodeIdx);
return info.GetReturnValue().Set(
Nan::New<String>(mgmtNode).ToLocalChecked());
}
NAN_METHOD(CouchbaseImpl::fnShutdown)
{
CouchbaseImpl *me = ObjectWrap::Unwrap<CouchbaseImpl>(info.This());
Nan::HandleScope scope;
lcb_destroy_async(me->getLcbHandle(), NULL);
me->onShutdown();
return info.GetReturnValue().Set(true);
}
NAN_METHOD(CouchbaseImpl::fnErrorTest)
{
Nan::HandleScope scope;
info.GetReturnValue().Set(Error::create("test error"));
}
|
Use lcbvb to select random nodes of a type.
|
JSCBC-316: Use lcbvb to select random nodes of a type.
Previously we randomly selected any node, however this caused
an issue when a node did not contain that service due to MDS.
Change-Id: I044d8128c0816994dbbc263705137b577cf5cfb1
Reviewed-on: http://review.couchbase.org/66099
Reviewed-by: Mark Nunberg <[email protected]>
Tested-by: Brett Lawson <[email protected]>
|
C++
|
apache-2.0
|
brett19/couchnode,couchbase/couchnode,couchbase/couchnode,couchbase/couchnode,brett19/couchnode,brett19/couchnode,couchbase/couchnode
|
54276fd9bf18d3e252a7a16c549ca9eb98422fc8
|
src/buffer.cpp
|
src/buffer.cpp
|
/// \file buffer.cpp
/// Contains the main code for the Buffer.
#include <fcntl.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sstream>
#include <sys/time.h>
#include <mist/config.h>
#include "buffer_stream.h"
/// Holds all code unique to the Buffer.
namespace Buffer{
volatile bool buffer_running = true; ///< Set to false when shutting down.
Stream * thisStream = 0;
Socket::Server SS; ///< The server socket.
/// Gets the current system time in milliseconds.
long long int getNowMS(){
timeval t;
gettimeofday(&t, 0);
return t.tv_sec * 1000 + t.tv_usec/1000;
}//getNowMS
///A simple signal handler that ignores all signals.
void termination_handler (int signum){
switch (signum){
case SIGKILL: buffer_running = false; break;
case SIGPIPE: return; break;
default: return; break;
}
}
void handleStats(void * empty){
if (empty != 0){return;}
Socket::Connection StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
while (buffer_running){
usleep(1000000); //sleep one second
if (!StatsSocket.connected()){
StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
}
if (StatsSocket.connected()){
StatsSocket.write(Stream::get()->getStats()+"\n\n");
}
}
}
void handleUser(void * v_usr){
user * usr = (user*)v_usr;
std::cerr << "Thread launched for user " << usr->MyStr << ", socket number " << usr->S.getSocket() << std::endl;
usr->myRing = thisStream->getRing();
if (!usr->S.write(thisStream->getHeader())){
usr->Disconnect("failed to receive the header!");
return;
}
while (usr->S.connected()){
usleep(5000); //sleep 5ms
if (usr->S.canRead()){
usr->inbuffer.clear();
char charbuf;
while ((usr->S.iread(&charbuf, 1) == 1) && charbuf != '\n' ){
usr->inbuffer += charbuf;
}
if (usr->inbuffer != ""){
if (usr->inbuffer[0] == 'P'){
std::cout << "Push attempt from IP " << usr->inbuffer.substr(2) << std::endl;
if (thisStream->checkWaitingIP(usr->inbuffer.substr(2))){
if (thisStream->setInput(usr->S)){
std::cout << "Push accepted!" << std::endl;
usr->S = Socket::Connection(-1);
return;
}else{
usr->Disconnect("Push denied - push already in progress!");
}
}else{
usr->Disconnect("Push denied - invalid IP address!");
}
}
if (usr->inbuffer[0] == 'S'){
usr->tmpStats = Stats(usr->inbuffer.substr(2));
unsigned int secs = usr->tmpStats.conntime - usr->lastStats.conntime;
if (secs < 1){secs = 1;}
usr->curr_up = (usr->tmpStats.up - usr->lastStats.up) / secs;
usr->curr_down = (usr->tmpStats.down - usr->lastStats.down) / secs;
usr->lastStats = usr->tmpStats;
thisStream->saveStats(usr->MyStr, usr->tmpStats);
}
}
}
usr->Send();
}
thisStream->cleanUsers();
std::cerr << "User " << usr->MyStr << " disconnected, socket number " << usr->S.getSocket() << std::endl;
}
/// Loop reading DTSC data from stdin and processing it at the correct speed.
void handleStdin(void * empty){
if (empty != 0){return;}
long long int timeDiff = 0;//difference between local time and stream time
unsigned int lastPacket = 0;//last parsed packet timestamp
std::string inBuffer;
char charBuffer[1024*10];
unsigned int charCount;
long long int now;
while (std::cin.good() && buffer_running){
//slow down packet receiving to real-time
now = getNowMS();
if ((now - timeDiff >= lastPacket) || (lastPacket - (now - timeDiff) > 5000)){
thisStream->getWriteLock();
if (thisStream->getStream()->parsePacket(inBuffer)){
thisStream->getStream()->outPacket(0);
lastPacket = thisStream->getStream()->getTime();
if ((now - timeDiff - lastPacket) > 5000 || (now - timeDiff - lastPacket < -5000)){
timeDiff = now - lastPacket;
}
thisStream->dropWriteLock(true);
}else{
thisStream->dropWriteLock(false);
std::cin.read(charBuffer, 1024*10);
charCount = std::cin.gcount();
inBuffer.append(charBuffer, charCount);
}
}else{
if ((lastPacket - (now - timeDiff)) > 999){
usleep(999000);
}else{
usleep((lastPacket - (now - timeDiff)) * 1000);
}
}
}
buffer_running = false;
SS.close();
}
/// Loop reading DTSC data from an IP push address.
/// No changes to the speed are made.
void handlePushin(void * empty){
if (empty != 0){return;}
std::string inBuffer;
while (buffer_running){
if (thisStream->getIPInput().connected()){
if (inBuffer.size() > 0){
thisStream->getWriteLock();
if (thisStream->getStream()->parsePacket(inBuffer)){
thisStream->getStream()->outPacket(0);
thisStream->dropWriteLock(true);
}else{
thisStream->dropWriteLock(false);
thisStream->getIPInput().iread(inBuffer);
usleep(1000);//1ms wait
}
}else{
thisStream->getIPInput().iread(inBuffer);
usleep(1000);//1ms wait
}
}else{
usleep(1000000);//1s wait
}
}
SS.close();
}
/// Starts a loop, waiting for connections to send data to.
int Start(int argc, char ** argv) {
Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION);
conf.addOption("stream_name", JSON::fromString("{\"arg_num\":1, \"arg\":\"string\", \"help\":\"Name of the stream this buffer will be providing.\"}"));
conf.addOption("awaiting_ip", JSON::fromString("{\"arg_num\":2, \"arg\":\"string\", \"default\":\"\", \"help\":\"IP address to expect incoming data from. This will completely disable reading from standard input if used.\"}"));
conf.parseArgs(argc, argv);
std::string name = conf.getString("stream_name");
SS = Socket::makeStream(name);
if (!SS.connected()) {
perror("Could not create stream socket");
return 1;
}
thisStream = Stream::get();
thisStream->setName(name);
Socket::Connection incoming;
Socket::Connection std_input(fileno(stdin));
tthread::thread StatsThread = tthread::thread(handleStats, 0);
tthread::thread * StdinThread = 0;
std::string await_ip = conf.getString("awaiting_ip");
if (await_ip == ""){
StdinThread = new tthread::thread(handleStdin, 0);
}else{
thisStream->setWaitingIP(await_ip);
StdinThread = new tthread::thread(handlePushin, 0);
}
while (buffer_running && SS.connected()){
//check for new connections, accept them if there are any
//starts a thread for every accepted connection
incoming = SS.accept(false);
if (incoming.connected()){
user * usr_ptr = new user(incoming);
thisStream->addUser(usr_ptr);
usr_ptr->Thread = new tthread::thread(handleUser, (void *)usr_ptr);
}
}//main loop
// disconnect listener
buffer_running = false;
std::cout << "End of input file - buffer shutting down" << std::endl;
SS.close();
StatsThread.join();
StdinThread->join();
delete thisStream;
return 0;
}
};//Buffer namespace
/// Entry point for Buffer, simply calls Buffer::Start().
int main(int argc, char ** argv){
return Buffer::Start(argc, argv);
}//main
|
/// \file buffer.cpp
/// Contains the main code for the Buffer.
#include <fcntl.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sstream>
#include <sys/time.h>
#include <mist/config.h>
#include "buffer_stream.h"
/// Holds all code unique to the Buffer.
namespace Buffer{
volatile bool buffer_running = true; ///< Set to false when shutting down.
Stream * thisStream = 0;
Socket::Server SS; ///< The server socket.
/// Gets the current system time in milliseconds.
long long int getNowMS(){
timeval t;
gettimeofday(&t, 0);
return t.tv_sec * 1000 + t.tv_usec/1000;
}//getNowMS
void handleStats(void * empty){
if (empty != 0){return;}
Socket::Connection StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
while (buffer_running){
usleep(1000000); //sleep one second
if (!StatsSocket.connected()){
StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
}
if (StatsSocket.connected()){
StatsSocket.write(Stream::get()->getStats()+"\n\n");
}
}
StatsSocket.close();
}
void handleUser(void * v_usr){
user * usr = (user*)v_usr;
std::cerr << "Thread launched for user " << usr->MyStr << ", socket number " << usr->S.getSocket() << std::endl;
usr->myRing = thisStream->getRing();
if (!usr->S.write(thisStream->getHeader())){
usr->Disconnect("failed to receive the header!");
return;
}
while (usr->S.connected()){
usleep(5000); //sleep 5ms
if (usr->S.canRead()){
usr->inbuffer.clear();
char charbuf;
while ((usr->S.iread(&charbuf, 1) == 1) && charbuf != '\n' ){
usr->inbuffer += charbuf;
}
if (usr->inbuffer != ""){
if (usr->inbuffer[0] == 'P'){
std::cout << "Push attempt from IP " << usr->inbuffer.substr(2) << std::endl;
if (thisStream->checkWaitingIP(usr->inbuffer.substr(2))){
if (thisStream->setInput(usr->S)){
std::cout << "Push accepted!" << std::endl;
usr->S = Socket::Connection(-1);
return;
}else{
usr->Disconnect("Push denied - push already in progress!");
}
}else{
usr->Disconnect("Push denied - invalid IP address!");
}
}
if (usr->inbuffer[0] == 'S'){
usr->tmpStats = Stats(usr->inbuffer.substr(2));
unsigned int secs = usr->tmpStats.conntime - usr->lastStats.conntime;
if (secs < 1){secs = 1;}
usr->curr_up = (usr->tmpStats.up - usr->lastStats.up) / secs;
usr->curr_down = (usr->tmpStats.down - usr->lastStats.down) / secs;
usr->lastStats = usr->tmpStats;
thisStream->saveStats(usr->MyStr, usr->tmpStats);
}
}
}
usr->Send();
}
thisStream->cleanUsers();
std::cerr << "User " << usr->MyStr << " disconnected, socket number " << usr->S.getSocket() << std::endl;
}
/// Loop reading DTSC data from stdin and processing it at the correct speed.
void handleStdin(void * empty){
if (empty != 0){return;}
long long int timeDiff = 0;//difference between local time and stream time
unsigned int lastPacket = 0;//last parsed packet timestamp
std::string inBuffer;
char charBuffer[1024*10];
unsigned int charCount;
long long int now;
while (std::cin.good() && buffer_running){
//slow down packet receiving to real-time
now = getNowMS();
if ((now - timeDiff >= lastPacket) || (lastPacket - (now - timeDiff) > 5000)){
thisStream->getWriteLock();
if (thisStream->getStream()->parsePacket(inBuffer)){
thisStream->getStream()->outPacket(0);
lastPacket = thisStream->getStream()->getTime();
if ((now - timeDiff - lastPacket) > 5000 || (now - timeDiff - lastPacket < -5000)){
timeDiff = now - lastPacket;
}
thisStream->dropWriteLock(true);
}else{
thisStream->dropWriteLock(false);
std::cin.read(charBuffer, 1024*10);
charCount = std::cin.gcount();
inBuffer.append(charBuffer, charCount);
}
}else{
if ((lastPacket - (now - timeDiff)) > 999){
usleep(999000);
}else{
usleep((lastPacket - (now - timeDiff)) * 1000);
}
}
}
buffer_running = false;
SS.close();
}
/// Loop reading DTSC data from an IP push address.
/// No changes to the speed are made.
void handlePushin(void * empty){
if (empty != 0){return;}
std::string inBuffer;
while (buffer_running){
if (thisStream->getIPInput().connected()){
if (inBuffer.size() > 0){
thisStream->getWriteLock();
if (thisStream->getStream()->parsePacket(inBuffer)){
thisStream->getStream()->outPacket(0);
thisStream->dropWriteLock(true);
}else{
thisStream->dropWriteLock(false);
thisStream->getIPInput().iread(inBuffer);
usleep(1000);//1ms wait
}
}else{
thisStream->getIPInput().iread(inBuffer);
usleep(1000);//1ms wait
}
}else{
usleep(1000000);//1s wait
}
}
SS.close();
}
/// Starts a loop, waiting for connections to send data to.
int Start(int argc, char ** argv) {
Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION);
conf.addOption("stream_name", JSON::fromString("{\"arg_num\":1, \"arg\":\"string\", \"help\":\"Name of the stream this buffer will be providing.\"}"));
conf.addOption("awaiting_ip", JSON::fromString("{\"arg_num\":2, \"arg\":\"string\", \"default\":\"\", \"help\":\"IP address to expect incoming data from. This will completely disable reading from standard input if used.\"}"));
conf.addOption("reportstats", JSON::fromString("{\"default\":0, \"help\":\"Report stats to a controller process.\", \"short\":\"s\", \"long\":\"reportstats\"}"));
conf.parseArgs(argc, argv);
std::string name = conf.getString("stream_name");
SS = Socket::makeStream(name);
if (!SS.connected()) {
perror("Could not create stream socket");
return 1;
}
conf.activate();
thisStream = Stream::get();
thisStream->setName(name);
Socket::Connection incoming;
Socket::Connection std_input(fileno(stdin));
tthread::thread * StatsThread = 0;
if (conf.getBool("reportstats")){StatsThread = new tthread::thread(handleStats, 0);}
tthread::thread * StdinThread = 0;
std::string await_ip = conf.getString("awaiting_ip");
if (await_ip == ""){
StdinThread = new tthread::thread(handleStdin, 0);
}else{
thisStream->setWaitingIP(await_ip);
StdinThread = new tthread::thread(handlePushin, 0);
}
while (buffer_running && SS.connected() && conf.is_active){
//check for new connections, accept them if there are any
//starts a thread for every accepted connection
incoming = SS.accept(false);
if (incoming.connected()){
user * usr_ptr = new user(incoming);
thisStream->addUser(usr_ptr);
usr_ptr->Thread = new tthread::thread(handleUser, (void *)usr_ptr);
}
}//main loop
// disconnect listener
buffer_running = false;
std::cout << "End of input file - buffer shutting down" << std::endl;
SS.close();
if (StatsThread){StatsThread->join();}
StdinThread->join();
delete thisStream;
return 0;
}
};//Buffer namespace
/// Entry point for Buffer, simply calls Buffer::Start().
int main(int argc, char ** argv){
return Buffer::Start(argc, argv);
}//main
|
Make buffer's stats reporting optional through a new commandline option - defaulting to false.
|
Make buffer's stats reporting optional through a new commandline option - defaulting to false.
|
C++
|
unlicense
|
DDVTECH/mistserver,DDVTECH/mistserver,DDVTECH/mistserver,rbouqueau/mistserver,rbouqueau/mistserver,DDVTECH/mistserver,rbouqueau/mistserver,rbouqueau/mistserver,rbouqueau/mistserver,DDVTECH/mistserver
|
abfaaa777d96213ab65db108d480692fcac3f174
|
src/canvas.cpp
|
src/canvas.cpp
|
#include "canvas.h"
#include <algorithm>
#include <wx/dcclient.h>
namespace draw {
wxBEGIN_EVENT_TABLE(WXCanvas, wxGLCanvas)
EVT_SIZE(WXCanvas::onSize)
EVT_PAINT(WXCanvas::onPaint)
wxEND_EVENT_TABLE()
WXCanvas::WXCanvas(wxWindow* parent, wxWindowID id, int* attribs) :
wxGLCanvas(parent, id, attribs, wxDefaultPosition,
wxDefaultSize, wxFULL_REPAINT_ON_RESIZE) {
using namespace draw;
renderer_ = makeRenderer(std::move(make_unique<WXContext>(*this)));
font_ = renderer_->makeFont("cour.ttf", 10);
}
ShapePtr WXCanvas::addRect(const Point& position, const Size& size, const Color& color) {
auto obj = renderer_->makeRect(false);
obj->position(position);
obj->size(size);
obj->color(color);
obj->visibility(true);
return obj;
}
TextPtr WXCanvas::addText(const Point& position, const Color& color, const wchar_t* text) {
auto obj = renderer_->makeText();
obj->position(position);
obj->font(font_);
obj->color(color);
obj->text(text);
obj->visibility(true);
return obj;
}
void WXCanvas::repaint() {
if (!IsShownOnScreen())
return;
wxClientDC(this);
doRepaint();
}
void WXCanvas::onSize(wxSizeEvent& event) {
screenSize_.width = event.GetSize().x;
screenSize_.height = event.GetSize().y;
}
void WXCanvas::onPaint(wxPaintEvent&) {
if (!IsShownOnScreen())
return;
wxPaintDC(this);
doRepaint();
}
void WXCanvas::doRepaint() {
renderer_->draw(screenSize_, clearColor_);
SwapBuffers();
}
}; // namespace draw {
|
#include "canvas.h"
#include <algorithm>
#include <wx/dcclient.h>
namespace draw {
wxBEGIN_EVENT_TABLE(WXCanvas, wxGLCanvas)
EVT_SIZE(WXCanvas::onSize)
EVT_PAINT(WXCanvas::onPaint)
wxEND_EVENT_TABLE()
WXCanvas::WXCanvas(wxWindow* parent, wxWindowID id, int* attribs) :
wxGLCanvas(parent, id, attribs, wxDefaultPosition,
wxDefaultSize, wxFULL_REPAINT_ON_RESIZE) {
using namespace draw;
renderer_ = makeRenderer(std::move(make_unique<WXContext>(*this)));
font_ = renderer_->makeFont("cour.ttf", 10);
}
ShapePtr WXCanvas::addRect(const Point& position, const Size& size, const Color& color) {
auto obj = renderer_->makeRect();
obj->position(position);
obj->size(size);
obj->color(color);
obj->visibility(true);
return obj;
}
TextPtr WXCanvas::addText(const Point& position, const Color& color, const wchar_t* text) {
auto obj = renderer_->makeText();
obj->position(position);
obj->font(font_);
obj->color(color);
obj->text(text);
obj->visibility(true);
return obj;
}
void WXCanvas::repaint() {
if (!IsShownOnScreen())
return;
wxClientDC(this);
doRepaint();
}
void WXCanvas::onSize(wxSizeEvent& event) {
screenSize_.width = event.GetSize().x;
screenSize_.height = event.GetSize().y;
}
void WXCanvas::onPaint(wxPaintEvent&) {
if (!IsShownOnScreen())
return;
wxPaintDC(this);
doRepaint();
}
void WXCanvas::doRepaint() {
renderer_->draw(screenSize_, clearColor_);
SwapBuffers();
}
}; // namespace draw {
|
update draw interface call
|
update draw interface call
|
C++
|
bsd-2-clause
|
vsergey3d/draw-wxWidgets
|
e2f6b9a393f4ad0832ce4508a307851a2af84808
|
src/changes.cc
|
src/changes.cc
|
#include "changes.hh"
namespace Kakoune
{
void ForwardChangesTracker::update(const Buffer::Change& change)
{
kak_assert(change.begin >= cur_pos);
if (change.type == Buffer::Change::Insert)
{
old_pos = get_old_coord(change.begin);
cur_pos = change.end;
}
else if (change.type == Buffer::Change::Erase)
{
old_pos = get_old_coord(change.end);
cur_pos = change.begin;
}
}
void ForwardChangesTracker::update(const Buffer& buffer, size_t& timestamp)
{
for (auto& change : buffer.changes_since(timestamp))
update(change);
timestamp = buffer.timestamp();
}
BufferCoord ForwardChangesTracker::get_old_coord(BufferCoord coord) const
{
kak_assert(cur_pos <= coord);
auto pos_change = cur_pos - old_pos;
if (cur_pos.line == coord.line)
{
kak_assert(pos_change.column <= coord.column);
coord.column -= pos_change.column;
}
coord.line -= pos_change.line;
kak_assert(old_pos <= coord);
return coord;
}
BufferCoord ForwardChangesTracker::get_new_coord(BufferCoord coord) const
{
kak_assert(old_pos <= coord);
auto pos_change = cur_pos - old_pos;
if (old_pos.line == coord.line)
{
kak_assert(-pos_change.column <= coord.column);
coord.column += pos_change.column;
}
coord.line += pos_change.line;
kak_assert(cur_pos <= coord);
return coord;
}
BufferCoord ForwardChangesTracker::get_new_coord_tolerant(BufferCoord coord) const
{
if (coord < old_pos)
return cur_pos;
return get_new_coord(coord);
}
bool ForwardChangesTracker::relevant(const Buffer::Change& change, BufferCoord old_coord) const
{
auto new_coord = get_new_coord_tolerant(old_coord);
return change.type == Buffer::Change::Insert ? change.begin <= new_coord
: change.begin < new_coord;
}
const Buffer::Change* forward_sorted_until(const Buffer::Change* first, const Buffer::Change* last)
{
if (first != last) {
const Buffer::Change* next = first;
while (++next != last) {
const auto& ref = first->type == Buffer::Change::Insert ? first->end : first->begin;
if (next->begin <= ref)
return next;
first = next;
}
}
return last;
}
const Buffer::Change* backward_sorted_until(const Buffer::Change* first, const Buffer::Change* last)
{
if (first != last) {
const Buffer::Change* next = first;
while (++next != last) {
if (first->begin <= next->end)
return next;
first = next;
}
}
return last;
}
}
|
#include "changes.hh"
namespace Kakoune
{
void ForwardChangesTracker::update(const Buffer::Change& change)
{
kak_assert(change.begin >= cur_pos);
if (change.type == Buffer::Change::Insert)
{
old_pos = get_old_coord(change.begin);
cur_pos = change.end;
}
else if (change.type == Buffer::Change::Erase)
{
old_pos = get_old_coord(change.end);
cur_pos = change.begin;
}
}
void ForwardChangesTracker::update(const Buffer& buffer, size_t& timestamp)
{
for (auto& change : buffer.changes_since(timestamp))
update(change);
timestamp = buffer.timestamp();
}
BufferCoord ForwardChangesTracker::get_old_coord(BufferCoord coord) const
{
kak_assert(cur_pos <= coord);
auto pos_change = cur_pos - old_pos;
if (cur_pos.line == coord.line)
{
kak_assert(pos_change.column <= coord.column);
coord.column -= pos_change.column;
}
coord.line -= pos_change.line;
kak_assert(old_pos <= coord);
return coord;
}
BufferCoord ForwardChangesTracker::get_new_coord(BufferCoord coord) const
{
kak_assert(old_pos <= coord);
auto pos_change = cur_pos - old_pos;
if (old_pos.line == coord.line)
{
kak_assert(-pos_change.column <= coord.column);
coord.column += pos_change.column;
}
coord.line += pos_change.line;
kak_assert(cur_pos <= coord);
return coord;
}
BufferCoord ForwardChangesTracker::get_new_coord_tolerant(BufferCoord coord) const
{
if (coord < old_pos)
return cur_pos;
return get_new_coord(coord);
}
bool ForwardChangesTracker::relevant(const Buffer::Change& change, BufferCoord old_coord) const
{
auto new_coord = get_new_coord_tolerant(old_coord);
return change.type == Buffer::Change::Insert ? change.begin <= new_coord
: change.begin < new_coord;
}
const Buffer::Change* forward_sorted_until(const Buffer::Change* first, const Buffer::Change* last)
{
if (first != last) {
const Buffer::Change* next = first;
while (++next != last) {
const auto& ref = first->type == Buffer::Change::Insert ? first->end : first->begin;
if (next->begin <= ref)
return next;
first = next;
}
}
return last;
}
const Buffer::Change* backward_sorted_until(const Buffer::Change* first, const Buffer::Change* last)
{
if (first != last) {
const Buffer::Change* next = first;
while (++next != last) {
if (first->begin < next->end)
return next;
first = next;
}
}
return last;
}
}
|
Fix overly strict backward_sorted_until
|
Fix overly strict backward_sorted_until
A change that ended exactly where the previous one started was not
considered backward sorted. Leading to some very bad performances in
certain cases, like '100000o<esc>u'
|
C++
|
unlicense
|
ekie/kakoune,jjthrash/kakoune,Somasis/kakoune,mawww/kakoune,mawww/kakoune,jkonecny12/kakoune,occivink/kakoune,Somasis/kakoune,jkonecny12/kakoune,Somasis/kakoune,alexherbo2/kakoune,alexherbo2/kakoune,lenormf/kakoune,alexherbo2/kakoune,mawww/kakoune,casimir/kakoune,jjthrash/kakoune,Somasis/kakoune,ekie/kakoune,ekie/kakoune,danr/kakoune,occivink/kakoune,lenormf/kakoune,alexherbo2/kakoune,casimir/kakoune,ekie/kakoune,jkonecny12/kakoune,jjthrash/kakoune,danr/kakoune,casimir/kakoune,jjthrash/kakoune,occivink/kakoune,danr/kakoune,jkonecny12/kakoune,lenormf/kakoune,casimir/kakoune,danr/kakoune,occivink/kakoune,lenormf/kakoune,mawww/kakoune
|
c1f1a7724d3b442d4ce2ef6e2d7cb1af54fcaf01
|
src/client.cpp
|
src/client.cpp
|
/*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* 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.
*
* For more about this software visit:
*
* http://ipads.se.sjtu.edu.cn/projects/wukong.html
*
*/
#include "client.h"
client::client(thread_cfg *_cfg, string_server *_str_server):
cfg(_cfg), str_server(_str_server), parser(_str_server) { }
void
client::send(request_or_reply &req)
{
assert(req.pid != -1);
if (req.start_from_index()) {
int nthread = max(1, min(global_mt_threshold, global_nbewkrs));
for (int i = 0; i < global_nsrvs; i++) {
for (int j = 0; j < nthread; j++) {
req.mt_total_thread = nthread;
req.mt_current_thread = j;
SendR(cfg, i, global_nfewkrs + j, req);
}
}
return ;
}
req.first_target = mymath::hash_mod(req.cmd_chains[0], global_nsrvs);
// one-to-one mapping
//int server_per_client = global_nbewkrs / global_nfewkrs;
//int mid = global_nfewkrs + server_per_client * cfg->wid + cfg->get_random() % server_per_client;
// random
int tid = global_nfewkrs + cfg->get_random() % global_nbewkrs;
SendR(cfg, req.first_target, tid, req);
}
request_or_reply
client::recv(void)
{
request_or_reply r = RecvR(cfg);
if (r.start_from_index()) {
int nthread = max(1, min(global_mt_threshold, global_nbewkrs));
for (int count = 0; count < global_nsrvs * nthread - 1 ; count++) {
request_or_reply r2 = RecvR(cfg);
r.row_num += r2.row_num;
int new_size = r.result_table.size() + r2.result_table.size();
r.result_table.reserve(new_size);
r.result_table.insert(r.result_table.end(), r2.result_table.begin(), r2.result_table.end());
}
}
return r;
}
void
client::print_result(request_or_reply &r, int row2print)
{
cout << "The first " << row2print << " rows of results: " << endl;
for (int i = 0; i < row2print; i++) {
cout << i + 1 << ": ";
for (int c = 0; c < r.get_col_num(); c++) {
int id = r.get_row_col(i, c);
if (str_server->id2str.find(id) == str_server->id2str.end())
cout << id << "\t";
else
cout << str_server->id2str[r.get_row_col(i, c)] << " ";
}
cout << endl;
}
}
|
/*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* 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.
*
* For more about this software visit:
*
* http://ipads.se.sjtu.edu.cn/projects/wukong.html
*
*/
#include "client.h"
client::client(thread_cfg *_cfg, string_server *_str_server):
cfg(_cfg), str_server(_str_server), parser(_str_server) { }
void
client::send(request_or_reply &req)
{
assert(req.pid != -1);
if (req.start_from_index()) {
int nthread = max(1, min(global_mt_threshold, global_nbewkrs));
for (int i = 0; i < global_nsrvs; i++) {
for (int j = 0; j < nthread; j++) {
req.mt_total_thread = nthread;
req.mt_current_thread = j;
SendR(cfg, i, global_nfewkrs + j, req);
}
}
return ;
}
req.first_target = mymath::hash_mod(req.cmd_chains[0], global_nsrvs);
// one-to-one mapping
//int server_per_client = global_nbewkrs / global_nfewkrs;
//int mid = global_nfewkrs + server_per_client * cfg->wid + cfg->get_random() % server_per_client;
// random
int tid = global_nfewkrs + cfg->get_random() % global_nbewkrs;
SendR(cfg, req.first_target, tid, req);
}
request_or_reply
client::recv(void)
{
request_or_reply r = RecvR(cfg);
if (r.start_from_index()) {
int nthread = max(1, min(global_mt_threshold, global_nbewkrs));
for (int count = 0; count < global_nsrvs * nthread - 1 ; count++) {
request_or_reply r2 = RecvR(cfg);
r.row_num += r2.row_num;
int new_size = r.result_table.size() + r2.result_table.size();
r.result_table.reserve(new_size);
r.result_table.insert(r.result_table.end(), r2.result_table.begin(), r2.result_table.end());
}
}
return r;
}
void
client::print_result(request_or_reply &r, int row2print)
{
cout << "The first " << row2print << " rows of results: " << endl;
for (int i = 0; i < row2print; i++) {
cout << i + 1 << ": ";
for (int c = 0; c < r.get_col_num(); c++) {
int id = r.get_row_col(i, c);
/*
* Must load the entire ID mapping files (incl. normal and index),
* If you want to print the query results with strings.
*/
if (str_server->id2str.find(id) == str_server->id2str.end())
cout << id << "\t";
else
cout << str_server->id2str[r.get_row_col(i, c)] << " ";
}
cout << endl;
}
}
|
add comment
|
add comment
|
C++
|
apache-2.0
|
SJTU-IPADS/wukong,SJTU-IPADS/wukong
|
935105268d1d9eb1ea0e2f570085f77dd98a8572
|
bs_pvt/src/pvt_3p_serialize.cpp
|
bs_pvt/src/pvt_3p_serialize.cpp
|
/// @file pvt_3p_serialize.cpp
/// @brief pvt_3p serialization implementation
/// @author uentity
/// @version
/// @date 26.01.2012
/// @copyright This source code is released under the terms of
/// the BSD License. See LICENSE for more details.
#include "bs_bos_core_data_storage_stdafx.h"
#include "bs_pvt_stdafx.h"
#include "pvt_3p_serialize.h"
//#include "common_types_serialize.h"
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
using namespace blue_sky;
namespace boser = boost::serialization;
/*-----------------------------------------------------------------
* serialize pvt_base
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_base)
ar & t.p_step;
ar & t.surface_density;
ar & t.molar_density;
ar & t.init_dependent;
ar & t.pvt_input_props;
ar & t.pvt_props_table;
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_base)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_base)
/*-----------------------------------------------------------------
* serialize pvt_dead_oil
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_dead_oil)
// just redirect to base class
ar & boser::bs_base_object< pvt_base >(t);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_dead_oil)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_dead_oil)
/*-----------------------------------------------------------------
* serialize pvt_gas
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_gas)
// just redirect to base class
ar & boser::bs_base_object< pvt_base >(t);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_gas)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_gas)
/*-----------------------------------------------------------------
* serialize pvt_oil
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_oil)
// just redirect to base class
ar & boser::bs_base_object< pvt_base >(t);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_oil)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_oil)
/*-----------------------------------------------------------------
* serialize pvt_water
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_water)
// just redirect to base class
ar & boser::bs_base_object< pvt_base >(t);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_water)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_water)
/*-----------------------------------------------------------------
* serialize pvt_3p
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_3p)
// register conversion to interface
boser::bs_void_cast_register(
static_cast< pvt_3p* >(NULL),
static_cast< pvt_3p_iface* >(NULL)
);
ar & t.n_pvt_regions;
ar & t.pvt_oil_array;
ar & t.pvt_water_array;
ar & t.pvt_gas_array;
ar & t.density_table;
ar & t.density;
BLUE_SKY_CLASS_SRZ_FCN_END
BOOST_SERIALIZATION_ASSUME_ABSTRACT(pvt_3p_iface)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_3p)
|
/// @file pvt_3p_serialize.cpp
/// @brief pvt_3p serialization implementation
/// @author uentity
/// @version
/// @date 26.01.2012
/// @copyright This source code is released under the terms of
/// the BSD License. See LICENSE for more details.
#include "bs_bos_core_data_storage_stdafx.h"
#include "bs_pvt_stdafx.h"
#include "pvt_3p_serialize.h"
//#include "common_types_serialize.h"
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
using namespace blue_sky;
namespace boser = boost::serialization;
/*-----------------------------------------------------------------
* serialize pvt_base
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_base)
ar & t.p_step;
ar & t.surface_density;
ar & t.molar_density;
ar & t.init_dependent;
ar & t.pvt_input_props;
ar & t.pvt_props_table;
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_base)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_base)
/*-----------------------------------------------------------------
* serialize pvt_dead_oil
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_dead_oil)
// just redirect to base class
ar & boser::bs_base_object< pvt_base >(t);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_dead_oil)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_dead_oil)
/*-----------------------------------------------------------------
* serialize pvt_gas
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_gas)
// just redirect to base class
ar & boser::bs_base_object< pvt_base >(t);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_gas)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_gas)
/*-----------------------------------------------------------------
* serialize pvt_oil
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_oil)
// just redirect to base class
ar & boser::bs_base_object< pvt_dead_oil >(t);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_oil)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_oil)
/*-----------------------------------------------------------------
* serialize pvt_water
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_water)
// just redirect to base class
ar & boser::bs_base_object< pvt_base >(t);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_TYPE_SERIALIZE_DECL(pvt_water)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_water)
/*-----------------------------------------------------------------
* serialize pvt_3p
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, pvt_3p)
// register conversion to interface
boser::bs_void_cast_register(
static_cast< pvt_3p* >(NULL),
static_cast< pvt_3p_iface* >(NULL)
);
ar & t.n_pvt_regions;
ar & t.pvt_oil_array;
ar & t.pvt_water_array;
ar & t.pvt_gas_array;
ar & t.density_table;
ar & t.density;
BLUE_SKY_CLASS_SRZ_FCN_END
BOOST_SERIALIZATION_ASSUME_ABSTRACT(pvt_3p_iface)
BLUE_SKY_TYPE_SERIALIZE_IMPL(pvt_3p)
|
fix pvt_oil base class serialization (pvt_dead_oil)
|
SRZ: fix pvt_oil base class serialization (pvt_dead_oil)
|
C++
|
bsd-3-clause
|
bs-eagle/bs-eagle,bs-eagle/bs-eagle,bs-eagle/bs-eagle
|
ccedd142cea489476d999024157ddb37e2708aee
|
tutorials/dataframe/tdf013_InspectAnalysis.C
|
tutorials/dataframe/tdf013_InspectAnalysis.C
|
/// \file
/// \ingroup tutorial_tdataframe
/// \notebook -nodraw
/// Showcase registration of callback functions that act on partial results while
/// the event-loop is running using `OnPartialResult` and `OnPartialResultSlot`.
/// This tutorial is not meant to run in batch mode.
///
/// \macro_code
///
/// \date September 2017
/// \author Enrico Guiraud
using namespace ROOT::Experimental; // TDataFrame lives in here
void tdf013_InspectAnalysis()
{
ROOT::EnableImplicitMT();
const auto nSlots = ROOT::GetImplicitMTPoolSize();
// ## Setup a simple TDataFrame
// We start by creating a TDataFrame with a good number of empty events
const auto nEvents = nSlots * 10000ull;
TDataFrame d(nEvents);
// `heavyWork` is a lambda that fakes some interesting computation and just returns a normally distributed double
TRandom r;
auto heavyWork = [&r]() {
for (volatile int i = 0; i < 1000000; ++i);
return r.Gaus();
};
// Let's define a column "x" produced by invoking `heavyWork` for each event
// `tdf` stores a modified data-frame that contains "x"
auto tdf = d.Define("x", heavyWork);
// Now we register a histogram-filling action with the TDataFrame.
// `h` can be used just like a pointer to TH1D but it is actually a TResultProxy<TH1D>, a smart object that triggers
// an event-loop to fill the pointee histogram if needed.
auto h = tdf.Histo1D<double>({"browserHisto", "", 100, -2., 2.}, "x");
// ## Use the callback mechanism to draw the histogram on a TBrowser while it is being filled
// So far we have registered a column "x" to a data-frame with `nEvents` events and we registered the filling of a
// histogram with the values of column "x".
// In the following we will register three functions for execution during the event-loop:
// - one is to be executed once just before the loop and adds a partially-filled histogram to a TBrowser
// - the next is executed every 50 events and draws the partial histogram on the TBrowser's TPad
// - another callback is responsible of updating a simple progress bar from multiple threads
// First off we create a TBrowser that contains a "TDFResults" directory
auto *tdfDirectory = new TMemFile("TDFResults", "RECREATE");
auto *browser = new TBrowser("b", tdfDirectory);
// The global pad should now be set to the TBrowser's canvas, let's store its value in a local variable
auto browserPad = gPad;
// A useful feature of `TResultProxy` is its `OnPartialResult` method: it allows us to register a callback that is
// executed once per specified number of events during the event-loop, on "partial" versions of the result objects
// contained in the `TResultProxy`. In this case, the partial result is going to be a histogram filled with an
// increasing number of events.
// Instead of requesting the callback to be executed every N entries, this time we use the special value `kOnce` to
// request that it is executed once right before starting the event-loop.
// The callback is a C++11 lambda that registers the partial result object in `tdfDirectory`.
h.OnPartialResult(h.kOnce, [tdfDirectory](TH1D &h_) { tdfDirectory->Add(&h_); });
// Note that we called `OnPartialResult` with a dot, `.`, since this is a method of `TResultProxy` itself.
// We do not want to call `OnPartialResult` on the pointee histogram!)
// Multiple callbacks can be registered on the same `TResultProxy` (they are executed one after the other in the
// same order as they were registered). We now request that the partial result is drawn and the TBrowser's TPad is
// updated every 50 events.
h.OnPartialResult(50, [&browserPad](TH1D &hist) {
if (!browserPad) return; // in case root -b was invoked
browserPad->cd();
hist.Draw();
browserPad->Update();
// This call tells ROOT to process all pending GUI events
// It allows users to use the TBrowser as usual while the event-loop is running
gSystem->ProcessEvents();
});
// Finally, we would like to print a progress bar on the terminal to show how the event-loop is progressing.
// To take into account _all_ events we use `OnPartialResultSlot`: when Implicit Multi-Threading is enabled, in fact,
// `OnPartialResult` invokes the callback only in one of the worker threads, and always returns that worker threads'
// partial result. This is useful because it means we don't have to worry about concurrent execution and
// thread-safety of the callbacks if we are happy with just one threads' partial result.
// `OnPartialResultSlot`, on the other hand, invokes the callback in each one of the worker threads, every time a
// thread finishes processing a batch of `everyN` events. This is what we want for the progress bar, but we need to
// take care that two threads will not print to terminal at the same time: we need a std::mutex for synchronization.
std::string progressBar;
std::mutex barMutex; // Only one thread at a time can lock a mutex. Let's use this to avoid concurrent printing.
// Magic numbers that yield good progress bars for nSlots = 1,2,4,8
const auto everyN = nSlots == 8 ? 1000 : 100ull * nSlots;
const auto barWidth = nEvents / everyN;
h.OnPartialResultSlot(everyN, [&barWidth, &progressBar, &barMutex](unsigned int /*slot*/, TH1D &/*partialHist*/) {
std::lock_guard<std::mutex> l(barMutex); // lock_guard locks the mutex at construction, releases it at destruction
progressBar.push_back('#');
// re-print the line with the progress bar
std::cout << "\r[" << std::left << std::setw(barWidth) << progressBar << ']' << std::flush;
});
// ## Running the analysis
// So far we told TDataFrame what we want to happen during the event-loop, but we have not actually run any of those
// actions: the TBrowser is still empty, the progress bar has not been printed even once, and we haven't produced
// a single data-point!
// As usual with TDataFrame, the event-loop is triggered by accessing the contents of a TResultProxy for the first
// time. Let's run!
std::cout << "Analysis running..." << std::endl;
h->Draw(); // the final, complete result will be drawn after the event-loop has completed.
std::cout << "\nDone!" << std::endl;
// Finally, some book-keeping: in the TMemFile that we are using as TBrowser directory, we substitute the partial
// result with a clone of the final result (the "original" final result will be deleted at the end of the macro).
tdfDirectory->Clear();
auto clone = static_cast<TH1D*>(h->Clone());
clone->SetDirectory(nullptr);
tdfDirectory->Add(clone);
if (!browserPad) return; // in case root -b was invoked
browserPad->cd();
clone->Draw();
}
|
/// \file
/// \ingroup tutorial_tdataframe
/// \notebook -nodraw
/// Showcase registration of callback functions that act on partial results while
/// the event-loop is running using `OnPartialResult` and `OnPartialResultSlot`.
/// This tutorial is not meant to run in batch mode.
///
/// \macro_code
///
/// \date September 2017
/// \author Enrico Guiraud
using namespace ROOT::Experimental; // TDataFrame lives in here
void tdf013_InspectAnalysis()
{
ROOT::EnableImplicitMT();
const auto poolSize = ROOT::GetImplicitMTPoolSize();
const auto nSlots = 0 == poolSize ? 1 : poolSize;
// ## Setup a simple TDataFrame
// We start by creating a TDataFrame with a good number of empty events
const auto nEvents = nSlots * 10000ull;
TDataFrame d(nEvents);
// `heavyWork` is a lambda that fakes some interesting computation and just returns a normally distributed double
TRandom r;
auto heavyWork = [&r]() {
for (volatile int i = 0; i < 1000000; ++i);
return r.Gaus();
};
// Let's define a column "x" produced by invoking `heavyWork` for each event
// `tdf` stores a modified data-frame that contains "x"
auto tdf = d.Define("x", heavyWork);
// Now we register a histogram-filling action with the TDataFrame.
// `h` can be used just like a pointer to TH1D but it is actually a TResultProxy<TH1D>, a smart object that triggers
// an event-loop to fill the pointee histogram if needed.
auto h = tdf.Histo1D<double>({"browserHisto", "", 100, -2., 2.}, "x");
// ## Use the callback mechanism to draw the histogram on a TBrowser while it is being filled
// So far we have registered a column "x" to a data-frame with `nEvents` events and we registered the filling of a
// histogram with the values of column "x".
// In the following we will register three functions for execution during the event-loop:
// - one is to be executed once just before the loop and adds a partially-filled histogram to a TBrowser
// - the next is executed every 50 events and draws the partial histogram on the TBrowser's TPad
// - another callback is responsible of updating a simple progress bar from multiple threads
// First off we create a TBrowser that contains a "TDFResults" directory
auto *tdfDirectory = new TMemFile("TDFResults", "RECREATE");
auto *browser = new TBrowser("b", tdfDirectory);
// The global pad should now be set to the TBrowser's canvas, let's store its value in a local variable
auto browserPad = gPad;
// A useful feature of `TResultProxy` is its `OnPartialResult` method: it allows us to register a callback that is
// executed once per specified number of events during the event-loop, on "partial" versions of the result objects
// contained in the `TResultProxy`. In this case, the partial result is going to be a histogram filled with an
// increasing number of events.
// Instead of requesting the callback to be executed every N entries, this time we use the special value `kOnce` to
// request that it is executed once right before starting the event-loop.
// The callback is a C++11 lambda that registers the partial result object in `tdfDirectory`.
h.OnPartialResult(h.kOnce, [tdfDirectory](TH1D &h_) { tdfDirectory->Add(&h_); });
// Note that we called `OnPartialResult` with a dot, `.`, since this is a method of `TResultProxy` itself.
// We do not want to call `OnPartialResult` on the pointee histogram!)
// Multiple callbacks can be registered on the same `TResultProxy` (they are executed one after the other in the
// same order as they were registered). We now request that the partial result is drawn and the TBrowser's TPad is
// updated every 50 events.
h.OnPartialResult(50, [&browserPad](TH1D &hist) {
if (!browserPad) return; // in case root -b was invoked
browserPad->cd();
hist.Draw();
browserPad->Update();
// This call tells ROOT to process all pending GUI events
// It allows users to use the TBrowser as usual while the event-loop is running
gSystem->ProcessEvents();
});
// Finally, we would like to print a progress bar on the terminal to show how the event-loop is progressing.
// To take into account _all_ events we use `OnPartialResultSlot`: when Implicit Multi-Threading is enabled, in fact,
// `OnPartialResult` invokes the callback only in one of the worker threads, and always returns that worker threads'
// partial result. This is useful because it means we don't have to worry about concurrent execution and
// thread-safety of the callbacks if we are happy with just one threads' partial result.
// `OnPartialResultSlot`, on the other hand, invokes the callback in each one of the worker threads, every time a
// thread finishes processing a batch of `everyN` events. This is what we want for the progress bar, but we need to
// take care that two threads will not print to terminal at the same time: we need a std::mutex for synchronization.
std::string progressBar;
std::mutex barMutex; // Only one thread at a time can lock a mutex. Let's use this to avoid concurrent printing.
// Magic numbers that yield good progress bars for nSlots = 1,2,4,8
const auto everyN = nSlots == 8 ? 1000 : 100ull * nSlots;
const auto barWidth = nEvents / everyN;
h.OnPartialResultSlot(everyN, [&barWidth, &progressBar, &barMutex](unsigned int /*slot*/, TH1D &/*partialHist*/) {
std::lock_guard<std::mutex> l(barMutex); // lock_guard locks the mutex at construction, releases it at destruction
progressBar.push_back('#');
// re-print the line with the progress bar
std::cout << "\r[" << std::left << std::setw(barWidth) << progressBar << ']' << std::flush;
});
// ## Running the analysis
// So far we told TDataFrame what we want to happen during the event-loop, but we have not actually run any of those
// actions: the TBrowser is still empty, the progress bar has not been printed even once, and we haven't produced
// a single data-point!
// As usual with TDataFrame, the event-loop is triggered by accessing the contents of a TResultProxy for the first
// time. Let's run!
std::cout << "Analysis running..." << std::endl;
h->Draw(); // the final, complete result will be drawn after the event-loop has completed.
std::cout << "\nDone!" << std::endl;
// Finally, some book-keeping: in the TMemFile that we are using as TBrowser directory, we substitute the partial
// result with a clone of the final result (the "original" final result will be deleted at the end of the macro).
tdfDirectory->Clear();
auto clone = static_cast<TH1D*>(h->Clone());
clone->SetDirectory(nullptr);
tdfDirectory->Add(clone);
if (!browserPad) return; // in case root -b was invoked
browserPad->cd();
clone->Draw();
}
|
Allow some events to be run also in non-imt builds
|
[TDF] tdf013: Allow some events to be run also in non-imt builds
|
C++
|
lgpl-2.1
|
zzxuanyuan/root,zzxuanyuan/root,olifre/root,karies/root,root-mirror/root,karies/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,zzxuanyuan/root,karies/root,karies/root,olifre/root,olifre/root,root-mirror/root,zzxuanyuan/root,root-mirror/root,olifre/root,zzxuanyuan/root,olifre/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,zzxuanyuan/root,zzxuanyuan/root,olifre/root,olifre/root,karies/root,karies/root,root-mirror/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,karies/root,karies/root,zzxuanyuan/root,root-mirror/root,olifre/root,karies/root,karies/root
|
5f19afe7fa9c6f0c5b6c13890006b8d76086c405
|
folly/Range.cpp
|
folly/Range.cpp
|
/*
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @author Mark Rabkin ([email protected])
// @author Andrei Alexandrescu ([email protected])
#include "folly/Range.h"
#include <emmintrin.h> // __v16qi
#include <iostream>
namespace folly {
/**
* Predicates that can be used with qfind and startsWith
*/
const AsciiCaseSensitive asciiCaseSensitive = AsciiCaseSensitive();
const AsciiCaseInsensitive asciiCaseInsensitive = AsciiCaseInsensitive();
std::ostream& operator<<(std::ostream& os, const StringPiece& piece) {
os.write(piece.start(), piece.size());
return os;
}
namespace detail {
size_t qfind_first_byte_of_memchr(const StringPiece& haystack,
const StringPiece& needles) {
size_t best = haystack.size();
for (char needle: needles) {
const void* ptr = memchr(haystack.data(), needle, best);
if (ptr) {
auto found = static_cast<const char*>(ptr) - haystack.data();
best = std::min<size_t>(best, found);
}
}
if (best == haystack.size()) {
return StringPiece::npos;
}
return best;
}
} // namespace detail
namespace {
// It's okay if pages are bigger than this (as powers of two), but they should
// not be smaller.
constexpr size_t kMinPageSize = 4096;
static_assert(kMinPageSize >= 16,
"kMinPageSize must be at least SSE register size");
#define PAGE_FOR(addr) \
(reinterpret_cast<uintptr_t>(addr) / kMinPageSize)
#if FOLLY_HAVE_EMMINTRIN_H
inline size_t nextAlignedIndex(const char* arr) {
auto firstPossible = reinterpret_cast<uintptr_t>(arr) + 1;
return 1 + // add 1 because the index starts at 'arr'
((firstPossible + 15) & ~0xF) // round up to next multiple of 16
- firstPossible;
}
// build sse4.2-optimized version even if -msse4.2 is not passed to GCC
size_t qfind_first_byte_of_needles16(const StringPiece& haystack,
const StringPiece& needles)
__attribute__ ((__target__("sse4.2"), noinline));
// helper method for case where needles.size() <= 16
size_t qfind_first_byte_of_needles16(const StringPiece& haystack,
const StringPiece& needles) {
DCHECK(!haystack.empty());
DCHECK(!needles.empty());
DCHECK_LE(needles.size(), 16);
// benchmarking shows that memchr beats out SSE for small needle-sets
// with large haystacks.
if ((needles.size() <= 2 && haystack.size() >= 256) ||
// must bail if we can't even SSE-load a single segment of haystack
(haystack.size() < 16 &&
PAGE_FOR(haystack.end() - 1) != PAGE_FOR(haystack.data() + 15)) ||
// can't load needles into SSE register if it could cross page boundary
PAGE_FOR(needles.end() - 1) != PAGE_FOR(needles.data() + 15)) {
return detail::qfind_first_byte_of_memchr(haystack, needles);
}
auto arr2 = __builtin_ia32_loaddqu(needles.data());
// do an unaligned load for first block of haystack
auto arr1 = __builtin_ia32_loaddqu(haystack.data());
auto index = __builtin_ia32_pcmpestri128(arr2, needles.size(),
arr1, haystack.size(), 0);
if (index < 16) {
return index;
}
// Now, we can do aligned loads hereafter...
size_t i = nextAlignedIndex(haystack.data());
for (; i < haystack.size(); i+= 16) {
void* ptr1 = __builtin_assume_aligned(haystack.data() + i, 16);
auto arr1 = *reinterpret_cast<const __v16qi*>(ptr1);
auto index = __builtin_ia32_pcmpestri128(arr2, needles.size(),
arr1, haystack.size() - i, 0);
if (index < 16) {
return i + index;
}
}
return StringPiece::npos;
}
#endif // FOLLY_HAVE_EMMINTRIN_H
// Aho, Hopcroft, and Ullman refer to this trick in "The Design and Analysis
// of Computer Algorithms" (1974), but the best description is here:
// http://research.swtch.com/sparse
class FastByteSet {
public:
FastByteSet() : size_(0) { } // no init of arrays required!
inline void add(uint8_t i) {
if (!contains(i)) {
dense_[size_] = i;
sparse_[i] = size_;
size_++;
}
}
inline bool contains(uint8_t i) const {
DCHECK_LE(size_, 256);
return sparse_[i] < size_ && dense_[sparse_[i]] == i;
}
private:
uint16_t size_; // can't use uint8_t because it would overflow if all
// possible values were inserted.
uint8_t sparse_[256];
uint8_t dense_[256];
};
} // namespace
namespace detail {
size_t qfind_first_byte_of_byteset(const StringPiece& haystack,
const StringPiece& needles) {
FastByteSet s;
for (auto needle: needles) {
s.add(needle);
}
for (size_t index = 0; index < haystack.size(); ++index) {
if (s.contains(haystack[index])) {
return index;
}
}
return StringPiece::npos;
}
#if FOLLY_HAVE_EMMINTRIN_H
template <bool HAYSTACK_ALIGNED>
inline size_t scanHaystackBlock(const StringPiece& haystack,
const StringPiece& needles,
int64_t idx)
// inline is okay because it's only called from other sse4.2 functions
__attribute__ ((__target__("sse4.2")));
// Scans a 16-byte block of haystack (starting at blockStartIdx) to find first
// needle. If HAYSTACK_ALIGNED, then haystack must be 16byte aligned.
// If !HAYSTACK_ALIGNED, then caller must ensure that it is safe to load the
// block.
template <bool HAYSTACK_ALIGNED>
inline size_t scanHaystackBlock(const StringPiece& haystack,
const StringPiece& needles,
int64_t blockStartIdx) {
DCHECK_GT(needles.size(), 16); // should handled by *needles16() method
DCHECK(blockStartIdx + 16 <= haystack.size() ||
(PAGE_FOR(haystack.data() + blockStartIdx) ==
PAGE_FOR(haystack.data() + blockStartIdx + 15)));
__v16qi arr1;
if (HAYSTACK_ALIGNED) {
void* ptr1 = __builtin_assume_aligned(haystack.data() + blockStartIdx, 16);
arr1 = *reinterpret_cast<const __v16qi*>(ptr1);
} else {
arr1 = __builtin_ia32_loaddqu(haystack.data() + blockStartIdx);
}
// This load is safe because needles.size() >= 16
auto arr2 = __builtin_ia32_loaddqu(needles.data());
size_t b = __builtin_ia32_pcmpestri128(
arr2, 16, arr1, haystack.size() - blockStartIdx, 0);
size_t j = nextAlignedIndex(needles.data());
for (; j < needles.size(); j += 16) {
void* ptr2 = __builtin_assume_aligned(needles.data() + j, 16);
arr2 = *reinterpret_cast<const __v16qi*>(ptr2);
auto index = __builtin_ia32_pcmpestri128(
arr2, needles.size() - j, arr1, haystack.size() - blockStartIdx, 0);
b = std::min<size_t>(index, b);
}
if (b < 16) {
return blockStartIdx + b;
}
return StringPiece::npos;
}
size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
const StringPiece& needles)
__attribute__ ((__target__("sse4.2"), noinline));
size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
const StringPiece& needles) {
if (UNLIKELY(needles.empty() || haystack.empty())) {
return StringPiece::npos;
} else if (needles.size() <= 16) {
// we can save some unnecessary load instructions by optimizing for
// the common case of needles.size() <= 16
return qfind_first_byte_of_needles16(haystack, needles);
}
if (haystack.size() < 16 &&
PAGE_FOR(haystack.end() - 1) != PAGE_FOR(haystack.data() + 16)) {
// We can't safely SSE-load haystack. Use a different approach.
if (haystack.size() <= 2) {
return qfind_first_of(haystack, needles, asciiCaseSensitive);
}
return qfind_first_byte_of_byteset(haystack, needles);
}
auto ret = scanHaystackBlock<false>(haystack, needles, 0);
if (ret != StringPiece::npos) {
return ret;
}
size_t i = nextAlignedIndex(haystack.data());
for (; i < haystack.size(); i += 16) {
auto ret = scanHaystackBlock<true>(haystack, needles, i);
if (ret != StringPiece::npos) {
return ret;
}
}
return StringPiece::npos;
}
#endif // FOLLY_HAVE_EMMINTRIN_H
size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
const StringPiece& needles) {
if (UNLIKELY(needles.empty() || haystack.empty())) {
return StringPiece::npos;
}
// The thresholds below were empirically determined by benchmarking.
// This is not an exact science since it depends on the CPU, the size of
// needles, and the size of haystack.
if (haystack.size() == 1 ||
(haystack.size() < 4 && needles.size() <= 16)) {
return qfind_first_of(haystack, needles, asciiCaseSensitive);
} else if ((needles.size() >= 4 && haystack.size() <= 10) ||
(needles.size() >= 16 && haystack.size() <= 64) ||
needles.size() >= 32) {
return qfind_first_byte_of_byteset(haystack, needles);
}
return qfind_first_byte_of_memchr(haystack, needles);
}
} // namespace detail
} // namespace folly
|
/*
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @author Mark Rabkin ([email protected])
// @author Andrei Alexandrescu ([email protected])
#include "folly/Range.h"
#include <emmintrin.h> // __v16qi
#include <iostream>
namespace folly {
/**
* Predicates that can be used with qfind and startsWith
*/
const AsciiCaseSensitive asciiCaseSensitive = AsciiCaseSensitive();
const AsciiCaseInsensitive asciiCaseInsensitive = AsciiCaseInsensitive();
std::ostream& operator<<(std::ostream& os, const StringPiece& piece) {
os.write(piece.start(), piece.size());
return os;
}
namespace detail {
size_t qfind_first_byte_of_memchr(const StringPiece& haystack,
const StringPiece& needles) {
size_t best = haystack.size();
for (char needle: needles) {
const void* ptr = memchr(haystack.data(), needle, best);
if (ptr) {
auto found = static_cast<const char*>(ptr) - haystack.data();
best = std::min<size_t>(best, found);
}
}
if (best == haystack.size()) {
return StringPiece::npos;
}
return best;
}
} // namespace detail
namespace {
// It's okay if pages are bigger than this (as powers of two), but they should
// not be smaller.
constexpr size_t kMinPageSize = 4096;
static_assert(kMinPageSize >= 16,
"kMinPageSize must be at least SSE register size");
#define PAGE_FOR(addr) \
(reinterpret_cast<uintptr_t>(addr) / kMinPageSize)
#if FOLLY_HAVE_EMMINTRIN_H
inline size_t nextAlignedIndex(const char* arr) {
auto firstPossible = reinterpret_cast<uintptr_t>(arr) + 1;
return 1 + // add 1 because the index starts at 'arr'
((firstPossible + 15) & ~0xF) // round up to next multiple of 16
- firstPossible;
}
// build sse4.2-optimized version even if -msse4.2 is not passed to GCC
size_t qfind_first_byte_of_needles16(const StringPiece& haystack,
const StringPiece& needles)
__attribute__ ((__target__("sse4.2"), noinline))
FOLLY_DISABLE_ADDRESS_SANITIZER;
// helper method for case where needles.size() <= 16
size_t qfind_first_byte_of_needles16(const StringPiece& haystack,
const StringPiece& needles) {
DCHECK(!haystack.empty());
DCHECK(!needles.empty());
DCHECK_LE(needles.size(), 16);
// benchmarking shows that memchr beats out SSE for small needle-sets
// with large haystacks.
if ((needles.size() <= 2 && haystack.size() >= 256) ||
// must bail if we can't even SSE-load a single segment of haystack
(haystack.size() < 16 &&
PAGE_FOR(haystack.end() - 1) != PAGE_FOR(haystack.data() + 15)) ||
// can't load needles into SSE register if it could cross page boundary
PAGE_FOR(needles.end() - 1) != PAGE_FOR(needles.data() + 15)) {
return detail::qfind_first_byte_of_memchr(haystack, needles);
}
auto arr2 = __builtin_ia32_loaddqu(needles.data());
// do an unaligned load for first block of haystack
auto arr1 = __builtin_ia32_loaddqu(haystack.data());
auto index = __builtin_ia32_pcmpestri128(arr2, needles.size(),
arr1, haystack.size(), 0);
if (index < 16) {
return index;
}
// Now, we can do aligned loads hereafter...
size_t i = nextAlignedIndex(haystack.data());
for (; i < haystack.size(); i+= 16) {
void* ptr1 = __builtin_assume_aligned(haystack.data() + i, 16);
auto arr1 = *reinterpret_cast<const __v16qi*>(ptr1);
auto index = __builtin_ia32_pcmpestri128(arr2, needles.size(),
arr1, haystack.size() - i, 0);
if (index < 16) {
return i + index;
}
}
return StringPiece::npos;
}
#endif // FOLLY_HAVE_EMMINTRIN_H
// Aho, Hopcroft, and Ullman refer to this trick in "The Design and Analysis
// of Computer Algorithms" (1974), but the best description is here:
// http://research.swtch.com/sparse
class FastByteSet {
public:
FastByteSet() : size_(0) { } // no init of arrays required!
inline void add(uint8_t i) {
if (!contains(i)) {
dense_[size_] = i;
sparse_[i] = size_;
size_++;
}
}
inline bool contains(uint8_t i) const {
DCHECK_LE(size_, 256);
return sparse_[i] < size_ && dense_[sparse_[i]] == i;
}
private:
uint16_t size_; // can't use uint8_t because it would overflow if all
// possible values were inserted.
uint8_t sparse_[256];
uint8_t dense_[256];
};
} // namespace
namespace detail {
size_t qfind_first_byte_of_byteset(const StringPiece& haystack,
const StringPiece& needles) {
FastByteSet s;
for (auto needle: needles) {
s.add(needle);
}
for (size_t index = 0; index < haystack.size(); ++index) {
if (s.contains(haystack[index])) {
return index;
}
}
return StringPiece::npos;
}
#if FOLLY_HAVE_EMMINTRIN_H
template <bool HAYSTACK_ALIGNED>
inline size_t scanHaystackBlock(const StringPiece& haystack,
const StringPiece& needles,
int64_t idx)
// inline is okay because it's only called from other sse4.2 functions
__attribute__ ((__target__("sse4.2")));
// Scans a 16-byte block of haystack (starting at blockStartIdx) to find first
// needle. If HAYSTACK_ALIGNED, then haystack must be 16byte aligned.
// If !HAYSTACK_ALIGNED, then caller must ensure that it is safe to load the
// block.
template <bool HAYSTACK_ALIGNED>
inline size_t scanHaystackBlock(const StringPiece& haystack,
const StringPiece& needles,
int64_t blockStartIdx) {
DCHECK_GT(needles.size(), 16); // should handled by *needles16() method
DCHECK(blockStartIdx + 16 <= haystack.size() ||
(PAGE_FOR(haystack.data() + blockStartIdx) ==
PAGE_FOR(haystack.data() + blockStartIdx + 15)));
__v16qi arr1;
if (HAYSTACK_ALIGNED) {
void* ptr1 = __builtin_assume_aligned(haystack.data() + blockStartIdx, 16);
arr1 = *reinterpret_cast<const __v16qi*>(ptr1);
} else {
arr1 = __builtin_ia32_loaddqu(haystack.data() + blockStartIdx);
}
// This load is safe because needles.size() >= 16
auto arr2 = __builtin_ia32_loaddqu(needles.data());
size_t b = __builtin_ia32_pcmpestri128(
arr2, 16, arr1, haystack.size() - blockStartIdx, 0);
size_t j = nextAlignedIndex(needles.data());
for (; j < needles.size(); j += 16) {
void* ptr2 = __builtin_assume_aligned(needles.data() + j, 16);
arr2 = *reinterpret_cast<const __v16qi*>(ptr2);
auto index = __builtin_ia32_pcmpestri128(
arr2, needles.size() - j, arr1, haystack.size() - blockStartIdx, 0);
b = std::min<size_t>(index, b);
}
if (b < 16) {
return blockStartIdx + b;
}
return StringPiece::npos;
}
size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
const StringPiece& needles)
__attribute__ ((__target__("sse4.2"), noinline));
size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
const StringPiece& needles) {
if (UNLIKELY(needles.empty() || haystack.empty())) {
return StringPiece::npos;
} else if (needles.size() <= 16) {
// we can save some unnecessary load instructions by optimizing for
// the common case of needles.size() <= 16
return qfind_first_byte_of_needles16(haystack, needles);
}
if (haystack.size() < 16 &&
PAGE_FOR(haystack.end() - 1) != PAGE_FOR(haystack.data() + 16)) {
// We can't safely SSE-load haystack. Use a different approach.
if (haystack.size() <= 2) {
return qfind_first_of(haystack, needles, asciiCaseSensitive);
}
return qfind_first_byte_of_byteset(haystack, needles);
}
auto ret = scanHaystackBlock<false>(haystack, needles, 0);
if (ret != StringPiece::npos) {
return ret;
}
size_t i = nextAlignedIndex(haystack.data());
for (; i < haystack.size(); i += 16) {
auto ret = scanHaystackBlock<true>(haystack, needles, i);
if (ret != StringPiece::npos) {
return ret;
}
}
return StringPiece::npos;
}
#endif // FOLLY_HAVE_EMMINTRIN_H
size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
const StringPiece& needles) {
if (UNLIKELY(needles.empty() || haystack.empty())) {
return StringPiece::npos;
}
// The thresholds below were empirically determined by benchmarking.
// This is not an exact science since it depends on the CPU, the size of
// needles, and the size of haystack.
if (haystack.size() == 1 ||
(haystack.size() < 4 && needles.size() <= 16)) {
return qfind_first_of(haystack, needles, asciiCaseSensitive);
} else if ((needles.size() >= 4 && haystack.size() <= 10) ||
(needles.size() >= 16 && haystack.size() <= 64) ||
needles.size() >= 32) {
return qfind_first_byte_of_byteset(haystack, needles);
}
return qfind_first_byte_of_memchr(haystack, needles);
}
} // namespace detail
} // namespace folly
|
disable asan for qfind_first_byte_of_needles16
|
disable asan for qfind_first_byte_of_needles16
Summary:
It's expected to read past the string (within the same memory
page).
Test Plan: .
Reviewed By: [email protected]
FB internal diff: D962974
|
C++
|
apache-2.0
|
renyinew/folly,stonegithubs/folly,wildinto/folly,bobegir/folly,clearlylin/folly,bowlofstew/folly,tomhughes/folly,yangjin-unique/folly,cppfool/folly,tomhughes/folly,romange/folly,bikong2/folly,sakishum/folly,mqeizi/folly,loversInJapan/folly,unmeshvrije/C--,SeanRBurton/folly,bowlofstew/folly,Hincoin/folly,cppfool/folly,nickhen/folly,bikong2/folly,floxard/folly,rklabs/folly,sonnyhu/folly,sonnyhu/folly,Hincoin/folly,bobegir/folly,nickhen/folly,clearlinux/folly,upsoft/folly,clearlinux/folly,PPC64/folly,PPC64/folly,wildinto/folly,colemancda/folly,CJstar/folly,theiver9827/folly,colemancda/folly,project-zerus/folly,shaobz/folly,ykarlsbrun/folly,charsyam/folly,raphaelamorim/folly,SeanRBurton/folly,shaobz/folly,constantine001/folly,leolujuyi/folly,loverszhaokai/folly,rklabs/folly,unmeshvrije/C--,hongliangzhao/folly,reddit/folly,doctaweeks/folly,loverszhaokai/folly,CJstar/folly,gaoyingie/folly,constantine001/folly,hongliangzhao/folly,clearlinux/folly,bsampath/folly,clearlylin/folly,raphaelamorim/folly,brunomorishita/folly,PoisonBOx/folly,xzmagic/folly,loversInJapan/folly,yangjin-unique/folly,SammyK/folly,juniway/folly,loversInJapan/folly,PPC64/folly,leolujuyi/folly,tomhughes/folly,facebook/folly,loversInJapan/folly,bikong2/folly,stonegithubs/folly,CJstar/folly,zhiweicai/folly,zhiweicai/folly,loverszhaokai/folly,doctaweeks/folly,guker/folly,Eagle-X/folly,lifei/folly,stonegithubs/folly,sonnyhu/folly,upsoft/folly,bowlofstew/folly,nickhen/folly,gaoyingie/folly,bikong2/folly,alexst07/folly,alexst07/folly,brunomorishita/folly,PoisonBOx/folly,leolujuyi/folly,romange/folly,rklabs/folly,bobegir/folly,upsoft/folly,SammyK/folly,romange/folly,Hincoin/folly,kernelim/folly,xzmagic/folly,facebook/folly,zhiweicai/folly,SeanRBurton/folly,juniway/folly,zhiweicai/folly,renyinew/folly,stonegithubs/folly,raphaelamorim/folly,renyinew/folly,charsyam/folly,Hincoin/folly,guker/folly,theiver9827/folly,raphaelamorim/folly,Orvid/folly,bobegir/folly,facebook/folly,tempbottle/folly,mqeizi/folly,ykarlsbrun/folly,bobegir/folly,bikong2/folly,doctaweeks/folly,doctaweeks/folly,KSreeHarsha/folly,PPC64/folly,fw1121/folly,cppfool/folly,Eagle-X/folly,sonnyhu/folly,tempbottle/folly,unmeshvrije/C--,fw1121/folly,PoisonBOx/folly,renyinew/folly,brunomorishita/folly,arg0/folly,juniway/folly,alexst07/folly,loversInJapan/folly,floxard/folly,reddit/folly,ykarlsbrun/folly,guker/folly,PPC64/folly,floxard/folly,tempbottle/folly,kernelim/folly,bowlofstew/folly,rklabs/folly,Orvid/folly,SeanRBurton/folly,fw1121/folly,kernelim/folly,gavioto/folly,zhiweicai/folly,Orvid/folly,lifei/folly,rklabs/folly,nickhen/folly,cole14/folly,gavioto/folly,chjp2046/folly,sonnyhu/folly,constantine001/folly,nickhen/folly,colemancda/folly,KSreeHarsha/folly,juniway/folly,guker/folly,cole14/folly,clearlylin/folly,leolujuyi/folly,tomhughes/folly,Eagle-X/folly,mqeizi/folly,arg0/folly,tempbottle/folly,brunomorishita/folly,yangjin-unique/folly,alexst07/folly,Eagle-X/folly,doctaweeks/folly,colemancda/folly,romange/folly,PoisonBOx/folly,guker/folly,arg0/folly,wildinto/folly,hongliangzhao/folly,mqeizi/folly,tempbottle/folly,yangjin-unique/folly,shaobz/folly,romange/folly,fw1121/folly,kernelim/folly,shaobz/folly,hongliangzhao/folly,unmeshvrije/C--,reddit/folly,Eagle-X/folly,facebook/folly,charsyam/folly,reddit/folly,shaobz/folly,lifei/folly,SeanRBurton/folly,upsoft/folly,chjp2046/folly,PoisonBOx/folly,kernelim/folly,clearlinux/folly,xzmagic/folly,constantine001/folly,theiver9827/folly,alexst07/folly,brunomorishita/folly,lifei/folly,loverszhaokai/folly,project-zerus/folly,bowlofstew/folly,stonegithubs/folly,clearlylin/folly,floxard/folly,Orvid/folly,floxard/folly,reddit/folly,theiver9827/folly,renyinew/folly,yangjin-unique/folly,upsoft/folly,hongliangzhao/folly,sakishum/folly,charsyam/folly,sakishum/folly,gaoyingie/folly,gaoyingie/folly,chjp2046/folly,bsampath/folly,bsampath/folly,Orvid/folly,xzmagic/folly,cole14/folly,cppfool/folly,project-zerus/folly,sakishum/folly,CJstar/folly,project-zerus/folly,project-zerus/folly,clearlinux/folly,Hincoin/folly,SammyK/folly,arg0/folly,SammyK/folly,mqeizi/folly,fw1121/folly,chjp2046/folly,leolujuyi/folly,xzmagic/folly,unmeshvrije/C--,wildinto/folly,gavioto/folly,gavioto/folly,KSreeHarsha/folly,loverszhaokai/folly,KSreeHarsha/folly,wildinto/folly,cole14/folly,gavioto/folly,juniway/folly,bsampath/folly,sakishum/folly,clearlylin/folly,facebook/folly,constantine001/folly,cole14/folly,ykarlsbrun/folly,unmeshvrije/C--,SammyK/folly,bsampath/folly,raphaelamorim/folly,lifei/folly,cppfool/folly,colemancda/folly,gaoyingie/folly,KSreeHarsha/folly,arg0/folly,CJstar/folly,tomhughes/folly,theiver9827/folly,chjp2046/folly,ykarlsbrun/folly
|
55a0e665f1297452236dee6228a71194097c07c6
|
excercise04/sort/quick.cpp
|
excercise04/sort/quick.cpp
|
#include <string.h> /* memcpy() */
#include "quick.hpp"
#include "swap.hpp"
void quick(int *data, const int size_of_data)
{
return quick(data, 0, size_of_data - 1);
}
void quick(int *data, const int start, const int end)
{
if(start >= end) return; /* Base case */
/* Conquer */
int pivot = end; /* Set pivot */
int ps = start, pe = end - 1;
while(ps < pe)
{
while(ps < pe && data[ps] < data[pivot]) ++ps;
while(ps < pe && data[pe] >= data[pivot]) --pe;
if(ps < pe) swap(data[ps], data[pe]);
}
if(data[pe] > data[pivot]) swap(data[pe], data[pivot]);
/* Divide */
quick(data, start, pe);
quick(data, pe + 1, end);
}
|
#include "quick.hpp"
#include "swap.hpp"
void quick(int *data, const int size_of_data)
{
return quick(data, 0, size_of_data - 1);
}
void quick(int *data, const int start, const int end)
{
if(start >= end) return; /* Base case */
/* Conquer */
int pivot = end; /* Set pivot */
int ps = start, pe = end - 1;
while(ps < pe)
{
while(ps < pe && data[ps] < data[pivot]) ++ps;
while(ps < pe && data[pe] >= data[pivot]) --pe;
if(ps < pe) swap(data[ps], data[pe]);
}
if(data[pe] > data[pivot]) swap(data[pe], data[pivot]);
/* Divide */
quick(data, start, pe);
quick(data, pe + 1, end);
}
|
Remove unused includes
|
Remove unused includes
|
C++
|
mit
|
kdzlvaids/algorithm_and_practice-pknu-2016,kdzlvaids/algorithm_and_practice-pknu-2016
|
4bf69f1e7b29ce13eb3f78f7f19e8bc4ab7966e5
|
chrome/browser/chromeos/login/cookie_fetcher_unittest.cc
|
chrome/browser/chromeos/login/cookie_fetcher_unittest.cc
|
// Copyright (c) 2010 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 <errno.h>
#include <string>
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/login/cookie_fetcher.h"
#include "chrome/browser/chromeos/login/client_login_response_handler.h"
#include "chrome/browser/chromeos/login/issue_response_handler.h"
#include "chrome/browser/chromeos/login/mock_auth_response_handler.h"
#include "chrome/common/net/url_fetcher.h"
#include "chrome/test/testing_profile.h"
#include "googleurl/src/gurl.h"
#include "net/url_request/url_request_status.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace chromeos {
using ::testing::Return;
using ::testing::Invoke;
using ::testing::Unused;
using ::testing::_;
class MockDelegate : public CookieFetcher::Delegate {
public:
MockDelegate() {}
virtual ~MockDelegate() {}
MOCK_METHOD1(DoLaunch, void(Profile* profile));
};
class CookieFetcherTest : public ::testing::Test {
public:
CookieFetcherTest()
: iat_url_(AuthResponseHandler::kIssueAuthTokenUrl),
ta_url_(AuthResponseHandler::kTokenAuthUrl),
client_login_data_("SID n' LSID"),
token_("auth token"),
ui_thread_(ChromeThread::UI, &message_loop_) {
}
const GURL iat_url_;
const GURL ta_url_;
const std::string client_login_data_;
const std::string token_;
MessageLoopForUI message_loop_;
ChromeThread ui_thread_;
TestingProfile profile_;
};
// Check that successful HTTP responses from both end points results in
// the browser window getting put up.
TEST_F(CookieFetcherTest, SuccessfulFetchTest) {
URLRequestStatus status(URLRequestStatus::SUCCESS, 0);
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_, status, kHttpSuccess, token_);
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, status, kHttpSuccess, std::string());
MockDelegate* delegate = new MockDelegate;
CookieFetcher* cf = new CookieFetcher(NULL, cl_handler, i_handler, delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*i_handler, CanHandle(iat_url_))
.WillOnce(Return(true));
EXPECT_CALL(*i_handler, CanHandle(ta_url_))
.WillOnce(Return(false));
EXPECT_CALL(*i_handler, Handle(token_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
// Check that a network failure when trying IssueAuthToken results in us bailing
// and putting up the browser window.
TEST_F(CookieFetcherTest, IssueAuthTokenNetworkFailureTest) {
URLRequestStatus failed(URLRequestStatus::FAILED, ECONNRESET);
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_, failed, kHttpSuccess, token_);
MockDelegate* delegate = new MockDelegate;
// I expect nothing in i_handler to get called anyway
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, failed, kHttpSuccess, std::string());
CookieFetcher* cf = new CookieFetcher(&profile_,
cl_handler,
i_handler,
delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
// Check that a network failure when trying TokenAuth results in us bailing
// and putting up the browser window.
TEST_F(CookieFetcherTest, TokenAuthNetworkFailureTest) {
URLRequestStatus success;
URLRequestStatus failed(URLRequestStatus::FAILED, ECONNRESET);
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_, success, kHttpSuccess, token_);
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, failed, 0, std::string());
MockDelegate* delegate = new MockDelegate;
CookieFetcher* cf = new CookieFetcher(&profile_,
cl_handler,
i_handler,
delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*i_handler, CanHandle(iat_url_))
.WillOnce(Return(true));
EXPECT_CALL(*i_handler, Handle(token_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
// Check that an unsuccessful HTTP response when trying IssueAuthToken results
// in us bailing and putting up the browser window.
TEST_F(CookieFetcherTest, IssueAuthTokenDeniedTest) {
URLRequestStatus success;
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_, success, 403, std::string());
MockDelegate* delegate = new MockDelegate;
// I expect nothing in i_handler to get called anyway.
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, success, 0, std::string());
CookieFetcher* cf = new CookieFetcher(&profile_,
cl_handler,
i_handler,
delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
// Check that an unsuccessful HTTP response when trying TokenAuth results
// in us bailing and putting up the browser window.
TEST_F(CookieFetcherTest, TokenAuthDeniedTest) {
URLRequestStatus success;
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_,
success,
kHttpSuccess,
token_);
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, success, 403, std::string());
MockDelegate* delegate = new MockDelegate;
CookieFetcher* cf = new CookieFetcher(&profile_,
cl_handler,
i_handler,
delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*i_handler, CanHandle(iat_url_))
.WillOnce(Return(true));
EXPECT_CALL(*i_handler, Handle(token_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
TEST_F(CookieFetcherTest, ClientLoginResponseHandlerTest) {
ClientLoginResponseHandler handler(NULL);
std::string input("a\nb\n");
std::string expected("a&b&");
expected.append(ClientLoginResponseHandler::kService);
scoped_ptr<URLFetcher> fetcher(handler.Handle(input, NULL));
EXPECT_EQ(expected, handler.payload());
}
TEST_F(CookieFetcherTest, IssueResponseHandlerTest) {
IssueResponseHandler handler(NULL);
std::string input("a\n");
std::string expected(IssueResponseHandler::kTokenAuthUrl);
expected.append(input);
scoped_ptr<URLFetcher> fetcher(handler.Handle(input, NULL));
EXPECT_EQ(expected, handler.token_url());
}
} // namespace chromeos
|
// Copyright (c) 2010 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 <errno.h>
#include <string>
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/login/client_login_response_handler.h"
#include "chrome/browser/chromeos/login/cookie_fetcher.h"
#include "chrome/browser/chromeos/login/issue_response_handler.h"
#include "chrome/browser/chromeos/login/mock_auth_response_handler.h"
#include "chrome/common/net/url_fetcher.h"
#include "chrome/test/testing_profile.h"
#include "googleurl/src/gurl.h"
#include "net/url_request/url_request_status.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace chromeos {
using ::testing::Return;
using ::testing::Invoke;
using ::testing::Unused;
using ::testing::_;
class MockDelegate : public CookieFetcher::Delegate {
public:
MockDelegate() {}
virtual ~MockDelegate() {}
MOCK_METHOD1(DoLaunch, void(Profile* profile));
};
class CookieFetcherTest : public ::testing::Test {
public:
CookieFetcherTest()
: iat_url_(AuthResponseHandler::kIssueAuthTokenUrl),
ta_url_(AuthResponseHandler::kTokenAuthUrl),
client_login_data_("SID n' LSID"),
token_("auth token"),
ui_thread_(ChromeThread::UI, &message_loop_) {
}
const GURL iat_url_;
const GURL ta_url_;
const std::string client_login_data_;
const std::string token_;
MessageLoopForUI message_loop_;
ChromeThread ui_thread_;
TestingProfile profile_;
};
// Check that successful HTTP responses from both end points results in
// the browser window getting put up.
TEST_F(CookieFetcherTest, SuccessfulFetchTest) {
URLRequestStatus status(URLRequestStatus::SUCCESS, 0);
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_, status, kHttpSuccess, token_);
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, status, kHttpSuccess, std::string());
MockDelegate* delegate = new MockDelegate;
CookieFetcher* cf = new CookieFetcher(NULL, cl_handler, i_handler, delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*i_handler, CanHandle(iat_url_))
.WillOnce(Return(true));
EXPECT_CALL(*i_handler, CanHandle(ta_url_))
.WillOnce(Return(false));
EXPECT_CALL(*i_handler, Handle(token_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
// Check that a network failure when trying IssueAuthToken results in us bailing
// and putting up the browser window.
TEST_F(CookieFetcherTest, IssueAuthTokenNetworkFailureTest) {
URLRequestStatus failed(URLRequestStatus::FAILED, ECONNRESET);
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_, failed, kHttpSuccess, token_);
MockDelegate* delegate = new MockDelegate;
// I expect nothing in i_handler to get called anyway
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, failed, kHttpSuccess, std::string());
CookieFetcher* cf = new CookieFetcher(&profile_,
cl_handler,
i_handler,
delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
// Check that a network failure when trying TokenAuth results in us bailing
// and putting up the browser window.
TEST_F(CookieFetcherTest, TokenAuthNetworkFailureTest) {
URLRequestStatus success;
URLRequestStatus failed(URLRequestStatus::FAILED, ECONNRESET);
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_, success, kHttpSuccess, token_);
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, failed, 0, std::string());
MockDelegate* delegate = new MockDelegate;
CookieFetcher* cf = new CookieFetcher(&profile_,
cl_handler,
i_handler,
delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*i_handler, CanHandle(iat_url_))
.WillOnce(Return(true));
EXPECT_CALL(*i_handler, Handle(token_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
// Check that an unsuccessful HTTP response when trying IssueAuthToken results
// in us bailing and putting up the browser window.
TEST_F(CookieFetcherTest, IssueAuthTokenDeniedTest) {
URLRequestStatus success;
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_, success, 403, std::string());
MockDelegate* delegate = new MockDelegate;
// I expect nothing in i_handler to get called anyway.
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, success, 0, std::string());
CookieFetcher* cf = new CookieFetcher(&profile_,
cl_handler,
i_handler,
delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
// Check that an unsuccessful HTTP response when trying TokenAuth results
// in us bailing and putting up the browser window.
TEST_F(CookieFetcherTest, TokenAuthDeniedTest) {
URLRequestStatus success;
MockAuthResponseHandler* cl_handler =
new MockAuthResponseHandler(iat_url_,
success,
kHttpSuccess,
token_);
MockAuthResponseHandler* i_handler =
new MockAuthResponseHandler(ta_url_, success, 403, std::string());
MockDelegate* delegate = new MockDelegate;
CookieFetcher* cf = new CookieFetcher(&profile_,
cl_handler,
i_handler,
delegate);
EXPECT_CALL(*cl_handler, Handle(client_login_data_, cf))
.Times(1);
EXPECT_CALL(*i_handler, CanHandle(iat_url_))
.WillOnce(Return(true));
EXPECT_CALL(*i_handler, Handle(token_, cf))
.Times(1);
EXPECT_CALL(*delegate, DoLaunch(_))
.Times(1);
cf->AttemptFetch(client_login_data_);
message_loop_.RunAllPending();
}
TEST_F(CookieFetcherTest, ClientLoginResponseHandlerTest) {
ClientLoginResponseHandler handler(NULL);
std::string input("a\nb\n");
std::string expected("a&b&");
expected.append(ClientLoginResponseHandler::kService);
scoped_ptr<URLFetcher> fetcher(handler.Handle(input, NULL));
EXPECT_EQ(expected, handler.payload());
}
TEST_F(CookieFetcherTest, IssueResponseHandlerTest) {
IssueResponseHandler handler(NULL);
std::string input("a\n");
std::string expected(IssueResponseHandler::kTokenAuthUrl);
expected.append(input);
scoped_ptr<URLFetcher> fetcher(handler.Handle(input, NULL));
EXPECT_EQ(expected, handler.token_url());
}
} // namespace chromeos
|
Fix chromeos build. Part 2.
|
TBR: Fix chromeos build. Part 2.
git-svn-id: http://src.chromium.org/svn/trunk/src@56062 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 455bf06d75302f434c730bf141e59ae056366500
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
933ef7b76ee0bf780e6e38c0d74dd3a495a54b51
|
urbackupserver/verify_hashes.cpp
|
urbackupserver/verify_hashes.cpp
|
#include "../Interface/Database.h"
#include "../Interface/Server.h"
#include "../Interface/File.h"
#include "../Interface/DatabaseCursor.h"
#include "database.h"
#include "../stringtools.h"
#include <iostream>
#include <fstream>
#include "../urbackupcommon/sha2/sha2.h"
#include "../urbackupcommon/os_functions.h"
#include <memory.h>
#include <memory>
#include "dao/ServerBackupDao.h"
#include "FileIndex.h"
#include "create_files_index.h"
#include "server_hash.h"
#include "serverinterface/helper.h"
const _u32 c_read_blocksize=4096;
const size_t draw_segments=30;
const size_t c_speed_size=15;
const size_t c_max_l_length=80;
void draw_progress(std::wstring curr_fn, _i64 curr_verified, _i64 verify_size)
{
static _i64 last_progress_bytes=0;
static int64 last_time=0;
static size_t max_line_length=0;
int64 passed_time=Server->getTimeMS()-last_time;
if(passed_time>1000)
{
_i64 new_bytes=curr_verified-last_progress_bytes;
float pc_done=(float)curr_verified/(float)verify_size;
size_t segments=(size_t)(pc_done*draw_segments);
std::string toc="\r[";
for(size_t i=0;i<draw_segments;++i)
{
if(i<segments)
{
toc+="=";
}
else if(i==segments)
{
toc+=">";
}
else
{
toc+=" ";
}
}
std::string speed_str=PrettyPrintSpeed((size_t)((new_bytes*1000)/passed_time));
while(speed_str.size()<c_speed_size)
speed_str+=" ";
std::string pcdone=nconvert((int)(pc_done*100.f));
if(pcdone.size()==1)
pcdone=" "+pcdone;
toc+="] "+pcdone+"% "+speed_str+" "+Server->ConvertToUTF8(curr_fn);
if(toc.size()>=c_max_l_length)
toc=toc.substr(0, c_max_l_length);
if(toc.size()>max_line_length)
max_line_length=toc.size();
while(toc.size()<max_line_length)
toc+=" ";
std::cout << toc;
std::cout.flush();
last_progress_bytes=curr_verified;
last_time=Server->getTimeMS();
}
}
bool verify_file(db_single_result &res, _i64 &curr_verified, _i64 verify_size)
{
std::wstring fp=res[L"fullpath"];
IFile *f=Server->openFile(os_file_prefix(fp), MODE_READ);
if( f==NULL )
{
Server->Log(L"Error opening file \""+fp+L"\"", LL_ERROR);
return false;
}
if(watoi64(res[L"filesize"])!=f->Size())
{
Server->Log(L"Filesize of \""+fp+L"\" is wrong", LL_ERROR);
return false;
}
std::wstring f_name=ExtractFileName(fp);
sha512_ctx shactx;
sha512_init(&shactx);
_u32 r;
char buf[c_read_blocksize];
do
{
r=f->Read(buf, c_read_blocksize);
if(r>0)
{
sha512_update(&shactx, (unsigned char*) buf, r);
}
curr_verified+=r;
draw_progress(f_name, curr_verified, verify_size);
}
while(r>0);
Server->destroy(f);
const unsigned char * db_sha=(unsigned char*)res[L"shahash"].c_str();
unsigned char calc_dig[64];
sha512_final(&shactx, calc_dig);
if(memcmp(db_sha, calc_dig, 64)!=0)
{
Server->Log(L"Hash of \""+fp+L"\" is wrong", LL_ERROR);
return false;
}
return true;
}
bool verify_hashes(std::string arg)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER);
std::string working_dir=Server->ConvertToUTF8(Server->getServerWorkingDir());
std::string v_output_fn=working_dir+os_file_sepn()+"urbackup"+os_file_sepn()+"verification_result.txt";
std::fstream v_failure;
v_failure.open(v_output_fn.c_str(), std::ios::out|std::ios::binary);
if( !v_failure.is_open() )
Server->Log("Could not open \""+v_output_fn+"\" for writing", LL_ERROR);
else
Server->Log("Writing verification results to \""+v_output_fn+"\"", LL_INFO);
std::string clientname;
std::string backupname;
if(arg!="true")
{
if(arg.find("/")==std::string::npos)
{
clientname=arg;
}
else
{
clientname=getuntil("/", arg);
backupname=getafter("/", arg);
}
}
bool delete_failed = Server->getServerParameter("delete_verify_failed")=="true";
int cid=0;
int backupid=0;
std::string filter;
if(!clientname.empty())
{
if(clientname!="*")
{
IQuery *q=db->Prepare("SELECT id FROM clients WHERE name=?");
q->Bind(clientname);
db_results res=q->Read();
if(!res.empty())
{
cid=watoi(res[0][L"id"]);
}
else
{
Server->Log("Client \""+clientname+"\" not found", LL_ERROR);
return false;
}
filter=" WHERE clientid="+nconvert(cid);
}
else
{
filter+="WHERE 1=1";
}
if(!backupname.empty())
{
std::string backupid_filter;
if(backupname=="last")
{
if(clientname!="*")
{
IQuery* q=db->Prepare("SELECT id,path FROM backups WHERE clientid=? ORDER BY backuptime DESC LIMIT 1");
q->Bind(cid);
db_results res=q->Read();
if(!res.empty())
{
backupid_filter="= "+wnarrow(res[0][L"id"]);
Server->Log(L"Last backup: "+res[0][L"path"], LL_INFO);
}
else
{
Server->Log("Last backup not found", LL_ERROR);
return false;
}
}
else
{
backupid_filter=" IN (SELECT id, path FROM backups b WHERE NOT EXISTS (SELECT id FROM backups c WHERE c.backuptime > b.backuptime AND b.clientid=c.clientid))";
}
}
else if(backupname=="*")
{
backupid_filter=" IN (SELECT id FROM backups WHERE clientid="+nconvert(cid)+")";
}
else
{
IQuery* q=db->Prepare("SELECT id FROM backups WHERE path=? AND clientid=?");
q->Bind(backupname);
q->Bind(cid);
db_results res=q->Read();
if(!res.empty())
{
backupid_filter="= "+wnarrow(res[0][L"id"]);
}
else
{
Server->Log("Backup \""+backupname+"\" not found", LL_ERROR);
return false;
}
}
if(backupname!="*" || clientname!="*")
{
filter+=" AND backupid "+backupid_filter;
}
}
}
std::cout << "Calculating filesize..." << std::endl;
IQuery *q_num_files=db->Prepare("SELECT SUM(filesize) AS c FROM files"+filter);
db_results res=q_num_files->Read();
if(res.empty())
{
Server->Log("Error during filesize calculation.", LL_ERROR);
return false;
}
_i64 verify_size=watoi64(res[0][L"c"]);
_i64 curr_verified=0;
std::cout << "To be verified: " << PrettyPrintBytes(verify_size) << " of files" << std::endl;
_i64 crowid=0;
IQuery *q_get_files=db->Prepare("SELECT id, fullpath, shahash, filesize FROM files"+filter);
bool is_okay=true;
IDatabaseCursor* cursor = q_get_files->Cursor();
std::vector<int64> todelete;
db_single_result res_single;
while(cursor->next(res_single))
{
if(! verify_file( res_single, curr_verified, verify_size) )
{
v_failure << "Verification of \"" << Server->ConvertToUTF8(res_single[L"fullpath"]) << "\" failed\r\n";
is_okay=false;
if(delete_failed)
{
todelete.push_back(watoi64(res_single[L"id"]));
}
}
}
if(v_failure.is_open() && is_okay)
{
v_failure.close();
Server->deleteFile(v_output_fn);
}
std::cout << std::endl;
if(delete_failed)
{
std::cout << "Deleting " << todelete.size() << " file entries with failed verification from database..." << std::endl;
SStartupStatus status;
if(!create_files_index(status))
{
std::cout << "Error opening file index -1" << std::endl;
}
else
{
ServerBackupDao backupdao(db);
std::auto_ptr<FileIndex> fileindex(create_lmdb_files_index());
if(fileindex.get()==NULL)
{
std::cout << "Error opening file index -2" << std::endl;
}
else
{
for(size_t i=0;i<todelete.size();++i)
{
BackupServerHash::deleteFileSQL(backupdao, *fileindex, todelete[i]);
}
std::cout << "done." << std::endl;
}
}
}
return is_okay;
}
|
#include "../Interface/Database.h"
#include "../Interface/Server.h"
#include "../Interface/File.h"
#include "../Interface/DatabaseCursor.h"
#include "database.h"
#include "../stringtools.h"
#include <iostream>
#include <fstream>
#include "../urbackupcommon/sha2/sha2.h"
#include "../urbackupcommon/os_functions.h"
#include <memory.h>
#include <memory>
#include "dao/ServerBackupDao.h"
#include "FileIndex.h"
#include "create_files_index.h"
#include "server_hash.h"
#include "serverinterface/helper.h"
const _u32 c_read_blocksize=4096;
const size_t draw_segments=30;
const size_t c_speed_size=15;
const size_t c_max_l_length=80;
void draw_progress(std::wstring curr_fn, _i64 curr_verified, _i64 verify_size)
{
static _i64 last_progress_bytes=0;
static int64 last_time=0;
static size_t max_line_length=0;
int64 passed_time=Server->getTimeMS()-last_time;
if(passed_time>1000)
{
_i64 new_bytes=curr_verified-last_progress_bytes;
float pc_done=(float)curr_verified/(float)verify_size;
size_t segments=(size_t)(pc_done*draw_segments);
std::string toc="\r[";
for(size_t i=0;i<draw_segments;++i)
{
if(i<segments)
{
toc+="=";
}
else if(i==segments)
{
toc+=">";
}
else
{
toc+=" ";
}
}
std::string speed_str=PrettyPrintSpeed((size_t)((new_bytes*1000)/passed_time));
while(speed_str.size()<c_speed_size)
speed_str+=" ";
std::string pcdone=nconvert((int)(pc_done*100.f));
if(pcdone.size()==1)
pcdone=" "+pcdone;
toc+="] "+pcdone+"% "+speed_str+" "+Server->ConvertToUTF8(curr_fn);
if(toc.size()>=c_max_l_length)
toc=toc.substr(0, c_max_l_length);
if(toc.size()>max_line_length)
max_line_length=toc.size();
while(toc.size()<max_line_length)
toc+=" ";
std::cout << toc;
std::cout.flush();
last_progress_bytes=curr_verified;
last_time=Server->getTimeMS();
}
}
bool verify_file(db_single_result &res, _i64 &curr_verified, _i64 verify_size)
{
std::wstring fp=res[L"fullpath"];
IFile *f=Server->openFile(os_file_prefix(fp), MODE_READ);
if( f==NULL )
{
Server->Log(L"Error opening file \""+fp+L"\"", LL_ERROR);
return false;
}
if(watoi64(res[L"filesize"])!=f->Size())
{
Server->Log(L"Filesize of \""+fp+L"\" is wrong", LL_ERROR);
return false;
}
std::wstring f_name=ExtractFileName(fp);
sha512_ctx shactx;
sha512_init(&shactx);
_u32 r;
char buf[c_read_blocksize];
do
{
r=f->Read(buf, c_read_blocksize);
if(r>0)
{
sha512_update(&shactx, (unsigned char*) buf, r);
}
curr_verified+=r;
draw_progress(f_name, curr_verified, verify_size);
}
while(r>0);
Server->destroy(f);
const unsigned char * db_sha=(unsigned char*)res[L"shahash"].c_str();
unsigned char calc_dig[64];
sha512_final(&shactx, calc_dig);
if(memcmp(db_sha, calc_dig, 64)!=0)
{
Server->Log(L"Hash of \""+fp+L"\" is wrong", LL_ERROR);
return false;
}
return true;
}
bool verify_hashes(std::string arg)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER);
std::string working_dir=Server->ConvertToUTF8(Server->getServerWorkingDir());
std::string v_output_fn=working_dir+os_file_sepn()+"urbackup"+os_file_sepn()+"verification_result.txt";
std::fstream v_failure;
v_failure.open(v_output_fn.c_str(), std::ios::out|std::ios::binary);
if( !v_failure.is_open() )
Server->Log("Could not open \""+v_output_fn+"\" for writing", LL_ERROR);
else
Server->Log("Writing verification results to \""+v_output_fn+"\"", LL_INFO);
std::string clientname;
std::string backupname;
if(arg!="true")
{
if(arg.find("/")==std::string::npos)
{
clientname=arg;
}
else
{
clientname=getuntil("/", arg);
backupname=getafter("/", arg);
}
}
bool delete_failed = Server->getServerParameter("delete_verify_failed")=="true";
int cid=0;
int backupid=0;
std::string filter;
if(!clientname.empty())
{
if(clientname!="*")
{
IQuery *q=db->Prepare("SELECT id FROM clients WHERE name=?");
q->Bind(clientname);
db_results res=q->Read();
if(!res.empty())
{
cid=watoi(res[0][L"id"]);
}
else
{
Server->Log("Client \""+clientname+"\" not found", LL_ERROR);
return false;
}
filter=" WHERE clientid="+nconvert(cid);
}
else
{
filter+=" WHERE 1=1";
}
if(!backupname.empty())
{
std::string backupid_filter;
if(backupname=="last")
{
if(clientname!="*")
{
IQuery* q=db->Prepare("SELECT id,path FROM backups WHERE clientid=? ORDER BY backuptime DESC LIMIT 1");
q->Bind(cid);
db_results res=q->Read();
if(!res.empty())
{
backupid_filter="= "+wnarrow(res[0][L"id"]);
Server->Log(L"Last backup: "+res[0][L"path"], LL_INFO);
}
else
{
Server->Log("Last backup not found", LL_ERROR);
return false;
}
}
else
{
backupid_filter=" IN (SELECT id, path FROM backups b WHERE NOT EXISTS (SELECT id FROM backups c WHERE c.backuptime > b.backuptime AND b.clientid=c.clientid))";
}
}
else if(backupname=="*")
{
backupid_filter=" IN (SELECT id FROM backups WHERE clientid="+nconvert(cid)+")";
}
else
{
IQuery* q=db->Prepare("SELECT id FROM backups WHERE path=? AND clientid=?");
q->Bind(backupname);
q->Bind(cid);
db_results res=q->Read();
if(!res.empty())
{
backupid_filter="= "+wnarrow(res[0][L"id"]);
}
else
{
Server->Log("Backup \""+backupname+"\" not found", LL_ERROR);
return false;
}
}
if(backupname!="*" || clientname!="*")
{
filter+=" AND backupid "+backupid_filter;
}
}
}
std::cout << "Calculating filesize..." << std::endl;
IQuery *q_num_files=db->Prepare("SELECT SUM(filesize) AS c FROM files"+filter);
db_results res=q_num_files->Read();
if(res.empty())
{
Server->Log("Error during filesize calculation.", LL_ERROR);
return false;
}
_i64 verify_size=watoi64(res[0][L"c"]);
_i64 curr_verified=0;
std::cout << "To be verified: " << PrettyPrintBytes(verify_size) << " of files" << std::endl;
_i64 crowid=0;
IQuery *q_get_files=db->Prepare("SELECT id, fullpath, shahash, filesize FROM files"+filter);
bool is_okay=true;
IDatabaseCursor* cursor = q_get_files->Cursor();
std::vector<int64> todelete;
db_single_result res_single;
while(cursor->next(res_single))
{
if(! verify_file( res_single, curr_verified, verify_size) )
{
v_failure << "Verification of \"" << Server->ConvertToUTF8(res_single[L"fullpath"]) << "\" failed\r\n";
is_okay=false;
if(delete_failed)
{
todelete.push_back(watoi64(res_single[L"id"]));
}
}
}
if(v_failure.is_open() && is_okay)
{
v_failure.close();
Server->deleteFile(v_output_fn);
}
std::cout << std::endl;
if(delete_failed)
{
std::cout << "Deleting " << todelete.size() << " file entries with failed verification from database..." << std::endl;
SStartupStatus status;
if(!create_files_index(status))
{
std::cout << "Error opening file index -1" << std::endl;
}
else
{
ServerBackupDao backupdao(db);
std::auto_ptr<FileIndex> fileindex(create_lmdb_files_index());
if(fileindex.get()==NULL)
{
std::cout << "Error opening file index -2" << std::endl;
}
else
{
for(size_t i=0;i<todelete.size();++i)
{
BackupServerHash::deleteFileSQL(backupdao, *fileindex, todelete[i]);
}
std::cout << "done." << std::endl;
}
}
}
return is_okay;
}
|
Allow wildcards in file backup verification selection
|
Allow wildcards in file backup verification selection
|
C++
|
agpl-3.0
|
uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend
|
ffcaeac917f846d978c5d5b216ccb06def6d22be
|
chrome/browser/extensions/extension_messages_unittest.cc
|
chrome/browser/extensions/extension_messages_unittest.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"
static void DispatchOnConnect(int source_port_id, const std::string& name,
const std::string& tab_json) {
ListValue args;
args.Set(0, Value::CreateIntegerValue(source_port_id));
args.Set(1, Value::CreateStringValue(name));
args.Set(2, Value::CreateStringValue(tab_json));
args.Set(3, Value::CreateStringValue("")); // extension ID is empty for tests
args.Set(4, Value::CreateStringValue("")); // extension ID is empty for tests
RendererExtensionBindings::Invoke(
ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL());
}
static void DispatchOnDisconnect(int source_port_id) {
ListValue args;
args.Set(0, Value::CreateIntegerValue(source_port_id));
RendererExtensionBindings::Invoke(
ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false,
GURL());
}
static void DispatchOnMessage(const std::string& message, int source_port_id) {
ListValue args;
args.Set(0, Value::CreateStringValue(message));
args.Set(1, Value::CreateIntegerValue(source_port_id));
RendererExtensionBindings::Invoke(
ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL());
}
// Tests that the bindings for opening a channel to an extension and sending
// and receiving messages through that channel all works.
TEST_F(RenderViewTest, ExtensionMessagesOpenChannel) {
render_thread_.sink().ClearMessages();
LoadHTML("<body></body>");
ExecuteJavaScript(
"var port = chrome.extension.connect({name:'testName'});"
"port.onMessage.addListener(doOnMessage);"
"port.postMessage({message: 'content ready'});"
"function doOnMessage(msg, port) {"
" alert('content got: ' + msg.val);"
"}");
// Verify that we opened a channel and sent a message through it.
const IPC::Message* open_channel_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_OpenChannelToExtension::ID);
ASSERT_TRUE(open_channel_msg);
void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg);
ViewHostMsg_OpenChannelToExtension::SendParam open_params;
ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params));
EXPECT_EQ("testName", open_params.d);
const IPC::Message* post_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_ExtensionPostMessage::ID);
ASSERT_TRUE(post_msg);
ViewHostMsg_ExtensionPostMessage::Param post_params;
ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
EXPECT_EQ("{\"message\":\"content ready\"}", post_params.b);
// Now simulate getting a message back from the other side.
render_thread_.sink().ClearMessages();
const int kPortId = 0;
DispatchOnMessage("{\"val\": 42}", kPortId);
// Verify that we got it.
const IPC::Message* alert_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_RunJavaScriptMessage::ID);
ASSERT_TRUE(alert_msg);
iter = IPC::SyncMessage::GetDataIterator(alert_msg);
ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
EXPECT_EQ(L"content got: 42", alert_param.a);
}
// Tests that the bindings for handling a new channel connection and channel
// closing all works.
TEST_F(RenderViewTest, ExtensionMessagesOnConnect) {
LoadHTML("<body></body>");
ExecuteJavaScript(
"chrome.extension.onConnect.addListener(function (port) {"
" port.test = 24;"
" port.onMessage.addListener(doOnMessage);"
" port.onDisconnect.addListener(doOnDisconnect);"
" port.postMessage({message: 'onconnect from ' + port.tab.url + "
" ' name ' + port.name});"
"});"
"function doOnMessage(msg, port) {"
" alert('got: ' + msg.val);"
"}"
"function doOnDisconnect(port) {"
" alert('disconnected: ' + port.test);"
"}");
render_thread_.sink().ClearMessages();
// Simulate a new connection being opened.
const int kPortId = 0;
const std::string kPortName = "testName";
DispatchOnConnect(kPortId, kPortName, "{\"url\":\"foo://bar\"}");
// Verify that we handled the new connection by posting a message.
const IPC::Message* post_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_ExtensionPostMessage::ID);
ASSERT_TRUE(post_msg);
ViewHostMsg_ExtensionPostMessage::Param post_params;
ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
std::string expected_msg =
"{\"message\":\"onconnect from foo://bar name " + kPortName + "\"}";
EXPECT_EQ(expected_msg, post_params.b);
// Now simulate getting a message back from the channel opener.
render_thread_.sink().ClearMessages();
DispatchOnMessage("{\"val\": 42}", kPortId);
// Verify that we got it.
const IPC::Message* alert_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_RunJavaScriptMessage::ID);
ASSERT_TRUE(alert_msg);
void* iter = IPC::SyncMessage::GetDataIterator(alert_msg);
ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
EXPECT_EQ(L"got: 42", alert_param.a);
// Now simulate the channel closing.
render_thread_.sink().ClearMessages();
DispatchOnDisconnect(kPortId);
// Verify that we got it.
alert_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_RunJavaScriptMessage::ID);
ASSERT_TRUE(alert_msg);
iter = IPC::SyncMessage::GetDataIterator(alert_msg);
ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
EXPECT_EQ(L"disconnected: 24", alert_param.a);
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"
static void DispatchOnConnect(int source_port_id, const std::string& name,
const std::string& tab_json) {
ListValue args;
args.Set(0, Value::CreateIntegerValue(source_port_id));
args.Set(1, Value::CreateStringValue(name));
args.Set(2, Value::CreateStringValue(tab_json));
args.Set(3, Value::CreateStringValue("")); // extension ID is empty for tests
args.Set(4, Value::CreateStringValue("")); // extension ID is empty for tests
RendererExtensionBindings::Invoke(
ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL());
}
static void DispatchOnDisconnect(int source_port_id) {
ListValue args;
args.Set(0, Value::CreateIntegerValue(source_port_id));
RendererExtensionBindings::Invoke(
ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false,
GURL());
}
static void DispatchOnMessage(const std::string& message, int source_port_id) {
ListValue args;
args.Set(0, Value::CreateStringValue(message));
args.Set(1, Value::CreateIntegerValue(source_port_id));
RendererExtensionBindings::Invoke(
ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL());
}
// Tests that the bindings for opening a channel to an extension and sending
// and receiving messages through that channel all works.
TEST_F(RenderViewTest, DISABLED_ExtensionMessagesOpenChannel) {
render_thread_.sink().ClearMessages();
LoadHTML("<body></body>");
ExecuteJavaScript(
"var port = chrome.extension.connect({name:'testName'});"
"port.onMessage.addListener(doOnMessage);"
"port.postMessage({message: 'content ready'});"
"function doOnMessage(msg, port) {"
" alert('content got: ' + msg.val);"
"}");
// Verify that we opened a channel and sent a message through it.
const IPC::Message* open_channel_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_OpenChannelToExtension::ID);
ASSERT_TRUE(open_channel_msg);
void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg);
ViewHostMsg_OpenChannelToExtension::SendParam open_params;
ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params));
EXPECT_EQ("testName", open_params.d);
const IPC::Message* post_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_ExtensionPostMessage::ID);
ASSERT_TRUE(post_msg);
ViewHostMsg_ExtensionPostMessage::Param post_params;
ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
EXPECT_EQ("{\"message\":\"content ready\"}", post_params.b);
// Now simulate getting a message back from the other side.
render_thread_.sink().ClearMessages();
const int kPortId = 0;
DispatchOnMessage("{\"val\": 42}", kPortId);
// Verify that we got it.
const IPC::Message* alert_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_RunJavaScriptMessage::ID);
ASSERT_TRUE(alert_msg);
iter = IPC::SyncMessage::GetDataIterator(alert_msg);
ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
EXPECT_EQ(L"content got: 42", alert_param.a);
}
// Tests that the bindings for handling a new channel connection and channel
// closing all works.
TEST_F(RenderViewTest, DISABLED_ExtensionMessagesOnConnect) {
LoadHTML("<body></body>");
ExecuteJavaScript(
"chrome.extension.onConnect.addListener(function (port) {"
" port.test = 24;"
" port.onMessage.addListener(doOnMessage);"
" port.onDisconnect.addListener(doOnDisconnect);"
" port.postMessage({message: 'onconnect from ' + port.tab.url + "
" ' name ' + port.name});"
"});"
"function doOnMessage(msg, port) {"
" alert('got: ' + msg.val);"
"}"
"function doOnDisconnect(port) {"
" alert('disconnected: ' + port.test);"
"}");
render_thread_.sink().ClearMessages();
// Simulate a new connection being opened.
const int kPortId = 0;
const std::string kPortName = "testName";
DispatchOnConnect(kPortId, kPortName, "{\"url\":\"foo://bar\"}");
// Verify that we handled the new connection by posting a message.
const IPC::Message* post_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_ExtensionPostMessage::ID);
ASSERT_TRUE(post_msg);
ViewHostMsg_ExtensionPostMessage::Param post_params;
ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
std::string expected_msg =
"{\"message\":\"onconnect from foo://bar name " + kPortName + "\"}";
EXPECT_EQ(expected_msg, post_params.b);
// Now simulate getting a message back from the channel opener.
render_thread_.sink().ClearMessages();
DispatchOnMessage("{\"val\": 42}", kPortId);
// Verify that we got it.
const IPC::Message* alert_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_RunJavaScriptMessage::ID);
ASSERT_TRUE(alert_msg);
void* iter = IPC::SyncMessage::GetDataIterator(alert_msg);
ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
EXPECT_EQ(L"got: 42", alert_param.a);
// Now simulate the channel closing.
render_thread_.sink().ClearMessages();
DispatchOnDisconnect(kPortId);
// Verify that we got it.
alert_msg =
render_thread_.sink().GetUniqueMessageMatching(
ViewHostMsg_RunJavaScriptMessage::ID);
ASSERT_TRUE(alert_msg);
iter = IPC::SyncMessage::GetDataIterator(alert_msg);
ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
EXPECT_EQ(L"disconnected: 24", alert_param.a);
}
|
Disable RenderViewTest.ExtensionMessages* since they consistently crash localy and on the bots.
|
Disable RenderViewTest.ExtensionMessages* since they consistently crash localy and on the bots.
Code in question didn't change recently (9months) so it is possible it's a WebKit problem.
You need to run all tests to get the crash. Running with --gtest_filter=RenderViewTest.* passes.
There is a possible namespace clash with other RenderViewTest class.
Stack trace:
\src\third_party\WebKit\WebCore\platform\TreeShared.h:38 WebCore::TreeShared<class WebCore::Node>::TreeShared)
Backtrace:
WebCore::TreeShared<WebCore::Node>::TreeShared<WebCore::Node> [0x03AE8EBA+90] (d:\chromium2\src\third_party\webkit\webcore\platform\treeshared.h:38)
WebCore::Node::Node [0x03AD4011+49] (d:\chromium2\src\third_party\webkit\webcore\dom\document.h:1280)
WebCore::ContainerNode::ContainerNode [0x03AD3D7E+30] (d:\chromium2\src\third_party\webkit\webcore\dom\containernode.h:107)
WebCore::Document::Document [0x03AD331A+42] (d:\chromium2\src\third_party\webkit\webcore\dom\document.cpp:403)
WebCore::HTMLDocument::HTMLDocument [0x03DDF76E+30] (d:\chromium2\src\third_party\webkit\webcore\html\htmldocument.cpp:86)
WebCore::HTMLDocument::create [0x03E522B6+54] (d:\chromium2\src\third_party\webkit\webcore\html\htmldocument.h:40)
WebCore::DOMImplementation::createDocument [0x03E52360+112] (d:\chromium2\src\third_party\webkit\webcore\dom\domimplementation.cpp:312)
WebCore::DocumentWriter::createDocument [0x03B9B008+280] (d:\chromium2\src\third_party\webkit\webcore\loader\documentwriter.cpp:88)
WebCore::DocumentWriter::begin [0x03B9B214+52] (d:\chromium2\src\third_party\webkit\webcore\loader\documentwriter.cpp:99)
WebCore::FrameLoader::init [0x03B77539+441] (d:\chromium2\src\third_party\webkit\webcore\loader\frameloader.cpp:251)
WebCore::Frame::init [0x026D4FB9+25] (d:\chromium2\src\third_party\webkit\webcore\page\frame.h:370)
WebKit::WebFrameImpl::initializeAsMainFrame [0x026D4EE6+118] (d:\chromium2\src\third_party\webkit\webkit\chromium\src\webframeimpl.cpp:1712)
WebKit::WebViewImpl::initializeMainFrame [0x0270D1D1+81] (d:\chromium2\src\third_party\webkit\webkit\chromium\src\webviewimpl.cpp:209)
RenderView::Init [0x02BB1C04+660] (d:\chromium2\src\chrome\renderer\render_view.cc:533)
RenderView::Create [0x02BB14CB+267] (d:\chromium2\src\chrome\renderer\render_view.cc:479)
RenderViewTest::SetUp [0x01329E49+841] (d:\chromium2\src\chrome\test\render_view_test.cc:111)
testing::Test::Run [0x02A47DC3+163] (d:\chromium2\src\testing\gtest\src\gtest.cc:2060)
testing::internal::TestInfoImpl::Run [0x02A48B03+339] (d:\chromium2\src\testing\gtest\src\gtest.cc:2318
TBR=aa,mpcomplete,senorblanco
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@49046 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,nacl-webkit/chrome_deps,keishi/chromium,dednal/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,robclark/chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,keishi/chromium,M4sse/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,timopulkkinen/BubbleFish,keishi/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,littlstar/chromium.src,ltilve/chromium,rogerwang/chromium,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,anirudhSK/chromium,hujiajie/pa-chromium,Just-D/chromium-1,Jonekee/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,rogerwang/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,keishi/chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,rogerwang/chromium,robclark/chromium,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,rogerwang/chromium,dednal/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,rogerwang/chromium,ChromiumWebApps/chromium,patrickm/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,Just-D/chromium-1,markYoungH/chromium.src,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,robclark/chromium,Jonekee/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,keishi/chromium,littlstar/chromium.src,nacl-webkit/chrome_deps,robclark/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,littlstar/chromium.src,M4sse/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,keishi/chromium,Chilledheart/chromium,anirudhSK/chromium,Just-D/chromium-1,rogerwang/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,keishi/chromium,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,hgl888/chromium-crosswalk,keishi/chromium,Chilledheart/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,rogerwang/chromium,zcbenz/cefode-chromium,hujiajie/pa-chromium,zcbenz/cefode-chromium,M4sse/chromium.src,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,keishi/chromium,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,robclark/chromium,robclark/chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,robclark/chromium,timopulkkinen/BubbleFish,robclark/chromium,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,rogerwang/chromium,dushu1203/chromium.src,patrickm/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,robclark/chromium,patrickm/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,anirudhSK/chromium,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,keishi/chromium,dednal/chromium.src,anirudhSK/chromium,keishi/chromium,ondra-novak/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,anirudhSK/chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,rogerwang/chromium,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,hujiajie/pa-chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src
|
ab2e652938dd3f119f86c011f854ddce75702be1
|
serialport_native/serialport_native.cc
|
serialport_native/serialport_native.cc
|
// Copyright 2011 Chris Williams <[email protected]>
#include "serialport_native.h"
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <node.h> /* Includes for JS, node.js and v8 */
#include <node_buffer.h>
#include <v8.h>
#define THROW_BAD_ARGS ThrowException(Exception::TypeError(String::New("Bad argument")))
namespace node {
using namespace v8;
static Persistent<String> errno_symbol;
static Handle<Value> Read(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
}
int fd = args[0]->Int32Value();
char * buf = NULL;
if (!Buffer::HasInstance(args[1])) {
return ThrowException(Exception::Error(
String::New("Second argument needs to be a buffer")));
}
Local<Object> buffer_obj = args[1]->ToObject();
char *buffer_data = Buffer::Data(buffer_obj);
size_t buffer_length = Buffer::Length(buffer_obj);
ssize_t bytes_read = read(fd, buffer_data, buffer_length);
if (bytes_read < 0) return ThrowException(ErrnoException(errno));
// reset current pointer
size_t seek_ret = lseek(fd,bytes_read,SEEK_CUR);
return scope.Close(Integer::New(bytes_read));
}
static Handle<Value> Write(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
}
int fd = args[0]->Int32Value();
if (!Buffer::HasInstance(args[1])) {
return ThrowException(Exception::Error(String::New("Second argument needs to be a buffer")));
}
Local<Object> buffer_obj = args[1]->ToObject();
char *buffer_data = Buffer::Data(buffer_obj);
size_t buffer_length = Buffer::Length(buffer_obj);
int n = write(fd, buffer_data, buffer_length);
return scope.Close(Integer::New(n));
}
static Handle<Value> Close(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
}
int fd = args[0]->Int32Value();
close(fd);
return scope.Close(Integer::New(1));
}
static Handle<Value> Open(const Arguments& args) {
HandleScope scope;
struct termios options;
long Baud_Rate = 38400;
int Data_Bits = 8;
int Stop_Bits = 1;
int Parity = 0;
int Flowcontrol = 0;
long BAUD;
long DATABITS;
long STOPBITS;
long PARITYON;
long PARITY;
long FLOWCONTROL;
if (!args[0]->IsString()) {
return scope.Close(THROW_BAD_ARGS);
}
// Baud Rate Argument
if (args.Length() >= 2 && !args[1]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Baud_Rate = args[1]->Int32Value();
}
// Data Bits Argument
if (args.Length() >= 3 && !args[2]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Data_Bits = args[2]->Int32Value();
}
// Stop Bits Arguments
if (args.Length() >= 4 && !args[3]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Stop_Bits = args[3]->Int32Value();
}
// Parity Arguments
if (args.Length() >= 5 && !args[4]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Parity = args[4]->Int32Value();
}
// Flow control Arguments
if (args.Length() >= 6 && !args[5]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Flowcontrol = args[5]->Int32Value();
}
switch (Baud_Rate)
{
case 38400:
default:
BAUD = B38400;
break;
case 115200:
BAUD = B115200;
break;
case 57600:
BAUD = B57600;
break;
case 19200:
BAUD = B19200;
break;
case 9600:
BAUD = B9600;
break;
case 4800:
BAUD = B4800;
break;
case 2400:
BAUD = B2400;
break;
case 1800:
BAUD = B1800;
break;
case 1200:
BAUD = B1200;
break;
case 600:
BAUD = B600;
break;
case 300:
BAUD = B300;
break;
case 200:
BAUD = B200;
break;
case 150:
BAUD = B150;
break;
case 134:
BAUD = B134;
break;
case 110:
BAUD = B110;
break;
case 75:
BAUD = B75;
break;
case 50:
BAUD = B50;
break;
}
switch (Data_Bits)
{
case 8:
default:
DATABITS = CS8;
break;
case 7:
DATABITS = CS7;
break;
case 6:
DATABITS = CS6;
break;
case 5:
DATABITS = CS5;
break;
}
switch (Stop_Bits)
{
case 1:
default:
STOPBITS = 0;
break;
case 2:
STOPBITS = CSTOPB;
break;
}
switch (Flowcontrol)
{
case 0:
default:
FLOWCONTROL = 0;
break;
case 1:
FLOWCONTROL = CRTSCTS;
break;
}
String::Utf8Value path(args[0]->ToString());
int flags = (O_RDWR | O_NOCTTY | O_NONBLOCK | O_NDELAY);
int fd = open(*path, flags);
if (fd == -1) {
// perror("open_port: Unable to open specified serial port connection.");
return scope.Close(Integer::New(fd));
} else {
struct sigaction saio;
saio.sa_handler = SIG_IGN;
sigemptyset(&saio.sa_mask); //saio.sa_mask = 0;
saio.sa_flags = 0;
// saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
//all process to receive SIGIO
fcntl(fd, F_SETOWN, getpid());
fcntl(fd, F_SETFL, FASYNC);
// Set baud and other configuration.
tcgetattr(fd, &options);
/* Specify the baud rate */
cfsetispeed(&options, BAUD);
cfsetospeed(&options, BAUD);
/* Specify data bits */
options.c_cflag &= ~CSIZE;
options.c_cflag |= DATABITS;
/* Specify flow control */
options.c_cflag &= ~FLOWCONTROL;
options.c_cflag |= FLOWCONTROL;
switch (Parity)
{
case 0:
default: //none
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
break;
case 1: //odd
options.c_cflag |= PARENB;
options.c_cflag |= PARODD;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS7;
break;
case 2: //even
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS7;
break;
}
options.c_cflag |= (CLOCAL | CREAD);
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0; //ICANON;
options.c_cc[VMIN]=1;
options.c_cc[VTIME]=0;
//memset(&options, 0, 128000);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &options);
return scope.Close(Integer::New(fd));
}
}
void SerialPort::Initialize(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "open", Open);
NODE_SET_METHOD(target, "write", Write);
NODE_SET_METHOD(target, "close", Close);
NODE_SET_METHOD(target, "read", Read);
errno_symbol = NODE_PSYMBOL("errno");
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
SerialPort::Initialize(target);
}
}
|
// Copyright 2011 Chris Williams <[email protected]>
#include "serialport_native.h"
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <node.h> /* Includes for JS, node.js and v8 */
#include <node_buffer.h>
#include <v8.h>
#define THROW_BAD_ARGS ThrowException(Exception::TypeError(String::New("Bad argument")))
namespace node {
using namespace v8;
static Persistent<String> errno_symbol;
static Handle<Value> Read(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
}
int fd = args[0]->Int32Value();
char * buf = NULL;
if (!Buffer::HasInstance(args[1])) {
return ThrowException(Exception::Error(
String::New("Second argument needs to be a buffer")));
}
Local<Object> buffer_obj = args[1]->ToObject();
char *buffer_data = Buffer::Data(buffer_obj);
size_t buffer_length = Buffer::Length(buffer_obj);
ssize_t bytes_read = read(fd, buffer_data, buffer_length);
if (bytes_read < 0) return ThrowException(ErrnoException(errno));
// reset current pointer
size_t seek_ret = lseek(fd,bytes_read,SEEK_CUR);
return scope.Close(Integer::New(bytes_read));
}
static Handle<Value> Write(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
}
int fd = args[0]->Int32Value();
if (!Buffer::HasInstance(args[1])) {
return ThrowException(Exception::Error(String::New("Second argument needs to be a buffer")));
}
Local<Object> buffer_obj = args[1]->ToObject();
char *buffer_data = Buffer::Data(buffer_obj);
size_t buffer_length = Buffer::Length(buffer_obj);
int n = write(fd, buffer_data, buffer_length);
return scope.Close(Integer::New(n));
}
static Handle<Value> Close(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
}
int fd = args[0]->Int32Value();
close(fd);
return scope.Close(Integer::New(1));
}
static Handle<Value> Open(const Arguments& args) {
HandleScope scope;
struct termios options;
long Baud_Rate = 38400;
int Data_Bits = 8;
int Stop_Bits = 1;
int Parity = 0;
int Flowcontrol = 0;
long BAUD;
long DATABITS;
long STOPBITS;
long PARITYON;
long PARITY;
long FLOWCONTROL;
if (!args[0]->IsString()) {
return scope.Close(THROW_BAD_ARGS);
}
// Baud Rate Argument
if (args.Length() >= 2 && !args[1]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Baud_Rate = args[1]->Int32Value();
}
// Data Bits Argument
if (args.Length() >= 3 && !args[2]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Data_Bits = args[2]->Int32Value();
}
// Stop Bits Arguments
if (args.Length() >= 4 && !args[3]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Stop_Bits = args[3]->Int32Value();
}
// Parity Arguments
if (args.Length() >= 5 && !args[4]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Parity = args[4]->Int32Value();
}
// Flow control Arguments
if (args.Length() >= 6 && !args[5]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Flowcontrol = args[5]->Int32Value();
}
switch (Baud_Rate)
{
case 38400:
default:
BAUD = B38400;
break;
case 115200:
BAUD = B115200;
break;
case 57600:
BAUD = B57600;
break;
case 19200:
BAUD = B19200;
break;
case 9600:
BAUD = B9600;
break;
case 4800:
BAUD = B4800;
break;
case 2400:
BAUD = B2400;
break;
case 1800:
BAUD = B1800;
break;
case 1200:
BAUD = B1200;
break;
case 600:
BAUD = B600;
break;
case 300:
BAUD = B300;
break;
case 200:
BAUD = B200;
break;
case 150:
BAUD = B150;
break;
case 134:
BAUD = B134;
break;
case 110:
BAUD = B110;
break;
case 75:
BAUD = B75;
break;
case 50:
BAUD = B50;
break;
}
switch (Data_Bits)
{
case 8:
default:
DATABITS = CS8;
break;
case 7:
DATABITS = CS7;
break;
case 6:
DATABITS = CS6;
break;
case 5:
DATABITS = CS5;
break;
}
switch (Stop_Bits)
{
case 1:
default:
STOPBITS = 0;
break;
case 2:
STOPBITS = CSTOPB;
break;
}
switch (Flowcontrol)
{
case 0:
default:
FLOWCONTROL = 0;
break;
case 1:
FLOWCONTROL = CRTSCTS;
break;
}
String::Utf8Value path(args[0]->ToString());
int flags = (O_RDWR | O_NOCTTY | O_NONBLOCK | O_NDELAY);
int fd = open(*path, flags);
if (fd == -1) {
// perror("open_port: Unable to open specified serial port connection.");
return scope.Close(Integer::New(fd));
} else {
struct sigaction saio;
saio.sa_handler = SIG_IGN;
sigemptyset(&saio.sa_mask); //saio.sa_mask = 0;
saio.sa_flags = 0;
// saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
//all process to receive SIGIO
fcntl(fd, F_SETOWN, getpid());
fcntl(fd, F_SETFL, FASYNC);
// Set baud and other configuration.
tcgetattr(fd, &options);
/* Specify the baud rate */
cfsetispeed(&options, BAUD);
cfsetospeed(&options, BAUD);
/* Specify data bits */
options.c_cflag &= ~CSIZE;
options.c_cflag |= DATABITS;
/* Specify flow control */
options.c_cflag &= ~FLOWCONTROL;
options.c_cflag |= FLOWCONTROL;
switch (Parity)
{
case 0:
default: //none
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
break;
case 1: //odd
options.c_cflag |= PARENB;
options.c_cflag |= PARODD;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS7;
break;
case 2: //even
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS7;
break;
}
options.c_cflag |= (CLOCAL | CREAD);
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0; //ICANON;
options.c_cc[VMIN]=1;
options.c_cc[VTIME]=0;
//memset(&options, 0, 128000);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &options);
return scope.Close(Integer::New(fd));
}
}
void SerialPort::Initialize(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "open", Open);
NODE_SET_METHOD(target, "write", Write);
NODE_SET_METHOD(target, "close", Close);
NODE_SET_METHOD(target, "read", Read);
errno_symbol = NODE_PSYMBOL("errno");
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
SerialPort::Initialize(target);
}
}
|
Convert some tabs to spaces
|
Convert some tabs to spaces
|
C++
|
mit
|
Jonekee/node-serialport,prodatakey/node-serialport,Scypho/node-serialport,rwaldron/node-serialport,ms-iot/node-serialport,alex1818/node-serialport,hybridgroup/node-serialport,julianduque/node-serialport,bfjelds/node-serialport,giseburt/node-serialport,mbedded-ninja/node-serialport,tmpvar/node-serialport,nebrius/node-serialport,munyirik/node-serialport,TooTallNate/node-serialport,suda/node-serialport,giseburt/node-serialport,alex1818/node-serialport,node-serialport/node-serialport,Pixformance/node-serialport,tigoe/node-serialport,pr0duc3r/node-serialport,Jonekee/node-serialport,suda/node-serialport,bfjelds/node-serialport,prodatakey/node-serialport,jacobrosenthal/node-serialport,bmathews/node-serialport,kt3k/node-serialport,TooTallNate/node-serialport,cmaglie/node-serialport,voodootikigod/node-serialport,voodootikigod/node-serialport,julianduque/node-serialport,EmergingTechnologyAdvisors/node-serialport,kt3k/node-serialport,TooTallNate/node-serialport,ms-iot/node-serialport,samofab/node-nisa-old,julianduque/node-serialport,Scypho/node-serialport,bfjelds/node-serialport,entrylabs/node-serialport,voodootikigod/node-serialport,songshuang00/node-serialport,keyvanfatehi/node-serialport,kt3k/node-serialport,AlexeyPopov/node-serialport,usefulthink/node-serialport,voodootikigod/node-serialport,SimplyComplexCo/node-serialport,ddm/node-serialport,hybridgroup/node-serialport,keyvanfatehi/node-serialport,bfjelds/node-serialport,SimplyComplexCo/node-serialport,nebrius/node-serialport,aessig/node-serialport,rodovich/node-serialport,djchie/node-serialport,bmathews/node-serialport,cmaglie/node-serialport,rwaldron/node-serialport,cmaglie/node-serialport,aessig/node-serialport,EmergingTechnologyAdvisors/node-serialport,tmpvar/node-serialport,hybridgroup/node-serialport,munyirik/node-serialport,songshuang00/node-serialport,nebrius/node-serialport,entrylabs/node-serialport,Jonekee/node-serialport,djchie/node-serialport,jacobrosenthal/node-serialport,usefulthink/node-serialport,tigoe/node-serialport,munyirik/node-serialport,ms-iot/node-serialport,entrylabs/node-serialport,rodovich/node-serialport,songshuang00/node-serialport,usefulthink/node-serialport,cmaglie/node-serialport,gregfriedland/node-serialport,mbedded-ninja/node-serialport,Pixformance/node-serialport,gregfriedland/node-serialport,usefulthink/node-serialport,mbedded-ninja/node-serialport,munyirik/node-serialport,entrylabs/node-serialport,tmpvar/node-serialport,mcanthony/node-serialport,samofab/node-nisa-old,entrylabs/node-serialport,pr0duc3r/node-serialport,ms-iot/node-serialport,nebrius/node-serialport,julianduque/node-serialport,EmergingTechnologyAdvisors/node-serialport,SimplyComplexCo/node-serialport,SimplyComplexCo/node-serialport,mcanthony/node-serialport,rodovich/node-serialport,alex1818/node-serialport,AlexeyPopov/node-serialport,Jonekee/node-serialport,AlexeyPopov/node-serialport,tigoe/node-serialport,Scypho/node-serialport,aessig/node-serialport,pr0duc3r/node-serialport,EmergingTechnologyAdvisors/node-serialport,gregfriedland/node-serialport,Scypho/node-serialport,alex1818/node-serialport,gregfriedland/node-serialport,keyvanfatehi/node-serialport,pr0duc3r/node-serialport,jacobrosenthal/node-serialport,node-serialport/node-serialport,rodovich/node-serialport,samofab/node-nisa-old,jacobrosenthal/node-serialport,ddm/node-serialport,songshuang00/node-serialport,ms-iot/node-serialport,aessig/node-serialport,bmathews/node-serialport,mcanthony/node-serialport,node-serialport/node-serialport,rhuehn/node-serialport,EmergingTechnologyAdvisors/node-serialport,node-serialport/node-serialport,djchie/node-serialport,Pixformance/node-serialport,suda/node-serialport,TooTallNate/node-serialport,ddm/node-serialport,rhuehn/node-serialport,hybridgroup/node-serialport,rhuehn/node-serialport,rwaldron/node-serialport,mbedded-ninja/node-serialport,keyvanfatehi/node-serialport,giseburt/node-serialport,ddm/node-serialport,AlexeyPopov/node-serialport,djchie/node-serialport,giseburt/node-serialport,prodatakey/node-serialport,suda/node-serialport,bmathews/node-serialport,rhuehn/node-serialport,prodatakey/node-serialport,kt3k/node-serialport,tigoe/node-serialport,mcanthony/node-serialport,Pixformance/node-serialport,tmpvar/node-serialport,node-serialport/node-serialport
|
ed1e69dfe016760509f411fcd230e938230ac90a
|
chrome/browser/media/chrome_webrtc_apprtc_browsertest.cc
|
chrome/browser/media/chrome_webrtc_apprtc_browsertest.cc
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/files/file_enumerator.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/rand_util.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/test/browser_test_utils.h"
#include "media/base/media_switches.h"
#include "net/test/python_utils.h"
#include "ui/gl/gl_switches.h"
// You need this solution to run this test. The solution will download appengine
// and the apprtc code for you.
const char kAdviseOnGclientSolution[] =
"You need to add this solution to your .gclient to run this test:\n"
"{\n"
" \"name\" : \"webrtc.DEPS\",\n"
" \"url\" : \"https://chromium.googlesource.com/chromium/deps/"
"webrtc/webrtc.DEPS\",\n"
"}";
const char kTitlePageOfAppEngineAdminPage[] = "Instances";
const char kIsApprtcCallUpJavascript[] =
"var remoteVideo = document.querySelector('#remote-video');"
"var remoteVideoActive ="
" remoteVideo != null &&"
" remoteVideo.classList.contains('active');"
"window.domAutomationController.send(remoteVideoActive.toString());";
// WebRTC-AppRTC integration test. Requires a real webcam and microphone
// on the running system. This test is not meant to run in the main browser
// test suite since normal tester machines do not have webcams. Chrome will use
// its fake camera for both tests, but Firefox will use the real webcam in the
// Firefox interop test. Thus, this test must on a machine with a real webcam.
//
// This test will bring up a AppRTC instance on localhost and verify that the
// call gets up when connecting to the same room from two tabs in a browser.
class WebRtcApprtcBrowserTest : public WebRtcTestBase {
public:
WebRtcApprtcBrowserTest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream));
// The video playback will not work without a GPU, so force its use here.
command_line->AppendSwitch(switches::kUseGpuInTests);
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
}
void TearDown() override {
// Kill any processes we may have brought up. Note: this isn't perfect,
// especially if the test hangs or if we're on Windows.
LOG(INFO) << "Entering TearDown";
if (dev_appserver_.IsValid())
dev_appserver_.Terminate(0, false);
if (collider_server_.IsValid())
collider_server_.Terminate(0, false);
if (firefox_.IsValid())
firefox_.Terminate(0, false);
LOG(INFO) << "Exiting TearDown";
}
protected:
bool LaunchApprtcInstanceOnLocalhost(const std::string& port) {
base::FilePath appengine_dev_appserver =
GetSourceDir().Append(
FILE_PATH_LITERAL("../google_appengine/dev_appserver.py"));
if (!base::PathExists(appengine_dev_appserver)) {
LOG(ERROR) << "Missing appengine sdk at " <<
appengine_dev_appserver.value() << ". " << kAdviseOnGclientSolution;
return false;
}
base::FilePath apprtc_dir =
GetSourceDir().Append(FILE_PATH_LITERAL("out/apprtc/out/app_engine"));
if (!base::PathExists(apprtc_dir)) {
LOG(ERROR) << "Missing AppRTC AppEngine app at " <<
apprtc_dir.value() << ". " << kAdviseOnGclientSolution;
return false;
}
if (!base::PathExists(apprtc_dir.Append(FILE_PATH_LITERAL("app.yaml")))) {
LOG(ERROR) << "The AppRTC AppEngine app at " <<
apprtc_dir.value() << " appears to have not been built." <<
"This should have been done by webrtc.DEPS scripts which invoke " <<
"'grunt build' on AppRTC.";
return false;
}
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
EXPECT_TRUE(GetPythonCommand(&command_line));
command_line.AppendArgPath(appengine_dev_appserver);
command_line.AppendArgPath(apprtc_dir);
command_line.AppendArg("--port=" + port);
command_line.AppendArg("--admin_port=9998");
command_line.AppendArg("--skip_sdk_update_check");
command_line.AppendArg("--clear_datastore=yes");
DVLOG(1) << "Running " << command_line.GetCommandLineString();
dev_appserver_ = base::LaunchProcess(command_line, base::LaunchOptions());
return dev_appserver_.IsValid();
}
bool LaunchColliderOnLocalHost(const std::string& apprtc_url,
const std::string& collider_port) {
// The go workspace should be created, and collidermain built, at the
// runhooks stage when webrtc.DEPS/build_apprtc_collider.py runs.
#if defined(OS_WIN)
base::FilePath collider_server = GetSourceDir().Append(
FILE_PATH_LITERAL("out/go-workspace/bin/collidermain.exe"));
#else
base::FilePath collider_server = GetSourceDir().Append(
FILE_PATH_LITERAL("out/go-workspace/bin/collidermain"));
#endif
if (!base::PathExists(collider_server)) {
LOG(ERROR) << "Missing Collider server binary at " <<
collider_server.value() << ". " << kAdviseOnGclientSolution;
return false;
}
base::CommandLine command_line(collider_server);
command_line.AppendArg("-tls=false");
command_line.AppendArg("-port=" + collider_port);
command_line.AppendArg("-room-server=" + apprtc_url);
DVLOG(1) << "Running " << command_line.GetCommandLineString();
collider_server_ = base::LaunchProcess(command_line, base::LaunchOptions());
return collider_server_.IsValid();
}
bool LocalApprtcInstanceIsUp() {
// Load the admin page and see if we manage to load it right.
ui_test_utils::NavigateToURL(browser(), GURL("localhost:9998"));
content::WebContents* tab_contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::string javascript =
"window.domAutomationController.send(document.title)";
std::string result;
if (!content::ExecuteScriptAndExtractString(tab_contents, javascript,
&result))
return false;
return result == kTitlePageOfAppEngineAdminPage;
}
bool WaitForCallToComeUp(content::WebContents* tab_contents) {
return test::PollingWaitUntil(kIsApprtcCallUpJavascript, "true",
tab_contents);
}
bool EvalInJavascriptFile(content::WebContents* tab_contents,
const base::FilePath& path) {
std::string javascript;
if (!ReadFileToString(path, &javascript)) {
LOG(ERROR) << "Missing javascript code at " << path.value() << ".";
return false;
}
if (!content::ExecuteScript(tab_contents, javascript)) {
LOG(ERROR) << "Failed to execute the following javascript: " <<
javascript;
return false;
}
return true;
}
bool DetectRemoteVideoPlaying(content::WebContents* tab_contents) {
if (!EvalInJavascriptFile(tab_contents, GetSourceDir().Append(
FILE_PATH_LITERAL("chrome/test/data/webrtc/test_functions.js"))))
return false;
if (!EvalInJavascriptFile(tab_contents, GetSourceDir().Append(
FILE_PATH_LITERAL("chrome/test/data/webrtc/video_detector.js"))))
return false;
// The remote video tag is called remoteVideo in the AppRTC code.
StartDetectingVideo(tab_contents, "remote-video");
WaitForVideoToPlay(tab_contents);
return true;
}
base::FilePath GetSourceDir() {
base::FilePath source_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &source_dir);
return source_dir;
}
bool LaunchFirefoxWithUrl(const GURL& url) {
base::FilePath firefox_binary =
GetSourceDir().Append(
FILE_PATH_LITERAL("../firefox-nightly/firefox/firefox"));
if (!base::PathExists(firefox_binary)) {
LOG(ERROR) << "Missing firefox binary at " <<
firefox_binary.value() << ". " << kAdviseOnGclientSolution;
return false;
}
base::FilePath firefox_launcher =
GetSourceDir().Append(
FILE_PATH_LITERAL("../webrtc.DEPS/run_firefox_webrtc.py"));
if (!base::PathExists(firefox_launcher)) {
LOG(ERROR) << "Missing firefox launcher at " <<
firefox_launcher.value() << ". " << kAdviseOnGclientSolution;
return false;
}
base::CommandLine command_line(firefox_launcher);
command_line.AppendSwitchPath("--binary", firefox_binary);
command_line.AppendSwitchASCII("--webpage", url.spec());
DVLOG(1) << "Running " << command_line.GetCommandLineString();
firefox_ = base::LaunchProcess(command_line, base::LaunchOptions());
return firefox_.IsValid();
}
private:
base::Process dev_appserver_;
base::Process firefox_;
base::Process collider_server_;
};
// Disabling while the AppRTC application is being fixed.
// See crbug.com/467471 for details.
IN_PROC_BROWSER_TEST_F(WebRtcApprtcBrowserTest, DISABLED_MANUAL_WorksOnApprtc) {
// Disabled on Win XP: http://code.google.com/p/webrtc/issues/detail?id=2703.
if (OnWinXp())
return;
DetectErrorsInJavaScript();
ASSERT_TRUE(LaunchApprtcInstanceOnLocalhost("9999"));
ASSERT_TRUE(LaunchColliderOnLocalHost("http://localhost:9999", "8089"));
while (!LocalApprtcInstanceIsUp())
DVLOG(1) << "Waiting for AppRTC to come up...";
GURL room_url = GURL("http://localhost:9999/r/some_room"
"?wshpp=localhost:8089&wstls=false");
chrome::AddTabAt(browser(), GURL(), -1, true);
content::WebContents* left_tab = OpenPageAndAcceptUserMedia(room_url);
chrome::AddTabAt(browser(), GURL(), -1, true);
content::WebContents* right_tab = OpenPageAndAcceptUserMedia(room_url);
ASSERT_TRUE(WaitForCallToComeUp(left_tab));
ASSERT_TRUE(WaitForCallToComeUp(right_tab));
ASSERT_TRUE(DetectRemoteVideoPlaying(left_tab));
ASSERT_TRUE(DetectRemoteVideoPlaying(right_tab));
chrome::CloseWebContents(browser(), left_tab, false);
chrome::CloseWebContents(browser(), right_tab, false);
}
#if defined(OS_LINUX)
// Disabling while the AppRTC application is being fixed.
// See crbug.com/467471 for details.
#define MAYBE_MANUAL_FirefoxApprtcInteropTest DISABLED_MANUAL_FirefoxApprtcInteropTest
#else
// Not implemented yet on Windows and Mac.
#define MAYBE_MANUAL_FirefoxApprtcInteropTest DISABLED_MANUAL_FirefoxApprtcInteropTest
#endif
IN_PROC_BROWSER_TEST_F(WebRtcApprtcBrowserTest,
MAYBE_MANUAL_FirefoxApprtcInteropTest) {
// Disabled on Win XP: http://code.google.com/p/webrtc/issues/detail?id=2703.
if (OnWinXp())
return;
DetectErrorsInJavaScript();
ASSERT_TRUE(LaunchApprtcInstanceOnLocalhost("9999"));
ASSERT_TRUE(LaunchColliderOnLocalHost("http://localhost:9999", "8089"));
while (!LocalApprtcInstanceIsUp())
DVLOG(1) << "Waiting for AppRTC to come up...";
GURL room_url = GURL("http://localhost:9999/r/some_room"
"?wshpp=localhost:8089&wstls=false"
"&firefox_fake_device=1");
content::WebContents* chrome_tab = OpenPageAndAcceptUserMedia(room_url);
ASSERT_TRUE(LaunchFirefoxWithUrl(room_url));
ASSERT_TRUE(WaitForCallToComeUp(chrome_tab));
// Ensure Firefox manages to send video our way.
ASSERT_TRUE(DetectRemoteVideoPlaying(chrome_tab));
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/files/file_enumerator.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/rand_util.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/test/browser_test_utils.h"
#include "media/base/media_switches.h"
#include "net/test/python_utils.h"
#include "ui/gl/gl_switches.h"
// You need this solution to run this test. The solution will download appengine
// and the apprtc code for you.
const char kAdviseOnGclientSolution[] =
"You need to add this solution to your .gclient to run this test:\n"
"{\n"
" \"name\" : \"webrtc.DEPS\",\n"
" \"url\" : \"https://chromium.googlesource.com/chromium/deps/"
"webrtc/webrtc.DEPS\",\n"
"}";
const char kTitlePageOfAppEngineAdminPage[] = "Instances";
const char kIsApprtcCallUpJavascript[] =
"var remoteVideo = document.querySelector('#remote-video');"
"var remoteVideoActive ="
" remoteVideo != null &&"
" remoteVideo.classList.contains('active');"
"window.domAutomationController.send(remoteVideoActive.toString());";
// WebRTC-AppRTC integration test. Requires a real webcam and microphone
// on the running system. This test is not meant to run in the main browser
// test suite since normal tester machines do not have webcams. Chrome will use
// its fake camera for both tests, but Firefox will use the real webcam in the
// Firefox interop test. Thus, this test must on a machine with a real webcam.
//
// This test will bring up a AppRTC instance on localhost and verify that the
// call gets up when connecting to the same room from two tabs in a browser.
class WebRtcApprtcBrowserTest : public WebRtcTestBase {
public:
WebRtcApprtcBrowserTest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream));
// The video playback will not work without a GPU, so force its use here.
command_line->AppendSwitch(switches::kUseGpuInTests);
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
}
void TearDown() override {
// Kill any processes we may have brought up. Note: this isn't perfect,
// especially if the test hangs or if we're on Windows.
LOG(INFO) << "Entering TearDown";
if (dev_appserver_.IsValid())
dev_appserver_.Terminate(0, false);
if (collider_server_.IsValid())
collider_server_.Terminate(0, false);
if (firefox_.IsValid())
firefox_.Terminate(0, false);
LOG(INFO) << "Exiting TearDown";
}
protected:
bool LaunchApprtcInstanceOnLocalhost(const std::string& port) {
base::FilePath appengine_dev_appserver =
GetSourceDir().Append(
FILE_PATH_LITERAL("../google_appengine/dev_appserver.py"));
if (!base::PathExists(appengine_dev_appserver)) {
LOG(ERROR) << "Missing appengine sdk at " <<
appengine_dev_appserver.value() << ". " << kAdviseOnGclientSolution;
return false;
}
base::FilePath apprtc_dir =
GetSourceDir().Append(FILE_PATH_LITERAL("out/apprtc/out/app_engine"));
if (!base::PathExists(apprtc_dir)) {
LOG(ERROR) << "Missing AppRTC AppEngine app at " <<
apprtc_dir.value() << ". " << kAdviseOnGclientSolution;
return false;
}
if (!base::PathExists(apprtc_dir.Append(FILE_PATH_LITERAL("app.yaml")))) {
LOG(ERROR) << "The AppRTC AppEngine app at " <<
apprtc_dir.value() << " appears to have not been built." <<
"This should have been done by webrtc.DEPS scripts which invoke " <<
"'grunt build' on AppRTC.";
return false;
}
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
EXPECT_TRUE(GetPythonCommand(&command_line));
command_line.AppendArgPath(appengine_dev_appserver);
command_line.AppendArgPath(apprtc_dir);
command_line.AppendArg("--port=" + port);
command_line.AppendArg("--admin_port=9998");
command_line.AppendArg("--skip_sdk_update_check");
command_line.AppendArg("--clear_datastore=yes");
DVLOG(1) << "Running " << command_line.GetCommandLineString();
dev_appserver_ = base::LaunchProcess(command_line, base::LaunchOptions());
return dev_appserver_.IsValid();
}
bool LaunchColliderOnLocalHost(const std::string& apprtc_url,
const std::string& collider_port) {
// The go workspace should be created, and collidermain built, at the
// runhooks stage when webrtc.DEPS/build_apprtc_collider.py runs.
#if defined(OS_WIN)
base::FilePath collider_server = GetSourceDir().Append(
FILE_PATH_LITERAL("out/go-workspace/bin/collidermain.exe"));
#else
base::FilePath collider_server = GetSourceDir().Append(
FILE_PATH_LITERAL("out/go-workspace/bin/collidermain"));
#endif
if (!base::PathExists(collider_server)) {
LOG(ERROR) << "Missing Collider server binary at " <<
collider_server.value() << ". " << kAdviseOnGclientSolution;
return false;
}
base::CommandLine command_line(collider_server);
command_line.AppendArg("-tls=false");
command_line.AppendArg("-port=" + collider_port);
command_line.AppendArg("-room-server=" + apprtc_url);
DVLOG(1) << "Running " << command_line.GetCommandLineString();
collider_server_ = base::LaunchProcess(command_line, base::LaunchOptions());
return collider_server_.IsValid();
}
bool LocalApprtcInstanceIsUp() {
// Load the admin page and see if we manage to load it right.
ui_test_utils::NavigateToURL(browser(), GURL("localhost:9998"));
content::WebContents* tab_contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::string javascript =
"window.domAutomationController.send(document.title)";
std::string result;
if (!content::ExecuteScriptAndExtractString(tab_contents, javascript,
&result))
return false;
return result == kTitlePageOfAppEngineAdminPage;
}
bool WaitForCallToComeUp(content::WebContents* tab_contents) {
return test::PollingWaitUntil(kIsApprtcCallUpJavascript, "true",
tab_contents);
}
bool EvalInJavascriptFile(content::WebContents* tab_contents,
const base::FilePath& path) {
std::string javascript;
if (!ReadFileToString(path, &javascript)) {
LOG(ERROR) << "Missing javascript code at " << path.value() << ".";
return false;
}
if (!content::ExecuteScript(tab_contents, javascript)) {
LOG(ERROR) << "Failed to execute the following javascript: " <<
javascript;
return false;
}
return true;
}
bool DetectRemoteVideoPlaying(content::WebContents* tab_contents) {
if (!EvalInJavascriptFile(tab_contents, GetSourceDir().Append(
FILE_PATH_LITERAL("chrome/test/data/webrtc/test_functions.js"))))
return false;
if (!EvalInJavascriptFile(tab_contents, GetSourceDir().Append(
FILE_PATH_LITERAL("chrome/test/data/webrtc/video_detector.js"))))
return false;
// The remote video tag is called remoteVideo in the AppRTC code.
StartDetectingVideo(tab_contents, "remote-video");
WaitForVideoToPlay(tab_contents);
return true;
}
base::FilePath GetSourceDir() {
base::FilePath source_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &source_dir);
return source_dir;
}
bool LaunchFirefoxWithUrl(const GURL& url) {
base::FilePath firefox_binary =
GetSourceDir().Append(
FILE_PATH_LITERAL("../firefox-nightly/firefox/firefox"));
if (!base::PathExists(firefox_binary)) {
LOG(ERROR) << "Missing firefox binary at " <<
firefox_binary.value() << ". " << kAdviseOnGclientSolution;
return false;
}
base::FilePath firefox_launcher =
GetSourceDir().Append(
FILE_PATH_LITERAL("../webrtc.DEPS/run_firefox_webrtc.py"));
if (!base::PathExists(firefox_launcher)) {
LOG(ERROR) << "Missing firefox launcher at " <<
firefox_launcher.value() << ". " << kAdviseOnGclientSolution;
return false;
}
base::CommandLine command_line(firefox_launcher);
command_line.AppendSwitchPath("--binary", firefox_binary);
command_line.AppendSwitchASCII("--webpage", url.spec());
DVLOG(1) << "Running " << command_line.GetCommandLineString();
firefox_ = base::LaunchProcess(command_line, base::LaunchOptions());
return firefox_.IsValid();
}
private:
base::Process dev_appserver_;
base::Process firefox_;
base::Process collider_server_;
};
IN_PROC_BROWSER_TEST_F(WebRtcApprtcBrowserTest, MANUAL_WorksOnApprtc) {
// Disabled on Win XP: http://code.google.com/p/webrtc/issues/detail?id=2703.
if (OnWinXp())
return;
DetectErrorsInJavaScript();
ASSERT_TRUE(LaunchApprtcInstanceOnLocalhost("9999"));
ASSERT_TRUE(LaunchColliderOnLocalHost("http://localhost:9999", "8089"));
while (!LocalApprtcInstanceIsUp())
DVLOG(1) << "Waiting for AppRTC to come up...";
GURL room_url = GURL("http://localhost:9999/r/some_room"
"?wshpp=localhost:8089&wstls=false");
chrome::AddTabAt(browser(), GURL(), -1, true);
content::WebContents* left_tab = OpenPageAndAcceptUserMedia(room_url);
chrome::AddTabAt(browser(), GURL(), -1, true);
content::WebContents* right_tab = OpenPageAndAcceptUserMedia(room_url);
ASSERT_TRUE(WaitForCallToComeUp(left_tab));
ASSERT_TRUE(WaitForCallToComeUp(right_tab));
ASSERT_TRUE(DetectRemoteVideoPlaying(left_tab));
ASSERT_TRUE(DetectRemoteVideoPlaying(right_tab));
chrome::CloseWebContents(browser(), left_tab, false);
chrome::CloseWebContents(browser(), right_tab, false);
}
#if defined(OS_LINUX)
#define MAYBE_MANUAL_FirefoxApprtcInteropTest MANUAL_FirefoxApprtcInteropTest
#else
// Not implemented yet on Windows and Mac.
#define MAYBE_MANUAL_FirefoxApprtcInteropTest DISABLED_MANUAL_FirefoxApprtcInteropTest
#endif
IN_PROC_BROWSER_TEST_F(WebRtcApprtcBrowserTest,
MAYBE_MANUAL_FirefoxApprtcInteropTest) {
// Disabled on Win XP: http://code.google.com/p/webrtc/issues/detail?id=2703.
if (OnWinXp())
return;
DetectErrorsInJavaScript();
ASSERT_TRUE(LaunchApprtcInstanceOnLocalhost("9999"));
ASSERT_TRUE(LaunchColliderOnLocalHost("http://localhost:9999", "8089"));
while (!LocalApprtcInstanceIsUp())
DVLOG(1) << "Waiting for AppRTC to come up...";
GURL room_url = GURL("http://localhost:9999/r/some_room"
"?wshpp=localhost:8089&wstls=false"
"&firefox_fake_device=1");
content::WebContents* chrome_tab = OpenPageAndAcceptUserMedia(room_url);
ASSERT_TRUE(LaunchFirefoxWithUrl(room_url));
ASSERT_TRUE(WaitForCallToComeUp(chrome_tab));
// Ensure Firefox manages to send video our way.
ASSERT_TRUE(DetectRemoteVideoPlaying(chrome_tab));
}
|
Revert of Disabling failing tests in WebRtcApprtcBrowserTest (patchset #2 id:20001 of https://codereview.chromium.org/1016693002/)
|
Revert of Disabling failing tests in WebRtcApprtcBrowserTest (patchset #2 id:20001 of https://codereview.chromium.org/1016693002/)
Reason for revert:
We have landed an update to the AppRTC app in https://codereview.chromium.org/1023683002/ now, so these tests should now work.
Original issue's description:
> Disabling failing tests in WebRtcApprtcBrowserTest.
>
> These tests will be enabled again once the AppRTC app is working again which we expect will happen rather soon.
>
> TBR=phoglund
> BUG=467471
>
> Committed: https://crrev.com/15103a5ff0f262c85309d4b6af957d7c089aab3d
> Cr-Commit-Position: refs/heads/master@{#320883}
[email protected],[email protected]
NOPRESUBMIT=true
NOTREECHECKS=true
NOTRY=true
BUG=467471
Review URL: https://codereview.chromium.org/1027673002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#321527}
|
C++
|
bsd-3-clause
|
ltilve/chromium,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,ltilve/chromium,axinging/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk
|
7ee5fa09b8f4d0b612fa39c4b6e9c6dcf2f2728e
|
chrome/browser/sync/glue/preference_change_processor.cc
|
chrome/browser/sync/glue/preference_change_processor.cc
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/preference_change_processor.h"
#include <set>
#include <string>
#include "base/json/json_reader.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/glue/preference_model_associator.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/protocol/preference_specifics.pb.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
namespace browser_sync {
PreferenceChangeProcessor::PreferenceChangeProcessor(
PreferenceModelAssociator* model_associator,
UnrecoverableErrorHandler* error_handler)
: ChangeProcessor(error_handler),
pref_service_(NULL),
model_associator_(model_associator) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
DCHECK(model_associator);
DCHECK(error_handler);
}
PreferenceChangeProcessor::~PreferenceChangeProcessor(){
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
}
void PreferenceChangeProcessor::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
DCHECK(running());
DCHECK(NotificationType::PREF_CHANGED == type);
DCHECK_EQ(pref_service_, Source<PrefService>(source).ptr());
std::wstring* name = Details<std::wstring>(details).ptr();
const PrefService::Preference* preference =
pref_service_->FindPreference((*name).c_str());
DCHECK(preference);
sync_api::WriteTransaction trans(share_handle());
sync_api::WriteNode node(&trans);
int64 sync_id = model_associator_->GetSyncIdFromChromeId(*name);
if (sync_api::kInvalidId == sync_id) {
LOG(ERROR) << "Unexpected notification for: " << *name;
error_handler()->OnUnrecoverableError();
return;
} else {
if (!node.InitByIdLookup(sync_id)) {
LOG(ERROR) << "Preference node lookup failed.";
error_handler()->OnUnrecoverableError();
return;
}
}
if (!WritePreference(&node, *name, preference->GetValue())) {
LOG(ERROR) << "Failed to update preference node.";
error_handler()->OnUnrecoverableError();
return;
}
}
void PreferenceChangeProcessor::ApplyChangesFromSyncModel(
const sync_api::BaseTransaction* trans,
const sync_api::SyncManager::ChangeRecord* changes,
int change_count) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (!running())
return;
StopObserving();
for (int i = 0; i < change_count; ++i) {
sync_api::ReadNode node(trans);
// TODO(ncarter): Can't look up the name for deletions: lookup of
// deleted items fails at the syncapi layer. However, the node should
// generally still exist in the syncable database; we just need to
// plumb the syncapi so that it succeeds.
if (sync_api::SyncManager::ChangeRecord::ACTION_DELETE ==
changes[i].action) {
// Until the above is fixed, we have no choice but to ignore deletions.
LOG(ERROR) << "No way to handle pref deletion";
continue;
}
if (!node.InitByIdLookup(changes[i].id)) {
LOG(ERROR) << "Preference node lookup failed.";
error_handler()->OnUnrecoverableError();
return;
}
DCHECK(syncable::PREFERENCES == node.GetModelType());
std::string name;
scoped_ptr<Value> value(ReadPreference(&node, &name));
if (sync_api::SyncManager::ChangeRecord::ACTION_DELETE ==
changes[i].action) {
pref_service_->ClearPref(UTF8ToWide(name).c_str());
} else {
const PrefService::Preference* preference =
pref_service_->FindPreference(UTF8ToWide(name).c_str());
if (value.get() && preference) {
pref_service_->Set(UTF8ToWide(name).c_str(), *value);
}
}
}
StartObserving();
}
bool PreferenceChangeProcessor::WritePreference(
sync_api::WriteNode* node,
const std::wstring& name,
const Value* value) {
std::string serialized;
JSONStringValueSerializer json(&serialized);
if (!json.Serialize(*value)) {
LOG(ERROR) << "Failed to serialize preference value.";
error_handler()->OnUnrecoverableError();
return false;
}
sync_pb::PreferenceSpecifics preference;
preference.set_name(WideToUTF8(name));
preference.set_value(serialized);
node->SetPreferenceSpecifics(preference);
node->SetTitle(name);
return true;
}
Value* PreferenceChangeProcessor::ReadPreference(
sync_api::ReadNode* node,
std::string* name) {
const sync_pb::PreferenceSpecifics& preference(
node->GetPreferenceSpecifics());
base::JSONReader reader;
scoped_ptr<Value> value(reader.JsonToValue(preference.value(), false, false));
if (!value.get()) {
LOG(ERROR) << "Failed to deserialize preference value: "
<< reader.error_message();
error_handler()->OnUnrecoverableError();
return NULL;
}
*name = preference.name();
return value.release();
}
void PreferenceChangeProcessor::StartImpl(Profile* profile) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
pref_service_ = profile->GetPrefs();
StartObserving();
}
void PreferenceChangeProcessor::StopImpl() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
StopObserving();
pref_service_ = NULL;
}
void PreferenceChangeProcessor::StartObserving() {
DCHECK(pref_service_);
for (std::set<std::wstring>::const_iterator it =
model_associator_->synced_preferences().begin();
it != model_associator_->synced_preferences().end(); ++it) {
pref_service_->AddPrefObserver((*it).c_str(), this);
}
}
void PreferenceChangeProcessor::StopObserving() {
DCHECK(pref_service_);
for (std::set<std::wstring>::const_iterator it =
model_associator_->synced_preferences().begin();
it != model_associator_->synced_preferences().end(); ++it) {
pref_service_->RemovePrefObserver((*it).c_str(), this);
}
}
} // namespace browser_sync
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/preference_change_processor.h"
#include <set>
#include <string>
#include "base/json/json_reader.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/glue/preference_model_associator.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/protocol/preference_specifics.pb.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
namespace browser_sync {
PreferenceChangeProcessor::PreferenceChangeProcessor(
PreferenceModelAssociator* model_associator,
UnrecoverableErrorHandler* error_handler)
: ChangeProcessor(error_handler),
pref_service_(NULL),
model_associator_(model_associator) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
DCHECK(model_associator);
DCHECK(error_handler);
}
PreferenceChangeProcessor::~PreferenceChangeProcessor(){
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
}
void PreferenceChangeProcessor::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
DCHECK(running());
DCHECK(NotificationType::PREF_CHANGED == type);
DCHECK_EQ(pref_service_, Source<PrefService>(source).ptr());
std::wstring* name = Details<std::wstring>(details).ptr();
const PrefService::Preference* preference =
pref_service_->FindPreference((*name).c_str());
DCHECK(preference);
sync_api::WriteTransaction trans(share_handle());
sync_api::WriteNode node(&trans);
int64 sync_id = model_associator_->GetSyncIdFromChromeId(*name);
if (sync_api::kInvalidId == sync_id) {
LOG(ERROR) << "Unexpected notification for: " << *name;
error_handler()->OnUnrecoverableError();
return;
} else {
if (!node.InitByIdLookup(sync_id)) {
LOG(ERROR) << "Preference node lookup failed.";
error_handler()->OnUnrecoverableError();
return;
}
}
if (!WritePreference(&node, *name, preference->GetValue())) {
LOG(ERROR) << "Failed to update preference node.";
error_handler()->OnUnrecoverableError();
return;
}
}
void PreferenceChangeProcessor::ApplyChangesFromSyncModel(
const sync_api::BaseTransaction* trans,
const sync_api::SyncManager::ChangeRecord* changes,
int change_count) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (!running())
return;
StopObserving();
for (int i = 0; i < change_count; ++i) {
sync_api::ReadNode node(trans);
// TODO(ncarter): Can't look up the name for deletions: lookup of
// deleted items fails at the syncapi layer. However, the node should
// generally still exist in the syncable database; we just need to
// plumb the syncapi so that it succeeds.
if (sync_api::SyncManager::ChangeRecord::ACTION_DELETE ==
changes[i].action) {
// Until the above is fixed, we have no choice but to ignore deletions.
LOG(ERROR) << "No way to handle pref deletion";
continue;
}
if (!node.InitByIdLookup(changes[i].id)) {
LOG(ERROR) << "Preference node lookup failed.";
error_handler()->OnUnrecoverableError();
return;
}
DCHECK(syncable::PREFERENCES == node.GetModelType());
std::string name;
scoped_ptr<Value> value(ReadPreference(&node, &name));
if (sync_api::SyncManager::ChangeRecord::ACTION_DELETE ==
changes[i].action) {
pref_service_->ClearPref(UTF8ToWide(name).c_str());
} else {
std::wstring pref_name(UTF8ToWide(name));
const PrefService::Preference* preference =
pref_service_->FindPreference(pref_name.c_str());
if (value.get() && preference) {
pref_service_->Set(pref_name.c_str(), *value);
if (pref_name == prefs::kShowBookmarkBar) {
// If it was the bookmark bar, send an additional notification.
NotificationService::current()->Notify(
NotificationType::BOOKMARK_BAR_VISIBILITY_PREF_CHANGED,
Source<PreferenceChangeProcessor>(this),
NotificationService::NoDetails());
}
}
}
}
StartObserving();
}
bool PreferenceChangeProcessor::WritePreference(
sync_api::WriteNode* node,
const std::wstring& name,
const Value* value) {
std::string serialized;
JSONStringValueSerializer json(&serialized);
if (!json.Serialize(*value)) {
LOG(ERROR) << "Failed to serialize preference value.";
error_handler()->OnUnrecoverableError();
return false;
}
sync_pb::PreferenceSpecifics preference;
preference.set_name(WideToUTF8(name));
preference.set_value(serialized);
node->SetPreferenceSpecifics(preference);
node->SetTitle(name);
return true;
}
Value* PreferenceChangeProcessor::ReadPreference(
sync_api::ReadNode* node,
std::string* name) {
const sync_pb::PreferenceSpecifics& preference(
node->GetPreferenceSpecifics());
base::JSONReader reader;
scoped_ptr<Value> value(reader.JsonToValue(preference.value(), false, false));
if (!value.get()) {
LOG(ERROR) << "Failed to deserialize preference value: "
<< reader.error_message();
error_handler()->OnUnrecoverableError();
return NULL;
}
*name = preference.name();
return value.release();
}
void PreferenceChangeProcessor::StartImpl(Profile* profile) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
pref_service_ = profile->GetPrefs();
StartObserving();
}
void PreferenceChangeProcessor::StopImpl() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
StopObserving();
pref_service_ = NULL;
}
void PreferenceChangeProcessor::StartObserving() {
DCHECK(pref_service_);
for (std::set<std::wstring>::const_iterator it =
model_associator_->synced_preferences().begin();
it != model_associator_->synced_preferences().end(); ++it) {
pref_service_->AddPrefObserver((*it).c_str(), this);
}
}
void PreferenceChangeProcessor::StopObserving() {
DCHECK(pref_service_);
for (std::set<std::wstring>::const_iterator it =
model_associator_->synced_preferences().begin();
it != model_associator_->synced_preferences().end(); ++it) {
pref_service_->RemovePrefObserver((*it).c_str(), this);
}
}
} // namespace browser_sync
|
Send out a notification when the bookmark bar changes.
|
Send out a notification when the bookmark bar changes.
BUG=38559
TEST=Turn on preference sync. Run two chromes. Press ctrl+b on one. Ensure that the bookmark bar changes on the other.
Review URL: http://codereview.chromium.org/1589007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@43273 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ropik/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium
|
a5b2f69869fa97e3befcaad94829496c9daa8f7d
|
examples/accel/OpenCLcontext.cpp
|
examples/accel/OpenCLcontext.cpp
|
#define CL_USE_DEPRECATED_OPENCL_1_1_APIS
#undef CL_HPP_ENABLE_EXCEPTIONS
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#define CL_HPP_TARGET_OPENCL_VERSION 120
#include <CL/cl2.hpp>
#include <string>
#include <vector>
#include <deque>
#include <chrono>
#include <mutex>
#include <cmath>
#include <condition_variable>
#include <map>
#include <set>
#include <thread>
#include <unordered_map>
#include "OpenCLcontext.h"
static const char *PX_COUNT_SOURCE = R"(
#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
__kernel void process_frame(global const uchar4 *input, global ulong* output) {
size_t x = get_global_id(0);
size_t y = get_global_id(1);
size_t width = get_global_size(0);
size_t height = get_global_size(1);
uchar4 px = input[y * width + x];
if (px.x > 100)
atom_add(output, 1);
}
)";
static const char *DOWNSAMPLE_SOURCE = R"(
#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
__kernel void downsample_image(global const uchar4 *input, global uchar4* output) {
size_t x = get_global_id(0);
size_t y = get_global_id(1);
size_t width = get_global_size(0);
size_t height = get_global_size(1);
/*
uint4 sum = input[y * width + x]
+ input[y * width + x + 1]
+ input[(y+1) * width + x]
+ input[(y+1) * width + x + 1];
output[y * (width/2) + x] = convert_uchar4(sum / 4);
*/
unsigned out_idx = y + x*width;
const unsigned factor = 2;
width *= factor;
height *= factor;
unsigned y1, y2, x1, x2;
y1=y*factor;
y2=y1+1;
x1=x*factor;
x2=x1+1;
uchar4 q11, q12, q21, q22;
q11 = input[y1 * width + x1];
q12 = input[y1 * width + x2];
q21 = input[y2 * width + x1];
q22 = input[y2 * width + x2];
uint4 sum = convert_uint4(q11) + convert_uint4(q12) + convert_uint4(q21) + convert_uint4(q22);
output[out_idx] = convert_uchar4(sum/4);
}
)";
#define OUTPUT_SIZE (cl::size_type)(sizeof(unsigned long)*64)
#define LOG_I(...)
#define LOG_D(...)
#define LOG_E(...)
#define CHECK_CL_ERROR(EXPR, ...) \
if (EXPR != CL_SUCCESS) { LOG_E(__VA_ARGS__); return false; }
class OpenCL_Context {
cl::Platform platform;
std::vector<cl::Device> devices;
cl::Context ClContext;
cl::Device GpuDev;
cl::CommandQueue GpuQueue;
cl::Program GpuProgram;
cl::Kernel GpuKernel;
cl::Device FpgaDev;
cl::CommandQueue FpgaQueue;
cl::Program FpgaProgram;
cl::Kernel FpgaKernel;
cl::Buffer GpuInputBuffer, InterBuffer, FpgaOutputBuffer;
unsigned long InputBufferSize;
std::mutex OclMutex;
cl::NDRange Offset, Global, Local;
bool initialized = false;
unsigned imgID = 0;
public:
OpenCL_Context() {};
bool isAvailable() {
std::unique_lock<std::mutex> lock(OclMutex);
if (!initialized)
return false;
if (GpuDev() == nullptr || FpgaDev() == nullptr)
return false;
// bool avail = GpuDev.getInfo<CL_DEVICE_AVAILABLE>() != CL_FALSE;
// return avail;
return true;
}
~OpenCL_Context() {
if (isAvailable())
shutdown();
}
bool initialize(unsigned width, unsigned height, unsigned bpp);
bool processCameraFrame(unsigned char* input, unsigned long *output);
private:
void shutdown();
};
bool OpenCL_Manager::initialize(unsigned width, unsigned height, unsigned bpp) {
if (Context->initialize(width, height, bpp))
isValid = true;
else {
LOG_E("Error in OpenCL->initialize\n");
isValid = false;
}
return isValid;
}
bool OpenCL_Manager::processCameraFrame(unsigned char* input, unsigned long *output) {
if (isValid) {
if (!Context->processCameraFrame(input, output)) {
LOG_E("Error in OpenCL->processCameraFrame\n");
isValid = false;
}
}
if (!isValid)
*output = 11223344;
return isValid;
}
OpenCL_Manager::OpenCL_Manager() : Context{std::make_unique<OpenCL_Context>()} {}
OpenCL_Manager::~OpenCL_Manager() {}
bool OpenCL_Context::initialize(unsigned width, unsigned height, unsigned bpp)
{
cl_int err;
InputBufferSize = width * height * bpp / 8;
// Take first platform and create a context for it.
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()) {
LOG_E("No OpenCL platforms available!\n");
return false;
}
platform = all_platforms[0];
Offset = cl::NullRange;
unsigned local_h = (height % 2) ? 1 : 2;
local_h = (height % 4) ? local_h : 4;
local_h = (height % 8) ? local_h : 8;
local_h = (height % 16) ? local_h : 16;
unsigned local_w = (width % 2) ? 1 : 2;
local_w = (width % 4) ? local_w : 4;
local_w = (width % 8) ? local_w : 8;
local_w = (width % 16) ? local_w : 16;
Local = cl::NDRange(local_w/2, local_h/2);
Global = cl::NDRange(width/2, height/2);
// Find all devices.
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(devices.size() == 0) {
LOG_E("No OpenCL devices available!\n");
return false;
}
LOG_I("OpenCL platform name: %s\n", platform.getInfo<CL_PLATFORM_NAME>().c_str());
LOG_I("OpenCL platform version: %s\n", platform.getInfo<CL_PLATFORM_VERSION>().c_str());
LOG_I("OpenCL platform vendor: %s\n", platform.getInfo<CL_PLATFORM_VENDOR>().c_str());
LOG_I("Found %lu OpenCL devices.\n", devices.size());
void* ptr;
#ifdef ENABLE_COMPRESSION
clSetBufferCompressionPOCL_fn SetBufferComPOCL = nullptr;
ptr = clGetExtensionFunctionAddressForPlatform(platform(), "clSetBufferCompressionPOCL");
if (ptr)
SetBufferComPOCL = (clSetBufferCompressionPOCL_fn)ptr;
#endif
ptr = clGetExtensionFunctionAddressForPlatform(platform(), "clEnqueueReadBufferContentPOCL");
if (ptr == nullptr)
LOG_I("platform doesn't support clEnqueueReadBufferContentPOCL\n");
else
if (devices.size() == 1) {
GpuDev = devices[0];
FpgaDev = devices[0];
} else if (devices[0].getInfo<CL_DEVICE_TYPE>() & CL_DEVICE_TYPE_GPU) {
GpuDev = devices[0];
FpgaDev = devices[1];
} else {
GpuDev = devices[1];
FpgaDev = devices[0];
}
ClContext = cl::Context(devices, nullptr, nullptr, nullptr, &err);
CHECK_CL_ERROR(err, "Context creation failed\n");
GpuQueue = cl::CommandQueue(ClContext, GpuDev, 0, &err); // , CL_QUEUE_PROFILING_ENABLE
CHECK_CL_ERROR(err, "CmdQueue creation failed\n");
if (devices.size() == 1)
FpgaQueue = GpuQueue;
else {
FpgaQueue = cl::CommandQueue(ClContext, FpgaDev, 0, &err); // , CL_QUEUE_PROFILING_ENABLE
CHECK_CL_ERROR(err, "CmdQueue creation failed\n");
}
std::vector<cl::Device> GpuDevs = {GpuDev};
GpuProgram = cl::Program{ClContext, DOWNSAMPLE_SOURCE, false, &err};
CHECK_CL_ERROR(err, "Program creation failed\n");
err = GpuProgram.build(GpuDevs);
CHECK_CL_ERROR(err, "Program build failed\n");
GpuKernel = cl::Kernel(GpuProgram, "downsample_image", &err);
CHECK_CL_ERROR(err, "Kernel creation failed\n");
std::string FpgaBuiltinKernels = FpgaDev.getInfo<CL_DEVICE_BUILT_IN_KERNELS>();
const std::string BuiltinKernelName{"pocl.countred"};
std::vector<cl::Device> FpgaDevs = {FpgaDev};
if (FpgaBuiltinKernels.find(BuiltinKernelName) != std::string::npos)
{
FpgaProgram = cl::Program{ClContext, FpgaDevs, BuiltinKernelName, &err};
CHECK_CL_ERROR(err, "Program creation failed\n");
}
else
{
FpgaProgram = cl::Program{ClContext, PX_COUNT_SOURCE, false, &err};
CHECK_CL_ERROR(err, "Program creation failed\n");
}
err = FpgaProgram.build(FpgaDevs);
CHECK_CL_ERROR(err, "Program build failed\n");
FpgaKernel = cl::Kernel(FpgaProgram, BuiltinKernelName.c_str(), &err);
CHECK_CL_ERROR(err, "Kernel creation failed\n");
GpuInputBuffer = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)(InputBufferSize), nullptr, &err);
CHECK_CL_ERROR(err, "Input buffer creation failed\n");
InterBuffer = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)(InputBufferSize/4), nullptr, &err);
CHECK_CL_ERROR(err, "Inter buffer creation failed\n");
FpgaOutputBuffer = cl::Buffer(ClContext, CL_MEM_READ_WRITE, OUTPUT_SIZE, nullptr, &err);
CHECK_CL_ERROR(err, "Output buffer creation failed\n");
#ifdef ENABLE_COMPRESSION
if (SetBufferComPOCL) {
int r = SetBufferComPOCL(InputBuffer(), CL_COMPRESSION_VBYTE, nullptr);
assert (r == CL_SUCCESS);
LOG_I ("Buffer compression VBYTE enabled\n");
}
#endif
GpuKernel.setArg(0, GpuInputBuffer);
GpuKernel.setArg(1, InterBuffer);
FpgaKernel.setArg(0, InterBuffer);
FpgaKernel.setArg(1, FpgaOutputBuffer);
initialized = true;
return true;
}
bool OpenCL_Context::processCameraFrame(unsigned char* input, unsigned long *output) {
if (!isAvailable()) {
LOG_E("Device not available");
return false;
}
std::unique_lock<std::mutex> lock(OclMutex);
#ifdef TIMING
LOG_D("OpenCL: start processCameraFrame\n");
auto start_time = std::chrono::steady_clock::now();
#endif
cl_int err;
*output = 0;
std::vector<cl::Event> evts;
cl::Event ev1, ev2, ev3, ev4;
err = GpuQueue.enqueueWriteBuffer(GpuInputBuffer, CL_FALSE, 0, InputBufferSize, input, nullptr, &ev1);
if (err != CL_SUCCESS)
return false;
evts.push_back(ev1);
err = GpuQueue.enqueueNDRangeKernel(GpuKernel, Offset, Global, Local, &evts, &ev2);
if (err != CL_SUCCESS)
return false;
err = FpgaQueue.enqueueWriteBuffer(FpgaOutputBuffer, CL_FALSE, 0, sizeof(cl_ulong), output, nullptr, &ev3);
if (err != CL_SUCCESS)
return false;
evts.clear();
evts.push_back(ev2);
evts.push_back(ev3);
err = FpgaQueue.enqueueNDRangeKernel(FpgaKernel, Offset, Global, Local, &evts, &ev4);
if (err != CL_SUCCESS)
return false;
evts.clear();
evts.push_back(ev4);
err = GpuQueue.enqueueReadBuffer(FpgaOutputBuffer, CL_TRUE, 0, sizeof(unsigned long), output, &evts);
if (err != CL_SUCCESS)
return false;
#ifdef DUMP_FRAMES
char filename[1024];
std::snprintf(filename, 1024, "/tmp/carla_%u_%zu.raw", imgID, *output);
FILE* outfile = std::fopen(filename, "w");
std::fwrite(input, 1, InputBufferSize, outfile);
std::fclose(outfile);
++imgID;
#endif
#ifdef TIMING
auto end_time = std::chrono::steady_clock::now();
std::chrono::duration<float> diff = end_time - start_time;
float s = diff.count() * 1000.0f;
LOG_D("OpenCL: end processCameraFrame: %03.1f ms\n", s);
#endif
return true;
}
void OpenCL_Context::shutdown() {
if (GpuQueue())
GpuQueue.finish();
}
|
#define CL_USE_DEPRECATED_OPENCL_1_1_APIS
#undef CL_HPP_ENABLE_EXCEPTIONS
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#define CL_HPP_TARGET_OPENCL_VERSION 120
#include <CL/cl2.hpp>
#include <string>
#include <vector>
#include <deque>
#include <chrono>
#include <mutex>
#include <cmath>
#include <condition_variable>
#include <map>
#include <set>
#include <thread>
#include <unordered_map>
#include "OpenCLcontext.h"
#ifdef LIBCARLA_INCLUDED_FROM_UE4
#include "carla/Debug.h"
#include "carla/Logging.h"
#endif
static const char *PX_COUNT_SOURCE = R"(
#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
__kernel void process_frame(global const uchar4 *input, global ulong* output) {
size_t x = get_global_id(0);
size_t y = get_global_id(1);
size_t width = get_global_size(0);
size_t height = get_global_size(1);
uchar4 px = input[y * width + x];
if (px.x > 100)
atom_add(output, 1);
}
)";
static const char *DOWNSAMPLE_SOURCE = R"(
#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
__kernel void downsample_image(global const uchar4 *input, global uchar4* output) {
size_t x = get_global_id(0);
size_t y = get_global_id(1);
size_t width = get_global_size(0);
size_t height = get_global_size(1);
/*
uint4 sum = input[y * width + x]
+ input[y * width + x + 1]
+ input[(y+1) * width + x]
+ input[(y+1) * width + x + 1];
output[y * (width/2) + x] = convert_uchar4(sum / 4);
*/
unsigned out_idx = y + x*width;
const unsigned factor = 2;
width *= factor;
height *= factor;
unsigned y1, y2, x1, x2;
y1=y*factor;
y2=y1+1;
x1=x*factor;
x2=x1+1;
uchar4 q11, q12, q21, q22;
q11 = input[y1 * width + x1];
q12 = input[y1 * width + x2];
q21 = input[y2 * width + x1];
q22 = input[y2 * width + x2];
uint4 sum = convert_uint4(q11) + convert_uint4(q12) + convert_uint4(q21) + convert_uint4(q22);
output[out_idx] = convert_uchar4(sum/4);
}
)";
#define OUTPUT_SIZE (cl::size_type)(sizeof(unsigned long)*64)
#ifdef LIBCARLA_INCLUDED_FROM_UE4
#define LOG_I(...) carla::log_info(__VA_ARGS__)
#define LOG_D(...) carla::log_debug(__VA_ARGS__)
#define LOG_E(...) carla::log_error(__VA_ARGS__)
#else
#define LOG_I(...)
#define LOG_D(...)
#define LOG_E(...)
#endif
#define CHECK_CL_ERROR(EXPR, ...) \
if (EXPR != CL_SUCCESS) { LOG_E(__VA_ARGS__); return false; }
class OpenCL_Context {
cl::Platform platform;
std::vector<cl::Device> devices;
cl::Context ClContext;
cl::Device GpuDev;
cl::CommandQueue GpuQueue;
cl::Program GpuProgram;
cl::Kernel GpuKernel;
cl::Device FpgaDev;
cl::CommandQueue FpgaQueue;
cl::Program FpgaProgram;
cl::Kernel FpgaKernel;
cl::Buffer GpuInputBuffer, InterBuffer, FpgaOutputBuffer;
unsigned long InputBufferSize;
std::mutex OclMutex;
cl::NDRange Offset, Global, Local;
bool initialized = false;
unsigned imgID = 0;
public:
OpenCL_Context() {};
bool isAvailable() {
std::unique_lock<std::mutex> lock(OclMutex);
if (!initialized)
return false;
if (GpuDev() == nullptr || FpgaDev() == nullptr)
return false;
// bool avail = GpuDev.getInfo<CL_DEVICE_AVAILABLE>() != CL_FALSE;
// return avail;
return true;
}
~OpenCL_Context() {
if (isAvailable())
shutdown();
}
bool initialize(unsigned width, unsigned height, unsigned bpp);
bool processCameraFrame(unsigned char* input, unsigned long *output);
private:
void shutdown();
};
bool OpenCL_Manager::initialize(unsigned width, unsigned height, unsigned bpp) {
if (Context->initialize(width, height, bpp))
isValid = true;
else {
LOG_E("Error in OpenCL->initialize\n");
isValid = false;
}
return isValid;
}
bool OpenCL_Manager::processCameraFrame(unsigned char* input, unsigned long *output) {
if (isValid) {
if (!Context->processCameraFrame(input, output)) {
LOG_E("Error in OpenCL->processCameraFrame\n");
isValid = false;
}
}
if (!isValid)
*output = 11223344;
return isValid;
}
OpenCL_Manager::OpenCL_Manager() : Context{std::make_unique<OpenCL_Context>()} {}
OpenCL_Manager::~OpenCL_Manager() {}
bool OpenCL_Context::initialize(unsigned width, unsigned height, unsigned bpp)
{
cl_int err;
InputBufferSize = width * height * bpp / 8;
// Take first platform and create a context for it.
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()) {
LOG_E("No OpenCL platforms available!\n");
return false;
}
platform = all_platforms[0];
Offset = cl::NullRange;
unsigned local_h = (height % 2) ? 1 : 2;
local_h = (height % 4) ? local_h : 4;
local_h = (height % 8) ? local_h : 8;
local_h = (height % 16) ? local_h : 16;
unsigned local_w = (width % 2) ? 1 : 2;
local_w = (width % 4) ? local_w : 4;
local_w = (width % 8) ? local_w : 8;
local_w = (width % 16) ? local_w : 16;
Local = cl::NDRange(local_w/2, local_h/2);
Global = cl::NDRange(width/2, height/2);
// Find all devices.
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(devices.size() == 0) {
LOG_E("No OpenCL devices available!\n");
return false;
}
LOG_I("OpenCL platform name: %s\n", platform.getInfo<CL_PLATFORM_NAME>().c_str());
LOG_I("OpenCL platform version: %s\n", platform.getInfo<CL_PLATFORM_VERSION>().c_str());
LOG_I("OpenCL platform vendor: %s\n", platform.getInfo<CL_PLATFORM_VENDOR>().c_str());
LOG_I("Found %lu OpenCL devices.\n", devices.size());
void* ptr;
#ifdef ENABLE_COMPRESSION
clSetBufferCompressionPOCL_fn SetBufferComPOCL = nullptr;
ptr = clGetExtensionFunctionAddressForPlatform(platform(), "clSetBufferCompressionPOCL");
if (ptr)
SetBufferComPOCL = (clSetBufferCompressionPOCL_fn)ptr;
#endif
if (devices.size() == 1) {
GpuDev = devices[0];
FpgaDev = devices[0];
} else if (devices[1].getInfo<CL_DEVICE_TYPE>() & CL_DEVICE_TYPE_CUSTOM) {
GpuDev = devices[0];
FpgaDev = devices[1];
} else {
GpuDev = devices[1];
FpgaDev = devices[0];
}
ClContext = cl::Context(devices, nullptr, nullptr, nullptr, &err);
CHECK_CL_ERROR(err, "Context creation failed\n");
GpuQueue = cl::CommandQueue(ClContext, GpuDev, 0, &err); // , CL_QUEUE_PROFILING_ENABLE
CHECK_CL_ERROR(err, "CmdQueue creation failed\n");
if (devices.size() == 1)
FpgaQueue = GpuQueue;
else {
FpgaQueue = cl::CommandQueue(ClContext, FpgaDev, 0, &err); // , CL_QUEUE_PROFILING_ENABLE
CHECK_CL_ERROR(err, "CmdQueue creation failed\n");
}
std::vector<cl::Device> GpuDevs = {GpuDev};
GpuProgram = cl::Program{ClContext, DOWNSAMPLE_SOURCE, false, &err};
CHECK_CL_ERROR(err, "Program creation failed\n");
err = GpuProgram.build(GpuDevs);
CHECK_CL_ERROR(err, "Program build failed\n");
GpuKernel = cl::Kernel(GpuProgram, "downsample_image", &err);
CHECK_CL_ERROR(err, "Kernel creation failed\n");
std::string FpgaBuiltinKernels = FpgaDev.getInfo<CL_DEVICE_BUILT_IN_KERNELS>();
const std::string BuiltinKernelName{"pocl.countred"};
std::vector<cl::Device> FpgaDevs = {FpgaDev};
if (FpgaBuiltinKernels.find(BuiltinKernelName) != std::string::npos)
{
FpgaProgram = cl::Program{ClContext, FpgaDevs, BuiltinKernelName, &err};
CHECK_CL_ERROR(err, "Program creation failed\n");
}
else
{
FpgaProgram = cl::Program{ClContext, PX_COUNT_SOURCE, false, &err};
CHECK_CL_ERROR(err, "Program creation failed\n");
}
err = FpgaProgram.build(FpgaDevs);
CHECK_CL_ERROR(err, "Program build failed\n");
FpgaKernel = cl::Kernel(FpgaProgram, BuiltinKernelName.c_str(), &err);
CHECK_CL_ERROR(err, "Kernel creation failed\n");
GpuInputBuffer = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)(InputBufferSize), nullptr, &err);
CHECK_CL_ERROR(err, "Input buffer creation failed\n");
InterBuffer = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)(InputBufferSize/4), nullptr, &err);
CHECK_CL_ERROR(err, "Inter buffer creation failed\n");
FpgaOutputBuffer = cl::Buffer(ClContext, CL_MEM_READ_WRITE, OUTPUT_SIZE, nullptr, &err);
CHECK_CL_ERROR(err, "Output buffer creation failed\n");
#ifdef ENABLE_COMPRESSION
if (SetBufferComPOCL) {
int r = SetBufferComPOCL(InputBuffer(), CL_COMPRESSION_VBYTE, nullptr);
assert (r == CL_SUCCESS);
LOG_I ("Buffer compression VBYTE enabled\n");
}
#endif
GpuKernel.setArg(0, GpuInputBuffer);
GpuKernel.setArg(1, InterBuffer);
FpgaKernel.setArg(0, InterBuffer);
FpgaKernel.setArg(1, FpgaOutputBuffer);
initialized = true;
return true;
}
bool OpenCL_Context::processCameraFrame(unsigned char* input, unsigned long *output) {
if (!isAvailable()) {
LOG_E("Device not available");
return false;
}
std::unique_lock<std::mutex> lock(OclMutex);
#ifdef TIMING
LOG_D("OpenCL: start processCameraFrame\n");
auto start_time = std::chrono::steady_clock::now();
#endif
cl_int err;
*output = 0;
std::vector<cl::Event> evts;
cl::Event ev1, ev2, ev3, ev4;
err = GpuQueue.enqueueWriteBuffer(GpuInputBuffer, CL_FALSE, 0, InputBufferSize, input, nullptr, &ev1);
if (err != CL_SUCCESS)
return false;
evts.push_back(ev1);
err = GpuQueue.enqueueNDRangeKernel(GpuKernel, Offset, Global, Local, &evts, &ev2);
if (err != CL_SUCCESS)
return false;
/*
err = FpgaQueue.enqueueWriteBuffer(FpgaOutputBuffer, CL_FALSE, 0, sizeof(cl_ulong), output, nullptr, &ev3);
if (err != CL_SUCCESS)
return false;
*/
evts.clear();
evts.push_back(ev2);
// evts.push_back(ev3);
err = FpgaQueue.enqueueNDRangeKernel(FpgaKernel, Offset, Global, Local, &evts, &ev4);
if (err != CL_SUCCESS)
return false;
evts.clear();
evts.push_back(ev4);
err = FpgaQueue.enqueueReadBuffer(FpgaOutputBuffer, CL_TRUE, 0, sizeof(unsigned long), output, &evts);
if (err != CL_SUCCESS)
return false;
#ifdef DUMP_FRAMES
char filename[1024];
std::snprintf(filename, 1024, "/tmp/carla_%u_%zu.raw", imgID, *output);
FILE* outfile = std::fopen(filename, "w");
std::fwrite(input, 1, InputBufferSize, outfile);
std::fclose(outfile);
++imgID;
#endif
#ifdef TIMING
auto end_time = std::chrono::steady_clock::now();
std::chrono::duration<float> diff = end_time - start_time;
float s = diff.count() * 1000.0f;
LOG_D("OpenCL: end processCameraFrame: %03.1f ms\n", s);
#endif
return true;
}
void OpenCL_Context::shutdown() {
if (GpuQueue())
GpuQueue.finish();
}
|
fix some bugs
|
examples/accel: fix some bugs
|
C++
|
mit
|
pocl/pocl,pocl/pocl,pocl/pocl,pocl/pocl,pocl/pocl
|
f8e17125984c8ff4087455a0117dcabf50e414ae
|
chrome/common/extensions/extension_file_util_unittest.cc
|
chrome/common/extensions/extension_file_util_unittest.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/extension_file_util.h"
#include "base/file_util.h"
#include "base/json/json_value_serializer.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
namespace keys = extension_manifest_keys;
#if defined(OS_WIN)
// http://crbug.com/106381
#define InstallUninstallGarbageCollect DISABLED_InstallUninstallGarbageCollect
#endif
TEST(ExtensionFileUtil, InstallUninstallGarbageCollect) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
// Create a source extension.
std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
std::string version("1.0");
FilePath src = temp.path().AppendASCII(extension_id);
ASSERT_TRUE(file_util::CreateDirectory(src));
// Create a extensions tree.
FilePath all_extensions = temp.path().AppendASCII("extensions");
ASSERT_TRUE(file_util::CreateDirectory(all_extensions));
// Install in empty directory. Should create parent directories as needed.
FilePath version_1 = extension_file_util::InstallExtension(src,
extension_id,
version,
all_extensions);
ASSERT_EQ(version_1.value(),
all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0")
.value());
ASSERT_TRUE(file_util::DirectoryExists(version_1));
// Should have moved the source.
ASSERT_FALSE(file_util::DirectoryExists(src));
// Install again. Should create a new one with different name.
ASSERT_TRUE(file_util::CreateDirectory(src));
FilePath version_2 = extension_file_util::InstallExtension(src,
extension_id,
version,
all_extensions);
ASSERT_EQ(version_2.value(),
all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1")
.value());
ASSERT_TRUE(file_util::DirectoryExists(version_2));
// Collect garbage. Should remove first one.
std::map<std::string, FilePath> extension_paths;
extension_paths[extension_id] =
FilePath().AppendASCII(extension_id).Append(version_2.BaseName());
extension_file_util::GarbageCollectExtensions(all_extensions,
extension_paths);
ASSERT_FALSE(file_util::DirectoryExists(version_1));
ASSERT_TRUE(file_util::DirectoryExists(version_2));
// Uninstall. Should remove entire extension subtree.
extension_file_util::UninstallExtension(all_extensions, extension_id);
ASSERT_FALSE(file_util::DirectoryExists(version_2.DirName()));
ASSERT_TRUE(file_util::DirectoryExists(all_extensions));
}
TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_TRUE(extension != NULL);
EXPECT_EQ("The first extension that I made.", extension->description());
}
TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
.AppendASCII("1.0");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_FALSE(extension == NULL);
EXPECT_TRUE(error.empty());
}
#if defined(OS_WIN)
// http://crbug.com/106381
#define CheckIllegalFilenamesNoUnderscores \
DISABLED_CheckIllegalFilenamesNoUnderscores
#endif
TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().AppendASCII("some_dir");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string data = "{ \"name\": { \"message\": \"foobar\" } }";
ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"),
data.c_str(), data.length()));
std::string error;
EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
#if defined(OS_WIN)
// http://crbug.com/106381
#define CheckIllegalFilenamesOnlyReserved \
DISABLED_CheckIllegalFilenamesOnlyReserved
#endif
TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string error;
EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
#if defined(OS_WIN)
// http://crbug.com/106381
#define CheckIllegalFilenamesReservedAndIllegal \
DISABLED_CheckIllegalFilenamesReservedAndIllegal
#endif
TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
ASSERT_TRUE(file_util::CreateDirectory(src_path));
src_path = temp.path().AppendASCII("_some_dir");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string error;
EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("Extensions")
.AppendASCII("dddddddddddddddddddddddddddddddd")
.AppendASCII("1.0");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str());
}
TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("Extensions")
.AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
.AppendASCII("1.0");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
ASSERT_STREQ("Manifest is not valid JSON. "
"Line: 2, column: 16, Syntax error.", error.c_str());
}
TEST(ExtensionFileUtil, FailLoadingNonUTF8Scripts) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("bad_encoding");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_STREQ("Could not load file 'bad_encoding.js' for content script. "
"It isn't UTF-8 encoded.", error.c_str());
}
#define URL_PREFIX "chrome-extension://extension-id/"
TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) {
struct TestCase {
const char* url;
const char* expected_relative_path;
} test_cases[] = {
{ URL_PREFIX "simple.html",
"simple.html" },
{ URL_PREFIX "directory/to/file.html",
"directory/to/file.html" },
{ URL_PREFIX "escape%20spaces.html",
"escape spaces.html" },
{ URL_PREFIX "%C3%9Cber.html",
"\xC3\x9C" "ber.html" },
#if defined(OS_WIN)
{ URL_PREFIX "C%3A/simple.html",
"" },
#endif
{ URL_PREFIX "////simple.html",
"simple.html" },
{ URL_PREFIX "/simple.html",
"simple.html" },
{ URL_PREFIX "\\simple.html",
"simple.html" },
{ URL_PREFIX "\\\\foo\\simple.html",
"foo/simple.html" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
GURL url(test_cases[i].url);
#if defined(OS_POSIX)
FilePath expected_path(test_cases[i].expected_relative_path);
#elif defined(OS_WIN)
FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path));
#endif
FilePath actual_path =
extension_file_util::ExtensionURLToRelativeFilePath(url);
EXPECT_FALSE(actual_path.IsAbsolute()) <<
" For the path " << actual_path.value();
EXPECT_EQ(expected_path.value(), actual_path.value()) <<
" For the path " << url;
}
}
static scoped_refptr<Extension> LoadExtensionManifest(
DictionaryValue* manifest,
const FilePath& manifest_dir,
Extension::Location location,
int extra_flags,
std::string* error) {
scoped_refptr<Extension> extension = Extension::Create(
manifest_dir, location, *manifest, extra_flags, error);
return extension;
}
static scoped_refptr<Extension> LoadExtensionManifest(
const std::string& manifest_value,
const FilePath& manifest_dir,
Extension::Location location,
int extra_flags,
std::string* error) {
JSONStringValueSerializer serializer(manifest_value);
scoped_ptr<Value> result(serializer.Deserialize(NULL, error));
if (!result.get())
return NULL;
CHECK_EQ(Value::TYPE_DICTIONARY, result->GetType());
return LoadExtensionManifest(static_cast<DictionaryValue*>(result.get()),
manifest_dir,
location,
extra_flags,
error);
}
#if defined(OS_WIN)
// http://crbug.com/108279
#define ValidateThemeUTF8 DISABLED_ValidateThemeUTF8
#endif
TEST(ExtensionFileUtil, ValidateThemeUTF8) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
// "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png";
FilePath non_ascii_path = temp.path().Append(FilePath::FromUTF8Unsafe(
non_ascii_file));
file_util::WriteFile(non_ascii_path, "", 0);
std::string kManifest =
base::StringPrintf(
"{ \"name\": \"Test\", \"version\": \"1.0\", "
" \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }"
"}", non_ascii_file.c_str());
std::string error;
scoped_refptr<Extension> extension = LoadExtensionManifest(
kManifest, temp.path(), Extension::LOAD, 0, &error);
ASSERT_TRUE(extension.get()) << error;
EXPECT_TRUE(extension_file_util::ValidateExtension(extension, &error)) <<
error;
}
#if defined(OS_WIN)
// This test is flaky on Windows. http://crbug.com/110279
#define MAYBE_BackgroundScriptsMustExist FLAKY_BackgroundScriptsMustExist
#else
#define MAYBE_BackgroundScriptsMustExist BackgroundScriptsMustExist
#endif
TEST(ExtensionFileUtil, MAYBE_BackgroundScriptsMustExist) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
scoped_ptr<DictionaryValue> value(new DictionaryValue());
value->SetString("name", "test");
value->SetString("version", "1");
value->SetInteger("manifest_version", 1);
ListValue* scripts = new ListValue();
scripts->Append(Value::CreateStringValue("foo.js"));
value->Set("background.scripts", scripts);
std::string error;
scoped_refptr<Extension> extension = LoadExtensionManifest(
value.get(), temp.path(), Extension::LOAD, 0, &error);
ASSERT_TRUE(extension.get()) << error;
EXPECT_FALSE(extension_file_util::ValidateExtension(extension, &error));
EXPECT_EQ(l10n_util::GetStringFUTF8(
IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED, ASCIIToUTF16("foo.js")),
error);
scripts->Clear();
scripts->Append(Value::CreateStringValue("http://google.com/foo.js"));
extension = LoadExtensionManifest(value.get(), temp.path(), Extension::LOAD,
0, &error);
ASSERT_TRUE(extension.get()) << error;
EXPECT_FALSE(extension_file_util::ValidateExtension(extension, &error));
EXPECT_EQ(l10n_util::GetStringFUTF8(
IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED,
ASCIIToUTF16("http://google.com/foo.js")),
error);
}
// TODO(aa): More tests as motivation allows. Maybe steal some from
// ExtensionService? Many of them could probably be tested here without the
// MessageLoop shenanigans.
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/extension_file_util.h"
#include "base/file_util.h"
#include "base/json/json_value_serializer.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
namespace keys = extension_manifest_keys;
#if defined(OS_WIN)
// http://crbug.com/106381
#define InstallUninstallGarbageCollect DISABLED_InstallUninstallGarbageCollect
#endif
TEST(ExtensionFileUtil, InstallUninstallGarbageCollect) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
// Create a source extension.
std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
std::string version("1.0");
FilePath src = temp.path().AppendASCII(extension_id);
ASSERT_TRUE(file_util::CreateDirectory(src));
// Create a extensions tree.
FilePath all_extensions = temp.path().AppendASCII("extensions");
ASSERT_TRUE(file_util::CreateDirectory(all_extensions));
// Install in empty directory. Should create parent directories as needed.
FilePath version_1 = extension_file_util::InstallExtension(src,
extension_id,
version,
all_extensions);
ASSERT_EQ(version_1.value(),
all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0")
.value());
ASSERT_TRUE(file_util::DirectoryExists(version_1));
// Should have moved the source.
ASSERT_FALSE(file_util::DirectoryExists(src));
// Install again. Should create a new one with different name.
ASSERT_TRUE(file_util::CreateDirectory(src));
FilePath version_2 = extension_file_util::InstallExtension(src,
extension_id,
version,
all_extensions);
ASSERT_EQ(version_2.value(),
all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1")
.value());
ASSERT_TRUE(file_util::DirectoryExists(version_2));
// Collect garbage. Should remove first one.
std::map<std::string, FilePath> extension_paths;
extension_paths[extension_id] =
FilePath().AppendASCII(extension_id).Append(version_2.BaseName());
extension_file_util::GarbageCollectExtensions(all_extensions,
extension_paths);
ASSERT_FALSE(file_util::DirectoryExists(version_1));
ASSERT_TRUE(file_util::DirectoryExists(version_2));
// Uninstall. Should remove entire extension subtree.
extension_file_util::UninstallExtension(all_extensions, extension_id);
ASSERT_FALSE(file_util::DirectoryExists(version_2.DirName()));
ASSERT_TRUE(file_util::DirectoryExists(all_extensions));
}
TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_TRUE(extension != NULL);
EXPECT_EQ("The first extension that I made.", extension->description());
}
TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
.AppendASCII("1.0");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_FALSE(extension == NULL);
EXPECT_TRUE(error.empty());
}
#if defined(OS_WIN)
// http://crbug.com/106381
#define CheckIllegalFilenamesNoUnderscores \
DISABLED_CheckIllegalFilenamesNoUnderscores
#endif
TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().AppendASCII("some_dir");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string data = "{ \"name\": { \"message\": \"foobar\" } }";
ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"),
data.c_str(), data.length()));
std::string error;
EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
#if defined(OS_WIN)
// http://crbug.com/106381
#define CheckIllegalFilenamesOnlyReserved \
DISABLED_CheckIllegalFilenamesOnlyReserved
#endif
TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string error;
EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
#if defined(OS_WIN)
// http://crbug.com/106381
#define CheckIllegalFilenamesReservedAndIllegal \
DISABLED_CheckIllegalFilenamesReservedAndIllegal
#endif
TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
ASSERT_TRUE(file_util::CreateDirectory(src_path));
src_path = temp.path().AppendASCII("_some_dir");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string error;
EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("Extensions")
.AppendASCII("dddddddddddddddddddddddddddddddd")
.AppendASCII("1.0");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str());
}
TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("Extensions")
.AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
.AppendASCII("1.0");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
ASSERT_STREQ("Manifest is not valid JSON. "
"Line: 2, column: 16, Syntax error.", error.c_str());
}
TEST(ExtensionFileUtil, FailLoadingNonUTF8Scripts) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("bad_encoding");
std::string error;
scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_STREQ("Could not load file 'bad_encoding.js' for content script. "
"It isn't UTF-8 encoded.", error.c_str());
}
#define URL_PREFIX "chrome-extension://extension-id/"
TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) {
struct TestCase {
const char* url;
const char* expected_relative_path;
} test_cases[] = {
{ URL_PREFIX "simple.html",
"simple.html" },
{ URL_PREFIX "directory/to/file.html",
"directory/to/file.html" },
{ URL_PREFIX "escape%20spaces.html",
"escape spaces.html" },
{ URL_PREFIX "%C3%9Cber.html",
"\xC3\x9C" "ber.html" },
#if defined(OS_WIN)
{ URL_PREFIX "C%3A/simple.html",
"" },
#endif
{ URL_PREFIX "////simple.html",
"simple.html" },
{ URL_PREFIX "/simple.html",
"simple.html" },
{ URL_PREFIX "\\simple.html",
"simple.html" },
{ URL_PREFIX "\\\\foo\\simple.html",
"foo/simple.html" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
GURL url(test_cases[i].url);
#if defined(OS_POSIX)
FilePath expected_path(test_cases[i].expected_relative_path);
#elif defined(OS_WIN)
FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path));
#endif
FilePath actual_path =
extension_file_util::ExtensionURLToRelativeFilePath(url);
EXPECT_FALSE(actual_path.IsAbsolute()) <<
" For the path " << actual_path.value();
EXPECT_EQ(expected_path.value(), actual_path.value()) <<
" For the path " << url;
}
}
static scoped_refptr<Extension> LoadExtensionManifest(
DictionaryValue* manifest,
const FilePath& manifest_dir,
Extension::Location location,
int extra_flags,
std::string* error) {
scoped_refptr<Extension> extension = Extension::Create(
manifest_dir, location, *manifest, extra_flags, error);
return extension;
}
static scoped_refptr<Extension> LoadExtensionManifest(
const std::string& manifest_value,
const FilePath& manifest_dir,
Extension::Location location,
int extra_flags,
std::string* error) {
JSONStringValueSerializer serializer(manifest_value);
scoped_ptr<Value> result(serializer.Deserialize(NULL, error));
if (!result.get())
return NULL;
CHECK_EQ(Value::TYPE_DICTIONARY, result->GetType());
return LoadExtensionManifest(static_cast<DictionaryValue*>(result.get()),
manifest_dir,
location,
extra_flags,
error);
}
#if defined(OS_WIN)
// http://crbug.com/108279
#define ValidateThemeUTF8 DISABLED_ValidateThemeUTF8
#endif
TEST(ExtensionFileUtil, ValidateThemeUTF8) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
// "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png";
FilePath non_ascii_path = temp.path().Append(FilePath::FromUTF8Unsafe(
non_ascii_file));
file_util::WriteFile(non_ascii_path, "", 0);
std::string kManifest =
base::StringPrintf(
"{ \"name\": \"Test\", \"version\": \"1.0\", "
" \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }"
"}", non_ascii_file.c_str());
std::string error;
scoped_refptr<Extension> extension = LoadExtensionManifest(
kManifest, temp.path(), Extension::LOAD, 0, &error);
ASSERT_TRUE(extension.get()) << error;
EXPECT_TRUE(extension_file_util::ValidateExtension(extension, &error)) <<
error;
}
#if defined(OS_WIN)
// This test hangs on Windows sometimes. http://crbug.com/110279
#define MAYBE_BackgroundScriptsMustExist DISABLED_BackgroundScriptsMustExist
#else
#define MAYBE_BackgroundScriptsMustExist BackgroundScriptsMustExist
#endif
TEST(ExtensionFileUtil, MAYBE_BackgroundScriptsMustExist) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
scoped_ptr<DictionaryValue> value(new DictionaryValue());
value->SetString("name", "test");
value->SetString("version", "1");
value->SetInteger("manifest_version", 1);
ListValue* scripts = new ListValue();
scripts->Append(Value::CreateStringValue("foo.js"));
value->Set("background.scripts", scripts);
std::string error;
scoped_refptr<Extension> extension = LoadExtensionManifest(
value.get(), temp.path(), Extension::LOAD, 0, &error);
ASSERT_TRUE(extension.get()) << error;
EXPECT_FALSE(extension_file_util::ValidateExtension(extension, &error));
EXPECT_EQ(l10n_util::GetStringFUTF8(
IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED, ASCIIToUTF16("foo.js")),
error);
scripts->Clear();
scripts->Append(Value::CreateStringValue("http://google.com/foo.js"));
extension = LoadExtensionManifest(value.get(), temp.path(), Extension::LOAD,
0, &error);
ASSERT_TRUE(extension.get()) << error;
EXPECT_FALSE(extension_file_util::ValidateExtension(extension, &error));
EXPECT_EQ(l10n_util::GetStringFUTF8(
IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED,
ASCIIToUTF16("http://google.com/foo.js")),
error);
}
// TODO(aa): More tests as motivation allows. Maybe steal some from
// ExtensionService? Many of them could probably be tested here without the
// MessageLoop shenanigans.
|
Disable BackgroundScriptsMustExist.
|
Disable BackgroundScriptsMustExist.
This test seems to hang on Windows sometimes.
BUG=110279
TEST=none
TBR=aa
Review URL: http://codereview.chromium.org/9222002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@117808 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,ropik/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium
|
9ea5a17d28ffe56e18eaaab0269bcbd20c2d99ce
|
chrome/browser/sync/notifier/chrome_system_resources.cc
|
chrome/browser/sync/notifier/chrome_system_resources.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/chrome_system_resources.h"
#include <cstdlib>
#include <cstring>
#include <string>
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"
namespace sync_notifier {
ChromeSystemResources::ChromeSystemResources() {
DCHECK(non_thread_safe_.CalledOnValidThread());
}
ChromeSystemResources::~ChromeSystemResources() {
DCHECK(non_thread_safe_.CalledOnValidThread());
StopScheduler();
}
invalidation::Time ChromeSystemResources::current_time() {
DCHECK(non_thread_safe_.CalledOnValidThread());
return base::Time::Now();
}
void ChromeSystemResources::StartScheduler() {
DCHECK(non_thread_safe_.CalledOnValidThread());
scoped_runnable_method_factory_.reset(
new ScopedRunnableMethodFactory<ChromeSystemResources>(this));
}
void ChromeSystemResources::StopScheduler() {
DCHECK(non_thread_safe_.CalledOnValidThread());
scoped_runnable_method_factory_.reset();
STLDeleteElements(&posted_tasks_);
}
void ChromeSystemResources::ScheduleWithDelay(
invalidation::TimeDelta delay,
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
Task* task_to_post = MakeTaskToPost(task);
if (!task_to_post) {
return;
}
MessageLoop::current()->PostDelayedTask(
FROM_HERE, task_to_post, delay.InMillisecondsRoundedUp());
}
void ChromeSystemResources::ScheduleImmediately(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
Task* task_to_post = MakeTaskToPost(task);
if (!task_to_post) {
return;
}
MessageLoop::current()->PostTask(FROM_HERE, task_to_post);
}
// The listener thread is just our current thread (i.e., the
// notifications thread).
void ChromeSystemResources::ScheduleOnListenerThread(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
ScheduleImmediately(task);
}
// 'Internal thread' means 'not the listener thread'. Since the
// listener thread is the notifications thread, always return false.
bool ChromeSystemResources::IsRunningOnInternalThread() {
DCHECK(non_thread_safe_.CalledOnValidThread());
return false;
}
void ChromeSystemResources::Log(
LogLevel level, const char* file, int line,
const char* format, ...) {
DCHECK(non_thread_safe_.CalledOnValidThread());
logging::LogSeverity log_severity = logging::LOG_INFO;
switch (level) {
case INFO_LEVEL:
log_severity = logging::LOG_INFO;
break;
case WARNING_LEVEL:
log_severity = logging::LOG_WARNING;
break;
case ERROR_LEVEL:
log_severity = logging::LOG_ERROR;
break;
}
// We treat LOG(INFO) as VLOG(1).
if ((log_severity >= logging::GetMinLogLevel()) &&
((log_severity != logging::LOG_INFO) ||
(1 <= logging::GetVlogLevelHelper(file, ::strlen(file))))) {
va_list ap;
va_start(ap, format);
std::string result;
StringAppendV(&result, format, ap);
logging::LogMessage(file, line, log_severity).stream() << result;
va_end(ap);
}
}
void ChromeSystemResources::WriteState(
const invalidation::string& state,
invalidation::StorageCallback* callback) {
// TODO(akalin): Write the given state to persistent storage.
callback->Run(false);
delete callback;
}
Task* ChromeSystemResources::MakeTaskToPost(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
DCHECK(invalidation::IsCallbackRepeatable(task));
if (!scoped_runnable_method_factory_.get()) {
delete task;
return NULL;
}
posted_tasks_.insert(task);
Task* task_to_post =
scoped_runnable_method_factory_->NewRunnableMethod(
&ChromeSystemResources::RunPostedTask, task);
return task_to_post;
}
void ChromeSystemResources::RunPostedTask(invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
RunAndDeleteClosure(task);
posted_tasks_.erase(task);
}
} // namespace sync_notifier
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/chrome_system_resources.h"
#include <cstdlib>
#include <cstring>
#include <string>
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"
namespace sync_notifier {
ChromeSystemResources::ChromeSystemResources() {
DCHECK(non_thread_safe_.CalledOnValidThread());
}
ChromeSystemResources::~ChromeSystemResources() {
DCHECK(non_thread_safe_.CalledOnValidThread());
StopScheduler();
}
invalidation::Time ChromeSystemResources::current_time() {
DCHECK(non_thread_safe_.CalledOnValidThread());
return base::Time::Now();
}
void ChromeSystemResources::StartScheduler() {
DCHECK(non_thread_safe_.CalledOnValidThread());
scoped_runnable_method_factory_.reset(
new ScopedRunnableMethodFactory<ChromeSystemResources>(this));
}
void ChromeSystemResources::StopScheduler() {
DCHECK(non_thread_safe_.CalledOnValidThread());
scoped_runnable_method_factory_.reset();
STLDeleteElements(&posted_tasks_);
}
void ChromeSystemResources::ScheduleWithDelay(
invalidation::TimeDelta delay,
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
Task* task_to_post = MakeTaskToPost(task);
if (!task_to_post) {
return;
}
MessageLoop::current()->PostDelayedTask(
FROM_HERE, task_to_post, delay.InMillisecondsRoundedUp());
}
void ChromeSystemResources::ScheduleImmediately(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
Task* task_to_post = MakeTaskToPost(task);
if (!task_to_post) {
return;
}
MessageLoop::current()->PostTask(FROM_HERE, task_to_post);
}
// The listener thread is just our current thread.
void ChromeSystemResources::ScheduleOnListenerThread(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
ScheduleImmediately(task);
}
// We're already on a separate thread, so always return true.
bool ChromeSystemResources::IsRunningOnInternalThread() {
DCHECK(non_thread_safe_.CalledOnValidThread());
return true;
}
void ChromeSystemResources::Log(
LogLevel level, const char* file, int line,
const char* format, ...) {
DCHECK(non_thread_safe_.CalledOnValidThread());
logging::LogSeverity log_severity = logging::LOG_INFO;
switch (level) {
case INFO_LEVEL:
log_severity = logging::LOG_INFO;
break;
case WARNING_LEVEL:
log_severity = logging::LOG_WARNING;
break;
case ERROR_LEVEL:
log_severity = logging::LOG_ERROR;
break;
}
// We treat LOG(INFO) as VLOG(1).
if ((log_severity >= logging::GetMinLogLevel()) &&
((log_severity != logging::LOG_INFO) ||
(1 <= logging::GetVlogLevelHelper(file, ::strlen(file))))) {
va_list ap;
va_start(ap, format);
std::string result;
StringAppendV(&result, format, ap);
logging::LogMessage(file, line, log_severity).stream() << result;
va_end(ap);
}
}
void ChromeSystemResources::WriteState(
const invalidation::string& state,
invalidation::StorageCallback* callback) {
// TODO(akalin): Write the given state to persistent storage.
callback->Run(false);
delete callback;
}
Task* ChromeSystemResources::MakeTaskToPost(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
DCHECK(invalidation::IsCallbackRepeatable(task));
if (!scoped_runnable_method_factory_.get()) {
delete task;
return NULL;
}
posted_tasks_.insert(task);
Task* task_to_post =
scoped_runnable_method_factory_->NewRunnableMethod(
&ChromeSystemResources::RunPostedTask, task);
return task_to_post;
}
void ChromeSystemResources::RunPostedTask(invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
RunAndDeleteClosure(task);
posted_tasks_.erase(task);
}
} // namespace sync_notifier
|
Revert 61881 (broke sync_unit_tests) - [Sync] Fixed flipped return value from 61851.
|
Revert 61881 (broke sync_unit_tests) - [Sync] Fixed flipped return value from 61851.
BUG=None
TEST=None
TBR=johnnyg
Review URL: http://codereview.chromium.org/3579018
[email protected]
Review URL: http://codereview.chromium.org/3599023
git-svn-id: http://src.chromium.org/svn/trunk/src@61891 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: f5e0d6f9a6efe524e88c9b35152fa15f35b91075
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
c0a08f9e42a85ea610633f4ea23d6e7913b3986b
|
libevmjit/GasMeter.cpp
|
libevmjit/GasMeter.cpp
|
#include "GasMeter.h"
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>
#include "Type.h"
#include "Ext.h"
#include "RuntimeManager.h"
namespace dev
{
namespace eth
{
namespace jit
{
namespace // Helper functions
{
uint64_t const c_stepGas = 1;
uint64_t const c_balanceGas = 20;
uint64_t const c_sha3Gas = 10;
uint64_t const c_sha3WordGas = 10;
uint64_t const c_sloadGas = 20;
uint64_t const c_sstoreSetGas = 300;
uint64_t const c_sstoreResetGas = 100;
uint64_t const c_sstoreRefundGas = 100;
uint64_t const c_createGas = 100;
uint64_t const c_createDataGas = 5;
uint64_t const c_callGas = 20;
uint64_t const c_expGas = 1;
uint64_t const c_expByteGas = 1;
uint64_t const c_memoryGas = 1;
uint64_t const c_txDataZeroGas = 1;
uint64_t const c_txDataNonZeroGas = 5;
uint64_t const c_txGas = 500;
uint64_t const c_logGas = 32;
uint64_t const c_logDataGas = 1;
uint64_t const c_logTopicGas = 32;
uint64_t const c_copyGas = 1;
uint64_t getStepCost(Instruction inst) // TODO: Add this function to FeeSructure (pull request submitted)
{
switch (inst)
{
default: // Assumes instruction code is valid
return c_stepGas;
case Instruction::STOP:
case Instruction::SUICIDE:
case Instruction::SSTORE: // Handle cost of SSTORE separately in GasMeter::countSStore()
return 0;
case Instruction::EXP: return c_expGas;
case Instruction::SLOAD: return c_sloadGas;
case Instruction::SHA3: return c_sha3Gas;
case Instruction::BALANCE: return c_balanceGas;
case Instruction::CALL:
case Instruction::CALLCODE: return c_callGas;
case Instruction::CREATE: return c_createGas;
case Instruction::LOG0:
case Instruction::LOG1:
case Instruction::LOG2:
case Instruction::LOG3:
case Instruction::LOG4:
{
auto numTopics = static_cast<uint64_t>(inst) - static_cast<uint64_t>(Instruction::LOG0);
return c_logGas + numTopics * c_logTopicGas;
}
}
}
}
GasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :
CompilerHelper(_builder),
m_runtimeManager(_runtimeManager)
{
auto module = getModule();
llvm::Type* gasCheckArgs[] = {Type::RuntimePtr, Type::Word};
m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, "gas.check", module);
InsertPointGuard guard(m_builder);
auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc);
auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc);
auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc);
m_builder.SetInsertPoint(checkBB);
auto arg = m_gasCheckFunc->arg_begin();
arg->setName("rt");
++arg;
arg->setName("cost");
auto cost = arg;
auto gas = m_runtimeManager.getGas();
auto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, "isOutOfGas");
m_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB);
m_builder.SetInsertPoint(outOfGasBB);
m_runtimeManager.raiseException(ReturnCode::OutOfGas);
m_builder.CreateUnreachable();
m_builder.SetInsertPoint(updateBB);
gas = m_builder.CreateSub(gas, cost);
m_runtimeManager.setGas(gas);
m_builder.CreateRetVoid();
}
void GasMeter::count(Instruction _inst)
{
if (!m_checkCall)
{
// Create gas check call with mocked block cost at begining of current cost-block
m_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getRuntimePtr(), llvm::UndefValue::get(Type::Word)});
}
m_blockCost += getStepCost(_inst);
}
void GasMeter::count(llvm::Value* _cost)
{
createCall(m_gasCheckFunc, {m_runtimeManager.getRuntimePtr(), _cost});
}
void GasMeter::countExp(llvm::Value* _exponent)
{
// Additional cost is 1 per significant byte of exponent
// lz - leading zeros
// cost = ((256 - lz) + 7) / 8
// OPT: All calculations can be done on 32/64 bits
auto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word);
auto lz = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false));
auto sigBits = m_builder.CreateSub(Constant::get(256), lz);
auto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, Constant::get(7)), Constant::get(8));
count(sigBytes);
}
void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)
{
auto oldValue = _ext.sload(_index);
auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero");
auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero");
auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero");
auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero");
auto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isInsert");
auto isDelete = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDelete");
auto cost = m_builder.CreateSelect(isInsert, Constant::get(c_sstoreSetGas), Constant::get(c_sstoreResetGas), "cost");
cost = m_builder.CreateSelect(isDelete, Constant::get(0), cost, "cost");
count(cost);
}
void GasMeter::countLogData(llvm::Value* _dataLength)
{
assert(m_checkCall);
assert(m_blockCost > 0); // LOGn instruction is already counted
static_assert(c_logDataGas == 1, "Log data gas cost has changed. Update GasMeter.");
count(_dataLength);
}
void GasMeter::countSha3Data(llvm::Value* _dataLength)
{
assert(m_checkCall);
assert(m_blockCost > 0); // SHA3 instruction is already counted
// TODO: This round ups to 32 happens in many places
// FIXME: Overflow possible but Memory::require() also called. Probably 64-bit arith can be used.
static_assert(c_sha3WordGas != 1, "SHA3 data cost has changed. Update GasMeter");
auto words = m_builder.CreateUDiv(m_builder.CreateAdd(_dataLength, Constant::get(31)), Constant::get(32));
auto cost = m_builder.CreateNUWMul(Constant::get(c_sha3WordGas), words);
count(cost);
}
void GasMeter::giveBack(llvm::Value* _gas)
{
m_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));
}
void GasMeter::commitCostBlock()
{
// If any uncommited block
if (m_checkCall)
{
if (m_blockCost == 0) // Do not check 0
{
m_checkCall->eraseFromParent(); // Remove the gas check call
m_checkCall = nullptr;
return;
}
m_checkCall->setArgOperand(1, Constant::get(m_blockCost)); // Update block cost in gas check call
m_checkCall = nullptr; // End cost-block
m_blockCost = 0;
}
assert(m_blockCost == 0);
}
void GasMeter::countMemory(llvm::Value* _additionalMemoryInWords)
{
static_assert(c_memoryGas == 1, "Memory gas cost has changed. Update GasMeter.");
count(_additionalMemoryInWords);
}
void GasMeter::countCopy(llvm::Value* _copyWords)
{
static_assert(c_copyGas == 1, "Copy gas cost has changed. Update GasMeter.");
count(_copyWords);
}
}
}
}
|
#include "GasMeter.h"
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>
#include "Type.h"
#include "Ext.h"
#include "RuntimeManager.h"
namespace dev
{
namespace eth
{
namespace jit
{
namespace // Helper functions
{
uint64_t const c_stepGas = 1;
uint64_t const c_balanceGas = 20;
uint64_t const c_sha3Gas = 10;
uint64_t const c_sha3WordGas = 10;
uint64_t const c_sloadGas = 20;
uint64_t const c_sstoreSetGas = 300;
uint64_t const c_sstoreResetGas = 100;
uint64_t const c_sstoreRefundGas = 100;
uint64_t const c_createGas = 100;
uint64_t const c_createDataGas = 5;
uint64_t const c_callGas = 20;
uint64_t const c_expGas = 1;
uint64_t const c_expByteGas = 1;
uint64_t const c_memoryGas = 1;
uint64_t const c_txDataZeroGas = 1;
uint64_t const c_txDataNonZeroGas = 5;
uint64_t const c_txGas = 500;
uint64_t const c_logGas = 32;
uint64_t const c_logDataGas = 1;
uint64_t const c_logTopicGas = 32;
uint64_t const c_copyGas = 1;
uint64_t getStepCost(Instruction inst)
{
switch (inst)
{
default: // Assumes instruction code is valid
return c_stepGas;
case Instruction::STOP:
case Instruction::SUICIDE:
case Instruction::SSTORE: // Handle cost of SSTORE separately in GasMeter::countSStore()
return 0;
case Instruction::EXP: return c_expGas;
case Instruction::SLOAD: return c_sloadGas;
case Instruction::SHA3: return c_sha3Gas;
case Instruction::BALANCE: return c_balanceGas;
case Instruction::CALL:
case Instruction::CALLCODE: return c_callGas;
case Instruction::CREATE: return c_createGas;
case Instruction::LOG0:
case Instruction::LOG1:
case Instruction::LOG2:
case Instruction::LOG3:
case Instruction::LOG4:
{
auto numTopics = static_cast<uint64_t>(inst) - static_cast<uint64_t>(Instruction::LOG0);
return c_logGas + numTopics * c_logTopicGas;
}
}
}
}
GasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :
CompilerHelper(_builder),
m_runtimeManager(_runtimeManager)
{
auto module = getModule();
llvm::Type* gasCheckArgs[] = {Type::RuntimePtr, Type::Word};
m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, "gas.check", module);
InsertPointGuard guard(m_builder);
auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc);
auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc);
auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc);
m_builder.SetInsertPoint(checkBB);
auto arg = m_gasCheckFunc->arg_begin();
arg->setName("rt");
++arg;
arg->setName("cost");
auto cost = arg;
auto gas = m_runtimeManager.getGas();
auto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, "isOutOfGas");
m_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB);
m_builder.SetInsertPoint(outOfGasBB);
m_runtimeManager.raiseException(ReturnCode::OutOfGas);
m_builder.CreateUnreachable();
m_builder.SetInsertPoint(updateBB);
gas = m_builder.CreateSub(gas, cost);
m_runtimeManager.setGas(gas);
m_builder.CreateRetVoid();
}
void GasMeter::count(Instruction _inst)
{
if (!m_checkCall)
{
// Create gas check call with mocked block cost at begining of current cost-block
m_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getRuntimePtr(), llvm::UndefValue::get(Type::Word)});
}
m_blockCost += getStepCost(_inst);
}
void GasMeter::count(llvm::Value* _cost)
{
createCall(m_gasCheckFunc, {m_runtimeManager.getRuntimePtr(), _cost});
}
void GasMeter::countExp(llvm::Value* _exponent)
{
// Additional cost is 1 per significant byte of exponent
// lz - leading zeros
// cost = ((256 - lz) + 7) / 8
// OPT: All calculations can be done on 32/64 bits
auto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word);
auto lz = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false));
auto sigBits = m_builder.CreateSub(Constant::get(256), lz);
auto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, Constant::get(7)), Constant::get(8));
count(sigBytes);
}
void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)
{
auto oldValue = _ext.sload(_index);
auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero");
auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero");
auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero");
auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero");
auto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isInsert");
auto isDelete = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDelete");
auto cost = m_builder.CreateSelect(isInsert, Constant::get(c_sstoreSetGas), Constant::get(c_sstoreResetGas), "cost");
cost = m_builder.CreateSelect(isDelete, Constant::get(0), cost, "cost");
count(cost);
}
void GasMeter::countLogData(llvm::Value* _dataLength)
{
assert(m_checkCall);
assert(m_blockCost > 0); // LOGn instruction is already counted
static_assert(c_logDataGas == 1, "Log data gas cost has changed. Update GasMeter.");
count(_dataLength);
}
void GasMeter::countSha3Data(llvm::Value* _dataLength)
{
assert(m_checkCall);
assert(m_blockCost > 0); // SHA3 instruction is already counted
// TODO: This round ups to 32 happens in many places
// FIXME: Overflow possible but Memory::require() also called. Probably 64-bit arith can be used.
static_assert(c_sha3WordGas != 1, "SHA3 data cost has changed. Update GasMeter");
auto words = m_builder.CreateUDiv(m_builder.CreateAdd(_dataLength, Constant::get(31)), Constant::get(32));
auto cost = m_builder.CreateNUWMul(Constant::get(c_sha3WordGas), words);
count(cost);
}
void GasMeter::giveBack(llvm::Value* _gas)
{
m_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));
}
void GasMeter::commitCostBlock()
{
// If any uncommited block
if (m_checkCall)
{
if (m_blockCost == 0) // Do not check 0
{
m_checkCall->eraseFromParent(); // Remove the gas check call
m_checkCall = nullptr;
return;
}
m_checkCall->setArgOperand(1, Constant::get(m_blockCost)); // Update block cost in gas check call
m_checkCall = nullptr; // End cost-block
m_blockCost = 0;
}
assert(m_blockCost == 0);
}
void GasMeter::countMemory(llvm::Value* _additionalMemoryInWords)
{
static_assert(c_memoryGas == 1, "Memory gas cost has changed. Update GasMeter.");
count(_additionalMemoryInWords);
}
void GasMeter::countCopy(llvm::Value* _copyWords)
{
static_assert(c_copyGas == 1, "Copy gas cost has changed. Update GasMeter.");
count(_copyWords);
}
}
}
}
|
Remove compleated TODO task
|
Remove compleated TODO task
|
C++
|
mit
|
ethereum/evmjit,ethereum/evmjit,ethereum/evmjit
|
d79d55eb260a46bd3ffabfc22a6f1bbd4754ca1e
|
_studio/shared/umc/codec/av1_dec/src/umc_av1_decoder_va.cpp
|
_studio/shared/umc/codec/av1_dec/src/umc_av1_decoder_va.cpp
|
// Copyright (c) 2017-2020 Intel Corporation
//
// 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 "umc_defs.h"
#ifdef MFX_ENABLE_AV1_VIDEO_DECODE
#include "umc_structures.h"
#include "umc_va_base.h"
#include "umc_av1_decoder_va.h"
#include "umc_av1_utils.h"
#include "umc_av1_frame.h"
#include "umc_av1_bitstream.h"
#include "umc_av1_va_packer.h"
#include "umc_frame_data.h"
#include <algorithm>
namespace UMC_AV1_DECODER
{
AV1DecoderVA::AV1DecoderVA()
: va(nullptr)
{}
UMC::Status AV1DecoderVA::SetParams(UMC::BaseCodecParams* info)
{
if (!info)
return UMC::UMC_ERR_NULL_PTR;
AV1DecoderParams* dp =
DynamicCast<AV1DecoderParams, UMC::BaseCodecParams>(info);
if (!dp)
return UMC::UMC_ERR_INVALID_PARAMS;
if (!dp->pVideoAccelerator)
return UMC::UMC_ERR_NULL_PTR;
va = dp->pVideoAccelerator;
packer.reset(Packer::CreatePacker(va));
uint32_t const dpb_size =
params.async_depth + TOTAL_REFS;
SetDPBSize(dpb_size);
SetRefSize(TOTAL_REFS);
return UMC::UMC_OK;
}
UMC::Status AV1DecoderVA::SubmitTiles(AV1DecoderFrame& frame, bool firstSubmission)
{
VM_ASSERT(va);
UMC::Status sts = UMC::UMC_OK;
if (firstSubmission)
{
// it's first submission for current frame - need to call BeginFrame
#ifdef UMC_VA_LINUX
sts = va->BeginFrame(frame.GetMemID(SURFACE_RECON));
#else
sts = va->BeginFrame(frame.GetMemID());
#endif
if (sts != UMC::UMC_OK)
return sts;
VM_ASSERT(packer);
packer->BeginFrame();
frame.StartDecoding();
}
auto &tileSets = frame.GetTileSets();
packer->PackAU(tileSets, frame, firstSubmission);
const bool lastSubmission = (GetNumMissingTiles(frame) == 0);
if (lastSubmission)
packer->EndFrame();
sts = va->Execute();
if (lastSubmission) // it's last submission for current frame - need to call EndFrame
sts = va->EndFrame();
return sts;
}
void AV1DecoderVA::AllocateFrameData(UMC::VideoDataInfo const& info, UMC::FrameMemID id, AV1DecoderFrame& frame)
{
VM_ASSERT(id != UMC::FRAME_MID_INVALID);
UMC::FrameData fd;
fd.Init(&info, id, allocator);
frame.AllocateAndLock(&fd);
}
inline bool InProgress(AV1DecoderFrame const& frame)
{
return frame.DecodingStarted() && !frame.DecodingCompleted();
}
bool AV1DecoderVA::QueryFrames()
{
std::unique_lock<std::mutex> auto_guard(guard);
// form frame queue in decoded order
DPBType decode_queue;
for (DPBType::iterator frm = dpb.begin(); frm != dpb.end(); frm++)
if (InProgress(**frm))
decode_queue.push_back(*frm);
std::sort(decode_queue.begin(), decode_queue.end(),
[](AV1DecoderFrame const* f1, AV1DecoderFrame const* f2) {return f1->UID < f2->UID; });
// below logic around "wasCompleted" was adopted from AVC/HEVC decoders
bool wasCompleted = false;
// iterate through frames submitted to the driver in decoded order
for (DPBType::iterator frm = decode_queue.begin(); frm != decode_queue.end(); frm++)
{
AV1DecoderFrame& frame = **frm;
uint32_t index = 0;
VAStatus surfErr = VA_STATUS_SUCCESS;
index = frame.GetMemID();
auto_guard.unlock();
UMC::Status sts = packer->SyncTask(index, &surfErr);
auto_guard.lock();
frame.CompleteDecoding();
wasCompleted = true;
if (sts < UMC::UMC_OK)
{
// TODO: [Global] Add GPU hang reporting
}
else if (sts == UMC::UMC_OK)
{
switch (surfErr)
{
case MFX_CORRUPTION_MAJOR:
frame.AddError(UMC::ERROR_FRAME_MAJOR);
break;
case MFX_CORRUPTION_MINOR:
frame.AddError(UMC::ERROR_FRAME_MINOR);
break;
}
}
}
return wasCompleted;
}
}
#endif //MFX_ENABLE_AV1_VIDEO_DECODE
|
// Copyright (c) 2017-2020 Intel Corporation
//
// 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 "umc_defs.h"
#ifdef MFX_ENABLE_AV1_VIDEO_DECODE
#include "umc_structures.h"
#include "umc_va_base.h"
#include "umc_av1_decoder_va.h"
#include "umc_av1_utils.h"
#include "umc_av1_frame.h"
#include "umc_av1_bitstream.h"
#include "umc_av1_va_packer.h"
#include "umc_frame_data.h"
#include <algorithm>
namespace UMC_AV1_DECODER
{
AV1DecoderVA::AV1DecoderVA()
: va(nullptr)
{}
UMC::Status AV1DecoderVA::SetParams(UMC::BaseCodecParams* info)
{
if (!info)
return UMC::UMC_ERR_NULL_PTR;
AV1DecoderParams* dp =
DynamicCast<AV1DecoderParams, UMC::BaseCodecParams>(info);
if (!dp)
return UMC::UMC_ERR_INVALID_PARAMS;
if (!dp->pVideoAccelerator)
return UMC::UMC_ERR_NULL_PTR;
va = dp->pVideoAccelerator;
packer.reset(Packer::CreatePacker(va));
uint32_t const dpb_size =
params.async_depth + TOTAL_REFS;
SetDPBSize(dpb_size);
SetRefSize(TOTAL_REFS);
return UMC::UMC_OK;
}
UMC::Status AV1DecoderVA::SubmitTiles(AV1DecoderFrame& frame, bool firstSubmission)
{
VM_ASSERT(va);
UMC::Status sts = UMC::UMC_OK;
if (firstSubmission)
{
// it's first submission for current frame - need to call BeginFrame
sts = va->BeginFrame(frame.GetMemID(SURFACE_RECON));
if (sts != UMC::UMC_OK)
return sts;
VM_ASSERT(packer);
packer->BeginFrame();
frame.StartDecoding();
}
auto &tileSets = frame.GetTileSets();
packer->PackAU(tileSets, frame, firstSubmission);
const bool lastSubmission = (GetNumMissingTiles(frame) == 0);
if (lastSubmission)
packer->EndFrame();
sts = va->Execute();
if (lastSubmission) // it's last submission for current frame - need to call EndFrame
sts = va->EndFrame();
return sts;
}
void AV1DecoderVA::AllocateFrameData(UMC::VideoDataInfo const& info, UMC::FrameMemID id, AV1DecoderFrame& frame)
{
VM_ASSERT(id != UMC::FRAME_MID_INVALID);
UMC::FrameData fd;
fd.Init(&info, id, allocator);
frame.AllocateAndLock(&fd);
}
inline bool InProgress(AV1DecoderFrame const& frame)
{
return frame.DecodingStarted() && !frame.DecodingCompleted();
}
bool AV1DecoderVA::QueryFrames()
{
std::unique_lock<std::mutex> auto_guard(guard);
// form frame queue in decoded order
DPBType decode_queue;
for (DPBType::iterator frm = dpb.begin(); frm != dpb.end(); frm++)
if (InProgress(**frm))
decode_queue.push_back(*frm);
std::sort(decode_queue.begin(), decode_queue.end(),
[](AV1DecoderFrame const* f1, AV1DecoderFrame const* f2) {return f1->UID < f2->UID; });
// below logic around "wasCompleted" was adopted from AVC/HEVC decoders
bool wasCompleted = false;
// iterate through frames submitted to the driver in decoded order
for (DPBType::iterator frm = decode_queue.begin(); frm != decode_queue.end(); frm++)
{
AV1DecoderFrame& frame = **frm;
uint32_t index = 0;
VAStatus surfErr = VA_STATUS_SUCCESS;
index = frame.GetMemID();
auto_guard.unlock();
UMC::Status sts = packer->SyncTask(index, &surfErr);
auto_guard.lock();
frame.CompleteDecoding();
wasCompleted = true;
if (sts < UMC::UMC_OK)
{
// TODO: [Global] Add GPU hang reporting
}
else if (sts == UMC::UMC_OK)
{
switch (surfErr)
{
case MFX_CORRUPTION_MAJOR:
frame.AddError(UMC::ERROR_FRAME_MAJOR);
break;
case MFX_CORRUPTION_MINOR:
frame.AddError(UMC::ERROR_FRAME_MINOR);
break;
}
}
}
return wasCompleted;
}
}
#endif //MFX_ENABLE_AV1_VIDEO_DECODE
|
Remove UMC_VA_LINUX macro for av1d
|
Remove UMC_VA_LINUX macro for av1d
Signed-off-by: Yan Wang <[email protected]>
|
C++
|
mit
|
Intel-Media-SDK/MediaSDK,Intel-Media-SDK/MediaSDK,Intel-Media-SDK/MediaSDK,Intel-Media-SDK/MediaSDK,Intel-Media-SDK/MediaSDK
|
2d970aead71b5ec203887d14f5cb36ae1f31aec1
|
dali/internal/update/animation/scene-graph-animation.cpp
|
dali/internal/update/animation/scene-graph-animation.cpp
|
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/update/animation/scene-graph-animation.h>
// EXTERNAL INCLUDES
#include <cmath> // fmod
// INTERNAL INCLUDES
#include <dali/internal/common/memory-pool-object-allocator.h>
#include <dali/internal/render/common/performance-monitor.h>
#include <dali/public-api/math/math-utils.h>
namespace //Unnamed namespace
{
//Memory pool used to allocate new animations. Memory used by this pool will be released when shutting down DALi
Dali::Internal::MemoryPoolObjectAllocator<Dali::Internal::SceneGraph::Animation> gAnimationMemoryPool;
inline void WrapInPlayRange( float& elapsed, const float& playRangeStartSeconds, const float& playRangeEndSeconds)
{
if( elapsed > playRangeEndSeconds )
{
elapsed = playRangeStartSeconds + fmodf( ( elapsed - playRangeStartSeconds ), ( playRangeEndSeconds - playRangeStartSeconds ) );
}
else if( elapsed < playRangeStartSeconds )
{
elapsed = playRangeEndSeconds - fmodf( ( playRangeStartSeconds - elapsed ), ( playRangeEndSeconds - playRangeStartSeconds ) );
}
}
/// Compares the end times of the animators and if the end time is less, then it is moved earlier in the list. If end times are the same, then no change.
bool CompareAnimatorEndTimes( const Dali::Internal::SceneGraph::AnimatorBase* lhs, const Dali::Internal::SceneGraph::AnimatorBase* rhs )
{
return ( ( lhs->GetIntervalDelay() + lhs->GetDuration() ) < ( rhs->GetIntervalDelay() + rhs->GetDuration() ) );
}
} // unnamed namespace
namespace Dali
{
namespace Internal
{
namespace SceneGraph
{
Animation* Animation::New( float durationSeconds, float speedFactor, const Vector2& playRange, int32_t loopCount, EndAction endAction, EndAction disconnectAction )
{
return new ( gAnimationMemoryPool.AllocateRawThreadSafe() ) Animation( durationSeconds, speedFactor, playRange, loopCount, endAction, disconnectAction );
}
Animation::Animation( float durationSeconds, float speedFactor, const Vector2& playRange, int32_t loopCount, Dali::Animation::EndAction endAction, Dali::Animation::EndAction disconnectAction )
: mPlayRange( playRange ),
mDurationSeconds( durationSeconds ),
mDelaySeconds( 0.0f ),
mElapsedSeconds( playRange.x*mDurationSeconds ),
mSpeedFactor( speedFactor ),
mProgressMarker( 0.0f ),
mPlayedCount( 0 ),
mLoopCount(loopCount),
mCurrentLoop(0),
mEndAction(endAction),
mDisconnectAction(disconnectAction),
mState(Stopped),
mProgressReachedSignalRequired( false ),
mAutoReverseEnabled( false ),
mIsActive{ false }
{
}
Animation::~Animation() = default;
void Animation::operator delete( void* ptr )
{
gAnimationMemoryPool.FreeThreadSafe( static_cast<Animation*>( ptr ) );
}
void Animation::SetDuration(float durationSeconds)
{
mDurationSeconds = durationSeconds;
}
void Animation::SetProgressNotification( float progress )
{
mProgressMarker = progress;
if ( mProgressMarker > 0.0f )
{
mProgressReachedSignalRequired = true;
}
}
void Animation::SetLoopCount(int32_t loopCount)
{
mLoopCount = loopCount;
mCurrentLoop = 0;
}
void Animation::SetEndAction(Dali::Animation::EndAction action)
{
mEndAction = action;
}
void Animation::SetDisconnectAction(Dali::Animation::EndAction action)
{
if ( mDisconnectAction != action )
{
mDisconnectAction = action;
for ( auto&& item : mAnimators )
{
item->SetDisconnectAction( action );
}
}
}
void Animation::SetPlayRange( const Vector2& range )
{
mPlayRange = range;
// Make sure mElapsedSeconds is within the new range
if( mState == Stopped )
{
// Ensure that the animation starts at the right place
mElapsedSeconds = mPlayRange.x * mDurationSeconds;
}
else
{
// If already past the end of the range, but before end of duration, then clamp will
// ensure that the animation stops on the next update.
// If not yet at the start of the range, clamping will jump to the start
mElapsedSeconds = Dali::Clamp(mElapsedSeconds, mPlayRange.x*mDurationSeconds , mPlayRange.y*mDurationSeconds );
}
}
void Animation::Play()
{
// Sort according to end time with earlier end times coming first, if the end time is the same, then the animators are not moved
std::stable_sort( mAnimators.Begin(), mAnimators.End(), CompareAnimatorEndTimes );
mState = Playing;
if ( mSpeedFactor < 0.0f && mElapsedSeconds <= mPlayRange.x*mDurationSeconds )
{
mElapsedSeconds = mPlayRange.y * mDurationSeconds;
}
SetAnimatorsActive( true );
mCurrentLoop = 0;
}
void Animation::PlayFrom( float progress )
{
// If the animation is already playing this has no effect
// Progress is guaranteed to be in range.
if( mState != Playing )
{
mElapsedSeconds = progress * mDurationSeconds;
mState = Playing;
SetAnimatorsActive( true );
mCurrentLoop = 0;
}
}
void Animation::PlayAfter( float delaySeconds )
{
if( mState != Playing )
{
mDelaySeconds = delaySeconds;
mState = Playing;
if ( mSpeedFactor < 0.0f && mElapsedSeconds <= mPlayRange.x*mDurationSeconds )
{
mElapsedSeconds = mPlayRange.y * mDurationSeconds;
}
SetAnimatorsActive( true );
mCurrentLoop = 0;
}
}
void Animation::Pause()
{
if (mState == Playing)
{
mState = Paused;
}
}
void Animation::Bake(BufferIndex bufferIndex, EndAction action)
{
if( action == Dali::Animation::BAKE_FINAL )
{
if( mSpeedFactor > 0.0f )
{
mElapsedSeconds = mPlayRange.y*mDurationSeconds + Math::MACHINE_EPSILON_1; // Force animation to reach it's end
}
else
{
mElapsedSeconds = mPlayRange.x*mDurationSeconds - Math::MACHINE_EPSILON_1; //Force animation to reach it's beginning
}
}
UpdateAnimators( bufferIndex, true/*bake the final result*/, true /*animation finished*/ );
}
void Animation::SetAnimatorsActive( bool active )
{
for ( auto&& item : mAnimators )
{
item->SetActive( active );
}
}
bool Animation::Stop(BufferIndex bufferIndex)
{
bool animationFinished(false);
if (mState == Playing || mState == Paused)
{
animationFinished = true; // The actor-thread should be notified of this
if( mEndAction != Dali::Animation::DISCARD )
{
Bake( bufferIndex, mEndAction );
// Animators are automatically set to inactive in Bake
}
else
{
SetAnimatorsActive( false );
}
// The animation has now been played to completion
++mPlayedCount;
mCurrentLoop = 0;
}
mElapsedSeconds = mPlayRange.x*mDurationSeconds;
mState = Stopped;
return animationFinished;
}
void Animation::OnDestroy(BufferIndex bufferIndex)
{
if (mState == Playing || mState == Paused)
{
if (mEndAction != Dali::Animation::DISCARD)
{
Bake( bufferIndex, mEndAction );
// Animators are automatically set to inactive in Bake
}
else
{
SetAnimatorsActive( false );
}
}
mState = Destroyed;
}
void Animation::SetLoopingMode( bool loopingMode )
{
mAutoReverseEnabled = loopingMode;
for ( auto&& item : mAnimators )
{
// Send some variables together to figure out the Animation status
item->SetSpeedFactor( mSpeedFactor );
item->SetLoopCount( mLoopCount );
item->SetLoopingMode( loopingMode );
}
}
void Animation::AddAnimator( OwnerPointer<AnimatorBase>& animator )
{
animator->ConnectToSceneGraph();
animator->SetDisconnectAction( mDisconnectAction );
mAnimators.PushBack( animator.Release() );
}
void Animation::Update( BufferIndex bufferIndex, float elapsedSeconds, bool& looped, bool& finished, bool& progressReached )
{
looped = false;
finished = false;
if (mState == Stopped || mState == Destroyed)
{
// Short circuit when animation isn't running
return;
}
// The animation must still be applied when Paused/Stopping
if (mState == Playing)
{
// Sign value of speed factor. It can optimize many arithmetic comparision
float signSpeedFactor = ( mSpeedFactor < 0.0f ) ? -1.f : 1.f;
// If there is delay time before Animation starts, wait the Animation until mDelaySeconds.
if( mDelaySeconds > 0.0f )
{
float reduceSeconds = fabsf( elapsedSeconds * mSpeedFactor );
if( reduceSeconds > mDelaySeconds )
{
// add overflowed time to mElapsedSecond.
// If speed factor > 0, add it. if speed factor < 0, subtract it.
float overflowSeconds = reduceSeconds - mDelaySeconds;
mElapsedSeconds += signSpeedFactor * overflowSeconds;
mDelaySeconds = 0.0f;
}
else
{
mDelaySeconds -= reduceSeconds;
}
}
else
{
mElapsedSeconds += ( elapsedSeconds * mSpeedFactor );
}
const float playRangeStartSeconds = mPlayRange.x * mDurationSeconds;
const float playRangeEndSeconds = mPlayRange.y * mDurationSeconds;
// Final reached seconds. It can optimize many arithmetic comparision
float edgeRangeSeconds = ( mSpeedFactor < 0.0f ) ? playRangeStartSeconds : playRangeEndSeconds;
// Optimized Factors.
// elapsed > edge --> check if looped
// elapsed >= marker --> check if elapsed reached to marker in normal case
// edge >= marker --> check if elapsed reached to marker in looped case
float elapsedFactor = signSpeedFactor * mElapsedSeconds;
float edgeFactor = signSpeedFactor * edgeRangeSeconds;
float markerFactor = signSpeedFactor * mProgressMarker;
// check it is looped
looped = ( elapsedFactor > edgeFactor );
if( looped )
{
WrapInPlayRange( mElapsedSeconds, playRangeStartSeconds, playRangeEndSeconds );
// Recalculate elapsedFactor here
elapsedFactor = signSpeedFactor * mElapsedSeconds;
if( mLoopCount != 0 )
{
// Check If this animation is finished
++mCurrentLoop;
if( mCurrentLoop >= mLoopCount )
{
DALI_ASSERT_DEBUG( mCurrentLoop == mLoopCount );
finished = true;
// The animation has now been played to completion
++mPlayedCount;
// Make elapsed second as edge of range forcely.
mElapsedSeconds = edgeRangeSeconds + signSpeedFactor * Math::MACHINE_EPSILON_10;
UpdateAnimators(bufferIndex, finished && (mEndAction != Dali::Animation::DISCARD), finished );
// After update animation, mElapsedSeconds must be begin of value
mElapsedSeconds = playRangeStartSeconds + playRangeEndSeconds - edgeRangeSeconds;
mState = Stopped;
}
}
// when it is on looped state, 2 case to send progress signal.
// (require && range_value >= marker) || << Signal at previous loop
// (marker > 0 && !finished && elaped >= marker) << Signal at current loop
if( ( mProgressMarker > 0.0f ) && !finished && ( elapsedFactor >= markerFactor ) )
{
// The application should be notified by NotificationManager, in another thread
progressReached = true;
mProgressReachedSignalRequired = false;
}
else
{
if( mProgressReachedSignalRequired && ( edgeFactor >= markerFactor ) )
{
progressReached = true;
}
mProgressReachedSignalRequired = mProgressMarker > 0.0f;
}
}
else
{
// when it is not on looped state, only 1 case to send progress signal.
// (require && elaped >= marker)
if( mProgressReachedSignalRequired && ( elapsedFactor >= markerFactor ) )
{
// The application should be notified by NotificationManager, in another thread
progressReached = true;
mProgressReachedSignalRequired = false;
}
}
}
// Already updated when finished. So skip.
if( !finished )
{
UpdateAnimators(bufferIndex, false, false );
}
}
void Animation::UpdateAnimators( BufferIndex bufferIndex, bool bake, bool animationFinished )
{
mIsActive[bufferIndex] = false;
const Vector2 playRange( mPlayRange * mDurationSeconds );
float elapsedSecondsClamped = Clamp( mElapsedSeconds, playRange.x, playRange.y );
//Remove animators whose PropertyOwner has been destroyed
mAnimators.Erase(std::remove_if(mAnimators.begin(),
mAnimators.end(),
[](auto animator) { return animator->Orphan(); }),
mAnimators.end());
//Loop through all animators
for(auto& animator : mAnimators)
{
bool applied(true);
if(animator->IsEnabled())
{
const float intervalDelay(animator->GetIntervalDelay());
if(elapsedSecondsClamped >= intervalDelay)
{
// Calculate a progress specific to each individual animator
float progress(1.0f);
const float animatorDuration = animator->GetDuration();
if(animatorDuration > 0.0f) // animators can be "immediate"
{
progress = Clamp((elapsedSecondsClamped - intervalDelay) / animatorDuration, 0.0f, 1.0f);
}
animator->Update(bufferIndex, progress, bake);
if (animatorDuration > 0.0f && (elapsedSecondsClamped - intervalDelay) <= animatorDuration)
{
mIsActive[bufferIndex] = true;
}
}
applied = true;
}
else
{
applied = false;
}
if(animationFinished)
{
animator->SetActive(false);
}
if(applied)
{
INCREASE_COUNTER(PerformanceMonitor::ANIMATORS_APPLIED);
}
}
}
} // namespace SceneGraph
} // namespace Internal
} // namespace Dali
|
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/update/animation/scene-graph-animation.h>
// EXTERNAL INCLUDES
#include <cmath> // fmod
// INTERNAL INCLUDES
#include <dali/internal/common/memory-pool-object-allocator.h>
#include <dali/internal/render/common/performance-monitor.h>
#include <dali/public-api/math/math-utils.h>
namespace //Unnamed namespace
{
//Memory pool used to allocate new animations. Memory used by this pool will be released when shutting down DALi
Dali::Internal::MemoryPoolObjectAllocator<Dali::Internal::SceneGraph::Animation> gAnimationMemoryPool;
inline void WrapInPlayRange( float& elapsed, const float& playRangeStartSeconds, const float& playRangeEndSeconds)
{
if( elapsed > playRangeEndSeconds )
{
elapsed = playRangeStartSeconds + fmodf( ( elapsed - playRangeStartSeconds ), ( playRangeEndSeconds - playRangeStartSeconds ) );
}
else if( elapsed < playRangeStartSeconds )
{
elapsed = playRangeEndSeconds - fmodf( ( playRangeStartSeconds - elapsed ), ( playRangeEndSeconds - playRangeStartSeconds ) );
}
}
/// Compares the end times of the animators and if the end time is less, then it is moved earlier in the list. If end times are the same, then no change.
bool CompareAnimatorEndTimes( const Dali::Internal::SceneGraph::AnimatorBase* lhs, const Dali::Internal::SceneGraph::AnimatorBase* rhs )
{
return ( ( lhs->GetIntervalDelay() + lhs->GetDuration() ) < ( rhs->GetIntervalDelay() + rhs->GetDuration() ) );
}
} // unnamed namespace
namespace Dali
{
namespace Internal
{
namespace SceneGraph
{
Animation* Animation::New( float durationSeconds, float speedFactor, const Vector2& playRange, int32_t loopCount, EndAction endAction, EndAction disconnectAction )
{
return new ( gAnimationMemoryPool.AllocateRawThreadSafe() ) Animation( durationSeconds, speedFactor, playRange, loopCount, endAction, disconnectAction );
}
Animation::Animation( float durationSeconds, float speedFactor, const Vector2& playRange, int32_t loopCount, Dali::Animation::EndAction endAction, Dali::Animation::EndAction disconnectAction )
: mPlayRange( playRange ),
mDurationSeconds( durationSeconds ),
mDelaySeconds( 0.0f ),
mElapsedSeconds( playRange.x*mDurationSeconds ),
mSpeedFactor( speedFactor ),
mProgressMarker( 0.0f ),
mPlayedCount( 0 ),
mLoopCount(loopCount),
mCurrentLoop(0),
mEndAction(endAction),
mDisconnectAction(disconnectAction),
mState(Stopped),
mProgressReachedSignalRequired( false ),
mAutoReverseEnabled( false ),
mIsActive{ false }
{
}
Animation::~Animation() = default;
void Animation::operator delete( void* ptr )
{
gAnimationMemoryPool.FreeThreadSafe( static_cast<Animation*>( ptr ) );
}
void Animation::SetDuration(float durationSeconds)
{
mDurationSeconds = durationSeconds;
}
void Animation::SetProgressNotification( float progress )
{
mProgressMarker = progress;
if ( mProgressMarker > 0.0f )
{
mProgressReachedSignalRequired = true;
}
}
void Animation::SetLoopCount(int32_t loopCount)
{
mLoopCount = loopCount;
mCurrentLoop = 0;
}
void Animation::SetEndAction(Dali::Animation::EndAction action)
{
mEndAction = action;
}
void Animation::SetDisconnectAction(Dali::Animation::EndAction action)
{
if ( mDisconnectAction != action )
{
mDisconnectAction = action;
for ( auto&& item : mAnimators )
{
item->SetDisconnectAction( action );
}
}
}
void Animation::SetPlayRange( const Vector2& range )
{
mPlayRange = range;
// Make sure mElapsedSeconds is within the new range
if( mState == Stopped )
{
// Ensure that the animation starts at the right place
mElapsedSeconds = mPlayRange.x * mDurationSeconds;
}
else
{
// If already past the end of the range, but before end of duration, then clamp will
// ensure that the animation stops on the next update.
// If not yet at the start of the range, clamping will jump to the start
mElapsedSeconds = Dali::Clamp(mElapsedSeconds, mPlayRange.x*mDurationSeconds , mPlayRange.y*mDurationSeconds );
}
}
void Animation::Play()
{
// Sort according to end time with earlier end times coming first, if the end time is the same, then the animators are not moved
std::stable_sort( mAnimators.Begin(), mAnimators.End(), CompareAnimatorEndTimes );
mState = Playing;
if ( mSpeedFactor < 0.0f && mElapsedSeconds <= mPlayRange.x*mDurationSeconds )
{
mElapsedSeconds = mPlayRange.y * mDurationSeconds;
}
SetAnimatorsActive( true );
mCurrentLoop = 0;
}
void Animation::PlayFrom( float progress )
{
// If the animation is already playing this has no effect
// Progress is guaranteed to be in range.
if( mState != Playing )
{
mElapsedSeconds = progress * mDurationSeconds;
mState = Playing;
SetAnimatorsActive( true );
mCurrentLoop = 0;
}
}
void Animation::PlayAfter( float delaySeconds )
{
if( mState != Playing )
{
mDelaySeconds = delaySeconds;
mState = Playing;
if ( mSpeedFactor < 0.0f && mElapsedSeconds <= mPlayRange.x*mDurationSeconds )
{
mElapsedSeconds = mPlayRange.y * mDurationSeconds;
}
SetAnimatorsActive( true );
mCurrentLoop = 0;
}
}
void Animation::Pause()
{
if (mState == Playing)
{
mState = Paused;
}
}
void Animation::Bake(BufferIndex bufferIndex, EndAction action)
{
if( action == Dali::Animation::BAKE_FINAL )
{
if( mSpeedFactor > 0.0f )
{
mElapsedSeconds = mPlayRange.y*mDurationSeconds + Math::MACHINE_EPSILON_1; // Force animation to reach it's end
}
else
{
mElapsedSeconds = mPlayRange.x*mDurationSeconds - Math::MACHINE_EPSILON_1; //Force animation to reach it's beginning
}
}
UpdateAnimators( bufferIndex, true/*bake the final result*/, true /*animation finished*/ );
}
void Animation::SetAnimatorsActive( bool active )
{
for ( auto&& item : mAnimators )
{
item->SetActive( active );
}
}
bool Animation::Stop(BufferIndex bufferIndex)
{
bool animationFinished(false);
if (mState == Playing || mState == Paused)
{
animationFinished = true; // The actor-thread should be notified of this
if( mEndAction != Dali::Animation::DISCARD )
{
Bake( bufferIndex, mEndAction );
// Animators are automatically set to inactive in Bake
}
else
{
SetAnimatorsActive( false );
}
// The animation has now been played to completion
++mPlayedCount;
mCurrentLoop = 0;
}
mElapsedSeconds = mPlayRange.x*mDurationSeconds;
mState = Stopped;
return animationFinished;
}
void Animation::OnDestroy(BufferIndex bufferIndex)
{
if (mState == Playing || mState == Paused)
{
if (mEndAction != Dali::Animation::DISCARD)
{
Bake( bufferIndex, mEndAction );
// Animators are automatically set to inactive in Bake
}
else
{
SetAnimatorsActive( false );
}
}
mState = Destroyed;
}
void Animation::SetLoopingMode( bool loopingMode )
{
mAutoReverseEnabled = loopingMode;
for ( auto&& item : mAnimators )
{
// Send some variables together to figure out the Animation status
item->SetSpeedFactor( mSpeedFactor );
item->SetLoopCount( mLoopCount );
item->SetLoopingMode( loopingMode );
}
}
void Animation::AddAnimator( OwnerPointer<AnimatorBase>& animator )
{
animator->ConnectToSceneGraph();
animator->SetDisconnectAction( mDisconnectAction );
mAnimators.PushBack( animator.Release() );
}
void Animation::Update( BufferIndex bufferIndex, float elapsedSeconds, bool& looped, bool& finished, bool& progressReached )
{
looped = false;
finished = false;
if (mState == Stopped || mState == Destroyed)
{
// Short circuit when animation isn't running
return;
}
// The animation must still be applied when Paused/Stopping
if (mState == Playing)
{
// Sign value of speed factor. It can optimize many arithmetic comparision
float signSpeedFactor = ( mSpeedFactor < 0.0f ) ? -1.f : 1.f;
// If there is delay time before Animation starts, wait the Animation until mDelaySeconds.
if( mDelaySeconds > 0.0f )
{
float reduceSeconds = fabsf( elapsedSeconds * mSpeedFactor );
if( reduceSeconds > mDelaySeconds )
{
// add overflowed time to mElapsedSecond.
// If speed factor > 0, add it. if speed factor < 0, subtract it.
float overflowSeconds = reduceSeconds - mDelaySeconds;
mElapsedSeconds += signSpeedFactor * overflowSeconds;
mDelaySeconds = 0.0f;
}
else
{
mDelaySeconds -= reduceSeconds;
}
}
else
{
mElapsedSeconds += ( elapsedSeconds * mSpeedFactor );
}
const float playRangeStartSeconds = mPlayRange.x * mDurationSeconds;
const float playRangeEndSeconds = mPlayRange.y * mDurationSeconds;
// Final reached seconds. It can optimize many arithmetic comparision
float edgeRangeSeconds = ( mSpeedFactor < 0.0f ) ? playRangeStartSeconds : playRangeEndSeconds;
// Optimized Factors.
// elapsed > edge --> check if looped
// elapsed >= marker --> check if elapsed reached to marker in normal case
// edge >= marker --> check if elapsed reached to marker in looped case
float elapsedFactor = signSpeedFactor * mElapsedSeconds;
float edgeFactor = signSpeedFactor * edgeRangeSeconds;
float markerFactor = signSpeedFactor * mProgressMarker;
// check it is looped
looped = ( elapsedFactor > edgeFactor );
if( looped )
{
WrapInPlayRange( mElapsedSeconds, playRangeStartSeconds, playRangeEndSeconds );
// Recalculate elapsedFactor here
elapsedFactor = signSpeedFactor * mElapsedSeconds;
if( mLoopCount != 0 )
{
// Check If this animation is finished
++mCurrentLoop;
if( mCurrentLoop >= mLoopCount )
{
DALI_ASSERT_DEBUG( mCurrentLoop == mLoopCount );
finished = true;
// The animation has now been played to completion
++mPlayedCount;
// Make elapsed second as edge of range forcely.
mElapsedSeconds = edgeRangeSeconds + signSpeedFactor * Math::MACHINE_EPSILON_10;
UpdateAnimators(bufferIndex, finished && (mEndAction != Dali::Animation::DISCARD), finished );
// After update animation, mElapsedSeconds must be begin of value
mElapsedSeconds = playRangeStartSeconds + playRangeEndSeconds - edgeRangeSeconds;
mState = Stopped;
}
}
// when it is on looped state, 2 case to send progress signal.
// (require && range_value >= marker) || << Signal at previous loop
// (marker > 0 && !finished && elaped >= marker) << Signal at current loop
if( ( mProgressMarker > 0.0f ) && !finished && ( elapsedFactor >= markerFactor ) )
{
// The application should be notified by NotificationManager, in another thread
progressReached = true;
mProgressReachedSignalRequired = false;
}
else
{
if( mProgressReachedSignalRequired && ( edgeFactor >= markerFactor ) )
{
progressReached = true;
}
mProgressReachedSignalRequired = mProgressMarker > 0.0f;
}
}
else
{
// when it is not on looped state, only 1 case to send progress signal.
// (require && elaped >= marker)
if( mProgressReachedSignalRequired && ( elapsedFactor >= markerFactor ) )
{
// The application should be notified by NotificationManager, in another thread
progressReached = true;
mProgressReachedSignalRequired = false;
}
}
}
// Already updated when finished. So skip.
if( !finished )
{
UpdateAnimators(bufferIndex, false, false );
}
}
void Animation::UpdateAnimators( BufferIndex bufferIndex, bool bake, bool animationFinished )
{
mIsActive[bufferIndex] = false;
const Vector2 playRange( mPlayRange * mDurationSeconds );
float elapsedSecondsClamped = Clamp( mElapsedSeconds, playRange.x, playRange.y );
bool cleanup = false;
//Loop through all animators
for(auto& animator : mAnimators)
{
if(animator->Orphan())
{
cleanup = true;
continue;
}
bool applied(true);
if(animator->IsEnabled())
{
const float intervalDelay(animator->GetIntervalDelay());
if(elapsedSecondsClamped >= intervalDelay)
{
// Calculate a progress specific to each individual animator
float progress(1.0f);
const float animatorDuration = animator->GetDuration();
if(animatorDuration > 0.0f) // animators can be "immediate"
{
progress = Clamp((elapsedSecondsClamped - intervalDelay) / animatorDuration, 0.0f, 1.0f);
}
animator->Update(bufferIndex, progress, bake);
if (animatorDuration > 0.0f && (elapsedSecondsClamped - intervalDelay) <= animatorDuration)
{
mIsActive[bufferIndex] = true;
}
}
applied = true;
}
else
{
applied = false;
}
if(animationFinished)
{
animator->SetActive(false);
}
if(applied)
{
INCREASE_COUNTER(PerformanceMonitor::ANIMATORS_APPLIED);
}
}
if(cleanup)
{
//Remove animators whose PropertyOwner has been destroyed
mAnimators.Erase(std::remove_if(mAnimators.begin(),
mAnimators.end(),
[](auto& animator) { return animator->Orphan(); }),
mAnimators.end());
}
}
} // namespace SceneGraph
} // namespace Internal
} // namespace Dali
|
Optimize Orphan animator Cleanup.
|
Optimize Orphan animator Cleanup.
keep a cleanup falg and update it if cleanup is required.
and then cleanup at onece all the orphan animators.
when there are no orphan animators we don't have to walk the animators twice.
Change-Id: I9c2f7f2bef9a7655481743a22abdf366d8b12f21
|
C++
|
apache-2.0
|
dalihub/dali-core,dalihub/dali-core,dalihub/dali-core,dalihub/dali-core
|
2feb6279294a38c9686c9f98047ec5083650c695
|
src/validators/common/CMAny.cpp
|
src/validators/common/CMAny.cpp
|
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 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.5 2001/07/09 15:22:35 knoaman
* complete <any> declaration.
*
* Revision 1.4 2001/06/07 20:58:38 tng
* Fix no newline at the end warning. By Pei Yong Zhang.
*
* Revision 1.3 2001/05/11 13:27:14 tng
* Copyright update.
*
* Revision 1.2 2001/05/03 21:02:27 tng
* Schema: Add SubstitutionGroupComparator and update exception messages. By Pei Yong Zhang.
*
* Revision 1.1 2001/02/27 14:48:45 tng
* Schema: Add CMAny and ContentLeafNameTypeVector, by Pei Yong Zhang
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XercesDefs.hpp>
#include <util/RuntimeException.hpp>
#include <validators/common/CMStateSet.hpp>
#include <validators/common/CMAny.hpp>
// ---------------------------------------------------------------------------
// CMUnaryOp: Constructors and Destructor
// ---------------------------------------------------------------------------
CMAny::CMAny( const ContentSpecNode::NodeTypes type
, const unsigned int URI
, const unsigned int position ) :
CMNode(type)
, fURI(URI)
, fPosition(position)
{
if ((type != ContentSpecNode::Any)
&& (type != ContentSpecNode::Any_Other)
&& (type != ContentSpecNode::Any_NS))
{
ThrowXML1(RuntimeException,
XMLExcepts::CM_NotValidSpecTypeForNode,
"CMAny");
}
}
CMAny::~CMAny()
{
}
// ---------------------------------------------------------------------------
// Getter methods
// ---------------------------------------------------------------------------
unsigned int CMAny::getURI() const
{
return fURI;
}
unsigned int CMAny::getPosition() const
{
return fPosition;
}
// ---------------------------------------------------------------------------
// Setter methods
// ---------------------------------------------------------------------------
void CMAny::setPosition(const unsigned int newPosition)
{
fPosition = newPosition;
}
// ---------------------------------------------------------------------------
// Implementation of public CMNode virtual interface
// ---------------------------------------------------------------------------
bool CMAny::isNullable() const
{
// Leaf nodes are never nullable unless its an epsilon node
return (fPosition == -1);
}
// ---------------------------------------------------------------------------
// Implementation of protected CMNode virtual interface
// ---------------------------------------------------------------------------
void CMAny::calcFirstPos(CMStateSet& toSet) const
{
// If we are an epsilon node, then the first pos is an empty set
if (fPosition == -1)
toSet.zeroBits();
else
// Otherwise, its just the one bit of our position
toSet.setBit(fPosition);
return;
}
void CMAny::calcLastPos(CMStateSet& toSet) const
{
// If we are an epsilon node, then the last pos is an empty set
if (fPosition == -1)
toSet.zeroBits();
// Otherwise, its just the one bit of our position
else
toSet.setBit(fPosition);
return;
}
|
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 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.6 2001/08/08 13:23:27 knoaman
* Fix condition check.
*
* Revision 1.5 2001/07/09 15:22:35 knoaman
* complete <any> declaration.
*
* Revision 1.4 2001/06/07 20:58:38 tng
* Fix no newline at the end warning. By Pei Yong Zhang.
*
* Revision 1.3 2001/05/11 13:27:14 tng
* Copyright update.
*
* Revision 1.2 2001/05/03 21:02:27 tng
* Schema: Add SubstitutionGroupComparator and update exception messages. By Pei Yong Zhang.
*
* Revision 1.1 2001/02/27 14:48:45 tng
* Schema: Add CMAny and ContentLeafNameTypeVector, by Pei Yong Zhang
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XercesDefs.hpp>
#include <util/RuntimeException.hpp>
#include <validators/common/CMStateSet.hpp>
#include <validators/common/CMAny.hpp>
// ---------------------------------------------------------------------------
// CMUnaryOp: Constructors and Destructor
// ---------------------------------------------------------------------------
CMAny::CMAny( const ContentSpecNode::NodeTypes type
, const unsigned int URI
, const unsigned int position ) :
CMNode(type)
, fURI(URI)
, fPosition(position)
{
if ((type & 0x0f) != ContentSpecNode::Any
&& (type & 0x0f) != ContentSpecNode::Any_Other
&& (type & 0x0f) != ContentSpecNode::Any_NS)
{
ThrowXML1(RuntimeException,
XMLExcepts::CM_NotValidSpecTypeForNode,
"CMAny");
}
}
CMAny::~CMAny()
{
}
// ---------------------------------------------------------------------------
// Getter methods
// ---------------------------------------------------------------------------
unsigned int CMAny::getURI() const
{
return fURI;
}
unsigned int CMAny::getPosition() const
{
return fPosition;
}
// ---------------------------------------------------------------------------
// Setter methods
// ---------------------------------------------------------------------------
void CMAny::setPosition(const unsigned int newPosition)
{
fPosition = newPosition;
}
// ---------------------------------------------------------------------------
// Implementation of public CMNode virtual interface
// ---------------------------------------------------------------------------
bool CMAny::isNullable() const
{
// Leaf nodes are never nullable unless its an epsilon node
return (fPosition == -1);
}
// ---------------------------------------------------------------------------
// Implementation of protected CMNode virtual interface
// ---------------------------------------------------------------------------
void CMAny::calcFirstPos(CMStateSet& toSet) const
{
// If we are an epsilon node, then the first pos is an empty set
if (fPosition == -1)
toSet.zeroBits();
else
// Otherwise, its just the one bit of our position
toSet.setBit(fPosition);
return;
}
void CMAny::calcLastPos(CMStateSet& toSet) const
{
// If we are an epsilon node, then the last pos is an empty set
if (fPosition == -1)
toSet.zeroBits();
// Otherwise, its just the one bit of our position
else
toSet.setBit(fPosition);
return;
}
|
Fix condition check.
|
Fix condition check.
git-svn-id: 3ec853389310512053d525963cab269c063bb453@172941 13f79535-47bb-0310-9956-ffa450edef68
|
C++
|
apache-2.0
|
AaronNGray/xerces,AaronNGray/xerces,AaronNGray/xerces,AaronNGray/xerces
|
968e5fc60ce4ffdf514313f619daf839ee7e22e1
|
chrome/browser/extensions/api/media_galleries_private/media_galleries_private_apitest.cc
|
chrome/browser/extensions/api/media_galleries_private/media_galleries_private_apitest.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/media_galleries_private/media_galleries_private_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/storage_monitor/storage_info.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "googleurl/src/gurl.h"
namespace {
// Id of test extension from
// chrome/test/data/extensions/api_test/|kTestExtensionPath|
const char kTestExtensionId[] = "lkegdcleigedmkiikoijjgfchobofdbe";
const char kTestExtensionPath[] = "media_galleries_private/attachdetach";
// JS commands.
const char kAddAttachListenerCmd[] = "addAttachListener()";
const char kAddDetachListenerCmd[] = "addDetachListener()";
const char kAddDummyDetachListenerCmd[] = "addDummyDetachListener()";
const char kRemoveAttachListenerCmd[] = "removeAttachListener()";
const char kRemoveDummyDetachListenerCmd[] = "removeDummyDetachListener()";
// And JS reply messages.
const char kAddAttachListenerOk[] = "add_attach_ok";
const char kAddDetachListenerOk[] = "add_detach_ok";
const char kAddDummyDetachListenerOk[] = "add_dummy_detach_ok";
const char kRemoveAttachListenerOk[] = "remove_attach_ok";
const char kRemoveDummyDetachListenerOk[] = "remove_dummy_detach_ok";
// Test reply messages.
const char kAttachTestOk[] = "attach_test_ok";
const char kDetachTestOk[] = "detach_test_ok";
// Dummy device properties.
const char kDeviceId[] = "testDeviceId";
const char kDeviceName[] = "foobar";
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");
} // namespace
class MediaGalleriesPrivateApiTest : public ExtensionApiTest {
public:
MediaGalleriesPrivateApiTest() {}
virtual ~MediaGalleriesPrivateApiTest() {}
// ExtensionApiTest overrides.
virtual void SetUp() OVERRIDE {
device_id_ = chrome::StorageInfo::MakeDeviceId(
chrome::StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);
ExtensionApiTest::SetUp();
}
protected:
// ExtensionApiTest overrides.
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kWhitelistedExtensionID,
kTestExtensionId);
}
void ChangeListener(content::RenderViewHost* host,
const std::string& js_command,
const std::string& ok_message) {
ExtensionTestMessageListener listener(ok_message, false /* no reply */);
host->ExecuteJavascriptInWebFrame(string16(), ASCIIToUTF16(js_command));
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
void AttachDetach() {
Attach();
Detach();
}
void Attach() {
chrome::StorageInfo info(device_id_, ASCIIToUTF16(kDeviceName), kDevicePath,
string16(), string16(), string16(), 0);
chrome::StorageMonitor::GetInstance()->receiver()->ProcessAttach(info);
WaitForDeviceEvents();
}
void Detach() {
chrome::StorageMonitor::GetInstance()->receiver()->ProcessDetach(
device_id_);
WaitForDeviceEvents();
}
private:
void WaitForDeviceEvents() {
content::RunAllPendingInMessageLoop();
}
std::string device_id_;
DISALLOW_COPY_AND_ASSIGN(MediaGalleriesPrivateApiTest);
};
// TODO(jschuh): Flaky on Win64 & Linux Aura build. crbug.com/247336
#if (defined(OS_WIN) && defined(ARCH_CPU_X86_64)) || \
(defined(OS_LINUX) && defined(USE_AURA))
#define MAYBE_DeviceAttachDetachEvents DISABLED_DeviceAttachDetachEvents
#else
#define MAYBE_DeviceAttachDetachEvents DeviceAttachDetachEvents
#endif
IN_PROC_BROWSER_TEST_F(MediaGalleriesPrivateApiTest,
MAYBE_DeviceAttachDetachEvents) {
// Setup.
const extensions::Extension* extension =
LoadExtension(test_data_dir_.AppendASCII(kTestExtensionPath));
ASSERT_TRUE(extension);
content::RenderViewHost* host =
extensions::ExtensionSystem::Get(browser()->profile())->
process_manager()->GetBackgroundHostForExtension(extension->id())->
render_view_host();
ASSERT_TRUE(host);
// No listeners, attach and detach a couple times.
AttachDetach();
AttachDetach();
// Add attach listener.
ChangeListener(host, kAddAttachListenerCmd, kAddAttachListenerOk);
// Attach / detach
const std::string expect_attach_msg =
base::StringPrintf("%s,%s", kAttachTestOk, kDeviceName);
ExtensionTestMessageListener attach_finished_listener(expect_attach_msg,
false /* no reply */);
Attach();
EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());
Detach();
// Attach / detach
Attach();
EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());
// Detach
Detach();
// Remove attach listener.
ChangeListener(host, kRemoveAttachListenerCmd, kRemoveAttachListenerOk);
// No listeners, attach and detach a couple times.
AttachDetach();
AttachDetach();
// Add detach listener.
ChangeListener(host, kAddDummyDetachListenerCmd, kAddDummyDetachListenerOk);
// Attach / detach
Attach();
ExtensionTestMessageListener detach_finished_listener(kDetachTestOk,
false /* no reply */);
Detach();
EXPECT_TRUE(detach_finished_listener.WaitUntilSatisfied());
// Attach / detach
Attach();
Detach();
EXPECT_TRUE(detach_finished_listener.WaitUntilSatisfied());
// Switch ok dummy detach listener for the regular one.
ChangeListener(host, kRemoveDummyDetachListenerCmd,
kRemoveDummyDetachListenerOk);
ChangeListener(host, kAddDetachListenerCmd, kAddDetachListenerOk);
// Add attach listener.
ChangeListener(host, kAddAttachListenerCmd, kAddAttachListenerOk);
Attach();
EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());
Detach();
EXPECT_TRUE(detach_finished_listener.WaitUntilSatisfied());
Attach();
EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());
Detach();
EXPECT_TRUE(detach_finished_listener.WaitUntilSatisfied());
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/media_galleries_private/media_galleries_private_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/storage_monitor/storage_info.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "chrome/browser/storage_monitor/test_storage_monitor.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "googleurl/src/gurl.h"
namespace {
// Id of test extension from
// chrome/test/data/extensions/api_test/|kTestExtensionPath|
const char kTestExtensionId[] = "lkegdcleigedmkiikoijjgfchobofdbe";
const char kTestExtensionPath[] = "media_galleries_private/attachdetach";
// JS commands.
const char kAddAttachListenerCmd[] = "addAttachListener()";
const char kAddDetachListenerCmd[] = "addDetachListener()";
const char kAddDummyDetachListenerCmd[] = "addDummyDetachListener()";
const char kRemoveAttachListenerCmd[] = "removeAttachListener()";
const char kRemoveDummyDetachListenerCmd[] = "removeDummyDetachListener()";
// And JS reply messages.
const char kAddAttachListenerOk[] = "add_attach_ok";
const char kAddDetachListenerOk[] = "add_detach_ok";
const char kAddDummyDetachListenerOk[] = "add_dummy_detach_ok";
const char kRemoveAttachListenerOk[] = "remove_attach_ok";
const char kRemoveDummyDetachListenerOk[] = "remove_dummy_detach_ok";
// Test reply messages.
const char kAttachTestOk[] = "attach_test_ok";
const char kDetachTestOk[] = "detach_test_ok";
// Dummy device properties.
const char kDeviceId[] = "testDeviceId";
const char kDeviceName[] = "foobar";
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");
} // namespace
class MediaGalleriesPrivateApiTest : public ExtensionApiTest {
public:
MediaGalleriesPrivateApiTest() {}
virtual ~MediaGalleriesPrivateApiTest() {}
// ExtensionApiTest overrides.
virtual void SetUp() OVERRIDE {
device_id_ = chrome::StorageInfo::MakeDeviceId(
chrome::StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);
ExtensionApiTest::SetUp();
}
protected:
// ExtensionApiTest overrides.
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kWhitelistedExtensionID,
kTestExtensionId);
}
void ChangeListener(content::RenderViewHost* host,
const std::string& js_command,
const std::string& ok_message) {
ExtensionTestMessageListener listener(ok_message, false /* no reply */);
host->ExecuteJavascriptInWebFrame(string16(), ASCIIToUTF16(js_command));
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
void AttachDetach() {
Attach();
Detach();
}
void Attach() {
DCHECK(chrome::StorageMonitor::GetInstance()->IsInitialized());
chrome::StorageInfo info(device_id_, ASCIIToUTF16(kDeviceName), kDevicePath,
string16(), string16(), string16(), 0);
chrome::StorageMonitor::GetInstance()->receiver()->ProcessAttach(info);
content::RunAllPendingInMessageLoop();
}
void Detach() {
DCHECK(chrome::StorageMonitor::GetInstance()->IsInitialized());
chrome::StorageMonitor::GetInstance()->receiver()->ProcessDetach(
device_id_);
content::RunAllPendingInMessageLoop();
}
private:
std::string device_id_;
DISALLOW_COPY_AND_ASSIGN(MediaGalleriesPrivateApiTest);
};
IN_PROC_BROWSER_TEST_F(MediaGalleriesPrivateApiTest, DeviceAttachDetachEvents) {
scoped_ptr<chrome::test::TestStorageMonitor> monitor(
chrome::test::TestStorageMonitor::CreateForBrowserTests());
monitor->Init();
monitor->MarkInitialized();
// Setup.
const extensions::Extension* extension =
LoadExtension(test_data_dir_.AppendASCII(kTestExtensionPath));
ASSERT_TRUE(extension);
content::RenderViewHost* host =
extensions::ExtensionSystem::Get(browser()->profile())->
process_manager()->GetBackgroundHostForExtension(extension->id())->
render_view_host();
ASSERT_TRUE(host);
// No listeners, attach and detach a couple times.
AttachDetach();
AttachDetach();
// Add attach listener.
ChangeListener(host, kAddAttachListenerCmd, kAddAttachListenerOk);
// Attach / detach
const std::string expect_attach_msg =
base::StringPrintf("%s,%s", kAttachTestOk, kDeviceName);
ExtensionTestMessageListener attach_finished_listener(expect_attach_msg,
false /* no reply */);
Attach();
EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());
Detach();
// Attach / detach
Attach();
EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());
// Detach
Detach();
// Remove attach listener.
ChangeListener(host, kRemoveAttachListenerCmd, kRemoveAttachListenerOk);
// No listeners, attach and detach a couple times.
AttachDetach();
AttachDetach();
// Add detach listener.
ChangeListener(host, kAddDummyDetachListenerCmd, kAddDummyDetachListenerOk);
// Attach / detach
Attach();
ExtensionTestMessageListener detach_finished_listener(kDetachTestOk,
false /* no reply */);
Detach();
EXPECT_TRUE(detach_finished_listener.WaitUntilSatisfied());
// Attach / detach
Attach();
Detach();
EXPECT_TRUE(detach_finished_listener.WaitUntilSatisfied());
// Switch ok dummy detach listener for the regular one.
ChangeListener(host, kRemoveDummyDetachListenerCmd,
kRemoveDummyDetachListenerOk);
ChangeListener(host, kAddDetachListenerCmd, kAddDetachListenerOk);
// Add attach listener.
ChangeListener(host, kAddAttachListenerCmd, kAddAttachListenerOk);
Attach();
EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());
Detach();
EXPECT_TRUE(detach_finished_listener.WaitUntilSatisfied());
Attach();
EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());
Detach();
EXPECT_TRUE(detach_finished_listener.WaitUntilSatisfied());
}
|
Add test storage monitor for this browser test.
|
Add test storage monitor for this browser test.
It looks like the test was flaky because this test slipped through the cracks.
We weren't initializing the storage monitor, so there was a race where it
might not be fully initialized when the test ran. Switched to using the test
storage monitor as the other API browser tests do (and are not flaky).
[email protected]
BUG=247336
Review URL: https://chromiumcodereview.appspot.com/17504004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@207866 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
krieger-od/nwjs_chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,anirudhSK/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,patrickm/chromium.src,Chilledheart/chromium,littlstar/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,M4sse/chromium.src,dednal/chromium.src,Chilledheart/chromium,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,dednal/chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,patrickm/chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,dushu1203/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,M4sse/chromium.src,dednal/chromium.src,jaruba/chromium.src,ltilve/chromium,jaruba/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,mogoweb/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,dednal/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,Chilledheart/chromium,Fireblend/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,M4sse/chromium.src,jaruba/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium
|
d21f970bcd61279bb6cedcbd4cb8fbe5e0fb2ad9
|
lib/vdraw/EPSImage.cpp
|
lib/vdraw/EPSImage.cpp
|
#pragma ident "$Id$"
///@file EPSImage.cpp Vector plotting in Encapsulated Postscript. Class definitions.
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
#include <iostream>
#include "EPSImage.hpp"
namespace vdraw
{
static char VIEWER_ENV_VAR_NAME[]="VDRAW_EPS_VIEWER";
EPSImage::EPSImage(std::ostream& stream,
double illx, double illy,
double iurx, double iury,
ORIGIN_LOCATION iloc):
PSImageBase(stream, iurx-illx, iury-illy, iloc),
viewerManager(VIEWER_ENV_VAR_NAME),
llx(illx), lly(illy),
urx(iurx), ury(iury)
{
outputHeader();
}
EPSImage::EPSImage(const char* fname,
double illx, double illy,
double iurx, double iury,
ORIGIN_LOCATION iloc):
PSImageBase(fname, iurx-illx, iury-illy, iloc),
viewerManager(VIEWER_ENV_VAR_NAME),
llx(illx), lly(illy),
urx(iurx), ury(iury)
{
outputHeader();
}
EPSImage::~EPSImage(void)
{
// No operations. Not yet.
}
/**
* Methods
*/
void EPSImage::outputHeader(void)
{
using namespace std;
ostr << "%!PS-Adobe EPSF-3.0" << endl;
ostr << "%%BoundingBox: " ;
ostr << llx << " " << lly << " " << urx << " " << ury << endl;
ostr << "%% Created by vdraw" << endl;
ostr << "%%" << endl;
}
void EPSImage::outputFooter(void)
{
}
void EPSImage::view(void) throw (VDrawException)
{
// close up the file's contents
outputFooter();
// First flush the file stream.
ostr.flush();
// Register viewers in case they haven't been registered.
viewerManager.registerViewer("ggv");
viewerManager.registerViewer("kghostview --portrait");
viewerManager.registerViewer("ghostview");
viewerManager.registerViewer("gv");
viewerManager.registerViewer("evince");
// Use the viewerManager
viewerManager.view(filename);
return;
}
} // namespace vdraw
|
#pragma ident "$Id$"
///@file EPSImage.cpp Vector plotting in Encapsulated Postscript. Class definitions.
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
#include <iostream>
#include "EPSImage.hpp"
namespace vdraw
{
static char VIEWER_ENV_VAR_NAME[]="VDRAW_EPS_VIEWER";
EPSImage::EPSImage(std::ostream& stream,
double illx, double illy,
double iurx, double iury,
ORIGIN_LOCATION iloc):
PSImageBase(stream, iurx-illx, iury-illy, iloc),
viewerManager(VIEWER_ENV_VAR_NAME),
llx(illx), lly(illy),
urx(iurx), ury(iury)
{
outputHeader();
}
EPSImage::EPSImage(const char* fname,
double illx, double illy,
double iurx, double iury,
ORIGIN_LOCATION iloc):
PSImageBase(fname, iurx-illx, iury-illy, iloc),
viewerManager(VIEWER_ENV_VAR_NAME),
llx(illx), lly(illy),
urx(iurx), ury(iury)
{
outputHeader();
}
EPSImage::~EPSImage(void)
{
// No operations. Not yet.
}
/**
* Methods
*/
void EPSImage::outputHeader(void)
{
using namespace std;
ostr << "%!PS-Adobe EPSF-3.0" << endl;
ostr << "%%BoundingBox: " ;
ostr << llx << " " << lly << " " << urx << " " << ury << endl;
ostr << "%% Created by vdraw" << endl;
ostr << "%%" << endl;
}
void EPSImage::outputFooter(void)
{
}
void EPSImage::view(void) throw (VDrawException)
{
// close up the file's contents
outputFooter();
// First flush the file stream.
ostr.flush();
// Register viewers in case they haven't been registered.
viewerManager.registerViewer("ggv");
viewerManager.registerViewer("kghostview --portrait");
viewerManager.registerViewer("ghostview");
viewerManager.registerViewer("gv");
viewerManager.registerViewer("evince");
viewerManager.registerViewer("gsview32");
// Use the viewerManager
viewerManager.view(filename);
return;
}
} // namespace vdraw
|
Add 'gsview32' to the ViewManager, and it works under windows.
|
Add 'gsview32' to the ViewManager, and it works under windows.
git-svn-id: 6625e4d6743179724b113c04fbf297d122273a36@2345 108fab2b-820f-0410-9f2c-e5cc2c41d7be
|
C++
|
lgpl-2.1
|
ianmartin/GPSTk,ianmartin/GPSTk,ianmartin/GPSTk,ianmartin/GPSTk,ianmartin/GPSTk,ianmartin/GPSTk
|
cd77c31d9d202f07b42a99ba5eb15c1fd9d678b7
|
src/viewer/qgl_render_widget.cc
|
src/viewer/qgl_render_widget.cc
|
#include "qgl_render_widget.h"
#include "qmath.h"
#include <cmath>
#include <algorithm>
#include <typeinfo>
namespace spica {
QGLRenderWidget::QGLRenderWidget(QWidget *parent)
: QGLWidget(parent)
, shaderProgram(0)
, timer(0)
, _useArcBall(false)
, _scrallDelta(0.0)
, _isRotate(false)
, _newX(0.0)
, _newY(0.0)
, _oldX(0.0)
, _oldY(0.0)
, rotationMat()
{
timer = new QTimer(this);
timer->start(10);
connect(timer, SIGNAL(timeout()), this, SLOT(animate()));
}
QGLRenderWidget::~QGLRenderWidget()
{
delete timer;
delete shaderProgram;
}
void QGLRenderWidget::setScene(const Scene& scene_, const Camera& camera_) {
scene = &scene_;
camera = &camera_;
this->resize(camera->imageW(), camera->imageH());
}
void QGLRenderWidget::initializeGL() {
qglClearColor(Qt::black);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
// Initialize GLSL
shaderProgram = new QOpenGLShaderProgram(this);
shaderProgram->addShaderFromSourceFile(QOpenGLShader::Vertex, "../../../src/viewer/blinn_phong.vs");
shaderProgram->addShaderFromSourceFile(QOpenGLShader::Fragment, "../../../src/viewer/blinn_phong.fs");
shaderProgram->link();
}
void QGLRenderWidget::resizeGL(int width, int height) {
glViewport(0, 0, width, height);
}
void QGLRenderWidget::paintGL() {
const Vector3 eye = camera->center();
const Vector3 lookTo = eye + camera->direction();
const Vector3 up = camera->up();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
QMatrix4x4 projMat, viewMat, modelMat;
projMat.perspective(30.0f, (float)width() / (float)height(), 1.0f, 1000.0f);
viewMat.lookAt(QVector3D(eye.x(), eye.y(), eye.z()),
QVector3D(lookTo.x(), lookTo.y(), lookTo.z()),
QVector3D(up.x(), up.y(), up.z()));
modelMat.setToIdentity();
modelMat = modelMat * rotationMat;
modelMat.scale(1.0 - _scrallDelta * 0.1);
shaderProgram->bind();
shaderProgram->setUniformValue("mMat", modelMat);
shaderProgram->setUniformValue("vMat", viewMat);
shaderProgram->setUniformValue("pMat", projMat);
for (int i = 0; i < scene->numObjects(); i++) {
const Primitive* ptr = scene->getObjectPtr(i);
if (i == scene->lightID()) {
const Sphere* lightSphere = reinterpret_cast<const Sphere*>(ptr);
float lightPos[4];
lightPos[0] = lightSphere->center().x();
lightPos[1] = lightSphere->center().y();
lightPos[2] = lightSphere->center().z();
lightPos[3] = 1.0f;
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
}
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glColor3f(ptr->color().red(), ptr->color().green(), ptr->color().blue());
glPushMatrix();
if (strcmp(typeid(*ptr).name(), "class spica::Sphere") == 0) {
const Sphere* sphere = reinterpret_cast<const Sphere*>(ptr);
glTranslated(sphere->center().x(), sphere->center().y(), sphere->center().z());
glutSolidSphere(sphere->radius(), 256, 256);
} else if (strcmp(typeid(*ptr).name(), "class spica::Trimesh") == 0) {
const Trimesh* trimesh = reinterpret_cast<const Trimesh*>(ptr);
glBegin(GL_TRIANGLES);
for (int i = 0; i < trimesh->numFaces(); i++) {
Triangle tri = trimesh->getTriangle(i);
Vector3 normal = trimesh->getNormal(i);
glNormal3d(normal.x(), normal.y(), normal.z());
glVertex3d(tri.p0().x(), tri.p0().y(), tri.p0().z());
glVertex3d(tri.p1().x(), tri.p1().y(), tri.p1().z());
glVertex3d(tri.p2().x(), tri.p2().y(), tri.p2().z());
}
glEnd();
}
glPopMatrix();
}
}
void QGLRenderWidget::animate() {
update();
}
void QGLRenderWidget::updateMouse() {
QVector3D u = getArcBallVector(_newX, _newY);
QVector3D v = getArcBallVector(_oldX, _oldY);
double angle = acos(std::min(1.0f, QVector3D::dotProduct(u, v)));
QVector3D rotAxis = QVector3D::crossProduct(v, u);
QMatrix4x4 eye2ObjSpaceMat = rotationMat.inverted();
QVector3D objSpaceRotAxis = eye2ObjSpaceMat * rotAxis;
QMatrix4x4 temp;
temp.rotate(4.0 * qRadiansToDegrees(angle), objSpaceRotAxis);
rotationMat = temp * rotationMat;
}
QVector3D QGLRenderWidget::getArcBallVector(int x, int y) {
QVector3D pt = QVector3D(2.0 * x / this->width() - 1.0, 2.0 * y / this->height() - 1.0, 0.0);
pt.setY(pt.y() * -1.0);
double xySquared = pt.x() * pt.x() + pt.y() * pt.y();
if (xySquared <= 1.0) {
pt.setZ(sqrt(1.0 - xySquared));
} else {
pt.normalize();
}
return pt;
}
void QGLRenderWidget::wheelEvent(QWheelEvent* e) {
_scrallDelta += e->delta() / 120.0;
}
void QGLRenderWidget::mousePressEvent(QMouseEvent* e) {
_isRotate = false;
if (e->button() == Qt::LeftButton) {
_oldX = e->x();
_oldY = e->y();
_newX = e->x();
_newY = e->y();
_isRotate = true;
_useArcBall = true;
}
}
void QGLRenderWidget::mouseMoveEvent(QMouseEvent* e) {
if (e->buttons() & Qt::LeftButton) {
if (_isRotate) {
_newX = e->x();
_newY = e->y();
updateMouse();
}
_oldX = e->x();
_oldY = e->y();
}
}
void QGLRenderWidget::mouseReleaseEvent(QMouseEvent* e) {
if (e->button() == Qt::LeftButton) {
_useArcBall = false;
}
}
} // namespace spica
|
#include "qgl_render_widget.h"
#include <QtMath>
#include <cmath>
#include <algorithm>
#include <typeinfo>
namespace spica {
QGLRenderWidget::QGLRenderWidget(QWidget *parent)
: QGLWidget(parent)
, shaderProgram(0)
, timer(0)
, _useArcBall(false)
, _scrallDelta(0.0)
, _isRotate(false)
, _newX(0.0)
, _newY(0.0)
, _oldX(0.0)
, _oldY(0.0)
, rotationMat()
{
timer = new QTimer(this);
timer->start(10);
connect(timer, SIGNAL(timeout()), this, SLOT(animate()));
}
QGLRenderWidget::~QGLRenderWidget()
{
delete timer;
delete shaderProgram;
}
void QGLRenderWidget::setScene(const Scene& scene_, const Camera& camera_) {
scene = &scene_;
camera = &camera_;
this->resize(camera->imageW(), camera->imageH());
}
void QGLRenderWidget::initializeGL() {
qglClearColor(Qt::black);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
// Initialize GLSL
shaderProgram = new QOpenGLShaderProgram(this);
shaderProgram->addShaderFromSourceFile(QOpenGLShader::Vertex, "../../../src/viewer/blinn_phong.vs");
shaderProgram->addShaderFromSourceFile(QOpenGLShader::Fragment, "../../../src/viewer/blinn_phong.fs");
shaderProgram->link();
}
void QGLRenderWidget::resizeGL(int width, int height) {
glViewport(0, 0, width, height);
}
void QGLRenderWidget::paintGL() {
const Vector3 eye = camera->center();
const Vector3 lookTo = eye + camera->direction();
const Vector3 up = camera->up();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
QMatrix4x4 projMat, viewMat, modelMat;
projMat.perspective(30.0f, (float)width() / (float)height(), 1.0f, 1000.0f);
viewMat.lookAt(QVector3D(eye.x(), eye.y(), eye.z()),
QVector3D(lookTo.x(), lookTo.y(), lookTo.z()),
QVector3D(up.x(), up.y(), up.z()));
modelMat.setToIdentity();
modelMat = modelMat * rotationMat;
modelMat.scale(1.0 - _scrallDelta * 0.1);
shaderProgram->bind();
shaderProgram->setUniformValue("mMat", modelMat);
shaderProgram->setUniformValue("vMat", viewMat);
shaderProgram->setUniformValue("pMat", projMat);
for (int i = 0; i < scene->numObjects(); i++) {
const Primitive* ptr = scene->getObjectPtr(i);
if (i == scene->lightID()) {
const Sphere* lightSphere = reinterpret_cast<const Sphere*>(ptr);
float lightPos[4];
lightPos[0] = lightSphere->center().x();
lightPos[1] = lightSphere->center().y();
lightPos[2] = lightSphere->center().z();
lightPos[3] = 1.0f;
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
}
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glColor3f(ptr->color().red(), ptr->color().green(), ptr->color().blue());
glPushMatrix();
if (strcmp(typeid(*ptr).name(), "class spica::Sphere") == 0) {
const Sphere* sphere = reinterpret_cast<const Sphere*>(ptr);
glTranslated(sphere->center().x(), sphere->center().y(), sphere->center().z());
glutSolidSphere(sphere->radius(), 256, 256);
} else if (strcmp(typeid(*ptr).name(), "class spica::Trimesh") == 0) {
const Trimesh* trimesh = reinterpret_cast<const Trimesh*>(ptr);
glBegin(GL_TRIANGLES);
for (int i = 0; i < trimesh->numFaces(); i++) {
Triangle tri = trimesh->getTriangle(i);
Vector3 normal = trimesh->getNormal(i);
glNormal3d(normal.x(), normal.y(), normal.z());
glVertex3d(tri.p0().x(), tri.p0().y(), tri.p0().z());
glVertex3d(tri.p1().x(), tri.p1().y(), tri.p1().z());
glVertex3d(tri.p2().x(), tri.p2().y(), tri.p2().z());
}
glEnd();
}
glPopMatrix();
}
}
void QGLRenderWidget::animate() {
update();
}
void QGLRenderWidget::updateMouse() {
QVector3D u = getArcBallVector(_newX, _newY);
QVector3D v = getArcBallVector(_oldX, _oldY);
double angle = acos(std::min(1.0f, QVector3D::dotProduct(u, v)));
QVector3D rotAxis = QVector3D::crossProduct(v, u);
QMatrix4x4 eye2ObjSpaceMat = rotationMat.inverted();
QVector3D objSpaceRotAxis = eye2ObjSpaceMat * rotAxis;
QMatrix4x4 temp;
temp.rotate(4.0 * qRadiansToDegrees(angle), objSpaceRotAxis);
rotationMat = temp * rotationMat;
}
QVector3D QGLRenderWidget::getArcBallVector(int x, int y) {
QVector3D pt = QVector3D(2.0 * x / this->width() - 1.0, 2.0 * y / this->height() - 1.0, 0.0);
pt.setY(pt.y() * -1.0);
double xySquared = pt.x() * pt.x() + pt.y() * pt.y();
if (xySquared <= 1.0) {
pt.setZ(sqrt(1.0 - xySquared));
} else {
pt.normalize();
}
return pt;
}
void QGLRenderWidget::wheelEvent(QWheelEvent* e) {
_scrallDelta += e->delta() / 120.0;
}
void QGLRenderWidget::mousePressEvent(QMouseEvent* e) {
_isRotate = false;
if (e->button() == Qt::LeftButton) {
_oldX = e->x();
_oldY = e->y();
_newX = e->x();
_newY = e->y();
_isRotate = true;
_useArcBall = true;
}
}
void QGLRenderWidget::mouseMoveEvent(QMouseEvent* e) {
if (e->buttons() & Qt::LeftButton) {
if (_isRotate) {
_newX = e->x();
_newY = e->y();
updateMouse();
}
_oldX = e->x();
_oldY = e->y();
}
}
void QGLRenderWidget::mouseReleaseEvent(QMouseEvent* e) {
if (e->button() == Qt::LeftButton) {
_useArcBall = false;
}
}
} // namespace spica
|
Fix unresolved dependencies.
|
Fix unresolved dependencies.
|
C++
|
mit
|
tatsy/spica,tatsy/spica,tatsy/spica
|
cb3958f3e15ec900ca45d829999512c66df81068
|
bindings/python/src/torrent_status.cpp
|
bindings/python/src/torrent_status.cpp
|
// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to 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 <libtorrent/torrent_handle.hpp>
#include <boost/python.hpp>
#include <libtorrent/bitfield.hpp>
using namespace boost::python;
using namespace libtorrent;
object pieces(torrent_status const& s)
{
list result;
for (bitfield::const_iterator i(s.pieces.begin()), e(s.pieces.end()); i != e; ++i)
result.append(*i);
return result;
}
void bind_torrent_status()
{
scope status = class_<torrent_status>("torrent_status")
.def_readonly("state", &torrent_status::state)
.def_readonly("paused", &torrent_status::paused)
.def_readonly("progress", &torrent_status::progress)
.add_property(
"next_announce"
, make_getter(
&torrent_status::next_announce, return_value_policy<return_by_value>()
)
)
.add_property(
"announce_interval"
, make_getter(
&torrent_status::announce_interval, return_value_policy<return_by_value>()
)
)
.def_readonly("current_tracker", &torrent_status::current_tracker)
.def_readonly("total_download", &torrent_status::total_download)
.def_readonly("total_upload", &torrent_status::total_upload)
.def_readonly("total_payload_download", &torrent_status::total_payload_download)
.def_readonly("total_payload_upload", &torrent_status::total_payload_upload)
.def_readonly("total_failed_bytes", &torrent_status::total_failed_bytes)
.def_readonly("total_redundant_bytes", &torrent_status::total_redundant_bytes)
.def_readonly("download_rate", &torrent_status::download_rate)
.def_readonly("upload_rate", &torrent_status::upload_rate)
.def_readonly("download_payload_rate", &torrent_status::download_payload_rate)
.def_readonly("upload_payload_rate", &torrent_status::upload_payload_rate)
.def_readonly("num_seeds", &torrent_status::num_seeds)
.def_readonly("num_peers", &torrent_status::num_peers)
.def_readonly("num_complete", &torrent_status::num_complete)
.def_readonly("num_incomplete", &torrent_status::num_incomplete)
.def_readonly("list_seeds", &torrent_status::list_seeds)
.def_readonly("list_peers", &torrent_status::list_peers)
.add_property("pieces", pieces)
.def_readonly("num_pieces", &torrent_status::num_pieces)
.def_readonly("total_done", &torrent_status::total_done)
.def_readonly("total_wanted_done", &torrent_status::total_wanted_done)
.def_readonly("total_wanted", &torrent_status::total_wanted)
.def_readonly("distributed_copies", &torrent_status::distributed_copies)
.def_readonly("block_size", &torrent_status::block_size)
.def_readonly("num_uploads", &torrent_status::num_uploads)
.def_readonly("num_connections", &torrent_status::num_connections)
.def_readonly("uploads_limit", &torrent_status::uploads_limit)
.def_readonly("connections_limit", &torrent_status::connections_limit)
.def_readonly("storage_mode", &torrent_status::storage_mode)
.def_readonly("up_bandwidth_queue", &torrent_status::up_bandwidth_queue)
.def_readonly("down_bandwidth_queue", &torrent_status::down_bandwidth_queue)
.def_readonly("all_time_upload", &torrent_status::all_time_upload)
.def_readonly("all_time_download", &torrent_status::all_time_download)
.def_readonly("active_time", &torrent_status::active_time)
.def_readonly("seeding_time", &torrent_status::seeding_time)
.def_readonly("seed_rank", &torrent_status::seed_rank)
.def_readonly("last_scrape", &torrent_status::last_scrape)
.def_readonly("error", &torrent_status::error)
;
enum_<torrent_status::state_t>("states")
.value("queued_for_checking", torrent_status::queued_for_checking)
.value("checking_files", torrent_status::checking_files)
.value("connecting_to_tracker", torrent_status::connecting_to_tracker)
.value("downloading", torrent_status::downloading)
.value("finished", torrent_status::finished)
.value("seeding", torrent_status::seeding)
.value("allocating", torrent_status::allocating)
.export_values()
;
}
|
// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to 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 <libtorrent/torrent_handle.hpp>
#include <boost/python.hpp>
#include <libtorrent/bitfield.hpp>
using namespace boost::python;
using namespace libtorrent;
object pieces(torrent_status const& s)
{
list result;
for (bitfield::const_iterator i(s.pieces.begin()), e(s.pieces.end()); i != e; ++i)
result.append(*i);
return result;
}
void bind_torrent_status()
{
scope status = class_<torrent_status>("torrent_status")
.def_readonly("state", &torrent_status::state)
.def_readonly("paused", &torrent_status::paused)
.def_readonly("progress", &torrent_status::progress)
.add_property(
"next_announce"
, make_getter(
&torrent_status::next_announce, return_value_policy<return_by_value>()
)
)
.add_property(
"announce_interval"
, make_getter(
&torrent_status::announce_interval, return_value_policy<return_by_value>()
)
)
.def_readonly("current_tracker", &torrent_status::current_tracker)
.def_readonly("total_download", &torrent_status::total_download)
.def_readonly("total_upload", &torrent_status::total_upload)
.def_readonly("total_payload_download", &torrent_status::total_payload_download)
.def_readonly("total_payload_upload", &torrent_status::total_payload_upload)
.def_readonly("total_failed_bytes", &torrent_status::total_failed_bytes)
.def_readonly("total_redundant_bytes", &torrent_status::total_redundant_bytes)
.def_readonly("download_rate", &torrent_status::download_rate)
.def_readonly("upload_rate", &torrent_status::upload_rate)
.def_readonly("download_payload_rate", &torrent_status::download_payload_rate)
.def_readonly("upload_payload_rate", &torrent_status::upload_payload_rate)
.def_readonly("num_seeds", &torrent_status::num_seeds)
.def_readonly("num_peers", &torrent_status::num_peers)
.def_readonly("num_complete", &torrent_status::num_complete)
.def_readonly("num_incomplete", &torrent_status::num_incomplete)
.def_readonly("list_seeds", &torrent_status::list_seeds)
.def_readonly("list_peers", &torrent_status::list_peers)
.add_property("pieces", pieces)
.def_readonly("num_pieces", &torrent_status::num_pieces)
.def_readonly("total_done", &torrent_status::total_done)
.def_readonly("total_wanted_done", &torrent_status::total_wanted_done)
.def_readonly("total_wanted", &torrent_status::total_wanted)
.def_readonly("distributed_copies", &torrent_status::distributed_copies)
.def_readonly("block_size", &torrent_status::block_size)
.def_readonly("num_uploads", &torrent_status::num_uploads)
.def_readonly("num_connections", &torrent_status::num_connections)
.def_readonly("uploads_limit", &torrent_status::uploads_limit)
.def_readonly("connections_limit", &torrent_status::connections_limit)
.def_readonly("storage_mode", &torrent_status::storage_mode)
.def_readonly("up_bandwidth_queue", &torrent_status::up_bandwidth_queue)
.def_readonly("down_bandwidth_queue", &torrent_status::down_bandwidth_queue)
.def_readonly("all_time_upload", &torrent_status::all_time_upload)
.def_readonly("all_time_download", &torrent_status::all_time_download)
.def_readonly("active_time", &torrent_status::active_time)
.def_readonly("seeding_time", &torrent_status::seeding_time)
.def_readonly("seed_rank", &torrent_status::seed_rank)
.def_readonly("last_scrape", &torrent_status::last_scrape)
.def_readonly("error", &torrent_status::error)
;
enum_<torrent_status::state_t>("states")
.value("queued_for_checking", torrent_status::queued_for_checking)
.value("checking_files", torrent_status::checking_files)
.value("downloading", torrent_status::downloading)
.value("finished", torrent_status::finished)
.value("seeding", torrent_status::seeding)
.value("allocating", torrent_status::allocating)
.export_values()
;
}
|
Remove 'connecting_to_tracker' state from bindings
|
Remove 'connecting_to_tracker' state from bindings
git-svn-id: 6df6a9299d9fe08e1e18eb0c01ae615f7df02338@2629 a83610d8-ad2a-0410-a6ab-fc0612d85776
|
C++
|
bsd-3-clause
|
cit/libtorrent-peer-idol,cit/libtorrent-peer-idol,cscheid/libtorrent,cit/libtorrent-peer-idol,cit/libtorrent-peer-idol,cit/libtorrent-peer-idol,cscheid/libtorrent,cscheid/libtorrent,kuro/libtorrent,cscheid/libtorrent,cit/libtorrent-peer-idol,cscheid/libtorrent,cscheid/libtorrent,kuro/libtorrent,kuro/libtorrent,kuro/libtorrent
|
f4d86777db8ec4ee998a0d3c6ebaae15e54e5ea1
|
src/radosacl.cc
|
src/radosacl.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This 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. See file COPYING.
*
*/
#include "include/types.h"
#include "include/rados/librados.hpp"
using namespace librados;
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
void buf_to_hex(const unsigned char *buf, int len, char *str)
{
str[0] = '\0';
for (int i = 0; i < len; i++) {
sprintf(&str[i*2], "%02x", (int)buf[i]);
}
}
#define ID_SIZE 8
#define ACL_RD 0x1
#define ACL_WR 0x2
struct ACLID {
char id[ID_SIZE + 1];
};
typedef __u32 ACLFlags;
void encode(const ACLID& id, bufferlist& bl)
{
bl.append((const char *)id.id, ID_SIZE);
}
void decode(ACLID& id, bufferlist::iterator& iter)
{
iter.copy(ID_SIZE, (char *)id.id);
}
inline bool operator<(const ACLID& l, const ACLID& r)
{
return (memcmp(&l, &r, ID_SIZE) > 0);
}
struct ACLPair {
ACLID id;
ACLFlags flags;
};
class ObjectACLs {
map<ACLID, ACLFlags> acls_map;
public:
void encode(bufferlist& bl) const {
::encode(acls_map, bl);
}
void decode(bufferlist::iterator& bl) {
::decode(acls_map, bl);
}
int read_acl(ACLID& id, ACLFlags *flags);
void set_acl(ACLID& id, ACLFlags flags);
};
WRITE_CLASS_ENCODER(ObjectACLs)
int ObjectACLs::read_acl(ACLID& id, ACLFlags *flags)
{
if (!flags)
return -EINVAL;
map<ACLID, ACLFlags>::iterator iter = acls_map.find(id);
if (iter == acls_map.end())
return -ENOENT;
*flags = iter->second;
return 0;
}
void ObjectACLs::set_acl(ACLID& id, ACLFlags flags)
{
acls_map[id] = flags;
}
class ACLEntity
{
string name;
map<ACLID, ACLEntity> groups;
};
typedef map<ACLID, ACLEntity> tACLIDEntityMap;
static map<ACLID, ACLEntity> users;
static map<ACLID, ACLEntity> groups;
void get_user(ACLID& aclid, ACLEntity *entity)
{
//users.find(aclid);
}
int main(int argc, const char **argv)
{
Rados rados;
if (rados.init(NULL) < 0) {
cerr << "couldn't initialize rados!" << std::endl;
exit(1);
}
if (rados.connect() < 0) {
cerr << "couldn't connect to cluster!" << std::endl;
exit(1);
}
time_t tm;
bufferlist bl, bl2;
char buf[128];
time(&tm);
snprintf(buf, 128, "%s", ctime(&tm));
bl.append(buf, strlen(buf));
const char *oid = "bar";
IoCtx io_ctx;
int r = rados.ioctx_create("data", io_ctx);
cout << "open io_ctx result = " << r << " pool = " << io_ctx.get_pool_name() << std::endl;
ACLID id;
snprintf(id.id, ID_SIZE + 1, "%.16x", 0x1234);
cout << "id=" << id.id << std::endl;
r = io_ctx.exec(oid, "acl", "get", bl, bl2);
cout << "exec returned " << r << " len=" << bl2.length() << std::endl;
ObjectACLs oa;
if (r >= 0) {
bufferlist::iterator iter = bl2.begin();
oa.decode(iter);
}
oa.set_acl(id, ACL_RD);
bl.clear();
oa.encode(bl);
r = io_ctx.exec(oid, "acl", "set", bl, bl2);
const unsigned char *md5 = (const unsigned char *)bl2.c_str();
char md5_str[bl2.length()*2 + 1];
buf_to_hex(md5, bl2.length(), md5_str);
cout << "md5 result=" << md5_str << std::endl;
int size = io_ctx.read(oid, bl2, 128, 0);
cout << "read result=" << bl2.c_str() << std::endl;
cout << "size=" << size << std::endl;
#if 0
Rados::ListCtx ctx;
int entries;
do {
list<object_t> vec;
r = rados.list(io_ctx, 2, vec, ctx);
entries = vec.size();
cout << "list result=" << r << " entries=" << entries << std::endl;
list<object_t>::iterator iter;
for (iter = vec.begin(); iter != vec.end(); ++iter) {
cout << *iter << std::endl;
}
} while (entries);
#endif
#if 0
r = rados.remove(io_ctx, oid);
cout << "remove result=" << r << std::endl;
rados.close_io_ctx(io_ctx);
#endif
return 0;
}
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This 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. See file COPYING.
*
*/
#include "include/types.h"
#include "include/rados/librados.hpp"
using namespace librados;
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
void buf_to_hex(const unsigned char *buf, int len, char *str)
{
str[0] = '\0';
for (int i = 0; i < len; i++) {
sprintf(&str[i*2], "%02x", (int)buf[i]);
}
}
#define ID_SIZE 8
#define ACL_RD 0x1
#define ACL_WR 0x2
struct ACLID {
char id[ID_SIZE + 1];
};
typedef __u32 ACLFlags;
void encode(const ACLID& id, bufferlist& bl)
{
bl.append((const char *)id.id, ID_SIZE);
}
void decode(ACLID& id, bufferlist::iterator& iter)
{
iter.copy(ID_SIZE, (char *)id.id);
}
inline bool operator<(const ACLID& l, const ACLID& r)
{
return (memcmp(&l, &r, ID_SIZE) > 0);
}
struct ACLPair {
ACLID id;
ACLFlags flags;
};
class ObjectACLs {
map<ACLID, ACLFlags> acls_map;
public:
void encode(bufferlist& bl) const {
::encode(acls_map, bl);
}
void decode(bufferlist::iterator& bl) {
::decode(acls_map, bl);
}
int read_acl(ACLID& id, ACLFlags *flags);
void set_acl(ACLID& id, ACLFlags flags);
};
WRITE_CLASS_ENCODER(ObjectACLs)
int ObjectACLs::read_acl(ACLID& id, ACLFlags *flags)
{
if (!flags)
return -EINVAL;
map<ACLID, ACLFlags>::iterator iter = acls_map.find(id);
if (iter == acls_map.end())
return -ENOENT;
*flags = iter->second;
return 0;
}
void ObjectACLs::set_acl(ACLID& id, ACLFlags flags)
{
acls_map[id] = flags;
}
class ACLEntity
{
string name;
map<ACLID, ACLEntity> groups;
};
typedef map<ACLID, ACLEntity> tACLIDEntityMap;
static map<ACLID, ACLEntity> users;
static map<ACLID, ACLEntity> groups;
void get_user(ACLID& aclid, ACLEntity *entity)
{
//users.find(aclid);
}
int main(int argc, const char **argv)
{
Rados rados;
if (rados.init(NULL) < 0) {
cerr << "couldn't initialize rados!" << std::endl;
exit(1);
}
if (rados.conf_read_file(NULL)) {
cerr << "couldn't read Ceph configuration file!" << std::endl;
exit(1);
}
if (rados.connect() < 0) {
cerr << "couldn't connect to cluster!" << std::endl;
exit(1);
}
time_t tm;
bufferlist bl, bl2;
char buf[128];
time(&tm);
snprintf(buf, 128, "%s", ctime(&tm));
bl.append(buf, strlen(buf));
const char *oid = "bar";
IoCtx io_ctx;
int r = rados.ioctx_create("data", io_ctx);
cout << "open io_ctx result = " << r << " pool = " << io_ctx.get_pool_name() << std::endl;
ACLID id;
snprintf(id.id, ID_SIZE + 1, "%.16x", 0x1234);
cout << "id=" << id.id << std::endl;
r = io_ctx.exec(oid, "acl", "get", bl, bl2);
cout << "exec returned " << r << " len=" << bl2.length() << std::endl;
ObjectACLs oa;
if (r >= 0) {
bufferlist::iterator iter = bl2.begin();
oa.decode(iter);
}
oa.set_acl(id, ACL_RD);
bl.clear();
oa.encode(bl);
r = io_ctx.exec(oid, "acl", "set", bl, bl2);
const unsigned char *md5 = (const unsigned char *)bl2.c_str();
char md5_str[bl2.length()*2 + 1];
buf_to_hex(md5, bl2.length(), md5_str);
cout << "md5 result=" << md5_str << std::endl;
int size = io_ctx.read(oid, bl2, 128, 0);
cout << "read result=" << bl2.c_str() << std::endl;
cout << "size=" << size << std::endl;
#if 0
Rados::ListCtx ctx;
int entries;
do {
list<object_t> vec;
r = rados.list(io_ctx, 2, vec, ctx);
entries = vec.size();
cout << "list result=" << r << " entries=" << entries << std::endl;
list<object_t>::iterator iter;
for (iter = vec.begin(); iter != vec.end(); ++iter) {
cout << *iter << std::endl;
}
} while (entries);
#endif
#if 0
r = rados.remove(io_ctx, oid);
cout << "remove result=" << r << std::endl;
rados.close_io_ctx(io_ctx);
#endif
return 0;
}
|
read Ceph configuration file
|
radosacl: read Ceph configuration file
Signed-off-by: Colin McCabe <[email protected]>
|
C++
|
lgpl-2.1
|
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
|
2a8cf57a56fca0c4d1b456f4990385fffc9de794
|
code/Templates/Builder/main.cpp
|
code/Templates/Builder/main.cpp
|
#include <iostream>
#include "DNest4/code/DNest4.h"
#include "MyModel.h"
using namespace DNest4;
int main(int argc, char** argv)
{
DNest4::start<MyModel>(argc, argv);
return 0;
}
|
#include <iostream>
#include "DNest4/code/DNest4.h"
#include "MyModel.h"
int main(int argc, char** argv)
{
// Use randh2
DNest4::RNG::randh_is_randh2 = true;
// Run sampler
DNest4::start<MyModel>(argc, argv);
return 0;
}
|
Use randh2
|
Use randh2
|
C++
|
mit
|
eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4
|
08e34cd4b1174c290a7088396cafb8f2f4e47823
|
src/hw/ide.cpp
|
src/hw/ide.cpp
|
// 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.
/**
* Intel IDE Controller datasheet at :
* ftp://download.intel.com/design/intarch/datashts/29055002.pdf
*/
#include <hw/ide.hpp>
#include <kernel/irq_manager.hpp>
#include <kernel/syscalls.hpp>
#define IDE_DATA 0x1F0
#define IDE_SECCNT 0x1F2
#define IDE_BLKLO 0x1F3
#define IDE_BLKMID 0x1F4
#define IDE_BLKHI 0x1F5
#define IDE_DRV 0x1F6
#define IDE_CMD 0x1F7
#define IDE_STATUS IDE_CMD
#define IDE_CMD_READ 0x20
#define IDE_CMD_WRITE 0x30
#define IDE_CMD_IDENTIFY 0xEC
#define IDE_DRQ (1 << 3)
#define IDE_DRDY (1 << 6)
#define IDE_BUSY (1 << 7)
#define IDE_CTRL_IRQ 0x3F6
#define IDE_IRQN 14
#define IDE_BLKSZ 512
#define IDE_VENDOR_ID PCI_Device::VENDOR_INTEL
#define IDE_PRODUCT_ID 0x7010
#define IDE_TIMEOUT 2048
namespace hw {
IDE::IDE(hw::PCI_Device& pcidev, selector_t sel) :
_pcidev {pcidev},
_drive {(uint8_t)sel},
_iobase {0U},
_nb_blk {0U}
{
INFO("IDE","VENDOR_ID : 0x%x, PRODUCT_ID : 0x%x", _pcidev.vendor_id(), _pcidev.product_id());
INFO("IDE","Attaching to PCI addr 0x%x",_pcidev.pci_addr());
/** PCI device checking */
if (_pcidev.vendor_id() not_eq IDE_VENDOR_ID) {
panic("This is not an Intel device");
}
CHECK(true, "Vendor ID is INTEL");
if (_pcidev.product_id() not_eq IDE_PRODUCT_ID) {
panic("This is not an IDE Controller");
}
CHECK(true, "Product ID is IDE Controller");
/** Probe PCI resources and fetch I/O-base for device */
_pcidev.probe_resources();
_iobase = _pcidev.iobase();
CHECK(_iobase, "Unit has valid I/O base (0x%x)", _iobase);
/** IRQ initialization */
CHECK(IDE_IRQN, "Unit has IRQ %i", IDE_IRQN);
enable_irq_handler();
INFO("IDE", "Enabling IRQ handler");
/** IDE device initialization */
set_irq_mode(false);
set_drive(0xA0 | _drive);
set_nbsectors(0U);
set_blocknum(0U);
set_command(IDE_CMD_IDENTIFY);
if (not inb(IDE_STATUS)) {
panic("Device not found");
}
CHECK(true, "IDE device found");
wait_status_flags(IDE_DRDY, false);
uint16_t buffer[256];
for (int i {0}; i < 256; ++i) {
buffer[i] = inw(IDE_DATA);
}
_nb_blk = (buffer[61] << 16) | buffer[60];
INFO("IDE", "Initialization complete");
}
struct ide_irq {
ide_irq(uint8_t* buff, IDE::on_read_func call)
: buffer(buff)
, callback(call)
{}
uint8_t* buffer; // Reading buffer
IDE::on_read_func callback; // IRQ callback
};
static int _nb_irqs = 0; // Number of IRQs that we expect
static IDE::on_read_func _current_callback = nullptr; // Callback for the current irq
static std::list<struct ide_irq> _ide_irqs; // IRQ queue
void IDE::read(block_t blk, on_read_func callback) {
if (blk >= _nb_blk) {
// avoid reading past the disk boundaries
callback(buffer_t());
return;
}
set_irq_mode(true);
set_drive(0xE0 | _drive | ((blk >> 24) & 0x0F));
set_nbsectors(1);
set_blocknum(blk);
set_command(IDE_CMD_READ);
_current_callback = callback;
_nb_irqs = 1;
}
void IDE::read(block_t blk, size_t count, on_read_func callback)
{
if (blk + count >= _nb_blk) {
// avoid reading past the disk boundaries
callback(buffer_t());
return;
}
set_irq_mode(true);
set_drive(0xE0 | _drive | ((blk >> 24) & 0x0F));
set_nbsectors(count);
set_blocknum(blk);
set_command(IDE_CMD_READ);
_current_callback = callback;
_nb_irqs = count;
}
IDE::buffer_t IDE::read_sync(block_t blk)
{
if (blk >= _nb_blk) {
// avoid reading past the disk boundaries
return buffer_t();
}
set_irq_mode(false);
set_drive(0xE0 | _drive | ((blk >> 24) & 0x0F));
set_nbsectors(1);
set_blocknum(blk);
set_command(IDE_CMD_READ);
auto* buffer = new uint8_t[block_size()];
wait_status_flags(IDE_DRDY, false);
uint16_t* wptr = (uint16_t*) buffer;
uint16_t* wend = (uint16_t*)&buffer[block_size()];
while (wptr < wend)
*(wptr++) = inw(IDE_DATA);
// return a shared_ptr wrapper for the buffer
return buffer_t(buffer, std::default_delete<uint8_t[]>());
}
IDE::buffer_t IDE::read_sync(block_t blk, size_t cnt) {
(void) blk;
(void) cnt;
// not yet implemented
return buffer_t();
}
void IDE::wait_status_busy() noexcept {
uint8_t ret;
while (((ret = inb(IDE_STATUS)) & IDE_BUSY) == IDE_BUSY);
}
void IDE::wait_status_flags(const int flags, const bool set) noexcept {
wait_status_busy();
auto ret = inb(IDE_STATUS);
for (int i {IDE_TIMEOUT}; i; --i) {
if (set) {
if ((ret & flags) == flags)
break;
} else {
if ((ret & flags) not_eq flags)
break;
}
ret = inb(IDE_STATUS);
}
}
void IDE::set_drive(const uint8_t drive) const noexcept {
wait_status_flags(IDE_DRQ, true);
outb(IDE_DRV, drive);
}
void IDE::set_nbsectors(const uint8_t cnt) const noexcept {
wait_status_flags(IDE_DRQ, true);
outb(IDE_SECCNT, cnt);
}
void IDE::set_blocknum(block_t blk) const noexcept {
wait_status_flags(IDE_DRQ, true);
outb(IDE_BLKLO, blk & 0xFF);
wait_status_flags(IDE_DRQ, true);
outb(IDE_BLKMID, (blk & 0xFF00) >> 8);
wait_status_flags(IDE_DRQ, true);
outb(IDE_BLKHI, (blk & 0xFF0000) >> 16);
}
void IDE::set_command(const uint16_t command) const noexcept {
wait_status_flags(IDE_DRDY, false);
outb(IDE_CMD, command);
}
void IDE::set_irq_mode(const bool on) noexcept {
wait_status_flags(IDE_DRDY, false);
outb(IDE_CTRL_IRQ, on ? 0 : 1);
}
extern "C"
void ide_irq_handler() {
if (!_nb_irqs || _current_callback == nullptr) {
IDE::set_irq_mode(false);
return;
}
uint8_t* buffer = new uint8_t[IDE_BLKSZ];
IDE::wait_status_flags(IDE_DRDY, false);
uint16_t* wptr = (uint16_t*) buffer;
for (IDE::block_t i = 0; i < IDE_BLKSZ / sizeof (uint16_t); ++i)
wptr[i] = inw(IDE_DATA);
_ide_irqs.push_back(ide_irq(buffer, _current_callback));
_nb_irqs--;
IRQ_manager::cpu(0).register_irq(IDE_IRQN);
}
extern "C" void ide_irq_entry();
void IDE::callback_wrapper()
{
IDE::on_read_func callback = _ide_irqs.front().callback;
callback(IDE::buffer_t(_ide_irqs.front().buffer, std::default_delete<uint8_t[]>()));
_ide_irqs.pop_front();
}
void IDE::enable_irq_handler() {
auto del(delegate<void()>::from<IDE, &IDE::callback_wrapper>(this));
IRQ_manager::cpu(0).subscribe(IDE_IRQN, del);
IRQ_manager::cpu(0).set_handler(IDE_IRQN + 32, ide_irq_entry);
}
} //< namespace hw
|
// 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.
/**
* Intel IDE Controller datasheet at :
* ftp://download.intel.com/design/intarch/datashts/29055002.pdf
*/
#include <hw/ide.hpp>
#include <kernel/irq_manager.hpp>
#include <kernel/syscalls.hpp>
#define IDE_DATA 0x1F0
#define IDE_SECCNT 0x1F2
#define IDE_BLKLO 0x1F3
#define IDE_BLKMID 0x1F4
#define IDE_BLKHI 0x1F5
#define IDE_DRV 0x1F6
#define IDE_CMD 0x1F7
#define IDE_STATUS IDE_CMD
#define IDE_CMD_READ 0x20
#define IDE_CMD_WRITE 0x30
#define IDE_CMD_IDENTIFY 0xEC
#define IDE_DRQ (1 << 3)
#define IDE_DRDY (1 << 6)
#define IDE_BUSY (1 << 7)
#define IDE_CTRL_IRQ 0x3F6
#define IDE_IRQN 14
#define IDE_BLKSZ 512
#define IDE_VENDOR_ID PCI_Device::VENDOR_INTEL
#define IDE_PRODUCT_ID 0x7010
#define IDE_TIMEOUT 2048
namespace hw {
IDE::IDE(hw::PCI_Device& pcidev, selector_t sel) :
_pcidev {pcidev},
_drive {(uint8_t)sel},
_iobase {0U},
_nb_blk {0U}
{
INFO("IDE","VENDOR_ID : 0x%x, PRODUCT_ID : 0x%x", _pcidev.vendor_id(), _pcidev.product_id());
INFO("IDE","Attaching to PCI addr 0x%x",_pcidev.pci_addr());
/** PCI device checking */
if (_pcidev.vendor_id() not_eq IDE_VENDOR_ID) {
panic("This is not an Intel device");
}
CHECK(true, "Vendor ID is INTEL");
if (_pcidev.product_id() not_eq IDE_PRODUCT_ID) {
panic("This is not an IDE Controller");
}
CHECK(true, "Product ID is IDE Controller");
/** Probe PCI resources and fetch I/O-base for device */
_pcidev.probe_resources();
_iobase = _pcidev.iobase();
CHECK(_iobase, "Unit has valid I/O base (0x%x)", _iobase);
/** IRQ initialization */
CHECK(IDE_IRQN, "Unit has IRQ %i", IDE_IRQN);
enable_irq_handler();
INFO("IDE", "Enabling IRQ handler");
/** IDE device initialization */
set_irq_mode(false);
set_drive(0xA0 | _drive);
set_nbsectors(0U);
set_blocknum(0U);
set_command(IDE_CMD_IDENTIFY);
if (not inb(IDE_STATUS)) {
panic("Device not found");
}
CHECK(true, "IDE device found");
wait_status_flags(IDE_DRDY, false);
uint16_t buffer[256];
for (int i {0}; i < 256; ++i) {
buffer[i] = inw(IDE_DATA);
}
_nb_blk = (buffer[61] << 16) | buffer[60];
INFO("IDE", "Initialization complete");
}
struct ide_irq {
ide_irq(uint8_t* buff, IDE::on_read_func call)
: buffer(buff)
, callback(call)
{}
uint8_t* buffer; // Reading buffer
IDE::on_read_func callback; // IRQ callback
};
static int _nb_irqs = 0; // Number of IRQs that we expect
static IDE::on_read_func _current_callback = nullptr; // Callback for the current irq
static std::list<struct ide_irq> _ide_irqs; // IRQ queue
void IDE::read(block_t blk, on_read_func callback) {
if (blk >= _nb_blk) {
// avoid reading past the disk boundaries
callback(buffer_t());
return;
}
set_irq_mode(true);
set_drive(0xE0 | _drive | ((blk >> 24) & 0x0F));
set_nbsectors(1);
set_blocknum(blk);
set_command(IDE_CMD_READ);
_current_callback = callback;
_nb_irqs = 1;
}
void IDE::read(block_t blk, size_t count, on_read_func callback)
{
if (blk + count >= _nb_blk) {
// avoid reading past the disk boundaries
callback(buffer_t());
return;
}
set_irq_mode(true);
set_drive(0xE0 | _drive | ((blk >> 24) & 0x0F));
set_nbsectors(count);
set_blocknum(blk);
set_command(IDE_CMD_READ);
_current_callback = callback;
_nb_irqs = count;
}
IDE::buffer_t IDE::read_sync(block_t blk)
{
if (blk >= _nb_blk) {
// avoid reading past the disk boundaries
return buffer_t();
}
set_irq_mode(false);
set_drive(0xE0 | _drive | ((blk >> 24) & 0x0F));
set_nbsectors(1);
set_blocknum(blk);
set_command(IDE_CMD_READ);
auto* buffer = new uint8_t[block_size()];
wait_status_flags(IDE_DRDY, false);
uint16_t* wptr = (uint16_t*) buffer;
uint16_t* wend = (uint16_t*)&buffer[block_size()];
while (wptr < wend)
*(wptr++) = inw(IDE_DATA);
// return a shared_ptr wrapper for the buffer
return buffer_t(buffer, std::default_delete<uint8_t[]>());
}
IDE::buffer_t IDE::read_sync(block_t blk, size_t cnt) {
(void) blk;
(void) cnt;
// not yet implemented
return buffer_t();
}
void IDE::wait_status_busy() noexcept {
uint8_t ret;
while (((ret = inb(IDE_STATUS)) & IDE_BUSY) == IDE_BUSY);
}
void IDE::wait_status_flags(const int flags, const bool set) noexcept {
wait_status_busy();
auto ret = inb(IDE_STATUS);
for (int i {IDE_TIMEOUT}; i; --i) {
if (set) {
if ((ret & flags) == flags)
break;
} else {
if ((ret & flags) not_eq flags)
break;
}
ret = inb(IDE_STATUS);
}
}
void IDE::set_drive(const uint8_t drive) const noexcept {
wait_status_flags(IDE_DRQ, true);
outb(IDE_DRV, drive);
}
void IDE::set_nbsectors(const uint8_t cnt) const noexcept {
wait_status_flags(IDE_DRQ, true);
outb(IDE_SECCNT, cnt);
}
void IDE::set_blocknum(block_t blk) const noexcept {
wait_status_flags(IDE_DRQ, true);
outb(IDE_BLKLO, blk & 0xFF);
wait_status_flags(IDE_DRQ, true);
outb(IDE_BLKMID, (blk & 0xFF00) >> 8);
wait_status_flags(IDE_DRQ, true);
outb(IDE_BLKHI, (blk & 0xFF0000) >> 16);
}
void IDE::set_command(const uint16_t command) const noexcept {
wait_status_flags(IDE_DRDY, false);
outb(IDE_CMD, command);
}
void IDE::set_irq_mode(const bool on) noexcept {
wait_status_flags(IDE_DRDY, false);
outb(IDE_CTRL_IRQ, on ? 0 : 1);
}
extern "C"
void ide_irq_handler() {
if (!_nb_irqs || _current_callback == nullptr) {
IDE::set_irq_mode(false);
return;
}
uint8_t* buffer = new uint8_t[IDE_BLKSZ];
IDE::wait_status_flags(IDE_DRDY, false);
uint16_t* wptr = (uint16_t*) buffer;
for (IDE::block_t i = 0; i < IDE_BLKSZ / sizeof (uint16_t); ++i)
wptr[i] = inw(IDE_DATA);
_ide_irqs.push_back(ide_irq(buffer, _current_callback));
_nb_irqs--;
}
extern "C" void ide_irq_entry();
void IDE::callback_wrapper()
{
IDE::on_read_func callback = _ide_irqs.front().callback;
callback(IDE::buffer_t(_ide_irqs.front().buffer, std::default_delete<uint8_t[]>()));
_ide_irqs.pop_front();
}
void IDE::enable_irq_handler() {
auto del(delegate<void()>::from<IDE, &IDE::callback_wrapper>(this));
IRQ_manager::cpu(0).subscribe(IDE_IRQN, del);
//IRQ_manager::cpu(0).set_irq_handler(IDE_IRQN + 32, ide_irq_entry);
}
} //< namespace hw
|
Disable async irq handler to allow fat test to build
|
ide: Disable async irq handler to allow fat test to build
|
C++
|
apache-2.0
|
ingve/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,mnordsletten/IncludeOS,hioa-cs/IncludeOS,hioa-cs/IncludeOS,mnordsletten/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,AnnikaH/IncludeOS,ingve/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,AndreasAakesson/IncludeOS,ingve/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,alfred-bratterud/IncludeOS,alfred-bratterud/IncludeOS,mnordsletten/IncludeOS,ingve/IncludeOS,alfred-bratterud/IncludeOS,hioa-cs/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,AnnikaH/IncludeOS,AndreasAakesson/IncludeOS,ingve/IncludeOS
|
f3945a0f931f532c6a1fbdfca277c073cf93a75e
|
src/icelist.cc
|
src/icelist.cc
|
#include "config.h"
#include "yfull.h"
#include <X11/Xatom.h>
#include "ylistbox.h"
#include "yscrollview.h"
#include "ymenu.h"
#include "yxapp.h"
#include "yaction.h"
#include "yinputline.h"
#include "wmmgr.h"
#include "yrect.h"
#include "ypaint.h"
#include "sysdep.h"
#include "yicon.h"
#include "ylocale.h"
#include <dirent.h>
#include "intl.h"
const char *ApplicationName = "icelist";
ref<YPixmap> listbackPixmap;
ref<YImage> listbackPixbuf;
class ObjectList;
class ObjectListBox;
ref<YIcon> folder;
ref<YIcon> file;
class ObjectListItem: public YListItem {
public:
ObjectListItem(char *container, ustring name): fName(name) {
fContainer = container;
fFolder = false;
struct stat sb;
char *path = getLocation();
if (lstat(path, &sb) == 0 && S_ISDIR(sb.st_mode))
fFolder = true;
delete[] path;
}
virtual ~ObjectListItem() { }
virtual ustring getText() { return fName; }
bool isFolder() { return fFolder; }
virtual ref<YIcon> getIcon() { return isFolder() ? folder : file; }
char *getLocation();
private:
char *fContainer;
ustring fName;
bool fFolder;
};
char *ObjectListItem::getLocation() {
char *dir = fContainer;
ustring name = getText();
int dlen;
int nlen = (dlen = strlen(dir)) + 1 + name.length() + 1;
char *npath;
npath = new char[nlen];
strcpy(npath, dir);
if (dlen == 0 || dir[dlen - 1] != '/') {
strcpy(npath + dlen, "/");
dlen++;
}
cstring cs(name);
strcpy(npath + dlen, cs.c_str());
return npath;
}
class ObjectListBox: public YListBox, public YActionListener {
public:
ObjectListBox(ObjectList *list, YScrollView *view, YWindow *aParent): YListBox(view, aParent) {
fObjList = list;
YMenu *openMenu = new YMenu();
openMenu->addItem(_("List View"), 0, null, actionOpenList);
openMenu->addItem(_("Icon View"), 0, null, actionOpenIcon);
folderMenu = new YMenu();
folderMenu->setActionListener(this);
folderMenu->addItem(_("Open"), 0, actionOpenList, openMenu);
}
virtual ~ObjectListBox() { }
virtual bool handleKey(const XKeyEvent &key) {
return YListBox::handleKey(key);
}
virtual void handleClick(const XButtonEvent &up, int count) {
if (up.button == 3 && count == 1) {
YMenu *menu = folderMenu;
menu->popup(this, 0, 0, up.x_root, up.y_root,
YPopupWindow::pfCanFlipVertical |
YPopupWindow::pfCanFlipHorizontal |
YPopupWindow::pfPopupMenu);
return ;
} else
return YListBox::handleClick(up, count);
}
virtual void activateItem(YListItem *item);
virtual void actionPerformed(YAction action, unsigned int /*modifiers*/) {
if (action == actionOpenList) {
}
}
private:
ObjectList *fObjList;
YMenu *folderMenu;
YAction actionClose;
YAction actionOpen;
YAction actionOpenList;
YAction actionOpenIcon;
};
class ObjectList: public YWindow {
public:
static int winCount;
ObjectList(const char *path, YWindow *aParent): YWindow(aParent) {
setDND(true);
fPath = newstr(path);
scroll = new YScrollView(this);
list = new ObjectListBox(this,
scroll,
scroll);
scroll->setView(list);
updateList();
list->show();
scroll->show();
setTitle(fPath);
int w = desktop->width();
int h = desktop->height();
setGeometry(YRect(w / 3, h / 3, w / 3, h / 3));
/*
Pixmap icons[4];
icons[0] = folder->small()->pixmap();
icons[1] = folder->small()->mask();
icons[2] = folder->large()->pixmap();
icons[3] = folder->large()->mask();
XChangeProperty(xapp->display(), handle(),
_XA_WIN_ICONS, XA_PIXMAP,
32, PropModeReplace,
(unsigned char *)icons, 4);
*/
winCount++;
}
~ObjectList() { winCount--; }
virtual void handleClose() {
if (winCount == 1)
xapp->exit(0);
delete this;
}
void updateList();
virtual void configure(const YRect &r) {
YWindow::configure(r);
scroll->setGeometry(YRect(0, 0, r.width(), r.height()));
}
char *getPath() { return fPath; }
private:
ObjectListBox *list;
YScrollView *scroll;
char *fPath;
};
int ObjectList::winCount = 0;
void ObjectList::updateList() {
DIR *dir;
if ((dir = opendir(fPath)) != NULL) {
struct dirent *de;
while ((de = readdir(dir)) != NULL) {
char *n = de->d_name;
if (n[0] == '.' && (n[1] == 0 || (n[1] == '.' && n[2] == 0)))
;
else {
ObjectListItem *o = new ObjectListItem(fPath, n);
if (o)
list->addItem(o);
}
}
closedir(dir);
}
}
void ObjectListBox::activateItem(YListItem *item) {
ObjectListItem *obj = (ObjectListItem *)item;
char *path = obj->getLocation();
if (obj->isFolder()) {
//if (fork() == 0)
// execl("./icelist", "icelist", path, NULL);
ObjectList *list = new ObjectList(path, 0);
list->show();
} else {
if (fork() == 0)
execl("./iceview", "iceview", path, (void *)NULL);
}
delete path;
}
class Panes;
#define NPANES 4
#define TH 20
class Pane: public YWindow {
public:
Pane(const char *title, const char *path, Panes *aParent);
virtual void paint(Graphics &g, const YRect &r);
virtual void handleButton(const XButtonEvent &button);
virtual void handleMotion(const XMotionEvent &motion);
virtual void configure(const YRect &r) {
YWindow::configure(r);
list->setGeometry(YRect(0, TH, r.width(), r.height() - TH));
}
private:
YColor *titleBg;
YColor *titleFg;
YColor *bg;
char *title;
int dragY;
ObjectList *list;
Panes *owner;
};
class Panes: public YWindow {
public:
Pane *panes[NPANES];
Panes(YWindow *aParent = 0);
virtual void handleClose() {
//if (winCount == 1)
xapp->exit(0);
delete this;
}
virtual void configure(const YRect &r) {
YWindow::configure(r);
for (int i = 0; i < NPANES; i++)
panes[i]->setSize(r.width(), panes[i]->height());
panes[NPANES - 1]->setSize(r.width(),
r.height() - panes[NPANES - 1]->y());
}
void movePane(Pane *pane, int delta);
};
Pane::Pane(const char *atitle, const char *path, Panes *aParent): YWindow(aParent) {
title = strdup(atitle);
titleBg = new YColor("#6666CC");
titleFg = YColor::white;
bg = new YColor("#CCCCCC");
list = new ObjectList(path, this);
list->show();
owner = aParent;
}
void Pane::paint(Graphics &g, const YRect &/*r*/) {
g.setColor(titleBg);
g.fillRect(0, 0, width(), TH);
g.setColor(titleFg);
/// !!! g.drawPixmap(folder->small(), 2, 4);
g.drawChars(title, 0, strlen(title), 20, 17);
//g.setColor(bg);
//g.fillRect(0, TH, width(), height() - TH);
}
void Pane::handleButton(const XButtonEvent &button) {
dragY = button.y_root - y();
}
void Pane::handleMotion(const XMotionEvent &motion) {
owner->movePane(this, motion.y_root - dragY);
}
Panes::Panes(YWindow *aParent): YWindow(aParent) {
panes[0] = new Pane("/", "/", this);
panes[1] = new Pane("Home", getenv("HOME"), this);
panes[2] = new Pane("Windows", "wmwinlist:", this);
panes[3] = new Pane("tmp", "/tmp", this);
int w = 200, h = 0;
int height = 600, h1 = height / (NPANES + 1);
for (int i = 0; i < NPANES; i++) {
panes[i]->setGeometry(YRect(0, h, w, h1));
h += h1;
panes[i]->show();
}
}
void Panes::movePane(Pane *pane, int delta) {
for (int i = 1; i < NPANES; i++) {
int oldY = pane->y();
if (panes[i] == pane) {
int min = TH * i;
int max = height() - TH * (NPANES - i - 1);
if (delta < min)
delta = min;
if (delta > max - TH)
delta = max - TH;
int ob = pane->y() + pane->height();
int b = ob - delta;
if (b < TH)
b = TH;
pane->setGeometry(YRect(pane->x(), delta, pane->width(), b));
}
if (pane->y() < oldY) {
int bottom = pane->y();
int n = i - 1;
do {
if (panes[n]->y() + TH > bottom) {
panes[n]->setGeometry(YRect(panes[n]->x(),
bottom - TH,
panes[n]->width(),
TH));
bottom -= TH;
} else {
panes[n]->setSize(panes[n]->width(),
bottom - panes[n]->y());
break;
}
n--;
} while (n > 0);
} else if (pane->y() > oldY) {
int top = pane->y() + pane->height();
int n = i + 1;
panes[i - 1]->setSize(panes[i - 1]->width(),
pane->y() - panes[i - 1]->y());
while (n < NPANES) {
if (panes[n]->y() < top && panes[n]->height() == TH) {
panes[n]->setPosition(panes[n]->x(),
top);
top += TH;
} else if (panes[n]->y() < top) {
panes[n]->setGeometry(
YRect(panes[n]->x(),
top,
panes[n]->width(),
panes[n]->y() + panes[n]->height() - top));
break;
}
n++;
}
}
}
}
int main(int argc, char **argv) {
YLocale locale;
#ifdef ENABLE_NLS
bindtextdomain(PACKAGE, LOCDIR);
textdomain(PACKAGE);
#endif
YXApplication app(&argc, &argv);
YWindow *w;
folder = YIcon::getIcon("folder");
file = YIcon::getIcon("file");
//ObjectList *list = new ObjectList(argv[1] ? argv[1] : (char *)"/", 0);
//list->show();
w = new YWindow();
Panes *p = new Panes(w);
p->setGeometry(YRect(0, 0, 200, 700));
p->show();
YInputLine *input = new YInputLine(w);
input->setGeometry(YRect(0, 700, 200, 20));
input->setText("http://slashdot.org/");
input->show();
w->setGeometry(YRect(0, 0, 200, 720));
w->show();
return app.mainLoop();
}
// vim: set sw=4 ts=4 et:
|
#include "config.h"
#include "yfull.h"
#include <X11/Xatom.h>
#include "ylistbox.h"
#include "yscrollview.h"
#include "ymenu.h"
#include "yxapp.h"
#include "yaction.h"
#include "yinputline.h"
#include "wmmgr.h"
#include "yrect.h"
#include "ypaint.h"
#include "sysdep.h"
#include "yicon.h"
#include "ylocale.h"
#include <dirent.h>
#include "intl.h"
const char *ApplicationName = "icelist";
ref<YPixmap> listbackPixmap;
ref<YImage> listbackPixbuf;
class ObjectList;
class ObjectListBox;
ref<YIcon> folder;
ref<YIcon> file;
class ObjectListItem: public YListItem {
public:
ObjectListItem(char *container, ustring name): fName(name) {
fContainer = container;
fFolder = false;
struct stat sb;
char *path = getLocation();
if (lstat(path, &sb) == 0 && S_ISDIR(sb.st_mode))
fFolder = true;
delete[] path;
}
virtual ~ObjectListItem() { }
virtual ustring getText() { return fName; }
bool isFolder() { return fFolder; }
virtual ref<YIcon> getIcon() { return isFolder() ? folder : file; }
char *getLocation();
private:
char *fContainer;
ustring fName;
bool fFolder;
};
char *ObjectListItem::getLocation() {
char *dir = fContainer;
ustring name = getText();
int dlen;
int nlen = (dlen = strlen(dir)) + 1 + name.length() + 1;
char *npath;
npath = new char[nlen];
memcpy(npath, dir, dlen + 1);
if (dlen == 0 || dir[dlen - 1] != '/') {
strcpy(npath + dlen, "/");
dlen++;
}
cstring cs(name);
strcpy(npath + dlen, cs.c_str());
return npath;
}
class ObjectListBox: public YListBox, public YActionListener {
public:
ObjectListBox(ObjectList *list, YScrollView *view, YWindow *aParent): YListBox(view, aParent) {
fObjList = list;
YMenu *openMenu = new YMenu();
openMenu->addItem(_("List View"), 0, null, actionOpenList);
openMenu->addItem(_("Icon View"), 0, null, actionOpenIcon);
folderMenu = new YMenu();
folderMenu->setActionListener(this);
folderMenu->addItem(_("Open"), 0, actionOpenList, openMenu);
}
virtual ~ObjectListBox() { }
virtual bool handleKey(const XKeyEvent &key) {
return YListBox::handleKey(key);
}
virtual void handleClick(const XButtonEvent &up, int count) {
if (up.button == 3 && count == 1) {
YMenu *menu = folderMenu;
menu->popup(this, 0, 0, up.x_root, up.y_root,
YPopupWindow::pfCanFlipVertical |
YPopupWindow::pfCanFlipHorizontal |
YPopupWindow::pfPopupMenu);
return ;
} else
return YListBox::handleClick(up, count);
}
virtual void activateItem(YListItem *item);
virtual void actionPerformed(YAction action, unsigned int /*modifiers*/) {
if (action == actionOpenList) {
}
}
private:
ObjectList *fObjList;
YMenu *folderMenu;
YAction actionClose;
YAction actionOpen;
YAction actionOpenList;
YAction actionOpenIcon;
};
class ObjectList: public YWindow {
public:
static int winCount;
ObjectList(const char *path, YWindow *aParent): YWindow(aParent) {
setDND(true);
fPath = newstr(path);
scroll = new YScrollView(this);
list = new ObjectListBox(this,
scroll,
scroll);
scroll->setView(list);
updateList();
list->show();
scroll->show();
setTitle(fPath);
int w = desktop->width();
int h = desktop->height();
setGeometry(YRect(w / 3, h / 3, w / 3, h / 3));
/*
Pixmap icons[4];
icons[0] = folder->small()->pixmap();
icons[1] = folder->small()->mask();
icons[2] = folder->large()->pixmap();
icons[3] = folder->large()->mask();
XChangeProperty(xapp->display(), handle(),
_XA_WIN_ICONS, XA_PIXMAP,
32, PropModeReplace,
(unsigned char *)icons, 4);
*/
winCount++;
}
~ObjectList() { winCount--; }
virtual void handleClose() {
if (winCount == 1)
xapp->exit(0);
delete this;
}
void updateList();
virtual void configure(const YRect &r) {
YWindow::configure(r);
scroll->setGeometry(YRect(0, 0, r.width(), r.height()));
}
char *getPath() { return fPath; }
private:
ObjectListBox *list;
YScrollView *scroll;
char *fPath;
};
int ObjectList::winCount = 0;
void ObjectList::updateList() {
DIR *dir;
if ((dir = opendir(fPath)) != NULL) {
struct dirent *de;
while ((de = readdir(dir)) != NULL) {
char *n = de->d_name;
if (n[0] == '.' && (n[1] == 0 || (n[1] == '.' && n[2] == 0)))
;
else {
ObjectListItem *o = new ObjectListItem(fPath, n);
if (o)
list->addItem(o);
}
}
closedir(dir);
}
}
void ObjectListBox::activateItem(YListItem *item) {
ObjectListItem *obj = (ObjectListItem *)item;
char *path = obj->getLocation();
if (obj->isFolder()) {
//if (fork() == 0)
// execl("./icelist", "icelist", path, NULL);
ObjectList *list = new ObjectList(path, 0);
list->show();
} else {
if (fork() == 0)
execl("./iceview", "iceview", path, (void *)NULL);
}
delete path;
}
class Panes;
#define NPANES 4
#define TH 20
class Pane: public YWindow {
public:
Pane(const char *title, const char *path, Panes *aParent);
virtual void paint(Graphics &g, const YRect &r);
virtual void handleButton(const XButtonEvent &button);
virtual void handleMotion(const XMotionEvent &motion);
virtual void configure(const YRect &r) {
YWindow::configure(r);
list->setGeometry(YRect(0, TH, r.width(), r.height() - TH));
}
private:
YColor *titleBg;
YColor *titleFg;
YColor *bg;
char *title;
int dragY;
ObjectList *list;
Panes *owner;
};
class Panes: public YWindow {
public:
Pane *panes[NPANES];
Panes(YWindow *aParent = 0);
virtual void handleClose() {
//if (winCount == 1)
xapp->exit(0);
delete this;
}
virtual void configure(const YRect &r) {
YWindow::configure(r);
for (int i = 0; i < NPANES; i++)
panes[i]->setSize(r.width(), panes[i]->height());
panes[NPANES - 1]->setSize(r.width(),
r.height() - panes[NPANES - 1]->y());
}
void movePane(Pane *pane, int delta);
};
Pane::Pane(const char *atitle, const char *path, Panes *aParent): YWindow(aParent) {
title = strdup(atitle);
titleBg = new YColor("#6666CC");
titleFg = YColor::white;
bg = new YColor("#CCCCCC");
list = new ObjectList(path, this);
list->show();
owner = aParent;
}
void Pane::paint(Graphics &g, const YRect &/*r*/) {
g.setColor(titleBg);
g.fillRect(0, 0, width(), TH);
g.setColor(titleFg);
/// !!! g.drawPixmap(folder->small(), 2, 4);
g.drawChars(title, 0, strlen(title), 20, 17);
//g.setColor(bg);
//g.fillRect(0, TH, width(), height() - TH);
}
void Pane::handleButton(const XButtonEvent &button) {
dragY = button.y_root - y();
}
void Pane::handleMotion(const XMotionEvent &motion) {
owner->movePane(this, motion.y_root - dragY);
}
Panes::Panes(YWindow *aParent): YWindow(aParent) {
panes[0] = new Pane("/", "/", this);
panes[1] = new Pane("Home", getenv("HOME"), this);
panes[2] = new Pane("Windows", "wmwinlist:", this);
panes[3] = new Pane("tmp", "/tmp", this);
int w = 200, h = 0;
int height = 600, h1 = height / (NPANES + 1);
for (int i = 0; i < NPANES; i++) {
panes[i]->setGeometry(YRect(0, h, w, h1));
h += h1;
panes[i]->show();
}
}
void Panes::movePane(Pane *pane, int delta) {
for (int i = 1; i < NPANES; i++) {
int oldY = pane->y();
if (panes[i] == pane) {
int min = TH * i;
int max = height() - TH * (NPANES - i - 1);
if (delta < min)
delta = min;
if (delta > max - TH)
delta = max - TH;
int ob = pane->y() + pane->height();
int b = ob - delta;
if (b < TH)
b = TH;
pane->setGeometry(YRect(pane->x(), delta, pane->width(), b));
}
if (pane->y() < oldY) {
int bottom = pane->y();
int n = i - 1;
do {
if (panes[n]->y() + TH > bottom) {
panes[n]->setGeometry(YRect(panes[n]->x(),
bottom - TH,
panes[n]->width(),
TH));
bottom -= TH;
} else {
panes[n]->setSize(panes[n]->width(),
bottom - panes[n]->y());
break;
}
n--;
} while (n > 0);
} else if (pane->y() > oldY) {
int top = pane->y() + pane->height();
int n = i + 1;
panes[i - 1]->setSize(panes[i - 1]->width(),
pane->y() - panes[i - 1]->y());
while (n < NPANES) {
if (panes[n]->y() < top && panes[n]->height() == TH) {
panes[n]->setPosition(panes[n]->x(),
top);
top += TH;
} else if (panes[n]->y() < top) {
panes[n]->setGeometry(
YRect(panes[n]->x(),
top,
panes[n]->width(),
panes[n]->y() + panes[n]->height() - top));
break;
}
n++;
}
}
}
}
int main(int argc, char **argv) {
YLocale locale;
#ifdef ENABLE_NLS
bindtextdomain(PACKAGE, LOCDIR);
textdomain(PACKAGE);
#endif
YXApplication app(&argc, &argv);
YWindow *w;
folder = YIcon::getIcon("folder");
file = YIcon::getIcon("file");
//ObjectList *list = new ObjectList(argv[1] ? argv[1] : (char *)"/", 0);
//list->show();
w = new YWindow();
Panes *p = new Panes(w);
p->setGeometry(YRect(0, 0, 200, 700));
p->show();
YInputLine *input = new YInputLine(w);
input->setGeometry(YRect(0, 700, 200, 20));
input->setText("http://slashdot.org/");
input->show();
w->setGeometry(YRect(0, 0, 200, 720));
w->show();
return app.mainLoop();
}
// vim: set sw=4 ts=4 et:
|
Replace strcpy by memcpy in icelist for OpenBSD.
|
Replace strcpy by memcpy in icelist for OpenBSD.
|
C++
|
lgpl-2.1
|
dicej/icewm,dicej/icewm,dicej/icewm,dicej/icewm
|
eb7c11be17d0db5eed628edea84c2f7f1bed342a
|
libdvbtee/channels.cpp
|
libdvbtee/channels.cpp
|
/*****************************************************************************
* Copyright (C) 2011-2014 Michael Ira Krufky
*
* Author: Michael Ira Krufky <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <stdlib.h>
#include "channels.h"
static int atsc_vsb_base_offset(const unsigned int channel)
{
int base_offset;
if (channel < 5)
base_offset = 45000000;
else if (channel < 7)
base_offset = 49000000;
else if (channel < 14)
base_offset = 135000000;
else
base_offset = 389000000;
return base_offset;
}
static int atsc_qam_base_offset(const unsigned int channel)
{
int base_offset;
if (channel < 5)
base_offset = 45000000;
else if (channel < 7)
base_offset = 49000000;
else if (channel < 14)
base_offset = 135000000;
else if (channel < 17)
base_offset = 39012500;
else if (channel < 23)
base_offset = 39000000;
else if (channel < 25)
base_offset = 81000000;
else if (channel < 54)
base_offset = 81012500;
else if (channel < 95)
base_offset = 81000000;
else if (channel < 98)
base_offset = -477000000;
else if (channel < 100)
base_offset = -476987500;
else
base_offset = 51000000;
return base_offset;
}
static int dvbt_base_offset(const unsigned int channel)
{
int base_offset;
if (channel < 13)
base_offset = 142500000;
else if (channel < 70)
base_offset = 306000000;
else
base_offset = 0; /* FIXME */
return base_offset;
}
unsigned int atsc_vsb_chan_to_freq(const unsigned int channel)
{
return (unsigned int)((int)channel*6000000 + atsc_vsb_base_offset(channel));
}
unsigned int atsc_qam_chan_to_freq(const unsigned int channel)
{
return (unsigned int)((int)channel*6000000 + atsc_qam_base_offset(channel));
}
unsigned int atsc_vsb_freq_to_chan(const unsigned int frequency)
{
for (int channel=2; channel <= 69; channel++) {
if (abs(atsc_vsb_chan_to_freq(channel) - frequency) < 1000000)
return channel;
}
return 0;
}
unsigned int atsc_qam_freq_to_chan(const unsigned int frequency)
{
for (int channel=2; channel <= 133; channel++) {
if (abs(atsc_qam_chan_to_freq(channel) - frequency) < 1000000)
return channel;
}
return 0;
}
#if 0
#define VHF_LOWER_FREQUENCY 177500 /* channel 5 */
#define VHF_UPPER_FREQUENCY 226500 /* channel 12 */
#define UHF_LOWER_FREQUENCY 474000 /* channel 21 */
#define UHF_UPPER_FREQUENCY 858000 /* channel 69 */
#endif
unsigned int dvbt_chan_to_freq(const unsigned int channel)
{
return (unsigned int)((int)channel* ((channel <= 12) ? 7000000 : 8000000) + dvbt_base_offset(channel));
}
unsigned int dvbt_freq_to_chan(const unsigned int frequency)
{
for (int channel=5; channel <= 69; channel++) {
if (abs(dvbt_chan_to_freq(channel) - frequency) < 1000000)
return channel;
}
return 0;
}
|
/*****************************************************************************
* Copyright (C) 2011-2014 Michael Ira Krufky
*
* Author: Michael Ira Krufky <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <stdlib.h>
#include "channels.h"
static int atsc_vsb_base_offset(const unsigned int channel)
{
int base_offset;
if (channel < 5)
base_offset = 45000000;
else if (channel < 7)
base_offset = 49000000;
else if (channel < 14)
base_offset = 135000000;
else
base_offset = 389000000;
return base_offset;
}
static int atsc_qam_base_offset(const unsigned int channel)
{
int base_offset;
if (channel < 5)
base_offset = 45000000;
else if (channel < 7)
base_offset = 49000000;
else if (channel < 14)
base_offset = 135000000;
else if (channel < 17)
base_offset = 39012500;
else if (channel < 23)
base_offset = 39000000;
else if (channel < 25)
base_offset = 81000000;
else if (channel < 54)
base_offset = 81012500;
else if (channel < 95)
base_offset = 81000000;
else if (channel < 98)
base_offset = -477000000;
else if (channel < 100)
base_offset = -476987500;
else
base_offset = 51000000;
return base_offset;
}
static int dvbt_base_offset(const unsigned int channel)
{
int base_offset;
if (channel < 13)
base_offset = 142500000;
else if (channel < 70)
base_offset = 306000000;
else
base_offset = 0; /* FIXME */
return base_offset;
}
unsigned int atsc_vsb_chan_to_freq(const unsigned int channel)
{
return (unsigned int)((int)channel*6000000 + atsc_vsb_base_offset(channel));
}
unsigned int atsc_qam_chan_to_freq(const unsigned int channel)
{
return (unsigned int)((int)channel*6000000 + atsc_qam_base_offset(channel));
}
unsigned int atsc_vsb_freq_to_chan(const unsigned int frequency)
{
for (int channel=2; channel <= 69; channel++) {
if (abs((int)atsc_vsb_chan_to_freq(channel) - (int)frequency) < 1000000)
return channel;
}
return 0;
}
unsigned int atsc_qam_freq_to_chan(const unsigned int frequency)
{
for (int channel=2; channel <= 133; channel++) {
if (abs((int)atsc_qam_chan_to_freq(channel) - (int)frequency) < 1000000)
return channel;
}
return 0;
}
#if 0
#define VHF_LOWER_FREQUENCY 177500 /* channel 5 */
#define VHF_UPPER_FREQUENCY 226500 /* channel 12 */
#define UHF_LOWER_FREQUENCY 474000 /* channel 21 */
#define UHF_UPPER_FREQUENCY 858000 /* channel 69 */
#endif
unsigned int dvbt_chan_to_freq(const unsigned int channel)
{
return (unsigned int)((int)channel* ((channel <= 12) ? 7000000 : 8000000) + dvbt_base_offset(channel));
}
unsigned int dvbt_freq_to_chan(const unsigned int frequency)
{
for (int channel=5; channel <= 69; channel++) {
if (abs((int)dvbt_chan_to_freq(channel) - (int)frequency) < 1000000)
return channel;
}
return 0;
}
|
fix warning: taking the absolute value of unsigned type 'unsigned int' has no effect
|
channels: fix warning: taking the absolute value of unsigned type 'unsigned int' has no effect
Signed-off-by: Michael Ira Krufky <[email protected]>
|
C++
|
lgpl-2.1
|
mkrufky/libdvbtee,mkrufky/libdvbtee,anshul1912/libdvbtee,pashamesh/libdvbtee,mkrufky/libdvbtee,pashamesh/libdvbtee,anshul1912/libdvbtee,anshul1912/libdvbtee,mkrufky/libdvbtee,pashamesh/libdvbtee,mkrufky/libdvbtee
|
1166fd226f13be3606ba4307e979f7c5e02c9ce2
|
libmary/server_app.cpp
|
libmary/server_app.cpp
|
/* LibMary - C++ library for high-performance network servers
Copyright (C) 2011 Dmitry Shatrov
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
*/
#include <libmary/libmary_config.h>
#include <libmary/deferred_connection_sender.h>
#include <libmary/util_time.h>
#include <libmary/log.h>
#include <libmary/server_app.h>
namespace M {
namespace {
LogGroup libMary_logGroup_server_app ("server_app", LogLevel::N);
}
ActivePollGroup::Frontend ServerApp::poll_frontend = {
pollIterationBegin,
pollIterationEnd
};
#ifdef LIBMARY_MT_SAFE
ServerThreadContext*
ServerApp::SA_ServerContext::selectThreadContext ()
{
ServerThreadContext *thread_ctx;
StateMutexLock l (server_app->mutex);
if (server_app->thread_selector) {
thread_ctx = &server_app->thread_selector->data->thread_ctx;
server_app->thread_selector = server_app->thread_selector->next;
} else {
if (!server_app->thread_data_list.isEmpty ()) {
thread_ctx = &server_app->thread_data_list.getFirst()->thread_ctx;
server_app->thread_selector = server_app->thread_data_list.getFirstElement()->next;
} else {
thread_ctx = &server_app->main_thread_ctx;
}
}
return thread_ctx;
}
#endif // LIBMARY_MT_SAFE
void
ServerApp::firstTimerAdded (void * const _active_poll_group)
{
logD (server_app, _func_);
ActivePollGroup * const active_poll_group = static_cast <ActivePollGroup*> (_active_poll_group);
active_poll_group->trigger ();
}
void
ServerApp::pollIterationBegin (void * const _thread_ctx)
{
ServerThreadContext * const thread_ctx = static_cast <ServerThreadContext*> (_thread_ctx);
if (!updateTime ())
logE_ (_func, exc->toString());
thread_ctx->getTimers()->processTimers ();
}
bool
ServerApp::pollIterationEnd (void * const _thread_ctx)
{
ServerThreadContext * const thread_ctx = static_cast <ServerThreadContext*> (_thread_ctx);
return thread_ctx->getDeferredProcessor()->process ();
}
namespace {
void deferred_processor_trigger (void * const _active_poll_group)
{
ActivePollGroup * const active_poll_group = static_cast <ActivePollGroup*> (_active_poll_group);
active_poll_group->trigger ();
}
DeferredProcessor::Backend deferred_processor_backend = {
deferred_processor_trigger
};
}
mt_throws Result
ServerApp::init ()
{
if (!poll_group.open ())
return Result::Failure;
server_ctx.init (&timers, &poll_group);
main_thread_ctx.init (&timers,
&poll_group,
&deferred_processor,
&dcs_queue);
poll_group.setFrontend (CbDesc<ActivePollGroup::Frontend> (
&poll_frontend, &main_thread_ctx, NULL /* coderef_container */));
deferred_processor.setBackend (CbDesc<DeferredProcessor::Backend> (
&deferred_processor_backend,
static_cast <ActivePollGroup*> (&poll_group) /* cb_data */,
NULL /* coderef_container */));
return Result::Success;
}
#ifdef LIBMARY_MT_SAFE
void
ServerApp::threadFunc (void * const _self)
{
ServerApp * const self = static_cast <ServerApp*> (_self);
Ref<ThreadData> const thread_data = grab (new ThreadData);
thread_data->dcs_queue.setDeferredProcessor (&thread_data->deferred_processor);
thread_data->thread_ctx.init (&thread_data->timers,
&thread_data->poll_group,
&thread_data->deferred_processor,
&thread_data->dcs_queue);
thread_data->poll_group.bindToThread (libMary_getThreadLocal());
if (!thread_data->poll_group.open ()) {
logE_ (_func, "poll_group.open() failed: ", exc->toString());
return;
}
thread_data->poll_group.setFrontend (CbDesc<ActivePollGroup::Frontend> (
&poll_frontend, &thread_data->thread_ctx, NULL /* coderef_container */));
thread_data->timers.setFirstTimerAddedCallback (CbDesc<Timers::FirstTimerAddedCallback> (
firstTimerAdded, &thread_data->poll_group, NULL /* coderef_container */));
thread_data->deferred_processor.setBackend (CbDesc<DeferredProcessor::Backend> (
&deferred_processor_backend,
static_cast <ActivePollGroup*> (&thread_data->poll_group) /* cb_data */,
NULL /* coderef_container */));
self->mutex.lock ();
if (self->should_stop.get()) {
self->mutex.unlock ();
return;
}
self->thread_data_list.append (thread_data);
self->mutex.unlock ();
for (;;) {
if (!thread_data->poll_group.poll (thread_data->timers.getSleepTime_microseconds())) {
logE_ (_func, "poll_group.poll() failed: ", exc->toString());
// TODO This is a fatal error, but we should exit gracefully nevertheless.
abort ();
break;
}
if (self->should_stop.get())
break;
}
}
#endif // LIBMARY_MT_SAFE
mt_throws Result
ServerApp::run ()
{
poll_group.bindToThread (libMary_getThreadLocal());
#ifdef LIBMARY_MT_SAFE
if (!multi_thread->spawn (true /* joinable */)) {
logE_ (_func, "multi_thread->spawn() failed: ", exc->toString());
return Result::Failure;
}
#endif
for (;;) {
if (!poll_group.poll (timers.getSleepTime_microseconds())) {
logE_ (_func, "poll_group.poll() failed: ", exc->toString());
stop ();
#ifdef LIBMARY_MT_SAFE
multi_thread->join ();
#endif
return Result::Failure;
}
if (should_stop.get())
break;
}
stop ();
#ifdef LIBMARY_MT_SAFE
multi_thread->join ();
#endif
return Result::Success;
}
void
ServerApp::stop ()
{
should_stop.set (1);
#ifdef LIBMARY_MT_SAFE
mutex.lock ();
{
ThreadDataList::iter iter (thread_data_list);
while (!thread_data_list.iter_done (iter)) {
ThreadData * const thread_data = thread_data_list.iter_next (iter)->data;
if (!thread_data->poll_group.trigger ())
logE_ (_func, "poll_group.trigger() failed: ", exc->toString());
}
}
mutex.unlock ();
#endif
}
ServerApp::ServerApp (Object * const coderef_container,
Count const num_threads)
: DependentCodeReferenced (coderef_container),
server_ctx (this),
timers (firstTimerAdded, &poll_group/* cb_data */, NULL /* coderef_container */),
poll_group (coderef_container),
dcs_queue (coderef_container)
#ifdef LIBMARY_MT_SAFE
, thread_selector (NULL)
#endif
{
dcs_queue.setDeferredProcessor (&deferred_processor);
#ifdef LIBMARY_MT_SAFE
multi_thread = grab (new MultiThread (
num_threads,
CbDesc<Thread::ThreadFunc> (threadFunc,
this /* cb_data */,
getCoderefContainer(),
NULL /* ref_data */)));
#endif
}
}
|
/* LibMary - C++ library for high-performance network servers
Copyright (C) 2011 Dmitry Shatrov
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
*/
#include <libmary/libmary_config.h>
#include <libmary/deferred_connection_sender.h>
#include <libmary/util_time.h>
#include <libmary/log.h>
#include <libmary/server_app.h>
namespace M {
namespace {
LogGroup libMary_logGroup_server_app ("server_app", LogLevel::N);
}
ActivePollGroup::Frontend ServerApp::poll_frontend = {
pollIterationBegin,
pollIterationEnd
};
ServerThreadContext*
ServerApp::SA_ServerContext::selectThreadContext ()
{
#ifdef LIBMARY_MT_SAFE
ServerThreadContext *thread_ctx;
StateMutexLock l (server_app->mutex);
if (server_app->thread_selector) {
thread_ctx = &server_app->thread_selector->data->thread_ctx;
server_app->thread_selector = server_app->thread_selector->next;
} else {
if (!server_app->thread_data_list.isEmpty ()) {
thread_ctx = &server_app->thread_data_list.getFirst()->thread_ctx;
server_app->thread_selector = server_app->thread_data_list.getFirstElement()->next;
} else {
thread_ctx = &server_app->main_thread_ctx;
}
}
return thread_ctx;
#else
return &server_app->main_thread_ctx;
#endif // LIBMARY_MT_SAFE
}
void
ServerApp::firstTimerAdded (void * const _active_poll_group)
{
logD (server_app, _func_);
ActivePollGroup * const active_poll_group = static_cast <ActivePollGroup*> (_active_poll_group);
active_poll_group->trigger ();
}
void
ServerApp::pollIterationBegin (void * const _thread_ctx)
{
ServerThreadContext * const thread_ctx = static_cast <ServerThreadContext*> (_thread_ctx);
if (!updateTime ())
logE_ (_func, exc->toString());
thread_ctx->getTimers()->processTimers ();
}
bool
ServerApp::pollIterationEnd (void * const _thread_ctx)
{
ServerThreadContext * const thread_ctx = static_cast <ServerThreadContext*> (_thread_ctx);
return thread_ctx->getDeferredProcessor()->process ();
}
namespace {
void deferred_processor_trigger (void * const _active_poll_group)
{
ActivePollGroup * const active_poll_group = static_cast <ActivePollGroup*> (_active_poll_group);
active_poll_group->trigger ();
}
DeferredProcessor::Backend deferred_processor_backend = {
deferred_processor_trigger
};
}
mt_throws Result
ServerApp::init ()
{
if (!poll_group.open ())
return Result::Failure;
server_ctx.init (&timers, &poll_group);
main_thread_ctx.init (&timers,
&poll_group,
&deferred_processor,
&dcs_queue);
poll_group.setFrontend (CbDesc<ActivePollGroup::Frontend> (
&poll_frontend, &main_thread_ctx, NULL /* coderef_container */));
deferred_processor.setBackend (CbDesc<DeferredProcessor::Backend> (
&deferred_processor_backend,
static_cast <ActivePollGroup*> (&poll_group) /* cb_data */,
NULL /* coderef_container */));
return Result::Success;
}
#ifdef LIBMARY_MT_SAFE
void
ServerApp::threadFunc (void * const _self)
{
ServerApp * const self = static_cast <ServerApp*> (_self);
Ref<ThreadData> const thread_data = grab (new ThreadData);
thread_data->dcs_queue.setDeferredProcessor (&thread_data->deferred_processor);
thread_data->thread_ctx.init (&thread_data->timers,
&thread_data->poll_group,
&thread_data->deferred_processor,
&thread_data->dcs_queue);
thread_data->poll_group.bindToThread (libMary_getThreadLocal());
if (!thread_data->poll_group.open ()) {
logE_ (_func, "poll_group.open() failed: ", exc->toString());
return;
}
thread_data->poll_group.setFrontend (CbDesc<ActivePollGroup::Frontend> (
&poll_frontend, &thread_data->thread_ctx, NULL /* coderef_container */));
thread_data->timers.setFirstTimerAddedCallback (CbDesc<Timers::FirstTimerAddedCallback> (
firstTimerAdded, &thread_data->poll_group, NULL /* coderef_container */));
thread_data->deferred_processor.setBackend (CbDesc<DeferredProcessor::Backend> (
&deferred_processor_backend,
static_cast <ActivePollGroup*> (&thread_data->poll_group) /* cb_data */,
NULL /* coderef_container */));
self->mutex.lock ();
if (self->should_stop.get()) {
self->mutex.unlock ();
return;
}
self->thread_data_list.append (thread_data);
self->mutex.unlock ();
for (;;) {
if (!thread_data->poll_group.poll (thread_data->timers.getSleepTime_microseconds())) {
logE_ (_func, "poll_group.poll() failed: ", exc->toString());
// TODO This is a fatal error, but we should exit gracefully nevertheless.
abort ();
break;
}
if (self->should_stop.get())
break;
}
}
#endif // LIBMARY_MT_SAFE
mt_throws Result
ServerApp::run ()
{
poll_group.bindToThread (libMary_getThreadLocal());
#ifdef LIBMARY_MT_SAFE
if (!multi_thread->spawn (true /* joinable */)) {
logE_ (_func, "multi_thread->spawn() failed: ", exc->toString());
return Result::Failure;
}
#endif
for (;;) {
if (!poll_group.poll (timers.getSleepTime_microseconds())) {
logE_ (_func, "poll_group.poll() failed: ", exc->toString());
stop ();
#ifdef LIBMARY_MT_SAFE
multi_thread->join ();
#endif
return Result::Failure;
}
if (should_stop.get())
break;
}
stop ();
#ifdef LIBMARY_MT_SAFE
multi_thread->join ();
#endif
return Result::Success;
}
void
ServerApp::stop ()
{
should_stop.set (1);
#ifdef LIBMARY_MT_SAFE
mutex.lock ();
{
ThreadDataList::iter iter (thread_data_list);
while (!thread_data_list.iter_done (iter)) {
ThreadData * const thread_data = thread_data_list.iter_next (iter)->data;
if (!thread_data->poll_group.trigger ())
logE_ (_func, "poll_group.trigger() failed: ", exc->toString());
}
}
mutex.unlock ();
#endif
}
ServerApp::ServerApp (Object * const coderef_container,
Count const num_threads)
: DependentCodeReferenced (coderef_container),
server_ctx (this),
timers (firstTimerAdded, &poll_group/* cb_data */, NULL /* coderef_container */),
poll_group (coderef_container),
dcs_queue (coderef_container)
#ifdef LIBMARY_MT_SAFE
, thread_selector (NULL)
#endif
{
dcs_queue.setDeferredProcessor (&deferred_processor);
#ifdef LIBMARY_MT_SAFE
multi_thread = grab (new MultiThread (
num_threads,
CbDesc<Thread::ThreadFunc> (threadFunc,
this /* cb_data */,
getCoderefContainer(),
NULL /* ref_data */)));
#endif
}
}
|
fix for previous commit
|
fix for previous commit
|
C++
|
lgpl-2.1
|
dshatrov/libmary,dshatrov/libmary,erdizz/libmary,erdizz/libmary,erdizz/libmary,dshatrov/libmary
|
df940fdd0db5c314d71f4fa8ad093b4cecd77ea3
|
type_traits.hpp
|
type_traits.hpp
|
#ifndef HMLIB_TYPETRAITS_INC
#define HMLIB_TYPETRAITS_INC 100
#
#include<type_traits>
namespace hmLib{
template<typename type1, typename type2>
struct select_derived{
template<typename type, bool Type1IsBase = std::is_base_of<type1,type2>::value, bool Type2IsBase = std::is_base_of<type2, type1>::value>
struct check{
using ans_type = void;
};
template<typename type>
struct check<type, true, false>{
using ans_type = type2;
};
template<typename type>
struct check<type, false, true>{
using ans_type = type1;
};
using type = typename check<void>::ans_type;
};
template<typename terget, typename... others>
struct near_base_of{
template<typename terget_, typename candidate_>
struct check{
using ans_type = candidate_;
};
using type = typename check<terget, void>::ans_type;
};
template<typename terget, typename try_type, typename... others>
struct near_base_of<terget, try_type, others...>{
template<typename terget_, typename candidate_, bool IsBase = std::is_base_of<try_type, terget>::value>
struct check{
using ans_type = typename near_base_of<terget, others...>::template check<terget_, candidate_>::ans_type;
};
template<typename terget_, typename candidate_>
struct check<terget_, candidate_, true>{
using new_candidate = typename select_derived<candidate_, try_type>::type;
using ans_type = typename near_base_of<terget, others...>::template check<terget_, new_candidate>::ans_type;
};
template<typename terget_>
struct check<terget_, void, true>{
using ans_type = typename near_base_of<terget, others...>::template check<terget_, try_type>::ans_type;
};
using type = typename check<terget, void>::ans_type;
};
}
#
#endif
|
#ifndef HMLIB_TYPETRAITS_INC
#define HMLIB_TYPETRAITS_INC 100
#
#include<type_traits>
namespace hmLib{
template<typename type1, typename type2>
struct select_derived{
template<typename type, bool Type1IsBase = std::is_base_of<type1,type2>::value, bool Type2IsBase = std::is_base_of<type2, type1>::value>
struct check{
using ans_type = void;
};
template<typename type>
struct check<type, true, false>{
using ans_type = type2;
};
template<typename type>
struct check<type, false, true>{
using ans_type = type1;
};
using type = typename check<void>::ans_type;
};
template<typename terget, typename... others>
struct near_base_of{
template<typename terget_, typename candidate_>
struct check{
using ans_type = candidate_;
};
using type = typename check<terget, void>::ans_type;
};
template<typename terget, typename try_type, typename... others>
struct near_base_of<terget, try_type, others...>{
template<typename terget_, typename candidate_, bool IsBase = std::is_base_of<try_type, terget>::value>
struct check{
using ans_type = typename near_base_of<terget, others...>::template check<terget_, candidate_>::ans_type;
};
template<typename terget_, typename candidate_>
struct check<terget_, candidate_, true>{
using new_candidate = typename select_derived<candidate_, try_type>::type;
using ans_type = typename near_base_of<terget, others...>::template check<terget_, new_candidate>::ans_type;
};
template<typename terget_>
struct check<terget_, void, true>{
using ans_type = typename near_base_of<terget, others...>::template check<terget_, try_type>::ans_type;
};
using type = typename check<terget, void>::ans_type;
};
namespace detail {
struct has_begin_and_end_impl {
template <class T>
static auto check(T&& x)->decltype(x.begin(), x.end(), std::true_type{});
template <class T>
static auto check(...)->std::false_type;
};
}
template <class T>
class has_begin_and_end :public decltype(detail::has_begin_and_end_impl::check<T>(std::declval<T>())) {};
}
#
#endif
|
Add has_begin_and_end in type_traits.
|
Add has_begin_and_end in type_traits.
|
C++
|
mit
|
hmito/hmLib,hmito/hmLib
|
1986af53354a083e0d432914c76d65ebbef26a1f
|
AssetInputMesh.C
|
AssetInputMesh.C
|
#include "AssetInputMesh.h"
#include <maya/MFnMesh.h>
#include <maya/MFloatPointArray.h>
#include <maya/MIntArray.h>
#include <maya/MItMeshPolygon.h>
#include <maya/MMatrix.h>
#include "util.h"
AssetInputMesh::AssetInputMesh(int assetId, int inputIdx) :
AssetInput(assetId, inputIdx),
myInputAssetId(0)
{
HAPI_CreateGeoInput(myAssetId, myInputIdx, &myInputInfo);
}
AssetInputMesh::~AssetInputMesh()
{
}
AssetInput::AssetInputType
AssetInputMesh::assetInputType() const
{
return AssetInput::AssetInputType_Mesh;
}
void
AssetInputMesh::setInputTransform(MDataHandle &dataHandle)
{
// Set the transform
MMatrix transformMat = dataHandle.asMatrix();
float inputMat[ 16 ];
for( int ii = 0; ii < 4; ii++ )
{
for( int jj = 0; jj < 4; jj++ )
{
inputMat[ii*4 + jj] = (float) transformMat.matrix[ii][jj];
}
}
HAPI_TransformEuler transformEuler;
HAPI_ConvertMatrixToEuler( inputMat, HAPI_TRS, HAPI_XYZ, &transformEuler );
HAPI_SetObjectTransform( myInputAssetId, myInputInfo.objectId, transformEuler );
}
void
AssetInputMesh::setInputGeo(MDataHandle &dataHandle)
{
// extract mesh data from Maya
MObject meshObj = dataHandle.asMesh();
MFnMesh meshFn(meshObj);
MItMeshPolygon itMeshPoly(meshObj);
// get points
MFloatPointArray points;
meshFn.getPoints(points);
// get face data
MIntArray faceCounts;
MIntArray vertexList;
while (!itMeshPoly.isDone())
{
int vc = itMeshPoly.polygonVertexCount();
faceCounts.append(vc);
for (int j=0; j<vc; j++)
{
vertexList.append(itMeshPoly.vertexIndex(j));
}
itMeshPoly.next();
}
Util::reverseWindingOrder(vertexList, faceCounts);
// set up part info
HAPI_PartInfo partInfo;
HAPI_PartInfo_Init(&partInfo);
partInfo.id = 0;
partInfo.faceCount = faceCounts.length();
partInfo.vertexCount = vertexList.length();
partInfo.pointCount = points.length();
// copy data to arrays
int * vl = new int[partInfo.vertexCount];
int * fc = new int[partInfo.faceCount];
vertexList.get(vl);
faceCounts.get(fc);
float* pos_attr = new float[ partInfo.pointCount * 3 ];
for ( int i = 0; i < partInfo.pointCount; ++i )
for ( int j = 0; j < 3; ++j )
pos_attr[ i * 3 + j ] = points[ i ][ j ];
// Set the data
HAPI_SetPartInfo(myInputAssetId, myInputInfo.objectId,
myInputInfo.geoId, &partInfo);
HAPI_SetFaceCounts(myInputAssetId, myInputInfo.objectId,
myInputInfo.geoId, fc, 0, partInfo.faceCount);
HAPI_SetVertexList(myInputAssetId, myInputInfo.objectId,
myInputInfo.geoId, vl, 0, partInfo.vertexCount);
// Set position attributes.
HAPI_AttributeInfo pos_attr_info;
pos_attr_info.exists = true;
pos_attr_info.owner = HAPI_ATTROWNER_POINT;
pos_attr_info.storage = HAPI_STORAGETYPE_FLOAT;
pos_attr_info.count = partInfo.pointCount;
pos_attr_info.tupleSize = 3;
HAPI_AddAttribute(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "P", &pos_attr_info );
HAPI_SetAttributeFloatData(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "P", &pos_attr_info,
pos_attr, 0, partInfo.pointCount);
// Commit it
HAPI_CommitGeo(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId);
delete[] vl;
delete[] fc;
delete[] pos_attr;
}
|
#include "AssetInputMesh.h"
#include <maya/MFnMesh.h>
#include <maya/MFloatPointArray.h>
#include <maya/MIntArray.h>
#include <maya/MMatrix.h>
#include "util.h"
AssetInputMesh::AssetInputMesh(int assetId, int inputIdx) :
AssetInput(assetId, inputIdx),
myInputAssetId(0)
{
HAPI_CreateGeoInput(myAssetId, myInputIdx, &myInputInfo);
}
AssetInputMesh::~AssetInputMesh()
{
}
AssetInput::AssetInputType
AssetInputMesh::assetInputType() const
{
return AssetInput::AssetInputType_Mesh;
}
void
AssetInputMesh::setInputTransform(MDataHandle &dataHandle)
{
// Set the transform
MMatrix transformMat = dataHandle.asMatrix();
float inputMat[ 16 ];
for( int ii = 0; ii < 4; ii++ )
{
for( int jj = 0; jj < 4; jj++ )
{
inputMat[ii*4 + jj] = (float) transformMat.matrix[ii][jj];
}
}
HAPI_TransformEuler transformEuler;
HAPI_ConvertMatrixToEuler( inputMat, HAPI_TRS, HAPI_XYZ, &transformEuler );
HAPI_SetObjectTransform( myInputAssetId, myInputInfo.objectId, transformEuler );
}
void
AssetInputMesh::setInputGeo(MDataHandle &dataHandle)
{
// extract mesh data from Maya
MObject meshObj = dataHandle.asMesh();
MFnMesh meshFn(meshObj);
// get points
MFloatPointArray points;
meshFn.getPoints(points);
// get face data
MIntArray faceCounts;
MIntArray vertexList;
meshFn.getVertices(faceCounts, vertexList);
Util::reverseWindingOrder(vertexList, faceCounts);
// set up part info
HAPI_PartInfo partInfo;
HAPI_PartInfo_Init(&partInfo);
partInfo.id = 0;
partInfo.faceCount = faceCounts.length();
partInfo.vertexCount = vertexList.length();
partInfo.pointCount = points.length();
// copy data to arrays
int * vl = new int[partInfo.vertexCount];
int * fc = new int[partInfo.faceCount];
vertexList.get(vl);
faceCounts.get(fc);
float* pos_attr = new float[ partInfo.pointCount * 3 ];
for ( int i = 0; i < partInfo.pointCount; ++i )
for ( int j = 0; j < 3; ++j )
pos_attr[ i * 3 + j ] = points[ i ][ j ];
// Set the data
HAPI_SetPartInfo(myInputAssetId, myInputInfo.objectId,
myInputInfo.geoId, &partInfo);
HAPI_SetFaceCounts(myInputAssetId, myInputInfo.objectId,
myInputInfo.geoId, fc, 0, partInfo.faceCount);
HAPI_SetVertexList(myInputAssetId, myInputInfo.objectId,
myInputInfo.geoId, vl, 0, partInfo.vertexCount);
// Set position attributes.
HAPI_AttributeInfo pos_attr_info;
pos_attr_info.exists = true;
pos_attr_info.owner = HAPI_ATTROWNER_POINT;
pos_attr_info.storage = HAPI_STORAGETYPE_FLOAT;
pos_attr_info.count = partInfo.pointCount;
pos_attr_info.tupleSize = 3;
HAPI_AddAttribute(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "P", &pos_attr_info );
HAPI_SetAttributeFloatData(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "P", &pos_attr_info,
pos_attr, 0, partInfo.pointCount);
// Commit it
HAPI_CommitGeo(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId);
delete[] vl;
delete[] fc;
delete[] pos_attr;
}
|
Use MFnMesh::getVertices instead of MItMeshPolygon
|
Use MFnMesh::getVertices instead of MItMeshPolygon
|
C++
|
mit
|
sonictk/HoudiniEngineForMaya,sonictk/HoudiniEngineForMaya,sonictk/HoudiniEngineForMaya
|
211cc9153239b08fc89270a1a33d3b5fedb59eb1
|
fpcmp/fpcmp.cpp
|
fpcmp/fpcmp.cpp
|
//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// fpcmp is a tool that basically works like the 'cmp' tool, except that it can
// tolerate errors due to floating point noise, with the -r option.
//
//===----------------------------------------------------------------------===//
#include "Support/CommandLine.h"
#include "Support/FileUtilities.h"
#include "Config/fcntl.h"
#include "Config/sys/mman.h"
#include <iostream>
#include <cmath>
using namespace llvm;
namespace {
cl::opt<std::string>
File1(cl::Positional, cl::desc("<input file #1>"), cl::Required);
cl::opt<std::string>
File2(cl::Positional, cl::desc("<input file #2>"), cl::Required);
cl::opt<double>
RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0));
cl::opt<double>
AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0));
}
/// OpenFile - mmap the specified file into the address space for reading, and
/// return the length and address of the buffer.
static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){
int FD = open(Filename.c_str(), O_RDONLY);
if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) {
std::cerr << "Error: cannot open file '" << Filename << "'\n";
exit(2);
}
// mmap in the file all at once...
BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0);
if (BufPtr == (char*)MAP_FAILED) {
std::cerr << "Error: cannot open file '" << Filename << "'\n";
exit(2);
}
}
static bool isNumberChar(char C) {
switch (C) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
case 'e':
case 'E': return true;
default: return false;
}
}
static char *BackupNumber(char *Pos, char *FirstChar) {
while (Pos < FirstChar && isNumberChar(Pos[-1]))
--Pos;
return Pos;
}
static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) {
char *F1NumEnd, *F2NumEnd;
double V1 = strtod(F1P, &F1NumEnd);
double V2 = strtod(F2P, &F2NumEnd);
if (F1NumEnd == F1P || F2NumEnd == F2P) {
std::cerr << "Comparison failed, not a numeric difference.\n";
exit(1);
}
// Check to see if these are inside the absolute tolerance
if (AbsTolerance < std::abs(V1-V2)) {
// Nope, check the relative tolerance...
double Diff;
if (V2)
Diff = std::abs(V1/V2 - 1.0);
else if (V1)
Diff = std::abs(V2/V1 - 1.0);
else
Diff = 0; // Both zero.
if (Diff > RelTolerance) {
std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = "
<< Diff << "\n";
std::cerr << "Out of tolerence: rel/abs: " << RelTolerance
<< "/" << AbsTolerance << "\n";
exit(1);
}
}
// Otherwise, advance our read pointers to the end of the numbers.
F1P = F1NumEnd; F2P = F2NumEnd;
}
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv);
// mmap in the files.
unsigned File1Len, File2Len;
char *File1Start, *File2Start;
OpenFile(File1, File1Len, File1Start);
OpenFile(File2, File2Len, File2Start);
// Okay, now that we opened the files, scan them for the first difference.
char *File1End = File1Start+File1Len;
char *File2End = File2Start+File2Len;
char *F1P = File1Start;
char *F2P = File2Start;
while (1) {
// Scan for the end of file or first difference.
while (F1P < File1End && F2P < File2End && *F1P == *F2P)
++F1P, ++F2P;
if (F1P >= File1End || F2P >= File2End) break;
// Okay, we must have found a difference. Backup to the start of the
// current number each stream is at so that we can compare from the
// beginning.
F1P = BackupNumber(F1P, File1Start);
F2P = BackupNumber(F2P, File2Start);
// Now that we are at the start of the numbers, compare them, exiting if
// they don't match.
CompareNumbers(F1P, F2P, File1End, File2End);
}
// Okay, we reached the end of file. If both files are at the end, we
// succeeded.
if (F1P >= File1End && F2P >= File2End) return 0;
// Otherwise, we might have run off the end due to a number, backup and retry.
F1P = BackupNumber(F1P, File1Start);
F2P = BackupNumber(F2P, File2Start);
// Now that we are at the start of the numbers, compare them, exiting if
// they don't match.
CompareNumbers(F1P, F2P, File1End, File2End);
// If we found the end, we succeeded.
if (F1P >= File1End && F2P >= File2End) return 0;
return 1;
}
|
//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// fpcmp is a tool that basically works like the 'cmp' tool, except that it can
// tolerate errors due to floating point noise, with the -r option.
//
//===----------------------------------------------------------------------===//
#include "Support/CommandLine.h"
#include "Support/FileUtilities.h"
#include "Config/fcntl.h"
#include "Config/sys/mman.h"
#include <iostream>
#include <cmath>
using namespace llvm;
namespace {
cl::opt<std::string>
File1(cl::Positional, cl::desc("<input file #1>"), cl::Required);
cl::opt<std::string>
File2(cl::Positional, cl::desc("<input file #2>"), cl::Required);
cl::opt<double>
RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0));
cl::opt<double>
AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0));
}
/// OpenFile - mmap the specified file into the address space for reading, and
/// return the length and address of the buffer.
static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){
int FD = open(Filename.c_str(), O_RDONLY);
if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) {
std::cerr << "Error: cannot open file '" << Filename << "'\n";
exit(2);
}
// mmap in the file all at once...
BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0);
if (BufPtr == (char*)MAP_FAILED) {
std::cerr << "Error: cannot open file '" << Filename << "'\n";
exit(2);
}
}
static bool isNumberChar(char C) {
switch (C) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.': case '+': case '-':
case 'e':
case 'E': return true;
default: return false;
}
}
static char *BackupNumber(char *Pos, char *FirstChar) {
while (Pos > FirstChar && isNumberChar(Pos[-1]))
--Pos;
return Pos;
}
static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) {
char *F1NumEnd, *F2NumEnd;
double V1 = strtod(F1P, &F1NumEnd);
double V2 = strtod(F2P, &F2NumEnd);
if (F1NumEnd == F1P || F2NumEnd == F2P) {
std::cerr << "Comparison failed, not a numeric difference.\n";
exit(1);
}
// Check to see if these are inside the absolute tolerance
if (AbsTolerance < std::abs(V1-V2)) {
// Nope, check the relative tolerance...
double Diff;
if (V2)
Diff = std::abs(V1/V2 - 1.0);
else if (V1)
Diff = std::abs(V2/V1 - 1.0);
else
Diff = 0; // Both zero.
if (Diff > RelTolerance) {
std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = "
<< Diff << "\n";
std::cerr << "Out of tolerence: rel/abs: " << RelTolerance
<< "/" << AbsTolerance << "\n";
exit(1);
}
}
// Otherwise, advance our read pointers to the end of the numbers.
F1P = F1NumEnd; F2P = F2NumEnd;
}
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv);
// mmap in the files.
unsigned File1Len, File2Len;
char *File1Start, *File2Start;
OpenFile(File1, File1Len, File1Start);
OpenFile(File2, File2Len, File2Start);
// Okay, now that we opened the files, scan them for the first difference.
char *File1End = File1Start+File1Len;
char *File2End = File2Start+File2Len;
char *F1P = File1Start;
char *F2P = File2Start;
while (1) {
// Scan for the end of file or first difference.
while (F1P < File1End && F2P < File2End && *F1P == *F2P)
++F1P, ++F2P;
if (F1P >= File1End || F2P >= File2End) break;
// Okay, we must have found a difference. Backup to the start of the
// current number each stream is at so that we can compare from the
// beginning.
F1P = BackupNumber(F1P, File1Start);
F2P = BackupNumber(F2P, File2Start);
// Now that we are at the start of the numbers, compare them, exiting if
// they don't match.
CompareNumbers(F1P, F2P, File1End, File2End);
}
// Okay, we reached the end of file. If both files are at the end, we
// succeeded.
if (F1P >= File1End && F2P >= File2End) return 0;
// Otherwise, we might have run off the end due to a number, backup and retry.
F1P = BackupNumber(F1P, File1Start);
F2P = BackupNumber(F2P, File2Start);
// Now that we are at the start of the numbers, compare them, exiting if
// they don't match.
CompareNumbers(F1P, F2P, File1End, File2End);
// If we found the end, we succeeded.
if (F1P >= File1End && F2P >= File2End) return 0;
return 1;
}
|
Fix bug, add support for +/-
|
Fix bug, add support for +/-
git-svn-id: a4a6f32337ebd29ad4763b423022f00f68d1c7b7@12934 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-3-clause
|
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
|
4ac40c194b7e8f0eed7f64a3c81e2c64ac3b0f75
|
Sources/Rosetta/Games/Game.cpp
|
Sources/Rosetta/Games/Game.cpp
|
// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Actions/Choose.hpp>
#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Enchants/Power.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameManager.hpp>
#include <Rosetta/Tasks/Tasks.hpp>
#include <effolkronium/random.hpp>
#include <algorithm>
using Random = effolkronium::random_static;
namespace RosettaStone
{
Game::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)
{
// Set game to player
for (auto& p : m_players)
{
p.SetGame(this);
}
// Add hero and hero power
GetPlayer1().AddHeroAndPower(
Cards::GetInstance().GetHeroCard(gameConfig.player1Class),
Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));
GetPlayer2().AddHeroAndPower(
Cards::GetInstance().GetHeroCard(gameConfig.player2Class),
Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));
// Set opponent player
GetPlayer1().SetOpponent(&GetPlayer2());
GetPlayer2().SetOpponent(&GetPlayer1());
}
Player& Game::GetPlayer1()
{
return m_players[0];
}
Player& Game::GetPlayer2()
{
return m_players[1];
}
Player& Game::GetCurrentPlayer() const
{
return *m_currentPlayer;
}
Player& Game::GetOpponentPlayer() const
{
return m_currentPlayer->GetOpponent();
}
std::size_t Game::GetNextID()
{
return m_entityID++;
}
std::size_t Game::GetNextOOP()
{
return m_oopIndex++;
}
void Game::BeginFirst()
{
// Set next step
nextStep = Step::BEGIN_SHUFFLE;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginShuffle()
{
// Shuffle cards in deck
if (m_gameConfig.doShuffle)
{
GetPlayer1().GetDeck().Shuffle();
GetPlayer2().GetDeck().Shuffle();
}
// Set next step
nextStep = Step::BEGIN_DRAW;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginDraw()
{
for (auto& p : m_players)
{
// Draw 3 cards
Generic::Draw(p);
Generic::Draw(p);
Generic::Draw(p);
if (&p != m_firstPlayer)
{
// Draw 4th card for second player
Generic::Draw(p);
// Give "The Coin" card to second player
Card coin = Cards::GetInstance().FindCardByID("GAME_005");
p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));
}
}
// Set next step
nextStep =
m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginMulligan()
{
// Start mulligan state
GetPlayer1().mulliganState = Mulligan::INPUT;
GetPlayer2().mulliganState = Mulligan::INPUT;
// Collect cards that can redraw
std::vector<std::size_t> p1HandIDs, p2HandIDs;
for (auto& entity : GetPlayer1().GetHand().GetAllCards())
{
p1HandIDs.emplace_back(entity->id);
}
for (auto& entity : GetPlayer2().GetHand().GetAllCards())
{
p2HandIDs.emplace_back(entity->id);
}
// Create choice for each player
Generic::CreateChoice(GetPlayer1(), ChoiceType::MULLIGAN,
ChoiceAction::HAND, p1HandIDs);
Generic::CreateChoice(GetPlayer2(), ChoiceType::MULLIGAN,
ChoiceAction::HAND, p2HandIDs);
}
void Game::MainBegin()
{
// Set next step
nextStep = Step::MAIN_READY;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainReady()
{
// Reset the number of attacked
for (auto& p : m_players)
{
// Hero
p.GetHero()->numAttacked = 0;
// Field
for (auto& m : p.GetField().GetAllMinions())
{
m->numAttacked = 0;
}
}
// Reset exhaust for current player
auto& curPlayer = GetCurrentPlayer();
// Hero
curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);
// Weapon
if (curPlayer.GetHero()->weapon != nullptr)
{
curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);
}
// Hero power
curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);
// Field
for (auto& m : curPlayer.GetField().GetAllMinions())
{
m->SetGameTag(GameTag::EXHAUSTED, 0);
}
// Set next step
nextStep = Step::MAIN_START_TRIGGERS;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainStartTriggers()
{
// Set next step
nextStep = Step::MAIN_RESOURCE;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainResource()
{
auto& curPlayer = GetCurrentPlayer();
// Add mana crystal to current player
Generic::ChangeManaCrystal(curPlayer, 1, false);
// Reset current mana
curPlayer.currentMana = curPlayer.maximumMana;
// Set next step
nextStep = Step::MAIN_DRAW;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainDraw()
{
// Draw a card for current player
Generic::Draw(GetCurrentPlayer());
// Set next step
nextStep = Step::MAIN_START;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainStart()
{
// Set next step
nextStep = Step::MAIN_ACTION;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainEnd()
{
// Set next step
nextStep = Step::MAIN_CLEANUP;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainCleanUp()
{
auto& curPlayer = GetCurrentPlayer();
// Unfreeze all characters they control that are Frozen, don't have
// summoning sickness (or do have Charge) and have not attacked that turn
// Hero
if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&
curPlayer.GetHero()->numAttacked == 0)
{
curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);
}
// Field
for (auto& m : curPlayer.GetField().GetAllMinions())
{
if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&
m->GetGameTag(GameTag::EXHAUSTED) == 0)
{
m->SetGameTag(GameTag::FROZEN, 0);
}
}
// Set next step
nextStep = Step::MAIN_NEXT;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainNext()
{
// Set player for next turn
m_currentPlayer = &m_currentPlayer->GetOpponent();
// Count next turn
m_turn++;
// Set next step
nextStep = Step::MAIN_READY;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::FinalWrapUp()
{
// Set game states according by result
for (auto& p : m_players)
{
if (p.playState == +PlayState::LOSING ||
p.playState == +PlayState::CONCEDED)
{
p.playState = PlayState::LOST;
p.GetOpponent().playState = PlayState::WON;
}
}
// Set next step
nextStep = Step::FINAL_GAMEOVER;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::FinalGameOver()
{
// Set game state to complete
state = State::COMPLETE;
}
void Game::StartGame()
{
// Reverse card order in deck
if (!m_gameConfig.doShuffle)
{
std::reverse(m_gameConfig.player1Deck.begin(),
m_gameConfig.player1Deck.end());
std::reverse(m_gameConfig.player2Deck.begin(),
m_gameConfig.player2Deck.end());
}
// Set up decks
for (auto& card : m_gameConfig.player1Deck)
{
if (card.cardType == +CardType::INVALID)
{
continue;
}
Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));
GetPlayer1().GetDeck().AddCard(*entity);
}
for (auto& card : m_gameConfig.player2Deck)
{
if (card.cardType == +CardType::INVALID)
{
continue;
}
Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));
GetPlayer2().GetDeck().AddCard(*entity);
}
// Fill cards to deck
if (m_gameConfig.doFillDecks)
{
for (auto& p : m_players)
{
for (auto& cardID : m_gameConfig.fillCardIDs)
{
Card card = Cards::GetInstance().FindCardByID(cardID);
Entity* entity = Entity::GetFromCard(p, std::move(card));
p.GetDeck().AddCard(*entity);
}
}
}
// Set game states
state = State::RUNNING;
for (auto& p : m_players)
{
p.playState = PlayState::PLAYING;
}
// Determine first player
switch (m_gameConfig.startPlayer)
{
case PlayerType::RANDOM:
{
const auto val = Random::get(0, 1);
m_firstPlayer = &m_players[val];
break;
}
case PlayerType::PLAYER1:
m_firstPlayer = &m_players[0];
break;
case PlayerType::PLAYER2:
m_firstPlayer = &m_players[1];
break;
}
m_currentPlayer = m_firstPlayer;
// Set first turn
m_turn = 1;
// Set next step
nextStep = Step::BEGIN_FIRST;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::ProcessDestroyAndUpdateAura()
{
UpdateAura();
// Destroy weapons
if (GetPlayer1().GetHero()->weapon != nullptr &&
GetPlayer1().GetHero()->weapon->isDestroyed == true)
{
GetPlayer1().GetHero()->RemoveWeapon();
}
if (GetPlayer2().GetHero()->weapon != nullptr &&
GetPlayer2().GetHero()->weapon->isDestroyed == true)
{
GetPlayer2().GetHero()->RemoveWeapon();
}
// Destroy minions
if (deadMinions.size() > 0)
{
for (auto& deadMinion : deadMinions)
{
Minion* minion = deadMinion.second;
// Process deathrattle tasks
for (auto& power : minion->card.power.GetDeathrattleTask())
{
if (power == nullptr)
{
continue;
}
power->Run(minion->GetOwner());
}
// Remove minion from battlefield
minion->GetOwner().GetField().RemoveMinion(*minion);
// Add minion to graveyard
minion->GetOwner().GetGraveyard().AddCard(*minion);
}
deadMinions.clear();
}
UpdateAura();
}
void Game::UpdateAura()
{
for (std::size_t i = auras.size(); i >= 0; --i)
{
auras[i]->Update();
}
}
} // namespace RosettaStone
|
// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Actions/Choose.hpp>
#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Enchants/Power.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameManager.hpp>
#include <Rosetta/Tasks/Tasks.hpp>
#include <effolkronium/random.hpp>
#include <algorithm>
using Random = effolkronium::random_static;
namespace RosettaStone
{
Game::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)
{
// Set game to player
for (auto& p : m_players)
{
p.SetGame(this);
}
// Add hero and hero power
GetPlayer1().AddHeroAndPower(
Cards::GetInstance().GetHeroCard(gameConfig.player1Class),
Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));
GetPlayer2().AddHeroAndPower(
Cards::GetInstance().GetHeroCard(gameConfig.player2Class),
Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));
// Set opponent player
GetPlayer1().SetOpponent(&GetPlayer2());
GetPlayer2().SetOpponent(&GetPlayer1());
}
Player& Game::GetPlayer1()
{
return m_players[0];
}
Player& Game::GetPlayer2()
{
return m_players[1];
}
Player& Game::GetCurrentPlayer() const
{
return *m_currentPlayer;
}
Player& Game::GetOpponentPlayer() const
{
return m_currentPlayer->GetOpponent();
}
std::size_t Game::GetNextID()
{
return m_entityID++;
}
std::size_t Game::GetNextOOP()
{
return m_oopIndex++;
}
void Game::BeginFirst()
{
// Set next step
nextStep = Step::BEGIN_SHUFFLE;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginShuffle()
{
// Shuffle cards in deck
if (m_gameConfig.doShuffle)
{
GetPlayer1().GetDeck().Shuffle();
GetPlayer2().GetDeck().Shuffle();
}
// Set next step
nextStep = Step::BEGIN_DRAW;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginDraw()
{
for (auto& p : m_players)
{
// Draw 3 cards
Generic::Draw(p);
Generic::Draw(p);
Generic::Draw(p);
if (&p != m_firstPlayer)
{
// Draw 4th card for second player
Generic::Draw(p);
// Give "The Coin" card to second player
Card coin = Cards::GetInstance().FindCardByID("GAME_005");
p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));
}
}
// Set next step
nextStep =
m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginMulligan()
{
// Start mulligan state
GetPlayer1().mulliganState = Mulligan::INPUT;
GetPlayer2().mulliganState = Mulligan::INPUT;
// Collect cards that can redraw
std::vector<std::size_t> p1HandIDs, p2HandIDs;
for (auto& entity : GetPlayer1().GetHand().GetAllCards())
{
p1HandIDs.emplace_back(entity->id);
}
for (auto& entity : GetPlayer2().GetHand().GetAllCards())
{
p2HandIDs.emplace_back(entity->id);
}
// Create choice for each player
Generic::CreateChoice(GetPlayer1(), ChoiceType::MULLIGAN,
ChoiceAction::HAND, p1HandIDs);
Generic::CreateChoice(GetPlayer2(), ChoiceType::MULLIGAN,
ChoiceAction::HAND, p2HandIDs);
}
void Game::MainBegin()
{
// Set next step
nextStep = Step::MAIN_READY;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainReady()
{
// Reset the number of attacked
for (auto& p : m_players)
{
// Hero
p.GetHero()->numAttacked = 0;
// Field
for (auto& m : p.GetField().GetAllMinions())
{
m->numAttacked = 0;
}
}
// Reset exhaust for current player
auto& curPlayer = GetCurrentPlayer();
// Hero
curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);
// Weapon
if (curPlayer.GetHero()->weapon != nullptr)
{
curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);
}
// Hero power
curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);
// Field
for (auto& m : curPlayer.GetField().GetAllMinions())
{
m->SetGameTag(GameTag::EXHAUSTED, 0);
}
// Set next step
nextStep = Step::MAIN_START_TRIGGERS;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainStartTriggers()
{
// Set next step
nextStep = Step::MAIN_RESOURCE;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainResource()
{
auto& curPlayer = GetCurrentPlayer();
// Add mana crystal to current player
Generic::ChangeManaCrystal(curPlayer, 1, false);
// Reset current mana
curPlayer.currentMana = curPlayer.maximumMana;
// Set next step
nextStep = Step::MAIN_DRAW;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainDraw()
{
// Draw a card for current player
Generic::Draw(GetCurrentPlayer());
// Set next step
nextStep = Step::MAIN_START;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainStart()
{
// Set next step
nextStep = Step::MAIN_ACTION;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainEnd()
{
// Set next step
nextStep = Step::MAIN_CLEANUP;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainCleanUp()
{
auto& curPlayer = GetCurrentPlayer();
// Unfreeze all characters they control that are Frozen, don't have
// summoning sickness (or do have Charge) and have not attacked that turn
// Hero
if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&
curPlayer.GetHero()->numAttacked == 0)
{
curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);
}
// Field
for (auto& m : curPlayer.GetField().GetAllMinions())
{
if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&
m->GetGameTag(GameTag::EXHAUSTED) == 0)
{
m->SetGameTag(GameTag::FROZEN, 0);
}
}
// Set next step
nextStep = Step::MAIN_NEXT;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::MainNext()
{
// Set player for next turn
m_currentPlayer = &m_currentPlayer->GetOpponent();
// Count next turn
m_turn++;
// Set next step
nextStep = Step::MAIN_READY;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::FinalWrapUp()
{
// Set game states according by result
for (auto& p : m_players)
{
if (p.playState == +PlayState::LOSING ||
p.playState == +PlayState::CONCEDED)
{
p.playState = PlayState::LOST;
p.GetOpponent().playState = PlayState::WON;
}
}
// Set next step
nextStep = Step::FINAL_GAMEOVER;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::FinalGameOver()
{
// Set game state to complete
state = State::COMPLETE;
}
void Game::StartGame()
{
// Reverse card order in deck
if (!m_gameConfig.doShuffle)
{
std::reverse(m_gameConfig.player1Deck.begin(),
m_gameConfig.player1Deck.end());
std::reverse(m_gameConfig.player2Deck.begin(),
m_gameConfig.player2Deck.end());
}
// Set up decks
for (auto& card : m_gameConfig.player1Deck)
{
if (card.cardType == +CardType::INVALID)
{
continue;
}
Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));
GetPlayer1().GetDeck().AddCard(*entity);
}
for (auto& card : m_gameConfig.player2Deck)
{
if (card.cardType == +CardType::INVALID)
{
continue;
}
Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));
GetPlayer2().GetDeck().AddCard(*entity);
}
// Fill cards to deck
if (m_gameConfig.doFillDecks)
{
for (auto& p : m_players)
{
for (auto& cardID : m_gameConfig.fillCardIDs)
{
Card card = Cards::GetInstance().FindCardByID(cardID);
Entity* entity = Entity::GetFromCard(p, std::move(card));
p.GetDeck().AddCard(*entity);
}
}
}
// Set game states
state = State::RUNNING;
for (auto& p : m_players)
{
p.playState = PlayState::PLAYING;
}
// Determine first player
switch (m_gameConfig.startPlayer)
{
case PlayerType::RANDOM:
{
const auto val = Random::get(0, 1);
m_firstPlayer = &m_players[val];
break;
}
case PlayerType::PLAYER1:
m_firstPlayer = &m_players[0];
break;
case PlayerType::PLAYER2:
m_firstPlayer = &m_players[1];
break;
}
m_currentPlayer = m_firstPlayer;
// Set first turn
m_turn = 1;
// Set next step
nextStep = Step::BEGIN_FIRST;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::ProcessDestroyAndUpdateAura()
{
UpdateAura();
// Destroy weapons
if (GetPlayer1().GetHero()->weapon != nullptr &&
GetPlayer1().GetHero()->weapon->isDestroyed == true)
{
GetPlayer1().GetHero()->RemoveWeapon();
}
if (GetPlayer2().GetHero()->weapon != nullptr &&
GetPlayer2().GetHero()->weapon->isDestroyed == true)
{
GetPlayer2().GetHero()->RemoveWeapon();
}
// Destroy minions
if (deadMinions.size() > 0)
{
for (auto& deadMinion : deadMinions)
{
Minion* minion = deadMinion.second;
// Process deathrattle tasks
for (auto& power : minion->card.power.GetDeathrattleTask())
{
if (power == nullptr)
{
continue;
}
power->Run(minion->GetOwner());
}
// Remove minion from battlefield
minion->GetOwner().GetField().RemoveMinion(*minion);
// Add minion to graveyard
minion->GetOwner().GetGraveyard().AddCard(*minion);
}
deadMinions.clear();
}
UpdateAura();
}
void Game::UpdateAura()
{
int auraSize = static_cast<int>(auras.size());
if (auraSize == 0)
{
return;
}
for (int i = auraSize - 1; i >= 0; --i)
{
auras[i]->Update();
}
}
} // namespace RosettaStone
|
Correct UpdateAura() method's code
|
fix: Correct UpdateAura() method's code
- Fix std::size_t underflow problem
- Add code to check boundary condition
|
C++
|
mit
|
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp
|
3436e1cb81f0d24a98637dea1f946572430bf27f
|
mjolnir/input/read_local_interaction.hpp
|
mjolnir/input/read_local_interaction.hpp
|
#ifndef MJOLNIR_READ_LOCAL_INTERACTION_HPP
#define MJOLNIR_READ_LOCAL_INTERACTION_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/interaction/BondLengthInteraction.hpp>
#include <mjolnir/interaction/BondAngleInteraction.hpp>
#include <mjolnir/interaction/DihedralAngleInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <mjolnir/util/get_toml_value.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/read_local_potential.hpp>
#include <memory>
namespace mjolnir
{
// ----------------------------------------------------------------------------
// individual local interaction. would be called from read_local_interaction
// defined at the bottom of this file.
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_length_interaction(const std::string& kind, const toml::Table& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_bond_length_interaction(), 0);
using real_type = typename traitsT::real_type;
const auto potential = get_toml_value<std::string>(
local, "potential", "[forcefield.local]");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "Go1012Contact")
{
MJOLNIR_LOG_NOTICE("-- potential functions is 10-12 Go contact.");
using potentialT = Go1012ContactPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as BondLengthInteraction: ", potential);
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::Table& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_bond_angle_interaction(), 0);
using real_type = typename traitsT::real_type;
const auto potential = get_toml_value<std::string>(
local, "potential", "[[forcefields.local]]");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else if(potential == "FlexibleLocalAngle")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Flexible Local Angle.");
using potentialT = FlexibleLocalAnglePotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as BondAngleInteraction: " + potential);
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_dihedral_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::Table& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_dihedral_angle_interaction(), 0);
using real_type = typename traitsT::real_type;
const auto potential = get_toml_value<std::string>(
local, "potential", "[[forcefields.local]]");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "ClementiDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Clementi-Go's dihedral.");
using potentialT = ClementiDihedralPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Gaussian.");
using potentialT = AngularGaussianPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "FlexibleLocalDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Flexible Local Dihedral.");
using potentialT = FlexibleLocalDihedralPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
// XXX generalization of this feature is too difficult (technically it's
// not so difficult, but practically, it makes the code messy...).
else if(potential == "Gaussian+FlexibleLocalDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Gaussian + FlexibleLocalDihedral.");
using potential_1_T = GaussianPotential<real_type>;
using potential_2_T = FlexibleLocalDihedralPotential<real_type>;
using potentialT =
SumLocalPotential<real_type, potential_1_T, potential_2_T>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(kind,
read_local_potentials<4, real_type, potential_1_T, potential_2_T>(
local, "Gaussian", "FlexibleLocalDihedral"));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as DihedralAngleInteraction: " + potential);
}
}
// ----------------------------------------------------------------------------
// general read_local_interaction function
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_local_interaction(const toml::Table& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_local_interaction(), 0);
const auto interaction = get_toml_value<std::string>(
local, "interaction", "[forcefields.local]");
const auto kind = get_toml_value<std::string>(
local, "topology", "[forcefield.local]");
MJOLNIR_LOG_INFO("connection kind = ", kind);
if(interaction == "BondLength")
{
MJOLNIR_LOG_NOTICE("Bond Length interaction found.");
return read_bond_length_interaction<traitsT>(kind, local);
}
else if(interaction == "BondAngle")
{
MJOLNIR_LOG_NOTICE("Bond Angle interaction found.");
return read_bond_angle_interaction<traitsT>(kind, local);
}
else if(interaction == "DihedralAngle")
{
MJOLNIR_LOG_NOTICE("Dihedral Angle interaction found.");
return read_dihedral_angle_interaction<traitsT>(kind, local);
}
else
{
throw std::runtime_error(
"invalid local interaction type: " + interaction);
}
}
} // mjolnir
#endif// MJOLNIR_READ_LOCAL_INTERACTION
|
#ifndef MJOLNIR_READ_LOCAL_INTERACTION_HPP
#define MJOLNIR_READ_LOCAL_INTERACTION_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/interaction/BondLengthInteraction.hpp>
#include <mjolnir/interaction/BondAngleInteraction.hpp>
#include <mjolnir/interaction/DihedralAngleInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/read_local_potential.hpp>
#include <memory>
namespace mjolnir
{
// ----------------------------------------------------------------------------
// individual local interaction. would be called from read_local_interaction
// defined at the bottom of this file.
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_length_interaction(const std::string& kind, const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_bond_length_interaction(), 0);
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "Go1012Contact")
{
MJOLNIR_LOG_NOTICE("-- potential functions is 10-12 Go contact.");
using potentialT = Go1012ContactPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_bond_length_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"Go1012Contact\": r^12 - r^10 type native contact potential",
"- \"Gaussian\" : well-known gaussian potential"
}));
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_bond_angle_interaction(), 0);
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else if(potential == "FlexibleLocalAngle")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Flexible Local Angle.");
using potentialT = FlexibleLocalAnglePotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_bond_angle_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"Gaussian\" : well-known gaussian potential"
"- \"FlexibleLocalAngle\": table-based potential for C-alpha protein model",
}));
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_dihedral_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_dihedral_angle_interaction(), 0);
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "ClementiDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Clementi-Go's dihedral.");
using potentialT = ClementiDihedralPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Gaussian.");
using potentialT = AngularGaussianPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "FlexibleLocalDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Flexible Local Dihedral.");
using potentialT = FlexibleLocalDihedralPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
// XXX generalization of this feature is too difficult (technically it's
// not so difficult, but practically, it makes the code messy...).
else if(potential == "Gaussian+FlexibleLocalDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential functions is Gaussian + FlexibleLocalDihedral.");
using potential_1_T = GaussianPotential<real_type>;
using potential_2_T = FlexibleLocalDihedralPotential<real_type>;
using potentialT =
SumLocalPotential<real_type, potential_1_T, potential_2_T>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(kind,
read_local_potentials<4, real_type, potential_1_T, potential_2_T>(
local, "Gaussian", "FlexibleLocalDihedral"));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_dihedral_angle_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"Gaussian\" : well-known gaussian potential"
"- \"ClementiDihedral\" : potential used in the off-lattice Go protein model"
"- \"FlexibleLocalDihedral\": table-based potential for C-alpha protein model",
}));
}
}
// ----------------------------------------------------------------------------
// general read_local_interaction function
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_local_interaction(const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_local_interaction(), 0);
const auto interaction = toml::find<std::string>(local, "interaction");
const auto kind = toml::find<std::string>(local, "topology");
MJOLNIR_LOG_INFO("connection kind = ", kind);
if(interaction == "BondLength")
{
MJOLNIR_LOG_NOTICE("Bond Length interaction found.");
return read_bond_length_interaction<traitsT>(kind, local);
}
else if(interaction == "BondAngle")
{
MJOLNIR_LOG_NOTICE("Bond Angle interaction found.");
return read_bond_angle_interaction<traitsT>(kind, local);
}
else if(interaction == "DihedralAngle")
{
MJOLNIR_LOG_NOTICE("Dihedral Angle interaction found.");
return read_dihedral_angle_interaction<traitsT>(kind, local);
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_local_interaction: invalid interaction",
toml::find<toml::value>(local, "interaction"), "here", {
"expected value is one of the following.",
"- \"BondLength\" : 2-body well-known chemical bond interaction",
"- \"BondAngle\" : 3-body well-known bond angle interaction",
"- \"DihedralAngle\" : 4-body well-known dihedral angle interaction",
}));
}
}
} // mjolnir
#endif// MJOLNIR_READ_LOCAL_INTERACTION
|
refactor read_local_interaction w/ toml11-v2 features
|
refactor read_local_interaction w/ toml11-v2 features
|
C++
|
mit
|
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
|
554fd90dc1c705e2a15b627d6a91f307ce47c013
|
mjolnir/input/read_local_interaction.hpp
|
mjolnir/input/read_local_interaction.hpp
|
#ifndef MJOLNIR_INPUT_READ_LOCAL_INTERACTION_HPP
#define MJOLNIR_INPUT_READ_LOCAL_INTERACTION_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/interaction/local/BondLengthInteraction.hpp>
#include <mjolnir/interaction/local/ContactInteraction.hpp>
#include <mjolnir/interaction/local/BondAngleInteraction.hpp>
#include <mjolnir/interaction/local/DihedralAngleInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/read_local_potential.hpp>
#include <memory>
namespace mjolnir
{
// ----------------------------------------------------------------------------
// individual local interaction. would be called from read_local_interaction
// defined at the bottom of this file.
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_length_interaction(const std::string& kind, const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential function is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "GoContact")
{
MJOLNIR_LOG_NOTICE("-- potential function is 10-12 Go contact.");
using potentialT = GoContactPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_bond_length_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"GoContact\": r^12 - r^10 type native contact potential",
"- \"Gaussian\" : well-known gaussian potential"
}));
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_contact_interaction(const std::string& kind, const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "GoContact")
{
MJOLNIR_LOG_NOTICE("-- potential function is 10-12 Go contact.");
using potentialT = GoContactPotential<real_type>;
return make_unique<ContactInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<ContactInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_bond_length_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"GoContact\": r^12 - r^10 type native contact potential",
"- \"Gaussian\" : well-known gaussian potential"
}));
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential function is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else if(potential == "FlexibleLocalAngle")
{
MJOLNIR_LOG_NOTICE("-- potential function is Flexible Local Angle.");
using potentialT = FlexibleLocalAnglePotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_bond_angle_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"Gaussian\" : well-known gaussian potential"
"- \"FlexibleLocalAngle\": table-based potential for C-alpha protein model",
}));
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_dihedral_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential function is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "ClementiDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential function is Clementi-Go's dihedral.");
using potentialT = ClementiDihedralPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "PeriodicGaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is PeriodicGaussian.");
using potentialT = PeriodicGaussianPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "FlexibleLocalDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential function is Flexible Local Dihedral.");
using potentialT = FlexibleLocalDihedralPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
// XXX generalization of this feature is too difficult (technically it's
// not so difficult, but practically, it makes the code messy...).
else if(potential == "PeriodicGaussian+FlexibleLocalDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential function is "
"PeriodicGaussian + FlexibleLocalDihedral.");
using potential_1_T = PeriodicGaussianPotential<real_type>;
using potential_2_T = FlexibleLocalDihedralPotential<real_type>;
using potentialT =
SumLocalPotential<real_type, potential_1_T, potential_2_T>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(kind,
read_local_potentials<4, real_type, potential_1_T, potential_2_T>(
local, "PeriodicGaussian", "FlexibleLocalDihedral"));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_dihedral_angle_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"Gaussian\" : well-known gaussian potential"
"- \"ClementiDihedral\" : potential used in the off-lattice Go protein model"
"- \"FlexibleLocalDihedral\": table-based potential for C-alpha protein model",
}));
}
}
// ----------------------------------------------------------------------------
// general read_local_interaction function
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_local_interaction(const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto interaction = toml::find<std::string>(local, "interaction");
const auto kind = toml::find<std::string>(local, "topology");
MJOLNIR_LOG_INFO("connection kind = ", kind);
if(interaction == "BondLength")
{
MJOLNIR_LOG_NOTICE("Bond Length interaction found.");
return read_bond_length_interaction<traitsT>(kind, local);
}
else if(interaction == "Contact")
{
MJOLNIR_LOG_NOTICE("Contact interaction found.");
return read_contact_interaction<traitsT>(kind, local);
}
else if(interaction == "BondAngle")
{
MJOLNIR_LOG_NOTICE("Bond Angle interaction found.");
return read_bond_angle_interaction<traitsT>(kind, local);
}
else if(interaction == "DihedralAngle")
{
MJOLNIR_LOG_NOTICE("Dihedral Angle interaction found.");
return read_dihedral_angle_interaction<traitsT>(kind, local);
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_local_interaction: invalid interaction",
toml::find<toml::value>(local, "interaction"), "here", {
"expected value is one of the following.",
"- \"BondLength\" : 2-body well-known chemical bond interaction",
"- \"BondAngle\" : 3-body well-known bond angle interaction",
"- \"DihedralAngle\" : 4-body well-known dihedral angle interaction",
}));
}
}
} // mjolnir
#endif// MJOLNIR_READ_LOCAL_INTERACTION
|
#ifndef MJOLNIR_INPUT_READ_LOCAL_INTERACTION_HPP
#define MJOLNIR_INPUT_READ_LOCAL_INTERACTION_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/interaction/local/BondLengthInteraction.hpp>
#include <mjolnir/interaction/local/ContactInteraction.hpp>
#include <mjolnir/interaction/local/BondAngleInteraction.hpp>
#include <mjolnir/interaction/local/DihedralAngleInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/read_local_potential.hpp>
#include <memory>
namespace mjolnir
{
// ----------------------------------------------------------------------------
// individual local interaction. would be called from read_local_interaction
// defined at the bottom of this file.
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_length_interaction(const std::string& kind, const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential function is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "GoContact")
{
MJOLNIR_LOG_NOTICE("-- potential function is 10-12 Go contact.");
using potentialT = GoContactPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<BondLengthInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_bond_length_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"GoContact\": r^12 - r^10 type native contact potential",
"- \"Gaussian\" : well-known gaussian potential"
}));
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_contact_interaction(const std::string& kind, const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
real_type margin = 0.5; // default value
if(local.as_table().count("margin") == 1)
{
margin = toml::find<real_type>(local, "margin");
}
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "GoContact")
{
MJOLNIR_LOG_NOTICE("-- potential function is 10-12 Go contact.");
using potentialT = GoContactPotential<real_type>;
return make_unique<ContactInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local), margin);
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<ContactInteraction<traitsT, potentialT>>(
kind, read_local_potential<2, potentialT>(local), margin);
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_bond_length_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"GoContact\": r^12 - r^10 type native contact potential",
"- \"Gaussian\" : well-known gaussian potential"
}));
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential function is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else if(potential == "FlexibleLocalAngle")
{
MJOLNIR_LOG_NOTICE("-- potential function is Flexible Local Angle.");
using potentialT = FlexibleLocalAnglePotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<BondAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<3, potentialT>(local));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_bond_angle_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"Gaussian\" : well-known gaussian potential"
"- \"FlexibleLocalAngle\": table-based potential for C-alpha protein model",
}));
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_dihedral_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
using real_type = typename traitsT::real_type;
const auto potential = toml::find<std::string>(local, "potential");
if(potential == "Harmonic")
{
MJOLNIR_LOG_NOTICE("-- potential function is Harmonic.");
using potentialT = HarmonicPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "ClementiDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential function is Clementi-Go's dihedral.");
using potentialT = ClementiDihedralPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "Gaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is Gaussian.");
using potentialT = GaussianPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "PeriodicGaussian")
{
MJOLNIR_LOG_NOTICE("-- potential function is PeriodicGaussian.");
using potentialT = PeriodicGaussianPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
else if(potential == "FlexibleLocalDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential function is Flexible Local Dihedral.");
using potentialT = FlexibleLocalDihedralPotential<real_type>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(
kind, read_local_potential<4, potentialT>(local));
}
// XXX generalization of this feature is too difficult (technically it's
// not so difficult, but practically, it makes the code messy...).
else if(potential == "PeriodicGaussian+FlexibleLocalDihedral")
{
MJOLNIR_LOG_NOTICE("-- potential function is "
"PeriodicGaussian + FlexibleLocalDihedral.");
using potential_1_T = PeriodicGaussianPotential<real_type>;
using potential_2_T = FlexibleLocalDihedralPotential<real_type>;
using potentialT =
SumLocalPotential<real_type, potential_1_T, potential_2_T>;
return make_unique<DihedralAngleInteraction<traitsT, potentialT>>(kind,
read_local_potentials<4, real_type, potential_1_T, potential_2_T>(
local, "PeriodicGaussian", "FlexibleLocalDihedral"));
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_dihedral_angle_interaction: invalid potential",
toml::find<toml::value>(local, "potential"), "here", {
"expected value is one of the following.",
"- \"Harmonic\" : well-known harmonic potential",
"- \"Gaussian\" : well-known gaussian potential"
"- \"ClementiDihedral\" : potential used in the off-lattice Go protein model"
"- \"FlexibleLocalDihedral\": table-based potential for C-alpha protein model",
}));
}
}
// ----------------------------------------------------------------------------
// general read_local_interaction function
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_local_interaction(const toml::value& local)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto interaction = toml::find<std::string>(local, "interaction");
const auto kind = toml::find<std::string>(local, "topology");
MJOLNIR_LOG_INFO("connection kind = ", kind);
if(interaction == "BondLength")
{
MJOLNIR_LOG_NOTICE("Bond Length interaction found.");
return read_bond_length_interaction<traitsT>(kind, local);
}
else if(interaction == "Contact")
{
MJOLNIR_LOG_NOTICE("Contact interaction found.");
return read_contact_interaction<traitsT>(kind, local);
}
else if(interaction == "BondAngle")
{
MJOLNIR_LOG_NOTICE("Bond Angle interaction found.");
return read_bond_angle_interaction<traitsT>(kind, local);
}
else if(interaction == "DihedralAngle")
{
MJOLNIR_LOG_NOTICE("Dihedral Angle interaction found.");
return read_dihedral_angle_interaction<traitsT>(kind, local);
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_local_interaction: invalid interaction",
toml::find<toml::value>(local, "interaction"), "here", {
"expected value is one of the following.",
"- \"BondLength\" : 2-body well-known chemical bond interaction",
"- \"BondAngle\" : 3-body well-known bond angle interaction",
"- \"DihedralAngle\" : 4-body well-known dihedral angle interaction",
}));
}
}
} // mjolnir
#endif// MJOLNIR_READ_LOCAL_INTERACTION
|
enable to set margin for ContactInteraction
|
feat: enable to set margin for ContactInteraction
|
C++
|
mit
|
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
|
fada959b4b0271e4cc19179f3b79076506ddfaab
|
modules/dnn/src/layers/layers_common.cpp
|
modules/dnn/src/layers/layers_common.cpp
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2017, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "../precomp.hpp"
#include "layers_common.hpp"
namespace cv
{
namespace dnn
{
namespace util
{
std::string makeName(const std::string& str1, const std::string& str2)
{
return str1 + str2;
}
bool getParameter(const LayerParams ¶ms, const std::string& nameBase, const std::string& nameAll,
std::vector<size_t>& parameter, bool hasDefault = false, const std::vector<size_t>& defaultValue = std::vector<size_t>(2, 0))
{
std::string nameH = makeName(nameBase, std::string("_h"));
std::string nameW = makeName(nameBase, std::string("_w"));
std::string nameAll_ = nameAll;
if (nameAll_ == "")
nameAll_ = nameBase;
if (params.has(nameH) && params.has(nameW))
{
CV_Assert(params.get<int>(nameH) >= 0 && params.get<int>(nameW) >= 0);
parameter.push_back(params.get<int>(nameH));
parameter.push_back(params.get<int>(nameW));
return true;
}
else
{
if (params.has(nameAll_))
{
DictValue param = params.get(nameAll_);
for (int i = 0; i < param.size(); i++) {
CV_Assert(param.get<int>(i) >= 0);
parameter.push_back(param.get<int>(i));
}
if (parameter.size() == 1)
parameter.resize(2, parameter[0]);
return true;
}
else
{
if (hasDefault)
{
parameter = defaultValue;
return true;
}
else
{
return false;
}
}
}
}
void getKernelSize(const LayerParams ¶ms, std::vector<size_t>& kernel)
{
if (!util::getParameter(params, "kernel", "kernel_size", kernel))
CV_Error(cv::Error::StsBadArg, "kernel_size (or kernel_h and kernel_w) not specified");
for (int i = 0; i < kernel.size(); i++)
CV_Assert(kernel[i] > 0);
}
void getStrideAndPadding(const LayerParams ¶ms, std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end,
std::vector<size_t>& strides, cv::String& padMode, size_t kernel_size = 2)
{
if (params.has("pad_l") && params.has("pad_t") && params.has("pad_r") && params.has("pad_b")) {
CV_Assert(params.get<int>("pad_t") >= 0 && params.get<int>("pad_l") >= 0 &&
params.get<int>("pad_b") >= 0 && params.get<int>("pad_r") >= 0);
pads_begin.push_back(params.get<int>("pad_t"));
pads_begin.push_back(params.get<int>("pad_l"));
pads_end.push_back(params.get<int>("pad_b"));
pads_end.push_back(params.get<int>("pad_r"));
}
else {
util::getParameter(params, "pad", "pad", pads_begin, true, std::vector<size_t>(kernel_size, 0));
if (pads_begin.size() < 4)
pads_end = pads_begin;
else
{
pads_end = std::vector<size_t>(pads_begin.begin() + pads_begin.size() / 2, pads_begin.end());
pads_begin.resize(pads_begin.size() / 2);
}
CV_Assert(pads_begin.size() == pads_end.size());
}
util::getParameter(params, "stride", "stride", strides, true, std::vector<size_t>(kernel_size, 1));
padMode = "";
if (params.has("pad_mode"))
{
padMode = params.get<String>("pad_mode");
}
for (int i = 0; i < strides.size(); i++)
CV_Assert(strides[i] > 0);
}
}
void getPoolingKernelParams(const LayerParams ¶ms, std::vector<size_t>& kernel, std::vector<bool>& globalPooling,
std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end,
std::vector<size_t>& strides, cv::String &padMode)
{
bool is_global = params.get<bool>("global_pooling", false);
globalPooling.resize(3);
globalPooling[0] = params.get<bool>("global_pooling_d", is_global);
globalPooling[1] = params.get<bool>("global_pooling_h", is_global);
globalPooling[2] = params.get<bool>("global_pooling_w", is_global);
is_global = globalPooling[0] || globalPooling[1] || globalPooling[2];
if (!is_global)
{
util::getKernelSize(params, kernel);
util::getStrideAndPadding(params, pads_begin, pads_end, strides, padMode, kernel.size());
}
else
{
util::getStrideAndPadding(params, pads_begin, pads_end, strides, padMode);
if ((globalPooling[0] && params.has("kernel_d")) ||
(globalPooling[1] && params.has("kernel_h")) ||
(globalPooling[2] && params.has("kernel_w")) ||
params.has("kernel_size")) {
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, kernel_size (or kernel_h and kernel_w) cannot be specified");
}
kernel.resize(3);
kernel[0] = params.get<int>("kernel_d", 1);
kernel[1] = params.get<int>("kernel_h", 1);
kernel[2] = params.get<int>("kernel_w", 1);
for (int i = 0, j = globalPooling.size() - pads_begin.size(); i < pads_begin.size(); i++, j++) {
if ((pads_begin[i] != 0 || pads_end[i] != 0) && globalPooling[j])
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, pads must be = 0");
}
for (int i = 0, j = globalPooling.size() - strides.size(); i < strides.size(); i++, j++) {
if (strides[i] != 1 && globalPooling[j])
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, strides must be = 1");
}
}
}
void getConvolutionKernelParams(const LayerParams ¶ms, std::vector<size_t>& kernel, std::vector<size_t>& pads_begin,
std::vector<size_t>& pads_end, std::vector<size_t>& strides,
std::vector<size_t>& dilations, cv::String &padMode, std::vector<size_t>& adjust_pads)
{
util::getKernelSize(params, kernel);
util::getStrideAndPadding(params, pads_begin, pads_end, strides, padMode, kernel.size());
util::getParameter(params, "dilation", "dilation", dilations, true, std::vector<size_t>(kernel.size(), 1));
util::getParameter(params, "adj", "adj", adjust_pads, true, std::vector<size_t>(kernel.size(), 0));
for (int i = 0; i < dilations.size(); i++)
CV_Assert(dilations[i] > 0);
}
// From TensorFlow code:
// Total padding on rows and cols is
// Pr = (R' - 1) * S + Kr - R
// Pc = (C' - 1) * S + Kc - C
// where (R', C') are output dimensions, (R, C) are input dimensions, S
// is stride, (Kr, Kc) are filter dimensions.
// We pad Pr/2 on the left and Pr - Pr/2 on the right, Pc/2 on the top
// and Pc - Pc/2 on the bottom. When Pr or Pc is odd, this means
// we pad more on the right and bottom than on the top and left.
void getConvPoolOutParams(const std::vector<int>& inp, const std::vector<size_t>& kernel,
const std::vector<size_t>& stride, const String &padMode,
const std::vector<size_t>& dilation, std::vector<int>& out)
{
if (padMode == "VALID")
{
for (int i = 0; i < inp.size(); i++)
out.push_back((inp[i] - dilation[i] * (kernel[i] - 1) - 1 + stride[i]) / stride[i]);
}
else if (padMode == "SAME")
{
for (int i = 0; i < inp.size(); i++)
out.push_back((inp[i] - 1 + stride[i]) / stride[i]);
}
else
{
CV_Error(Error::StsError, "Unsupported padding mode");
}
}
void getConvPoolPaddings(const std::vector<int>& inp, const std::vector<size_t>& kernel,
const std::vector<size_t>& strides, const String &padMode,
std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end)
{
if (padMode == "SAME" || padMode == "VALID")
{
pads_begin.assign(kernel.size(), 0);
pads_end.assign(kernel.size(), 0);
}
if (padMode == "SAME")
{
CV_Assert_N(kernel.size() == strides.size(), kernel.size() == inp.size());
for (int i = 0; i < pads_begin.size(); i++) {
// There are test cases with stride > kernel.
if (strides[i] <= kernel[i])
{
int pad = (kernel[i] - 1 - (inp[i] - 1 + strides[i]) % strides[i]) / 2;
pads_begin[i] = pads_end[i] = pad;
}
}
}
}
}
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2017, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "../precomp.hpp"
#include "layers_common.hpp"
namespace cv
{
namespace dnn
{
namespace util
{
std::string makeName(const std::string& str1, const std::string& str2)
{
return str1 + str2;
}
bool getParameter(const LayerParams ¶ms, const std::string& nameBase, const std::string& nameAll,
std::vector<size_t>& parameter, bool hasDefault = false, const std::vector<size_t>& defaultValue = std::vector<size_t>(2, 0))
{
std::string nameH = makeName(nameBase, std::string("_h"));
std::string nameW = makeName(nameBase, std::string("_w"));
std::string nameAll_ = nameAll;
if (nameAll_ == "")
nameAll_ = nameBase;
if (params.has(nameH) && params.has(nameW))
{
CV_Assert(params.get<int>(nameH) >= 0 && params.get<int>(nameW) >= 0);
parameter.push_back(params.get<int>(nameH));
parameter.push_back(params.get<int>(nameW));
return true;
}
else
{
if (params.has(nameAll_))
{
DictValue param = params.get(nameAll_);
for (int i = 0; i < param.size(); i++) {
CV_Assert(param.get<int>(i) >= 0);
parameter.push_back(param.get<int>(i));
}
if (parameter.size() == 1)
parameter.resize(2, parameter[0]);
return true;
}
else
{
if (hasDefault)
{
parameter = defaultValue;
return true;
}
else
{
return false;
}
}
}
}
void getKernelSize(const LayerParams ¶ms, std::vector<size_t>& kernel)
{
if (!util::getParameter(params, "kernel", "kernel_size", kernel))
CV_Error(cv::Error::StsBadArg, "kernel_size (or kernel_h and kernel_w) not specified");
for (int i = 0; i < kernel.size(); i++)
CV_Assert(kernel[i] > 0);
}
void getStrideAndPadding(const LayerParams ¶ms, std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end,
std::vector<size_t>& strides, cv::String& padMode, size_t kernel_size = 2)
{
if (params.has("pad_l") && params.has("pad_t") && params.has("pad_r") && params.has("pad_b")) {
CV_Assert(params.get<int>("pad_t") >= 0 && params.get<int>("pad_l") >= 0 &&
params.get<int>("pad_b") >= 0 && params.get<int>("pad_r") >= 0);
pads_begin.push_back(params.get<int>("pad_t"));
pads_begin.push_back(params.get<int>("pad_l"));
pads_end.push_back(params.get<int>("pad_b"));
pads_end.push_back(params.get<int>("pad_r"));
}
else {
util::getParameter(params, "pad", "pad", pads_begin, true, std::vector<size_t>(kernel_size, 0));
if (pads_begin.size() < 4)
pads_end = pads_begin;
else
{
pads_end = std::vector<size_t>(pads_begin.begin() + pads_begin.size() / 2, pads_begin.end());
pads_begin.resize(pads_begin.size() / 2);
}
CV_Assert(pads_begin.size() == pads_end.size());
}
util::getParameter(params, "stride", "stride", strides, true, std::vector<size_t>(kernel_size, 1));
padMode = "";
if (params.has("pad_mode"))
{
padMode = params.get<String>("pad_mode");
}
for (int i = 0; i < strides.size(); i++)
CV_Assert(strides[i] > 0);
}
}
void getPoolingKernelParams(const LayerParams ¶ms, std::vector<size_t>& kernel, std::vector<bool>& globalPooling,
std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end,
std::vector<size_t>& strides, cv::String &padMode)
{
bool is_global = params.get<bool>("global_pooling", false);
globalPooling.resize(3);
globalPooling[0] = params.get<bool>("global_pooling_d", is_global);
globalPooling[1] = params.get<bool>("global_pooling_h", is_global);
globalPooling[2] = params.get<bool>("global_pooling_w", is_global);
is_global = globalPooling[0] || globalPooling[1] || globalPooling[2];
if (is_global)
{
util::getStrideAndPadding(params, pads_begin, pads_end, strides, padMode);
if ((globalPooling[0] && params.has("kernel_d")) ||
(globalPooling[1] && params.has("kernel_h")) ||
(globalPooling[2] && params.has("kernel_w")) ||
params.has("kernel_size")) {
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, kernel_size (or kernel_h and kernel_w) cannot be specified");
}
kernel.resize(3);
kernel[0] = params.get<int>("kernel_d", 1);
kernel[1] = params.get<int>("kernel_h", 1);
kernel[2] = params.get<int>("kernel_w", 1);
for (int i = 0, j = globalPooling.size() - pads_begin.size(); i < pads_begin.size(); i++, j++) {
if ((pads_begin[i] != 0 || pads_end[i] != 0) && globalPooling[j])
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, pads must be = 0");
}
for (int i = 0, j = globalPooling.size() - strides.size(); i < strides.size(); i++, j++) {
if (strides[i] != 1 && globalPooling[j])
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, strides must be = 1");
}
}
else
{
util::getKernelSize(params, kernel);
util::getStrideAndPadding(params, pads_begin, pads_end, strides, padMode, kernel.size());
}
}
void getConvolutionKernelParams(const LayerParams ¶ms, std::vector<size_t>& kernel, std::vector<size_t>& pads_begin,
std::vector<size_t>& pads_end, std::vector<size_t>& strides,
std::vector<size_t>& dilations, cv::String &padMode, std::vector<size_t>& adjust_pads)
{
util::getKernelSize(params, kernel);
util::getStrideAndPadding(params, pads_begin, pads_end, strides, padMode, kernel.size());
util::getParameter(params, "dilation", "dilation", dilations, true, std::vector<size_t>(kernel.size(), 1));
util::getParameter(params, "adj", "adj", adjust_pads, true, std::vector<size_t>(kernel.size(), 0));
for (int i = 0; i < dilations.size(); i++)
CV_Assert(dilations[i] > 0);
}
// From TensorFlow code:
// Total padding on rows and cols is
// Pr = (R' - 1) * S + Kr - R
// Pc = (C' - 1) * S + Kc - C
// where (R', C') are output dimensions, (R, C) are input dimensions, S
// is stride, (Kr, Kc) are filter dimensions.
// We pad Pr/2 on the left and Pr - Pr/2 on the right, Pc/2 on the top
// and Pc - Pc/2 on the bottom. When Pr or Pc is odd, this means
// we pad more on the right and bottom than on the top and left.
void getConvPoolOutParams(const std::vector<int>& inp, const std::vector<size_t>& kernel,
const std::vector<size_t>& stride, const String &padMode,
const std::vector<size_t>& dilation, std::vector<int>& out)
{
if (padMode == "VALID")
{
for (int i = 0; i < inp.size(); i++)
out.push_back((inp[i] - dilation[i] * (kernel[i] - 1) - 1 + stride[i]) / stride[i]);
}
else if (padMode == "SAME")
{
for (int i = 0; i < inp.size(); i++)
out.push_back((inp[i] - 1 + stride[i]) / stride[i]);
}
else
{
CV_Error(Error::StsError, "Unsupported padding mode");
}
}
void getConvPoolPaddings(const std::vector<int>& inp, const std::vector<size_t>& kernel,
const std::vector<size_t>& strides, const String &padMode,
std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end)
{
if (padMode == "SAME" || padMode == "VALID")
{
pads_begin.assign(kernel.size(), 0);
pads_end.assign(kernel.size(), 0);
}
if (padMode == "SAME")
{
CV_Assert_N(kernel.size() == strides.size(), kernel.size() == inp.size());
for (int i = 0; i < pads_begin.size(); i++) {
// There are test cases with stride > kernel.
if (strides[i] <= kernel[i])
{
int pad = (kernel[i] - 1 - (inp[i] - 1 + strides[i]) % strides[i]) / 2;
pads_begin[i] = pads_end[i] = pad;
}
}
}
}
}
}
|
Fix comment
|
Fix comment
|
C++
|
apache-2.0
|
opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv
|
fa49f5f505b432c3b015778bc8fdd50c776b0bbb
|
modules/map/tools/proto_map_generator.cc
|
modules/map/tools/proto_map_generator.cc
|
/* Copyright 2017 The Apollo Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <string>
#include "gflags/gflags.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/map/hdmap/adapter/opendrive_adapter.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/map/proto/map.pb.h"
/**
* A map tool to transform opendrive map to pb map
*/
DEFINE_string(output_dir, "/tmp/", "output map directory");
int main(int argc, char **argv) {
google::InitGoogleLogging(argv[0]);
FLAGS_alsologtostderr = true;
google::ParseCommandLineFlags(&argc, &argv, true);
const auto map_filename = apollo::hdmap::BaseMapFile();
apollo::hdmap::Map pb_map;
CHECK(apollo::hdmap::adapter::OpendriveAdapter::LoadData(
map_filename, &pb_map)) << "fail to load data";
const std::string output_ascii_file = FLAGS_output_dir + "/base_map.txt";
CHECK(apollo::common::util::SetProtoToASCIIFile(pb_map, output_ascii_file));
const std::string output_bin_file = FLAGS_output_dir + "/base_map.bin";
CHECK(apollo::common::util::SetProtoToBinaryFile(pb_map, output_bin_file));
pb_map.Clear();
CHECK(apollo::common::util::GetProtoFromFile(output_bin_file, &pb_map))
<< "load map fail";
AINFO << "load map success";
return 0;
}
|
/* Copyright 2017 The Apollo Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <string>
#include "gflags/gflags.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/map/hdmap/adapter/opendrive_adapter.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/map/proto/map.pb.h"
/**
* A map tool to transform opendrive map to pb map
*/
DEFINE_string(output_dir, "/tmp/", "output map directory");
int main(int argc, char **argv) {
google::InitGoogleLogging(argv[0]);
FLAGS_alsologtostderr = true;
google::ParseCommandLineFlags(&argc, &argv, true);
const auto map_filename = FLAGS_map_dir + "/base_map.xml";;
apollo::hdmap::Map pb_map;
CHECK(apollo::hdmap::adapter::OpendriveAdapter::LoadData(
map_filename, &pb_map)) << "fail to load data";
const std::string output_ascii_file = FLAGS_output_dir + "/base_map.txt";
CHECK(apollo::common::util::SetProtoToASCIIFile(pb_map, output_ascii_file));
const std::string output_bin_file = FLAGS_output_dir + "/base_map.bin";
CHECK(apollo::common::util::SetProtoToBinaryFile(pb_map, output_bin_file));
pb_map.Clear();
CHECK(apollo::common::util::GetProtoFromFile(output_bin_file, &pb_map))
<< "load map fail";
AINFO << "load map success";
return 0;
}
|
fix proto map generator bug (#1814)
|
fix proto map generator bug (#1814)
|
C++
|
apache-2.0
|
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
|
3c0c482442659042e7f3ef0c753cbf21df2ef02d
|
plugins/robots/interpreters/trikKitInterpreterCommon/src/robotModel/twoD/parts/twoDLineSensor.cpp
|
plugins/robots/interpreters/trikKitInterpreterCommon/src/robotModel/twoD/parts/twoDLineSensor.cpp
|
/* Copyright 2007-2015 QReal Research Group
*
* 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 "trikKitInterpreterCommon/robotModel/twoD/parts/twoDLineSensor.h"
#include <QtGui/QImage>
using namespace trik::robotModel::twoD::parts;
using namespace kitBase::robotModel;
// The color of the pixel
const int tolerance = 10;
LineSensor::LineSensor(const DeviceInfo &info, const PortInfo &port
, twoDModel::engine::TwoDModelEngineInterface &engine)
: robotModel::parts::TrikLineSensor(info, port)
, mEngine(engine)
, mLineColor(qRgb(0, 0, 0)) // default line color is black
{
}
void LineSensor::init()
{
}
void LineSensor::detectLine()
{
const QImage image = mEngine.areaUnderSensor(port(), 0.2);
int size = 0;
int red = 0;
int green = 0;
int blue = 0;
for (int x = 0; x < image.width(); ++x) {
for (int y = 0; y < image.height(); ++y) {
const QRgb pixelColor = image.pixel(x, y);
if (qAlpha(pixelColor) > 0) {
++size;
red += qRed(pixelColor);
green += qGreen(pixelColor);
blue += qBlue(pixelColor);
}
}
}
mLineColor = qRgb(red / size, green / size, blue / size);
}
void LineSensor::read()
{
const QImage image = mEngine.areaUnderSensor(port(), 2.0);
if (image.isNull()) {
return;
}
const int height = image.height();
const int width = image.width();
int blacks = 0;
int crossBlacks = 0;
int usefulRows = 0;
int horizontalLineWidth = image.height() * 0.2;
qreal xCoordinates = 0;
for (int i = 0; i < height; ++i) {
int blacksInRow = 0;
qreal xSum = 0;
for (int j = 0; j < width; ++j) {
if (closeEnough(image.pixel(j, i))) {
++blacksInRow;
xSum += j - width / 2.0;
}
}
xCoordinates += (blacksInRow ? xSum * 100 / (width / 2.0) / blacksInRow : 0);
blacks += blacksInRow;
usefulRows += blacksInRow ? 1 : 0;
if (((height - horizontalLineWidth) / 2 < i) && (i < (height + horizontalLineWidth) / 2)) {
crossBlacks += blacksInRow;
}
}
const int x = qRound(xCoordinates / usefulRows);
const int lineWidth = blacks / height;
const int cross = qRound(crossBlacks * 100.0 / (height * horizontalLineWidth));
emit newData({ x, lineWidth, cross });
}
bool LineSensor::closeEnough(QRgb color) const
{
return qAlpha(color) > 0 && qMax(qAbs(qRed(color) - qRed(mLineColor))
, qMax(qAbs(qGreen(color) - qGreen(mLineColor))
, qAbs(qBlue(color) - qBlue(mLineColor)))) < tolerance;
}
|
/* Copyright 2007-2015 QReal Research Group
*
* 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 "trikKitInterpreterCommon/robotModel/twoD/parts/twoDLineSensor.h"
#include <QtGui/QImage>
using namespace trik::robotModel::twoD::parts;
using namespace kitBase::robotModel;
// The color of the pixel
const int tolerance = 10;
LineSensor::LineSensor(const DeviceInfo &info, const PortInfo &port
, twoDModel::engine::TwoDModelEngineInterface &engine)
: robotModel::parts::TrikLineSensor(info, port)
, mEngine(engine)
, mLineColor(qRgb(0, 0, 0)) // default line color is black
{
}
void LineSensor::init()
{
}
void LineSensor::detectLine()
{
const QImage image = mEngine.areaUnderSensor(port(), 0.2);
int size = 0;
int red = 0;
int green = 0;
int blue = 0;
for (int x = 0; x < image.width(); ++x) {
for (int y = 0; y < image.height(); ++y) {
const QRgb pixelColor = image.pixel(x, y);
if (qAlpha(pixelColor) > 0) {
++size;
red += qRed(pixelColor);
green += qGreen(pixelColor);
blue += qBlue(pixelColor);
}
}
}
mLineColor = qRgb(red / size, green / size, blue / size);
}
void LineSensor::read()
{
const QImage image = mEngine.areaUnderSensor(port(), 2.0);
if (image.isNull()) {
return;
}
const int height = image.height();
const int width = image.width();
int blacks = 0;
int crossBlacks = 0;
int usefulRows = 0;
int horizontalLineWidth = image.height() * 0.2;
qreal xCoordinates = 0;
for (int i = 0; i < height; ++i) {
int blacksInRow = 0;
qreal xSum = 0;
for (int j = 0; j < width; ++j) {
if (closeEnough(image.pixel(j, i))) {
++blacksInRow;
xSum += j - width / 2.0;
}
}
xCoordinates += (blacksInRow ? xSum * 100 / (width / 2.0) / blacksInRow : 0);
blacks += blacksInRow;
usefulRows += blacksInRow ? 1 : 0;
if (((height - horizontalLineWidth) / 2 < i) && (i < (height + horizontalLineWidth) / 2)) {
crossBlacks += blacksInRow;
}
}
const int x = qRound(xCoordinates / usefulRows);
const int cross = qRound(crossBlacks * 100.0 / (height * horizontalLineWidth));
const int lineWidth = blacks / height;
emit newData({ x, cross, lineWidth });
}
bool LineSensor::closeEnough(QRgb color) const
{
return qAlpha(color) > 0 && qMax(qAbs(qRed(color) - qRed(mLineColor))
, qMax(qAbs(qGreen(color) - qGreen(mLineColor))
, qAbs(qBlue(color) - qBlue(mLineColor)))) < tolerance;
}
|
fix correspondence between linesensors
|
fix correspondence between linesensors
|
C++
|
apache-2.0
|
qreal/qreal,qreal/qreal,qreal/qreal,qreal/qreal,qreal/qreal,qreal/qreal,qreal/qreal,qreal/qreal,qreal/qreal
|
ccc706559f2b5be9d60edc7806ac6d5107ac0f69
|
idl/partition_checksum.idl.hh
|
idl/partition_checksum.idl.hh
|
/*
* Copyright 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
enum class repair_checksum : uint8_t {
legacy = 0,
streamed = 1,
};
class partition_checksum {
std::array<uint8_t, 32> digest();
};
class repair_hash {
uint64_t hash;
};
enum class bound_weight : int8_t {
before_all_prefixed = -1,
equal = 0,
after_all_prefixed = 1,
};
enum class partition_region : uint8_t {
partition_start,
static_row,
clustered,
partition_end,
};
class position_in_partition {
partition_region get_type();
bound_weight get_bound_weight();
std::optional<clustering_key_prefix> get_clustering_key_prefix();
};
struct partition_key_and_mutation_fragments {
partition_key get_key();
std::list<frozen_mutation_fragment> get_mutation_fragments();
};
class repair_sync_boundary {
dht::decorated_key pk;
position_in_partition position;
};
|
/*
* Copyright 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
enum class repair_checksum : uint8_t {
legacy = 0,
streamed = 1,
};
class partition_checksum {
std::array<uint8_t, 32> digest();
};
class repair_hash {
uint64_t hash;
};
enum class bound_weight : int8_t {
before_all_prefixed = -1,
equal = 0,
after_all_prefixed = 1,
};
enum class partition_region : uint8_t {
partition_start,
static_row,
clustered,
partition_end,
};
class position_in_partition {
partition_region get_type();
bound_weight get_bound_weight();
std::optional<clustering_key_prefix> get_clustering_key_prefix();
};
struct partition_key_and_mutation_fragments {
partition_key get_key();
std::list<frozen_mutation_fragment> get_mutation_fragments();
};
class repair_sync_boundary {
dht::decorated_key pk;
position_in_partition position;
};
struct get_sync_boundary_response {
std::optional<repair_sync_boundary> boundary;
repair_hash row_buf_combined_csum;
uint64_t row_buf_size;
uint64_t new_rows_size;
uint64_t new_rows_nr;
};
|
Add get_sync_boundary_response
|
idl: Add get_sync_boundary_response
Needed by the row level repair RPC verbs.
|
C++
|
agpl-3.0
|
scylladb/scylla,scylladb/scylla,avikivity/scylla,scylladb/scylla,scylladb/scylla,avikivity/scylla,avikivity/scylla
|
a28fbebcee64c6a3db56c385385e3eb586bc2438
|
libpolyml/rtsentry.cpp
|
libpolyml/rtsentry.cpp
|
/*
Title: rtsentry.cpp - Entry points to the run-time system
Copyright (c) 2016, 2017 David C. J. Matthews
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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "rtsentry.h"
#include "save_vec.h"
#include "processes.h"
#include "run_time.h"
#include "polystring.h"
#include "arb.h"
#include "basicio.h"
#include "polyffi.h"
#include "xwindows.h"
#include "os_specific.h"
#include "timing.h"
#include "sighandler.h"
#include "sharedata.h"
#include "run_time.h"
#include "reals.h"
#include "profiling.h"
#include "processes.h"
#include "process_env.h"
#include "poly_specific.h"
#include "objsize.h"
#include "network.h"
#include "machine_dep.h"
#include "exporter.h"
#include "statistics.h"
#include "savestate.h"
#include "bytecode.h"
extern struct _entrypts rtsCallEPT[];
static entrypts entryPointTable[] =
{
rtsCallEPT,
arbitraryPrecisionEPT,
basicIOEPT,
polyFFIEPT,
xwindowsEPT,
osSpecificEPT,
timingEPT,
sigHandlerEPT,
shareDataEPT,
runTimeEPT,
realsEPT,
profilingEPT,
processesEPT,
processEnvEPT,
polySpecificEPT,
objSizeEPT,
networkingEPT,
exporterEPT,
statisticsEPT,
savestateEPT,
machineSpecificEPT,
byteCodeEPT,
NULL
};
extern "C" {
#ifdef _MSC_VER
__declspec(dllexport)
#endif
POLYUNSIGNED PolyCreateEntryPointObject(FirstArgument threadId, PolyWord arg);
};
// Create an entry point containing the address of the entry and the
// string name. Having the string in there allows us to export the entry.
Handle creatEntryPointObject(TaskData *taskData, Handle entryH, bool isFuncPtr)
{
TempCString entryName(Poly_string_to_C_alloc(entryH->Word()));
if ((const char *)entryName == 0) raise_syscall(taskData, "Insufficient memory", ENOMEM);
// Create space for the address followed by the name as a C string.
uintptr_t space = 1 + (strlen(entryName) + 1 + (isFuncPtr ? 0 : 1) + sizeof(polyRTSFunction*) - 1) / sizeof(PolyWord);
// Allocate a byte, weak, mutable, no-overwrite cell. It's not clear if
// it actually needs to be mutable but if it is it needs to be no-overwrite.
Handle refH = alloc_and_save(taskData, space, F_BYTE_OBJ|F_WEAK_BIT|F_MUTABLE_BIT|F_NO_OVERWRITE);
PolyObject *p = refH->WordP();
*(polyRTSFunction*)p = 0; // Clear it
char *entryPtr = (char*)(p->AsBytePtr() + sizeof(polyRTSFunction*));
if (! isFuncPtr) *entryPtr++ = 1; // Put in a type entry
strcpy(entryPtr, entryName);
return refH;
}
// Return the string entry point.
const char *getEntryPointName(PolyObject *p, bool *isFuncPtr)
{
if (p->Length() <= sizeof(polyRTSFunction*)/sizeof(PolyWord)) return 0; // Doesn't contain an entry point
const char *entryPtr = (const char*)(p->AsBytePtr() + sizeof(polyRTSFunction*));
*isFuncPtr = *entryPtr != 1; // If the type is 1 it is a data entry point
if (*entryPtr < ' ') entryPtr++; // Skip the type byte
return entryPtr;
}
// Sets the address of the entry point in an entry point object.
bool setEntryPoint(PolyObject *p)
{
if (p->Length() == 0) return false;
*(polyRTSFunction*)p = 0; // Clear it by default
if (p->Length() == 1) return false;
const char *entryName = (const char*)(p->AsBytePtr()+sizeof(polyRTSFunction*));
if (*entryName < ' ') entryName++; // Skip the type byte
// Search the entry point table list.
for (entrypts *ept=entryPointTable; *ept != NULL; ept++)
{
entrypts entryPtTable = *ept;
if (entryPtTable != 0)
{
for (struct _entrypts *ep = entryPtTable; ep->entry != NULL; ep++)
{
if (strcmp(entryName, ep->name) == 0)
{
polyRTSFunction entry = ep->entry;
*(polyRTSFunction*)p = entry;
return true;
}
}
}
}
return false;
}
// External call
POLYUNSIGNED PolyCreateEntryPointObject(FirstArgument threadId, PolyWord arg)
{
TaskData *taskData = TaskData::FindTaskForId(threadId);
ASSERT(taskData != 0);
taskData->PreRTSCall();
Handle reset = taskData->saveVec.mark();
Handle pushedArg = taskData->saveVec.push(arg);
Handle result = 0;
try {
result = creatEntryPointObject(taskData, pushedArg, true /* Always functions */);
if (!setEntryPoint(result->WordP()))
raise_fail(taskData, "entry point not found");
} catch (...) { } // If an ML exception is raised
taskData->saveVec.reset(reset); // Ensure the save vec is reset
taskData->PostRTSCall();
if (result == 0) return TAGGED(0).AsUnsigned();
else return result->Word().AsUnsigned();
}
struct _entrypts rtsCallEPT[] =
{
{ "PolyCreateEntryPointObject", (polyRTSFunction)&PolyCreateEntryPointObject},
{ NULL, NULL} // End of list.
};
|
/*
Title: rtsentry.cpp - Entry points to the run-time system
Copyright (c) 2016, 2017 David C. J. Matthews
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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "rtsentry.h"
#include "save_vec.h"
#include "processes.h"
#include "run_time.h"
#include "polystring.h"
#include "arb.h"
#include "basicio.h"
#include "polyffi.h"
#include "xwindows.h"
#include "os_specific.h"
#include "timing.h"
#include "sighandler.h"
#include "sharedata.h"
#include "run_time.h"
#include "reals.h"
#include "profiling.h"
#include "processes.h"
#include "process_env.h"
#include "poly_specific.h"
#include "objsize.h"
#include "network.h"
#include "machine_dep.h"
#include "exporter.h"
#include "statistics.h"
#include "savestate.h"
#include "bytecode.h"
extern struct _entrypts rtsCallEPT[];
static entrypts entryPointTable[] =
{
rtsCallEPT,
arbitraryPrecisionEPT,
basicIOEPT,
polyFFIEPT,
xwindowsEPT,
osSpecificEPT,
timingEPT,
sigHandlerEPT,
shareDataEPT,
runTimeEPT,
realsEPT,
profilingEPT,
processesEPT,
processEnvEPT,
polySpecificEPT,
objSizeEPT,
networkingEPT,
exporterEPT,
statisticsEPT,
savestateEPT,
machineSpecificEPT,
byteCodeEPT,
NULL
};
extern "C" {
#ifdef _MSC_VER
__declspec(dllexport)
#endif
POLYUNSIGNED PolyCreateEntryPointObject(FirstArgument threadId, PolyWord arg);
};
// Create an entry point containing the address of the entry and the
// string name. Having the string in there allows us to export the entry.
Handle creatEntryPointObject(TaskData *taskData, Handle entryH, bool isFuncPtr)
{
TempCString entryName(Poly_string_to_C_alloc(entryH->Word()));
if ((const char *)entryName == 0) raise_syscall(taskData, "Insufficient memory", ENOMEM);
// Create space for the address followed by the name as a C string.
uintptr_t space = 1 + (strlen(entryName) + 1 + (isFuncPtr ? 0 : 1) + sizeof(polyRTSFunction*) - 1) / sizeof(PolyWord);
// Allocate a byte, weak, mutable, no-overwrite cell. It's not clear if
// it actually needs to be mutable but if it is it needs to be no-overwrite.
Handle refH = alloc_and_save(taskData, space, F_BYTE_OBJ|F_WEAK_BIT|F_MUTABLE_BIT|F_NO_OVERWRITE);
PolyObject *p = refH->WordP();
*(polyRTSFunction*)p = 0; // Clear it
char *entryPtr = (char*)(p->AsBytePtr() + sizeof(polyRTSFunction*));
if (! isFuncPtr) *entryPtr++ = 1; // Put in a type entry
strcpy(entryPtr, entryName);
return refH;
}
// Return the string entry point.
const char *getEntryPointName(PolyObject *p, bool *isFuncPtr)
{
if (p->Length() <= sizeof(polyRTSFunction*)/sizeof(PolyWord)) return 0; // Doesn't contain an entry point
const char *entryPtr = (const char*)(p->AsBytePtr() + sizeof(polyRTSFunction*));
*isFuncPtr = *entryPtr != 1; // If the type is 1 it is a data entry point
if (*entryPtr < ' ') entryPtr++; // Skip the type byte
return entryPtr;
}
// Sets the address of the entry point in an entry point object.
bool setEntryPoint(PolyObject *p)
{
if (p->Length() == 0) return false;
*(polyRTSFunction*)p = 0; // Clear it by default
if (p->Length() == 1) return false;
const char *entryName = (const char*)(p->AsBytePtr()+sizeof(polyRTSFunction*));
if (*entryName < ' ') entryName++; // Skip the type byte
// Search the entry point table list.
for (entrypts *ept=entryPointTable; *ept != NULL; ept++)
{
entrypts entryPtTable = *ept;
if (entryPtTable != 0)
{
for (struct _entrypts *ep = entryPtTable; ep->entry != NULL; ep++)
{
if (strcmp(entryName, ep->name) == 0)
{
polyRTSFunction entry = ep->entry;
*(polyRTSFunction*)p = entry;
return true;
}
}
}
}
return false;
}
// External call
POLYUNSIGNED PolyCreateEntryPointObject(FirstArgument threadId, PolyWord arg)
{
TaskData *taskData = TaskData::FindTaskForId(threadId);
ASSERT(taskData != 0);
taskData->PreRTSCall();
Handle reset = taskData->saveVec.mark();
Handle pushedArg = taskData->saveVec.push(arg);
Handle result = 0;
try {
result = creatEntryPointObject(taskData, pushedArg, true /* Always functions */);
if (!setEntryPoint(result->WordP()))
{
// Include the name of the symbol. It's often helpful.
char buff[100];
strncpy(buff, "entry point not found: ", sizeof(buff) - 1);
size_t length = strlen(buff);
Poly_string_to_C(pushedArg->Word(), buff+ length, sizeof(buff) - length-1);
raise_fail(taskData, buff);
}
} catch (...) { } // If an ML exception is raised
taskData->saveVec.reset(reset); // Ensure the save vec is reset
taskData->PostRTSCall();
if (result == 0) return TAGGED(0).AsUnsigned();
else return result->Word().AsUnsigned();
}
struct _entrypts rtsCallEPT[] =
{
{ "PolyCreateEntryPointObject", (polyRTSFunction)&PolyCreateEntryPointObject},
{ NULL, NULL} // End of list.
};
|
Add the name of the entry point to the Fail exception packet.
|
Add the name of the entry point to the Fail exception packet.
|
C++
|
lgpl-2.1
|
dcjm/polyml,polyml/polyml,dcjm/polyml,polyml/polyml,polyml/polyml,dcjm/polyml,dcjm/polyml,polyml/polyml
|
16bcfd38fb409af170fb1190b7d837e87b138b7e
|
c/src/utils/XSECSOAPRequestorSimple.cpp
|
c/src/utils/XSECSOAPRequestorSimple.cpp
|
/*
* Copyright 2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* imitations under the License.
*/
/*
* XSEC
*
* XSECSOAPRequestorSimple := (Very) Basic implementation of a SOAP
* HTTP wrapper for testing the client code.
*
*
* $Id$
*
*/
#include "XSECSOAPRequestorSimple.hpp"
#include <xsec/framework/XSECError.hpp>
#include <xsec/utils/XSECSafeBuffer.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
#include <xsec/xkms/XKMSConstants.hpp>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLNetAccessor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLExceptMsgs.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
XERCES_CPP_NAMESPACE_USE
// --------------------------------------------------------------------------------
// Strings for constructing SOAP envelopes
// --------------------------------------------------------------------------------
static XMLCh s_prefix[] = {
chLatin_e,
chLatin_n,
chLatin_v,
chNull
};
static XMLCh s_Envelope[] = {
chLatin_E,
chLatin_n,
chLatin_v,
chLatin_e,
chLatin_l,
chLatin_o,
chLatin_p,
chLatin_e,
chNull
};
static XMLCh s_Body[] = {
chLatin_B,
chLatin_o,
chLatin_d,
chLatin_y,
chNull
};
// --------------------------------------------------------------------------------
// Constructors and Destructors
// --------------------------------------------------------------------------------
/* NOTE: This is initialised via the platform specific code */
XSECSOAPRequestorSimple::~XSECSOAPRequestorSimple() {
}
// --------------------------------------------------------------------------------
// Wrap and serialise the request message
// --------------------------------------------------------------------------------
char * XSECSOAPRequestorSimple::wrapAndSerialise(DOMDocument * request) {
// Create a new document to wrap the request in
XMLCh tempStr[100];
XMLString::transcode("Core", tempStr, 99);
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
safeBuffer str;
makeQName(str, s_prefix, s_Envelope);
DOMDocument *doc = impl->createDocument(
XKMSConstants::s_unicodeStrURISOAP11,
str.rawXMLChBuffer(),
NULL);// DOMDocumentType()); // document type object (DTD).
DOMElement *rootElem = doc->getDocumentElement();
makeQName(str, s_prefix, s_Body);
DOMElement *body = doc->createElementNS(
XKMSConstants::s_unicodeStrURISOAP11,
str.rawXMLChBuffer());
rootElem->appendChild(body);
// Now replicate the request into the document
DOMElement * reqElement = (DOMElement *) doc->importNode(request->getDocumentElement(), true);
body->appendChild(reqElement);
// OK - Now we have the SOAP request as a document, we serialise to a string buffer
// and return
DOMWriter *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
theSerializer->setEncoding(MAKE_UNICODE_STRING("UTF-8"));
if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false))
theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false);
MemBufFormatTarget *formatTarget = new MemBufFormatTarget;
theSerializer->writeNode(formatTarget, *doc);
// Now replicate the buffer
char * ret = XMLString::replicate((const char *) formatTarget->getRawBuffer());
delete theSerializer;
delete formatTarget;
doc->release();
return ret;
}
// --------------------------------------------------------------------------------
// UnWrap and de-serialise the response message
// --------------------------------------------------------------------------------
DOMDocument * XSECSOAPRequestorSimple::parseAndUnwrap(const char * buf, unsigned int len) {
XercesDOMParser * parser = new XercesDOMParser;
Janitor<XercesDOMParser> j_parser(parser);
parser->setDoNamespaces(true);
parser->setCreateEntityReferenceNodes(true);
parser->setDoSchema(true);
// Create an input source
MemBufInputSource* memIS = new MemBufInputSource ((const XMLByte*) buf, len, "XSECMem");
Janitor<MemBufInputSource> j_memIS(memIS);
int errorCount = 0;
parser->parse(*memIS);
errorCount = parser->getErrorCount();
if (errorCount > 0)
throw XSECException(XSECException::HTTPURIInputStreamError,
"Error parsing SOAP response message");
DOMDocument * responseDoc = parser->getDocument();
// Now create a new document for the Response message
XMLCh tempStr[100];
XMLString::transcode("Core", tempStr, 99);
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
DOMDocument * retDoc = impl->createDocument();
// Find the base of the response
DOMNode * e = responseDoc->getDocumentElement();
e = e->getFirstChild();
while (e != NULL && (e->getNodeType() != DOMNode::ELEMENT_NODE || !strEquals(e->getLocalName(), "Body")))
e = e->getNextSibling();
if (e == NULL)
throw XSECException(XSECException::HTTPURIInputStreamError,
"Could not find SOAP body");
e = findFirstChildOfType(e, DOMNode::ELEMENT_NODE);
if (e == NULL)
throw XSECException(XSECException::HTTPURIInputStreamError,
"Could not find message within SOAP body");
retDoc->appendChild(retDoc->importNode(e, true));
return retDoc;
}
|
/*
* Copyright 2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* imitations under the License.
*/
/*
* XSEC
*
* XSECSOAPRequestorSimple := (Very) Basic implementation of a SOAP
* HTTP wrapper for testing the client code.
*
*
* $Id$
*
*/
#include "XSECSOAPRequestorSimple.hpp"
#include <xsec/framework/XSECError.hpp>
#include <xsec/utils/XSECSafeBuffer.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
#include <xsec/xkms/XKMSConstants.hpp>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLNetAccessor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLExceptMsgs.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
XERCES_CPP_NAMESPACE_USE
// --------------------------------------------------------------------------------
// Strings for constructing SOAP envelopes
// --------------------------------------------------------------------------------
static XMLCh s_prefix[] = {
chLatin_e,
chLatin_n,
chLatin_v,
chNull
};
static XMLCh s_Envelope[] = {
chLatin_E,
chLatin_n,
chLatin_v,
chLatin_e,
chLatin_l,
chLatin_o,
chLatin_p,
chLatin_e,
chNull
};
static XMLCh s_Body[] = {
chLatin_B,
chLatin_o,
chLatin_d,
chLatin_y,
chNull
};
// --------------------------------------------------------------------------------
// Constructors and Destructors
// --------------------------------------------------------------------------------
/* NOTE: This is initialised via the platform specific code */
XSECSOAPRequestorSimple::~XSECSOAPRequestorSimple() {
}
// --------------------------------------------------------------------------------
// Wrap and serialise the request message
// --------------------------------------------------------------------------------
char * XSECSOAPRequestorSimple::wrapAndSerialise(DOMDocument * request) {
// Create a new document to wrap the request in
XMLCh tempStr[100];
XMLString::transcode("Core", tempStr, 99);
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
safeBuffer str;
makeQName(str, s_prefix, s_Envelope);
DOMDocument *doc = impl->createDocument(
XKMSConstants::s_unicodeStrURISOAP11,
str.rawXMLChBuffer(),
NULL);// DOMDocumentType()); // document type object (DTD).
DOMElement *rootElem = doc->getDocumentElement();
makeQName(str, s_prefix, s_Body);
DOMElement *body = doc->createElementNS(
XKMSConstants::s_unicodeStrURISOAP11,
str.rawXMLChBuffer());
rootElem->appendChild(body);
// Now replicate the request into the document
DOMElement * reqElement = (DOMElement *) doc->importNode(request->getDocumentElement(), true);
body->appendChild(reqElement);
// OK - Now we have the SOAP request as a document, we serialise to a string buffer
// and return
DOMWriter *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
theSerializer->setEncoding(MAKE_UNICODE_STRING("UTF-8"));
if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false))
theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false);
MemBufFormatTarget *formatTarget = new MemBufFormatTarget;
theSerializer->writeNode(formatTarget, *doc);
// Now replicate the buffer
char * ret = XMLString::replicate((const char *) formatTarget->getRawBuffer());
delete theSerializer;
delete formatTarget;
doc->release();
return ret;
}
// --------------------------------------------------------------------------------
// UnWrap and de-serialise the response message
// --------------------------------------------------------------------------------
DOMDocument * XSECSOAPRequestorSimple::parseAndUnwrap(const char * buf, unsigned int len) {
XercesDOMParser * parser = new XercesDOMParser;
Janitor<XercesDOMParser> j_parser(parser);
parser->setDoNamespaces(true);
parser->setCreateEntityReferenceNodes(true);
parser->setDoSchema(true);
// Create an input source
MemBufInputSource* memIS = new MemBufInputSource ((const XMLByte*) buf, len, "XSECMem");
Janitor<MemBufInputSource> j_memIS(memIS);
int errorCount = 0;
parser->parse(*memIS);
errorCount = parser->getErrorCount();
if (errorCount > 0)
throw XSECException(XSECException::HTTPURIInputStreamError,
"Error parsing SOAP response message");
DOMDocument * responseDoc = parser->getDocument();
// Now create a new document for the Response message
XMLCh tempStr[100];
XMLString::transcode("Core", tempStr, 99);
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
DOMDocument * retDoc = impl->createDocument();
// Find the base of the response
DOMNode * e = responseDoc->getDocumentElement();
e = e->getFirstChild();
while (e != NULL && (e->getNodeType() != DOMNode::ELEMENT_NODE || !strEquals(e->getLocalName(), "Body")))
e = e->getNextSibling();
if (e == NULL)
throw XSECException(XSECException::HTTPURIInputStreamError,
"Could not find SOAP body");
e = findFirstChildOfType(e, DOMNode::ELEMENT_NODE);
if (e == NULL)
throw XSECException(XSECException::HTTPURIInputStreamError,
"Could not find message within SOAP body");
/* See if this is a soap fault */
if (strEquals(e->getLocalName(), "Fault")) {
// Something has gone wrong somewhere!
safeBuffer sb;
sb.sbTranscodeIn("SOAP Fault : ");
// Find the fault code
e = findFirstElementChild(e);
while (e != NULL && !strEquals(e->getLocalName(), "Code"))
e = findNextElementChild(e);
if (e != NULL) {
DOMNode * c = findFirstElementChild(e);
while (c != NULL && !strEquals(c->getLocalName(), "Value"))
c = findNextElementChild(c);
if (c != NULL) {
DOMNode * t = findFirstChildOfType(c, DOMNode::TEXT_NODE);
if (t != NULL) {
sb.sbXMLChCat(t->getNodeValue());
sb.sbXMLChCat(" : ");
}
}
}
// Find the reason
while (e != NULL && !strEquals(e->getLocalName(), "Reason"))
e = findNextElementChild(e);
if (e != NULL) {
DOMNode * t = findFirstChildOfType(e, DOMNode::TEXT_NODE);
if (t != NULL) {
sb.sbXMLChCat(t->getNodeValue());
}
}
retDoc->release();
char * msg = XMLString::transcode(sb.rawXMLChBuffer());
ArrayJanitor<char> j_msg(msg);
throw XSECException(XSECException::HTTPURIInputStreamError,
msg);
}
retDoc->appendChild(retDoc->importNode(e, true));
return retDoc;
}
|
Implement checking of SOAP faults
|
Implement checking of SOAP faults
git-svn-id: c5bb8e2b15dc16fd1aec0e5653c08870c9ddec7d@351084 13f79535-47bb-0310-9956-ffa450edef68
|
C++
|
apache-2.0
|
apache/santuario-java,apache/santuario-java,apache/santuario-java
|
9c1bb7f34084da02e15a1dae4bec9a8734d64145
|
include/AnnSceneryManager.hpp
|
include/AnnSceneryManager.hpp
|
#ifndef ANN_SCENERY_MANAGER
#define ANN_SCENERY_MANAGER
#include "systemMacro.h"
#include "AnnSubsystem.hpp"
#include "OgreSceneManager.h"
#include "AnnTypes.h"
#include "OgreVRRender.hpp"
#include <memory>
#include <algorithm>
namespace Annwvyn
{
///Scenery Manager, scene configuration for lighting and sky.
class DLL AnnSceneryManager : public AnnSubSystem
{
public:
///Construct the AnnSceneryManager
AnnSceneryManager(std::shared_ptr<OgreVRRender> renderer);
///This subsystem doesn't need to be updated
bool needUpdate() override { return false; }
///Set the ogre material for the sky-dome with params
/// \param activate if true put a sky-dome
/// \param materialName name of a material known from the Ogre Resource group manager
/// \param curvature curvature of the texture
/// \param tiling tilling of the texture
void setSkyDomeMaterial(bool activate,
const std::string& materialName,
float curvature = 2.0f,
float tiling = 1.0f) const;
///Set the ogre material for the sky-box with params
/// \param activate if true put the sky-box on the scene
/// \param materialName name of a material declared on the resource manager
/// \param distance distance of the sky from the camera
/// \param renderedFirst if true, the sky-box will be the first thing rendered
void setSkyBoxMaterial(bool activate,
const std::string& materialName,
float distance = 8000,
bool renderedFirst = true) const;
///Remove the sky dome
void removeSkyDome() const;
///Remove the sky box
void removeSkyBox() const;
///Set the ambient light. Ambiant light is 2 hemisphere, and upper one and a lower one. HDR light values are color * multiplier
void setAmbientLight(AnnColor upperColor, float upperMul, AnnColor lowerColor, float lowerMul, AnnVect3 direction, float environementMapScaling = 16) const;
///Set the defautl ambient light
void setDefaultAmbientLight() const;
///Set the exposure value in "ev" (what's used in photography for exposure compensation). Also set the delta of adjustmen
void setExposure(float exposure, float minExposure, float maxExposure) const;
///Reset the default exposure
void setDefaultExposure() const;
///Set the color of the sky. Converted into HDR light values with the multiplier
void setSkyColor(AnnColor color, float multiplier) const;
///Reset the engine default sky color
void setDefaultSkyColor() const;
///Set the threshold that define where to put the bloom effect
void setBloomThreshold(float threshold) const;
///Reset the default bloom effect
void setDefaultBloomThreshold() const;
///Reset everything to engine default
void resetSceneParameters() const;
private:
///Scene manager created by the VR renderer
Ogre::SceneManager* smgr;
///Pointer to the VR renderer
std::shared_ptr<OgreVRRender> renderer;
///Defaults environmental floats
const float defaultExposure, defaultMinAutoExposure, defaultMaxAutoExposure, defaultSkyColorMultiplier, defaultBloom, defaultUpperAmbientLightMul, defaultLowerAmbientLightMul;
///Default sky color
const AnnColor defaultSkyColor, defaultUpperAmbient, defaultLowerAmbient;
};
}
#endif
|
#ifndef ANN_SCENERY_MANAGER
#define ANN_SCENERY_MANAGER
#include "systemMacro.h"
#include "AnnSubsystem.hpp"
#include "OgreSceneManager.h"
#include "AnnTypes.h"
#include "OgreVRRender.hpp"
#include <memory>
#include <algorithm>
namespace Annwvyn
{
///Scenery Manager. Set the scene rendering parameters, like the exposure or the ambient lighting...
class DLL AnnSceneryManager : public AnnSubSystem
{
public:
///Construct the AnnSceneryManager
AnnSceneryManager(std::shared_ptr<OgreVRRender> renderer);
///This subsystem doesn't need to be updated
bool needUpdate() override { return false; }
///Set the ogre material for the sky-dome with params
/// \param activate if true put a sky-dome
/// \param materialName name of a material known from the Ogre Resource group manager
/// \param curvature curvature of the texture
/// \param tiling tilling of the texture
void setSkyDomeMaterial(bool activate,
const std::string& materialName,
float curvature = 2.0f,
float tiling = 1.0f) const;
///Set the ogre material for the sky-box with params
/// \param activate if true put the sky-box on the scene
/// \param materialName name of a material declared on the resource manager
/// \param distance distance of the sky from the camera
/// \param renderedFirst if true, the sky-box will be the first thing rendered
void setSkyBoxMaterial(bool activate,
const std::string& materialName,
float distance = 8000,
bool renderedFirst = true) const;
///Remove the sky dome
void removeSkyDome() const;
///Remove the sky box
void removeSkyBox() const;
///Set the ambient light. Ambiant light is 2 hemisphere, and upper one and a lower one. HDR light values are color * multiplier
void setAmbientLight(AnnColor upperColor, float upperMul, AnnColor lowerColor, float lowerMul, AnnVect3 direction, float environementMapScaling = 16) const;
///Set the defautl ambient light
void setDefaultAmbientLight() const;
///Set the exposure value in "ev" (what's used in photography for exposure compensation). Also set the delta of adjustmen
void setExposure(float exposure, float minExposure, float maxExposure) const;
///Reset the default exposure
void setDefaultExposure() const;
///Set the color of the sky. Converted into HDR light values with the multiplier
void setSkyColor(AnnColor color, float multiplier) const;
///Reset the engine default sky color
void setDefaultSkyColor() const;
///Set the threshold that define where to put the bloom effect
void setBloomThreshold(float threshold) const;
///Reset the default bloom effect
void setDefaultBloomThreshold() const;
///Reset everything to engine default
void resetSceneParameters() const;
private:
///Scene manager created by the VR renderer
Ogre::SceneManager* smgr;
///Pointer to the VR renderer
std::shared_ptr<OgreVRRender> renderer;
///Defaults environmental floats
const float defaultExposure, defaultMinAutoExposure, defaultMaxAutoExposure, defaultSkyColorMultiplier, defaultBloom, defaultUpperAmbientLightMul, defaultLowerAmbientLightMul;
///Default sky color
const AnnColor defaultSkyColor, defaultUpperAmbient, defaultLowerAmbient;
};
}
#endif
|
Change scenery manager description for doxygen
|
Change scenery manager description for doxygen
|
C++
|
mit
|
Ybalrid/Annwvyn,Ybalrid/Annwvyn,Ybalrid/Annwvyn
|
1275eda464b4234da2f0bc1f4d095e4c3b4977bc
|
src/shaders.cpp
|
src/shaders.cpp
|
#include "shaders.h"
//#include "mathutils.h"
#define INVALID_SHADER 0
#define DEBUG_SHADER_ERRORS true
//
// AnyShader
//
AnyShader::AnyShader() {
//empty
}
AnyShader::~AnyShader() {
//empty
}
/**
* Create the shader program.
*/
bool AnyShader::create() {
if (failed) {
return false;
}
if (prog != INVALID_PROGRAM) {
return true;
}
//compile
GLuint handle = glCreateProgram();
if (handle == INVALID_PROGRAM) {
error = "glCreateProgram failed.";
return false;
}
if (!vertexShader.empty()) {
GLuint vertShader = compileShader(vertexShader, GL_VERTEX_SHADER);
if (vertShader == INVALID_SHADER) {
//cleanup
glDeleteProgram(handle);
return false;
}
glAttachShader(handle, vertShader);
glDeleteShader(vertShader);
}
if (!fragmentShader.empty()) {
GLuint fragShader = compileShader(fragmentShader, GL_FRAGMENT_SHADER);
if (fragShader == INVALID_SHADER) {
//cleanup
glDeleteProgram(handle);
return false;
}
glAttachShader(handle, fragShader);
glDeleteShader(fragShader);
}
//link
glLinkProgram(handle);
GLint linkStatus;
glGetProgramiv(handle, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
//cleanup
glDeleteProgram(handle);
//get error
GLchar messages[256];
glGetProgramInfoLog(handle, sizeof messages, 0, &messages[0]);
if (DEBUG_SHADER_ERRORS) {
printf("shader linking failed: %s\n", messages);
}
return false;
}
prog = handle;
//initialize
initShader();
return true;
}
/**
* Compile a shader.
*
* Note: sets error on failure.
*/
GLuint AnyShader::compileShader(std::string source, const GLenum type) {
GLint compileStatus;
GLuint handle = glCreateShader(type);
if (handle == INVALID_SHADER) {
error = "glCreateShader() failed";
return -1;
}
#ifdef RPI
//add GLSL version
source = "#version 100\n" + source;
#endif
GLchar *src = (GLchar *)source.c_str();
glShaderSource(handle, 1, (const GLchar **)&src, NULL);
glCompileShader(handle);
//get status
glGetShaderiv(handle, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus == GL_FALSE) {
//get error
GLchar messages[256];
glGetShaderInfoLog(handle, sizeof messages, 0, &messages[0]);
if (DEBUG_SHADER_ERRORS) {
std::string typeStr;
if (type == GL_VERTEX_SHADER) {
typeStr = "vertex shader";
} else if (type == GL_FRAGMENT_SHADER) {
typeStr = "fragment shader";
}
printf("shader compilation error: %s\ntype: %s\n\n%s\n", messages, typeStr.c_str(), src);
}
error = std::string(messages);
//free
glDeleteShader(handle);
handle = INVALID_SHADER;
}
return handle;
}
/**
* Destroy the shader.
*
* Note: has to be called in OpenGL thread.
*/
void AnyShader::destroy() {
if (prog != INVALID_PROGRAM) {
glDeleteProgram(prog);
prog = INVALID_PROGRAM;
}
//reset failed
failed = false;
}
/**
* Get attribute location.
*/
GLint AnyShader::getAttributeLocation(std::string name) {
GLint loc = glGetAttribLocation(prog, name.c_str());
if (DEBUG_SHADER_ERRORS) {
if (loc == -1) {
printf("could not get location of attribute %s\n", name.c_str());
}
}
return loc;
}
/**
* Get uniform location.
*/
GLint AnyShader::getUniformLocation(std::string name) {
GLint loc = glGetUniformLocation(prog, name.c_str());
if (DEBUG_SHADER_ERRORS) {
if (loc == -1) {
printf("could not get location of uniform %s\n", name.c_str());
}
}
return loc;
}
/**
* Use the shader.
*
* Note: has to be called before any setters are used!
*/
void AnyShader::useShader(bool active) {
if (!active) {
glUseProgram(prog);
}
}
//
// AnyAminoShader
//
AnyAminoShader::AnyAminoShader() : AnyShader() {
//default vertex shader
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
attribute vec4 pos;
void main() {
gl_Position = mvp * trans * pos;
}
)";
}
/**
* Initialize the shader.
*/
void AnyAminoShader::initShader() {
useShader(false);
//attributes
aPos = getAttributeLocation("pos");
//uniforms
uMVP = getUniformLocation("mvp");
uTrans = getUniformLocation("trans");
}
/**
* Set transformation matrix.
*/
void AnyAminoShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {
glUniformMatrix4fv(uMVP, 1, GL_FALSE, modelView);
glUniformMatrix4fv(uTrans, 1, GL_FALSE, transition);
}
/**
* Set vertex data.
*/
void AnyAminoShader::setVertexData(GLsizei dim, GLfloat *vertices) {
/*
* Coords per vertex (2 or 3).
*
* Note: vertices is NULL in case of VBO usage
*/
glVertexAttribPointer(aPos, dim, GL_FLOAT, GL_FALSE, 0, vertices);
}
/**
* Draw triangles.
*/
void AnyAminoShader::drawTriangles(GLsizei vertices, GLenum mode) {
glEnableVertexAttribArray(aPos);
glDrawArrays(mode, 0, vertices);
glDisableVertexAttribArray(aPos);
}
/**
* Draw elements.
*/
void AnyAminoShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {
glEnableVertexAttribArray(aPos);
//Note: indices is offset in case of VBO
glDrawElements(mode, elements, GL_UNSIGNED_SHORT, indices);
glDisableVertexAttribArray(aPos);
}
//
// ColorShader
//
/**
* Create color shader.
*/
ColorShader::ColorShader() : AnyAminoShader() {
//shaders
//Note: no performance difference seen between highp, mediump and lowp!
fragmentShader = R"(
#ifdef EGL_GBM
precision highp float;
#endif
uniform vec4 color;
void main() {
gl_FragColor = color;
}
)";
}
/**
* Initialize the color shader.
*/
void ColorShader::initShader() {
AnyAminoShader::initShader();
//uniforms
uColor = getUniformLocation("color");
}
/**
* Set color.
*/
void ColorShader::setColor(GLfloat color[4]) {
glUniform4f(uColor, color[0], color[1], color[2], color[3]);
}
//
// ColorLightingShader
//
/**
* Create color lighting shader.
*/
ColorLightingShader::ColorLightingShader() : ColorShader() {
//shaders
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
//uniform mat4 normalMatrix;
uniform vec3 lightDir;
attribute vec4 pos;
attribute vec3 normal;
varying float lightFac;
void main() {
gl_Position = mvp * trans * pos;
//simple version
vec4 normalTrans = trans * vec4(normal, 0.);
lightFac = abs(dot(normalTrans.xyz, -lightDir));
}
)";
fragmentShader = R"(
#ifdef EGL_GBM
precision highp float;
#endif
varying float lightFac;
uniform vec4 color;
void main() {
gl_FragColor = vec4(color.rgb * lightFac, color.a);
}
)";
}
/**
* Initialize the color lighting shader.
*/
void ColorLightingShader::initShader() {
ColorShader::initShader();
//attributes
aNormal = getAttributeLocation("normal");
//uniforms
//uNormalMatrix = getUniformLocation("normalMatrix");
uLightDir = getUniformLocation("lightDir");
//default values
GLfloat lightDir[3] = { 0, 0, -1 }; //parallel light on screen
setLightDirection(lightDir);
}
/**
* Set light direction.
*/
void ColorLightingShader::setLightDirection(GLfloat dir[3]) {
glUniform3f(uLightDir, dir[0], dir[1], dir[2]);
}
/**
* Set normal vectors.
*/
void ColorLightingShader::setNormalVectors(GLfloat *normals) {
glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, normals);
}
/**
* Set matrix.
*/
void ColorLightingShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {
AnyAminoShader::setTransformation(modelView, transition);
//normal matrix
/*
GLfloat invMatrix[16];
GLfloat normalMatrix[16];
assert(invert_matrix(transition, invMatrix));
transpose_matrix(normalMatrix, invMatrix);
glUniformMatrix4fv(uNormalMatrix, 1, GL_FALSE, normalMatrix);
*/
}
/**
* Draw triangles.
*/
void ColorLightingShader::drawTriangles(GLsizei vertices, GLenum mode) {
glEnableVertexAttribArray(aNormal);
AnyAminoShader::drawTriangles(vertices, mode);
glDisableVertexAttribArray(aNormal);
}
/**
* Draw elements.
*/
void ColorLightingShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {
glEnableVertexAttribArray(aNormal);
AnyAminoShader::drawElements(indices, elements, mode);
glDisableVertexAttribArray(aNormal);
}
//
// TextureShader
//
TextureShader::TextureShader() : AnyAminoShader() {
//shader
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
attribute vec4 pos;
attribute vec2 texCoord;
varying vec2 uv;
void main() {
gl_Position = mvp * trans * pos;
uv = texCoord;
}
)";
//supports opacity and discarding of fully transparent pixels
fragmentShader = R"(
#ifdef EGL_GBM
precision highp float;
#endif
varying vec2 uv;
uniform float opacity;
uniform sampler2D tex;
void main() {
vec4 pixel = texture2D(tex, uv);
//discard transparent pixels
if (pixel.a == 0.) {
discard;
}
gl_FragColor = vec4(pixel.rgb, pixel.a * opacity);
}
)";
//simplest shader (Note: not faster on video rendering)
/*
fragmentShader = R"(
varying vec2 uv;
uniform float opacity;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, uv);
}
)";
*/
}
/**
* Initialize the color shader.
*/
void TextureShader::initShader() {
AnyAminoShader::initShader();
//attributes
aTexCoord = getAttributeLocation("texCoord");
//uniforms
uOpacity = getUniformLocation("opacity");
uTex = getUniformLocation("tex");
//default values
glUniform1i(uTex, 0); //GL_TEXTURE0
}
/**
* Set opacity.
*/
void TextureShader::setOpacity(GLfloat opacity) {
glUniform1f(uOpacity, opacity);
}
/**
* Set texture coordinates.
*/
void TextureShader::setTextureCoordinates(GLfloat uv[][2]) {
glVertexAttribPointer(aTexCoord, 2, GL_FLOAT, GL_FALSE, 0, uv);
}
/**
* Draw texture.
*/
void TextureShader::drawTriangles(GLsizei vertices, GLenum mode) {
glEnableVertexAttribArray(aTexCoord);
glActiveTexture(GL_TEXTURE0);
AnyAminoShader::drawTriangles(vertices, mode);
glDisableVertexAttribArray(aTexCoord);
}
/**
* Draw elements.
*/
void TextureShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {
glEnableVertexAttribArray(aTexCoord);
glActiveTexture(GL_TEXTURE0);
AnyAminoShader::drawElements(indices, elements, mode);
glDisableVertexAttribArray(aTexCoord);
}
//
// TextureClampToBorderShader
//
TextureClampToBorderShader::TextureClampToBorderShader() : TextureShader() {
//Note: supports clamp to border, using transparent texture
fragmentShader = R"(
#ifdef EGL_GBM
precision highp float;
#endif
varying vec2 uv;
uniform float opacity;
uniform bvec2 repeat;
uniform sampler2D tex;
bool clamp_to_border(vec2 coords) {
bvec2 out1 = greaterThan(coords, vec2(1, 1));
bvec2 out2 = lessThan(coords, vec2(0, 0));
bool do_clamp = (any(out1) || any(out2));
return do_clamp;
}
void main() {
//repeat
vec2 uv2 = uv;
if (repeat.x) {
uv2.x = fract(uv.x);
}
if (repeat.y) {
uv2.y = fract(uv.y);
}
//show pixel
vec4 pixel = texture2D(tex, uv2);
//discard transparent pixels
if (pixel.a == 0. || clamp_to_border(uv2)) {
discard;
}
gl_FragColor = vec4(pixel.rgb, pixel.a * opacity);
}
)";
}
/**
* Initialize the shader.
*/
void TextureClampToBorderShader::initShader() {
TextureShader::initShader();
uRepeat = getUniformLocation("repeat");
}
/**
* Set repeat directions.
*/
void TextureClampToBorderShader::setRepeat(bool repeatX, bool repeatY) {
glUniform2i(uRepeat, repeatX, repeatY);
}
//
// TextureLightingShader
//
/**
* Create color lighting shader.
*/
TextureLightingShader::TextureLightingShader() : TextureShader() {
//shaders
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
uniform vec3 lightDir;
attribute vec4 pos;
attribute vec2 texCoord;
attribute vec3 normal;
varying vec2 uv;
varying float lightFac;
void main() {
gl_Position = mvp * trans * pos;
uv = texCoord;
vec4 normalTrans = trans * vec4(normal, 0.);
//translucent layers
lightFac = abs(dot(normalTrans.xyz, -lightDir));
}
)";
fragmentShader = R"(
varying vec2 uv;
varying float lightFac;
uniform float opacity;
uniform sampler2D tex;
void main() {
vec4 pixel = texture2D(tex, uv);
//discard transparent pixels
if (pixel.a == 0.) {
discard;
}
gl_FragColor = vec4(pixel.rgb * lightFac, pixel.a * opacity);
}
)";
}
/**
* Initialize the color lighting shader.
*/
void TextureLightingShader::initShader() {
TextureShader::initShader();
//attributes
aNormal = getAttributeLocation("normal");
//uniforms
//uNormalMatrix = getUniformLocation("normalMatrix");
uLightDir = getUniformLocation("lightDir");
//default values
GLfloat lightDir[3] = { 0, 0, -1 }; //parallel light on screen
setLightDirection(lightDir);
}
/**
* Set light direction.
*/
void TextureLightingShader::setLightDirection(GLfloat dir[3]) {
glUniform3f(uLightDir, dir[0], dir[1], dir[2]);
}
/**
* Set normal vectors.
*/
void TextureLightingShader::setNormalVectors(GLfloat *normals) {
glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, normals);
}
/**
* Draw triangles.
*/
void TextureLightingShader::drawTriangles(GLsizei vertices, GLenum mode) {
glEnableVertexAttribArray(aNormal);
TextureShader::drawTriangles(vertices, mode);
glDisableVertexAttribArray(aNormal);
}
/**
* Draw elements.
*/
void TextureLightingShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {
glEnableVertexAttribArray(aNormal);
TextureShader::drawElements(indices, elements, mode);
glDisableVertexAttribArray(aNormal);
}
|
#include "shaders.h"
//#include "mathutils.h"
#define INVALID_SHADER 0
#define DEBUG_SHADER_ERRORS true
//
// AnyShader
//
AnyShader::AnyShader() {
//empty
}
AnyShader::~AnyShader() {
//empty
}
/**
* Create the shader program.
*/
bool AnyShader::create() {
if (failed) {
return false;
}
if (prog != INVALID_PROGRAM) {
return true;
}
//compile
GLuint handle = glCreateProgram();
if (handle == INVALID_PROGRAM) {
error = "glCreateProgram failed.";
return false;
}
if (!vertexShader.empty()) {
GLuint vertShader = compileShader(vertexShader, GL_VERTEX_SHADER);
if (vertShader == INVALID_SHADER) {
//cleanup
glDeleteProgram(handle);
return false;
}
glAttachShader(handle, vertShader);
glDeleteShader(vertShader);
}
if (!fragmentShader.empty()) {
GLuint fragShader = compileShader(fragmentShader, GL_FRAGMENT_SHADER);
if (fragShader == INVALID_SHADER) {
//cleanup
glDeleteProgram(handle);
return false;
}
glAttachShader(handle, fragShader);
glDeleteShader(fragShader);
}
//link
glLinkProgram(handle);
GLint linkStatus;
glGetProgramiv(handle, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
//cleanup
glDeleteProgram(handle);
//get error
GLchar messages[256];
glGetProgramInfoLog(handle, sizeof messages, 0, &messages[0]);
if (DEBUG_SHADER_ERRORS) {
printf("shader linking failed: %s\n", messages);
}
return false;
}
prog = handle;
//initialize
initShader();
return true;
}
/**
* Compile a shader.
*
* Note: sets error on failure.
*/
GLuint AnyShader::compileShader(std::string source, const GLenum type) {
GLint compileStatus;
GLuint handle = glCreateShader(type);
if (handle == INVALID_SHADER) {
error = "glCreateShader() failed";
return -1;
}
#ifdef RPI
//add GLSL version
source = "#version 100\n" + source;
#endif
#ifdef EGL_GBM
//add define
//cbxx TODO verify
source += "define EGL_GBM;\n";
#endif
GLchar *src = (GLchar *)source.c_str();
glShaderSource(handle, 1, (const GLchar **)&src, NULL);
glCompileShader(handle);
//get status
glGetShaderiv(handle, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus == GL_FALSE) {
//get error
GLchar messages[256];
glGetShaderInfoLog(handle, sizeof messages, 0, &messages[0]);
if (DEBUG_SHADER_ERRORS) {
std::string typeStr;
if (type == GL_VERTEX_SHADER) {
typeStr = "vertex shader";
} else if (type == GL_FRAGMENT_SHADER) {
typeStr = "fragment shader";
}
printf("shader compilation error: %s\ntype: %s\n\n%s\n", messages, typeStr.c_str(), src);
}
error = std::string(messages);
//free
glDeleteShader(handle);
handle = INVALID_SHADER;
}
return handle;
}
/**
* Destroy the shader.
*
* Note: has to be called in OpenGL thread.
*/
void AnyShader::destroy() {
if (prog != INVALID_PROGRAM) {
glDeleteProgram(prog);
prog = INVALID_PROGRAM;
}
//reset failed
failed = false;
}
/**
* Get attribute location.
*/
GLint AnyShader::getAttributeLocation(std::string name) {
GLint loc = glGetAttribLocation(prog, name.c_str());
if (DEBUG_SHADER_ERRORS) {
if (loc == -1) {
printf("could not get location of attribute %s\n", name.c_str());
}
}
return loc;
}
/**
* Get uniform location.
*/
GLint AnyShader::getUniformLocation(std::string name) {
GLint loc = glGetUniformLocation(prog, name.c_str());
if (DEBUG_SHADER_ERRORS) {
if (loc == -1) {
printf("could not get location of uniform %s\n", name.c_str());
}
}
return loc;
}
/**
* Use the shader.
*
* Note: has to be called before any setters are used!
*/
void AnyShader::useShader(bool active) {
if (!active) {
glUseProgram(prog);
}
}
//
// AnyAminoShader
//
AnyAminoShader::AnyAminoShader() : AnyShader() {
//default vertex shader
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
attribute vec4 pos;
void main() {
gl_Position = mvp * trans * pos;
}
)";
}
/**
* Initialize the shader.
*/
void AnyAminoShader::initShader() {
useShader(false);
//attributes
aPos = getAttributeLocation("pos");
//uniforms
uMVP = getUniformLocation("mvp");
uTrans = getUniformLocation("trans");
}
/**
* Set transformation matrix.
*/
void AnyAminoShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {
glUniformMatrix4fv(uMVP, 1, GL_FALSE, modelView);
glUniformMatrix4fv(uTrans, 1, GL_FALSE, transition);
}
/**
* Set vertex data.
*/
void AnyAminoShader::setVertexData(GLsizei dim, GLfloat *vertices) {
/*
* Coords per vertex (2 or 3).
*
* Note: vertices is NULL in case of VBO usage
*/
glVertexAttribPointer(aPos, dim, GL_FLOAT, GL_FALSE, 0, vertices);
}
/**
* Draw triangles.
*/
void AnyAminoShader::drawTriangles(GLsizei vertices, GLenum mode) {
glEnableVertexAttribArray(aPos);
glDrawArrays(mode, 0, vertices);
glDisableVertexAttribArray(aPos);
}
/**
* Draw elements.
*/
void AnyAminoShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {
glEnableVertexAttribArray(aPos);
//Note: indices is offset in case of VBO
glDrawElements(mode, elements, GL_UNSIGNED_SHORT, indices);
glDisableVertexAttribArray(aPos);
}
//
// ColorShader
//
/**
* Create color shader.
*/
ColorShader::ColorShader() : AnyAminoShader() {
//shaders
//Note: no performance difference seen between highp, mediump and lowp!
fragmentShader = R"(
#ifdef EGL_GBM
precision highp float;
#endif
uniform vec4 color;
void main() {
gl_FragColor = color;
}
)";
}
/**
* Initialize the color shader.
*/
void ColorShader::initShader() {
AnyAminoShader::initShader();
//uniforms
uColor = getUniformLocation("color");
}
/**
* Set color.
*/
void ColorShader::setColor(GLfloat color[4]) {
glUniform4f(uColor, color[0], color[1], color[2], color[3]);
}
//
// ColorLightingShader
//
/**
* Create color lighting shader.
*/
ColorLightingShader::ColorLightingShader() : ColorShader() {
//shaders
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
//uniform mat4 normalMatrix;
uniform vec3 lightDir;
attribute vec4 pos;
attribute vec3 normal;
varying float lightFac;
void main() {
gl_Position = mvp * trans * pos;
//simple version
vec4 normalTrans = trans * vec4(normal, 0.);
lightFac = abs(dot(normalTrans.xyz, -lightDir));
}
)";
fragmentShader = R"(
#ifdef EGL_GBM
precision highp float;
#endif
varying float lightFac;
uniform vec4 color;
void main() {
gl_FragColor = vec4(color.rgb * lightFac, color.a);
}
)";
}
/**
* Initialize the color lighting shader.
*/
void ColorLightingShader::initShader() {
ColorShader::initShader();
//attributes
aNormal = getAttributeLocation("normal");
//uniforms
//uNormalMatrix = getUniformLocation("normalMatrix");
uLightDir = getUniformLocation("lightDir");
//default values
GLfloat lightDir[3] = { 0, 0, -1 }; //parallel light on screen
setLightDirection(lightDir);
}
/**
* Set light direction.
*/
void ColorLightingShader::setLightDirection(GLfloat dir[3]) {
glUniform3f(uLightDir, dir[0], dir[1], dir[2]);
}
/**
* Set normal vectors.
*/
void ColorLightingShader::setNormalVectors(GLfloat *normals) {
glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, normals);
}
/**
* Set matrix.
*/
void ColorLightingShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {
AnyAminoShader::setTransformation(modelView, transition);
//normal matrix
/*
GLfloat invMatrix[16];
GLfloat normalMatrix[16];
assert(invert_matrix(transition, invMatrix));
transpose_matrix(normalMatrix, invMatrix);
glUniformMatrix4fv(uNormalMatrix, 1, GL_FALSE, normalMatrix);
*/
}
/**
* Draw triangles.
*/
void ColorLightingShader::drawTriangles(GLsizei vertices, GLenum mode) {
glEnableVertexAttribArray(aNormal);
AnyAminoShader::drawTriangles(vertices, mode);
glDisableVertexAttribArray(aNormal);
}
/**
* Draw elements.
*/
void ColorLightingShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {
glEnableVertexAttribArray(aNormal);
AnyAminoShader::drawElements(indices, elements, mode);
glDisableVertexAttribArray(aNormal);
}
//
// TextureShader
//
TextureShader::TextureShader() : AnyAminoShader() {
//shader
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
attribute vec4 pos;
attribute vec2 texCoord;
varying vec2 uv;
void main() {
gl_Position = mvp * trans * pos;
uv = texCoord;
}
)";
//supports opacity and discarding of fully transparent pixels
fragmentShader = R"(
#ifdef EGL_GBM
precision highp float;
#endif
varying vec2 uv;
uniform float opacity;
uniform sampler2D tex;
void main() {
vec4 pixel = texture2D(tex, uv);
//discard transparent pixels
if (pixel.a == 0.) {
discard;
}
gl_FragColor = vec4(pixel.rgb, pixel.a * opacity);
}
)";
//simplest shader (Note: not faster on video rendering)
/*
fragmentShader = R"(
varying vec2 uv;
uniform float opacity;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, uv);
}
)";
*/
}
/**
* Initialize the color shader.
*/
void TextureShader::initShader() {
AnyAminoShader::initShader();
//attributes
aTexCoord = getAttributeLocation("texCoord");
//uniforms
uOpacity = getUniformLocation("opacity");
uTex = getUniformLocation("tex");
//default values
glUniform1i(uTex, 0); //GL_TEXTURE0
}
/**
* Set opacity.
*/
void TextureShader::setOpacity(GLfloat opacity) {
glUniform1f(uOpacity, opacity);
}
/**
* Set texture coordinates.
*/
void TextureShader::setTextureCoordinates(GLfloat uv[][2]) {
glVertexAttribPointer(aTexCoord, 2, GL_FLOAT, GL_FALSE, 0, uv);
}
/**
* Draw texture.
*/
void TextureShader::drawTriangles(GLsizei vertices, GLenum mode) {
glEnableVertexAttribArray(aTexCoord);
glActiveTexture(GL_TEXTURE0);
AnyAminoShader::drawTriangles(vertices, mode);
glDisableVertexAttribArray(aTexCoord);
}
/**
* Draw elements.
*/
void TextureShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {
glEnableVertexAttribArray(aTexCoord);
glActiveTexture(GL_TEXTURE0);
AnyAminoShader::drawElements(indices, elements, mode);
glDisableVertexAttribArray(aTexCoord);
}
//
// TextureClampToBorderShader
//
TextureClampToBorderShader::TextureClampToBorderShader() : TextureShader() {
//Note: supports clamp to border, using transparent texture
fragmentShader = R"(
#ifdef EGL_GBM
precision highp float;
#endif
varying vec2 uv;
uniform float opacity;
uniform bvec2 repeat;
uniform sampler2D tex;
bool clamp_to_border(vec2 coords) {
bvec2 out1 = greaterThan(coords, vec2(1, 1));
bvec2 out2 = lessThan(coords, vec2(0, 0));
bool do_clamp = (any(out1) || any(out2));
return do_clamp;
}
void main() {
//repeat
vec2 uv2 = uv;
if (repeat.x) {
uv2.x = fract(uv.x);
}
if (repeat.y) {
uv2.y = fract(uv.y);
}
//show pixel
vec4 pixel = texture2D(tex, uv2);
//discard transparent pixels
if (pixel.a == 0. || clamp_to_border(uv2)) {
discard;
}
gl_FragColor = vec4(pixel.rgb, pixel.a * opacity);
}
)";
}
/**
* Initialize the shader.
*/
void TextureClampToBorderShader::initShader() {
TextureShader::initShader();
uRepeat = getUniformLocation("repeat");
}
/**
* Set repeat directions.
*/
void TextureClampToBorderShader::setRepeat(bool repeatX, bool repeatY) {
glUniform2i(uRepeat, repeatX, repeatY);
}
//
// TextureLightingShader
//
/**
* Create color lighting shader.
*/
TextureLightingShader::TextureLightingShader() : TextureShader() {
//shaders
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
uniform vec3 lightDir;
attribute vec4 pos;
attribute vec2 texCoord;
attribute vec3 normal;
varying vec2 uv;
varying float lightFac;
void main() {
gl_Position = mvp * trans * pos;
uv = texCoord;
vec4 normalTrans = trans * vec4(normal, 0.);
//translucent layers
lightFac = abs(dot(normalTrans.xyz, -lightDir));
}
)";
fragmentShader = R"(
varying vec2 uv;
varying float lightFac;
uniform float opacity;
uniform sampler2D tex;
void main() {
vec4 pixel = texture2D(tex, uv);
//discard transparent pixels
if (pixel.a == 0.) {
discard;
}
gl_FragColor = vec4(pixel.rgb * lightFac, pixel.a * opacity);
}
)";
}
/**
* Initialize the color lighting shader.
*/
void TextureLightingShader::initShader() {
TextureShader::initShader();
//attributes
aNormal = getAttributeLocation("normal");
//uniforms
//uNormalMatrix = getUniformLocation("normalMatrix");
uLightDir = getUniformLocation("lightDir");
//default values
GLfloat lightDir[3] = { 0, 0, -1 }; //parallel light on screen
setLightDirection(lightDir);
}
/**
* Set light direction.
*/
void TextureLightingShader::setLightDirection(GLfloat dir[3]) {
glUniform3f(uLightDir, dir[0], dir[1], dir[2]);
}
/**
* Set normal vectors.
*/
void TextureLightingShader::setNormalVectors(GLfloat *normals) {
glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, normals);
}
/**
* Draw triangles.
*/
void TextureLightingShader::drawTriangles(GLsizei vertices, GLenum mode) {
glEnableVertexAttribArray(aNormal);
TextureShader::drawTriangles(vertices, mode);
glDisableVertexAttribArray(aNormal);
}
/**
* Draw elements.
*/
void TextureLightingShader::drawElements(GLushort *indices, GLsizei elements, GLenum mode) {
glEnableVertexAttribArray(aNormal);
TextureShader::drawElements(indices, elements, mode);
glDisableVertexAttribArray(aNormal);
}
|
set shader define
|
set shader define
|
C++
|
mit
|
cbratschi/aminogfx-gl,cbratschi/aminogfx-gl,cbratschi/aminogfx-gl,cbratschi/aminogfx-gl,cbratschi/aminogfx-gl
|
2ee3df29f5de2f231c2d3a83ab5b0c5d016e8eaa
|
core/src/oned/ODCode128Reader.cpp
|
core/src/oned/ODCode128Reader.cpp
|
/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "oned/ODCode128Reader.h"
#include "oned/ODCode128Patterns.h"
#include "Result.h"
#include "BitArray.h"
#include "DecodeHints.h"
#include "TextDecoder.h"
#include "ZXContainerAlgorithms.h"
#include "ZXStrConvWorkaround.h"
#include <algorithm>
#include <string>
#include <array>
namespace ZXing {
namespace OneD {
static const float MAX_AVG_VARIANCE = 0.25f;
static const float MAX_INDIVIDUAL_VARIANCE = 0.7f;
static const int CODE_SHIFT = 98;
static const int CODE_CODE_C = 99;
static const int CODE_CODE_B = 100;
static const int CODE_CODE_A = 101;
static const int CODE_FNC_1 = 102;
static const int CODE_FNC_2 = 97;
static const int CODE_FNC_3 = 96;
static const int CODE_FNC_4_A = 101;
static const int CODE_FNC_4_B = 100;
static const int CODE_START_A = 103;
static const int CODE_START_B = 104;
static const int CODE_START_C = 105;
static const int CODE_STOP = 106;
static BitArray::Range
FindStartPattern(const BitArray& row, int* startCode)
{
assert(startCode != nullptr);
using Counters = std::vector<int>;
Counters counters(Code128::CODE_PATTERNS[CODE_START_A].size());
return RowReader::FindPattern(
row.getNextSet(row.begin()), row.end(), counters,
[&row, startCode](BitArray::Iterator begin, BitArray::Iterator end, const Counters& counters) {
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (!row.hasQuiteZone(begin, -(end - begin) / 2))
return false;
float bestVariance = MAX_AVG_VARIANCE;
for (int code : {CODE_START_A, CODE_START_B, CODE_START_C}) {
float variance =
RowReader::PatternMatchVariance(counters, Code128::CODE_PATTERNS[code], MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance) {
bestVariance = variance;
*startCode = code;
}
}
return bestVariance < MAX_AVG_VARIANCE;
});
}
Code128Reader::Code128Reader(const DecodeHints& hints) :
_convertFNC1(hints.shouldAssumeGS1())
{
}
Result
Code128Reader::decodeRow(int rowNumber, const BitArray& row, std::unique_ptr<DecodingState>&) const
{
int startCode = 0;
auto range = FindStartPattern(row, &startCode);
if (!range) {
return Result(DecodeStatus::NotFound);
}
float left = (range.begin - row.begin()) + 0.5f * range.size();
ByteArray rawCodes;
rawCodes.reserve(20);
rawCodes.push_back(static_cast<uint8_t>(startCode));
int codeSet;
switch (startCode) {
case CODE_START_A:
codeSet = CODE_CODE_A;
break;
case CODE_START_B:
codeSet = CODE_CODE_B;
break;
case CODE_START_C:
codeSet = CODE_CODE_C;
break;
default:
return Result(DecodeStatus::FormatError);
}
bool done = false;
bool isNextShifted = false;
std::string result;
result.reserve(20);
std::vector<int> counters(6, 0);
int lastCode = 0;
int code = 0;
int checksumTotal = startCode;
int multiplier = 0;
bool lastCharacterWasPrintable = true;
bool upperMode = false;
bool shiftUpperMode = false;
while (!done) {
bool unshift = isNextShifted;
isNextShifted = false;
// Save off last code
lastCode = code;
range = RecordPattern(range.end, row.end(), counters);
if (!range)
return Result(DecodeStatus::NotFound);
// Decode another code from image
code = RowReader::DecodeDigit(counters, Code128::CODE_PATTERNS, MAX_AVG_VARIANCE, MAX_INDIVIDUAL_VARIANCE);
if (code == -1)
return Result(DecodeStatus::NotFound);
rawCodes.push_back(static_cast<uint8_t>(code));
// Remember whether the last code was printable or not (excluding CODE_STOP)
if (code != CODE_STOP) {
lastCharacterWasPrintable = true;
}
// Add to checksum computation (if not CODE_STOP of course)
if (code != CODE_STOP) {
multiplier++;
checksumTotal += multiplier * code;
}
// Take care of illegal start codes
switch (code) {
case CODE_START_A:
case CODE_START_B:
case CODE_START_C:
return Result(DecodeStatus::FormatError);
}
switch (codeSet) {
case CODE_CODE_A:
if (code < 64) {
if (shiftUpperMode == upperMode) {
result.push_back((char)(' ' + code));
}
else {
result.push_back((char)(' ' + code + 128));
}
shiftUpperMode = false;
}
else if (code < 96) {
if (shiftUpperMode == upperMode) {
result.push_back((char)(code - 64));
}
else {
result.push_back((char)(code + 64));
}
shiftUpperMode = false;
}
else {
// Don't let CODE_STOP, which always appears, affect whether whether we think the last
// code was printable or not.
if (code != CODE_STOP) {
lastCharacterWasPrintable = false;
}
switch (code) {
case CODE_FNC_1:
if (_convertFNC1) {
if (result.empty()) {
// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result.append("]C1");
}
else {
// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result.push_back((char)29);
}
}
break;
case CODE_FNC_2:
case CODE_FNC_3:
// do nothing?
break;
case CODE_FNC_4_A:
if (!upperMode && shiftUpperMode) {
upperMode = true;
shiftUpperMode = false;
}
else if (upperMode && shiftUpperMode) {
upperMode = false;
shiftUpperMode = false;
}
else {
shiftUpperMode = true;
}
break;
case CODE_SHIFT:
isNextShifted = true;
codeSet = CODE_CODE_B;
break;
case CODE_CODE_B:
codeSet = CODE_CODE_B;
break;
case CODE_CODE_C:
codeSet = CODE_CODE_C;
break;
case CODE_STOP:
done = true;
break;
}
}
break;
case CODE_CODE_B:
if (code < 96) {
if (shiftUpperMode == upperMode) {
result.push_back((char)(' ' + code));
}
else {
result.push_back((char)(' ' + code + 128));
}
shiftUpperMode = false;
}
else {
if (code != CODE_STOP) {
lastCharacterWasPrintable = false;
}
switch (code) {
case CODE_FNC_1:
if (_convertFNC1) {
if (result.empty()) {
// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result.append("]C1");
}
else {
// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result.push_back((char)29);
}
}
break;
case CODE_FNC_2:
case CODE_FNC_3:
// do nothing?
break;
case CODE_FNC_4_B:
if (!upperMode && shiftUpperMode) {
upperMode = true;
shiftUpperMode = false;
}
else if (upperMode && shiftUpperMode) {
upperMode = false;
shiftUpperMode = false;
}
else {
shiftUpperMode = true;
}
break;
case CODE_SHIFT:
isNextShifted = true;
codeSet = CODE_CODE_A;
break;
case CODE_CODE_A:
codeSet = CODE_CODE_A;
break;
case CODE_CODE_C:
codeSet = CODE_CODE_C;
break;
case CODE_STOP:
done = true;
break;
}
}
break;
case CODE_CODE_C:
if (code < 100) {
if (code < 10) {
result.push_back('0');
}
result.append(std::to_string(code));
}
else {
if (code != CODE_STOP) {
lastCharacterWasPrintable = false;
}
switch (code) {
case CODE_FNC_1:
if (_convertFNC1) {
if (result.empty()) {
// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result.append("]C1");
}
else {
// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result.push_back((char)29);
}
}
break;
case CODE_CODE_A:
codeSet = CODE_CODE_A;
break;
case CODE_CODE_B:
codeSet = CODE_CODE_B;
break;
case CODE_STOP:
done = true;
break;
}
}
break;
}
// Unshift back to another code set if we were shifted
if (unshift) {
codeSet = codeSet == CODE_CODE_A ? CODE_CODE_B : CODE_CODE_A;
}
}
// Check for ample whitespace following pattern, but, to do this we first need to remember that
// we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left
// to read off. Would be slightly better to properly read. Here we just skip it:
range.end = row.getNextUnset(range.end);
if (!row.hasQuiteZone(range.end, range.size() / 2))
return Result(DecodeStatus::NotFound);
// Pull out from sum the value of the penultimate check code
checksumTotal -= multiplier * lastCode;
// lastCode is the checksum then:
if (checksumTotal % 103 != lastCode) {
return Result(DecodeStatus::ChecksumError);
}
// Need to pull out the check digits from string
size_t resultLength = result.length();
if (resultLength == 0) {
// false positive
return Result(DecodeStatus::NotFound);
}
// Only bother if the result had at least one character, and if the checksum digit happened to
// be a printable character. If it was just interpreted as a control code, nothing to remove.
if (resultLength > 0 && lastCharacterWasPrintable) {
if (codeSet == CODE_CODE_C) {
result.resize(resultLength >= 2 ? resultLength - 2 : 0);
}
else {
result.resize(resultLength - 1);
}
}
float right = (range.begin - row.begin()) + 0.5f * range.size();
float ypos = static_cast<float>(rowNumber);
return Result(TextDecoder::FromLatin1(result), std::move(rawCodes), { ResultPoint(left, ypos), ResultPoint(right, ypos) }, BarcodeFormat::CODE_128);
}
} // OneD
} // ZXing
|
/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "oned/ODCode128Reader.h"
#include "oned/ODCode128Patterns.h"
#include "Result.h"
#include "BitArray.h"
#include "DecodeHints.h"
#include "TextDecoder.h"
#include "ZXContainerAlgorithms.h"
#include "ZXStrConvWorkaround.h"
#include <algorithm>
#include <string>
#include <array>
namespace ZXing {
namespace OneD {
static const float MAX_AVG_VARIANCE = 0.25f;
static const float MAX_INDIVIDUAL_VARIANCE = 0.7f;
static const int CODE_SHIFT = 98;
static const int CODE_CODE_C = 99;
static const int CODE_CODE_B = 100;
static const int CODE_CODE_A = 101;
static const int CODE_FNC_1 = 102;
static const int CODE_FNC_2 = 97;
static const int CODE_FNC_3 = 96;
static const int CODE_START_A = 103;
static const int CODE_START_B = 104;
static const int CODE_START_C = 105;
static const int CODE_STOP = 106;
static BitArray::Range
FindStartPattern(const BitArray& row, int* startCode)
{
assert(startCode != nullptr);
using Counters = std::vector<int>;
Counters counters(Code128::CODE_PATTERNS[CODE_START_A].size());
return RowReader::FindPattern(
row.getNextSet(row.begin()), row.end(), counters,
[&row, startCode](BitArray::Iterator begin, BitArray::Iterator end, const Counters& counters) {
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (!row.hasQuiteZone(begin, -(end - begin) / 2))
return false;
float bestVariance = MAX_AVG_VARIANCE;
for (int code : {CODE_START_A, CODE_START_B, CODE_START_C}) {
float variance =
RowReader::PatternMatchVariance(counters, Code128::CODE_PATTERNS[code], MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance) {
bestVariance = variance;
*startCode = code;
}
}
return bestVariance < MAX_AVG_VARIANCE;
});
}
Code128Reader::Code128Reader(const DecodeHints& hints) :
_convertFNC1(hints.shouldAssumeGS1())
{
}
Result
Code128Reader::decodeRow(int rowNumber, const BitArray& row, std::unique_ptr<DecodingState>&) const
{
int startCode = 0;
auto range = FindStartPattern(row, &startCode);
if (!range) {
return Result(DecodeStatus::NotFound);
}
float left = (range.begin - row.begin()) + 0.5f * range.size();
ByteArray rawCodes;
rawCodes.reserve(20);
std::string result;
result.reserve(20);
std::vector<int> counters(6, 0);
rawCodes.push_back(static_cast<uint8_t>(startCode));
int codeSet = 204 - startCode;
size_t lastResultSize = 0;
bool fnc4All = false;
bool fnc4Next = false;
bool shift = false;
auto fnc1 = [&] {
if (_convertFNC1) {
if (result.empty()) {
// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result.append("]C1");
}
else {
// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result.push_back((char)29);
}
}
};
while (true) {
range = RecordPattern(range.end, row.end(), counters);
if (!range)
return Result(DecodeStatus::NotFound);
// Decode another code from image
int code = RowReader::DecodeDigit(counters, Code128::CODE_PATTERNS, MAX_AVG_VARIANCE, MAX_INDIVIDUAL_VARIANCE);
if (code == -1)
return Result(DecodeStatus::NotFound);
if (code == CODE_STOP)
break;
if (code >= CODE_START_A)
return Result(DecodeStatus::FormatError);
rawCodes.push_back(static_cast<uint8_t>(code));
lastResultSize = result.size();
if (codeSet == CODE_CODE_C) {
if (code < 100) {
if (code < 10)
result.push_back('0');
result.append(std::to_string(code));
} else if (code == CODE_FNC_1) {
fnc1();
} else {
codeSet = code; // CODE_A / CODE_B
}
} else { // codeSet A or B
bool unshift = shift;
switch (code) {
case CODE_FNC_1: fnc1(); break;
case CODE_FNC_2:
case CODE_FNC_3:
// do nothing?
break;
case CODE_SHIFT:
if (shift)
return Result(DecodeStatus::FormatError); // two shifts in a row make no sense
shift = true;
codeSet = codeSet == CODE_CODE_A ? CODE_CODE_B : CODE_CODE_A;
break;
case CODE_CODE_A:
case CODE_CODE_B:
if (codeSet == code) {
// FNC4
if (fnc4Next)
fnc4All = !fnc4All;
fnc4Next = !fnc4Next;
} else {
codeSet = code;
}
break;
case CODE_CODE_C: codeSet = CODE_CODE_C; break;
default: {
// code < 96 at this point
int offset;
if (codeSet == CODE_CODE_A && code >= 64)
offset = fnc4All == fnc4Next ? -64 : +64;
else
offset = fnc4All == fnc4Next ? ' ' : ' ' + 128;
result.push_back((char)(code + offset));
fnc4Next = false;
break;
}
}
// Unshift back to another code set if we were shifted
if (unshift) {
codeSet = codeSet == CODE_CODE_A ? CODE_CODE_B : CODE_CODE_A;
shift = false;
}
}
}
// Check for ample whitespace following pattern, but, to do this we first need to remember that
// we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left
// to read off. Would be slightly better to properly read. Here we just skip it:
range.end = row.getNextUnset(range.end);
if (result.empty() || !row.hasQuiteZone(range.end, range.size() / 2))
return Result(DecodeStatus::NotFound);
int checksum = rawCodes.front();
for (size_t i = 1; i < rawCodes.size() - 1; ++i)
checksum += i * rawCodes[i];
// the last code is the checksum:
if (checksum % 103 != rawCodes.back()) {
return Result(DecodeStatus::ChecksumError);
}
// Need to pull out the check digit(s) from string (if the checksum code happened to
// be a printable character).
result.resize(lastResultSize);
float right = (range.begin - row.begin()) + 0.5f * range.size();
float ypos = static_cast<float>(rowNumber);
return Result(TextDecoder::FromLatin1(result), std::move(rawCodes), { ResultPoint(left, ypos), ResultPoint(right, ypos) }, BarcodeFormat::CODE_128);
}
} // OneD
} // ZXing
|
Simplify ODCode128Reader decoding logic
|
Simplify ODCode128Reader decoding logic
|
C++
|
apache-2.0
|
nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp
|
e7be5a07e5bb21bdcfa62d3455f2801bbe88505b
|
src/sim/root.cc
|
src/sim/root.cc
|
/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* Copyright (c) 2011 Advanced Micro Devices
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
* Steve Reinhardt
* Gabe Black
*/
#include "base/misc.hh"
#include "sim/core.hh"
#include "sim/root.hh"
Root *Root::_root = NULL;
/*
* This function is called periodically by an event in M5 and ensures that
* at least as much real time has passed between invocations as simulated time.
* If not, the function either sleeps, or if the difference is small enough
* spin waits.
*/
void
Root::timeSync()
{
Time cur_time, diff, period = timeSyncPeriod();
do {
cur_time.setTimer();
diff = cur_time - lastTime;
Time remainder = period - diff;
if (diff < period && remainder > _spinThreshold) {
DPRINTF(TimeSync, "Sleeping to sync with real time.\n");
// Sleep until the end of the period, or until a signal.
sleep(remainder);
// Refresh the current time.
cur_time.setTimer();
}
} while (diff < period);
lastTime = cur_time;
schedule(&syncEvent, curTick() + _periodTick);
}
void
Root::timeSyncEnable(bool en)
{
if (en == _enabled)
return;
_enabled = en;
if (_enabled) {
// Get event going.
Tick periods = ((curTick() + _periodTick - 1) / _periodTick);
Tick nextPeriod = periods * _periodTick;
schedule(&syncEvent, nextPeriod);
} else {
// Stop event.
deschedule(&syncEvent);
}
}
/// Configure the period for time sync events.
void
Root::timeSyncPeriod(Time newPeriod)
{
bool en = timeSyncEnabled();
_period = newPeriod;
_periodTick = _period.nsec() * SimClock::Int::ns +
_period.sec() * SimClock::Int::s;
timeSyncEnable(en);
}
/// Set the threshold for time remaining to spin wait.
void
Root::timeSyncSpinThreshold(Time newThreshold)
{
bool en = timeSyncEnabled();
_spinThreshold = newThreshold;
timeSyncEnable(en);
}
Root::Root(RootParams *p) : SimObject(p), _enabled(false),
_periodTick(p->time_sync_period), syncEvent(this)
{
uint64_t nsecs = p->time_sync_period / SimClock::Int::ns;
_period.set(nsecs / Time::NSEC_PER_SEC, nsecs % Time::NSEC_PER_SEC);
nsecs = p->time_sync_spin_threshold / SimClock::Int::ns;
_spinThreshold.set(nsecs / Time::NSEC_PER_SEC,
nsecs % Time::NSEC_PER_SEC);
assert(_root == NULL);
_root = this;
lastTime.setTimer();
timeSyncEnable(p->time_sync_enable);
}
Root *
RootParams::create()
{
static bool created = false;
if (created)
panic("only one root object allowed!");
created = true;
return new Root(this);
}
|
/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* Copyright (c) 2011 Advanced Micro Devices
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
* Steve Reinhardt
* Gabe Black
*/
#include "base/misc.hh"
#include "sim/root.hh"
Root *Root::_root = NULL;
/*
* This function is called periodically by an event in M5 and ensures that
* at least as much real time has passed between invocations as simulated time.
* If not, the function either sleeps, or if the difference is small enough
* spin waits.
*/
void
Root::timeSync()
{
Time cur_time, diff, period = timeSyncPeriod();
do {
cur_time.setTimer();
diff = cur_time - lastTime;
Time remainder = period - diff;
if (diff < period && remainder > _spinThreshold) {
DPRINTF(TimeSync, "Sleeping to sync with real time.\n");
// Sleep until the end of the period, or until a signal.
sleep(remainder);
// Refresh the current time.
cur_time.setTimer();
}
} while (diff < period);
lastTime = cur_time;
schedule(&syncEvent, curTick() + _periodTick);
}
void
Root::timeSyncEnable(bool en)
{
if (en == _enabled)
return;
_enabled = en;
if (_enabled) {
// Get event going.
Tick periods = ((curTick() + _periodTick - 1) / _periodTick);
Tick nextPeriod = periods * _periodTick;
schedule(&syncEvent, nextPeriod);
} else {
// Stop event.
deschedule(&syncEvent);
}
}
/// Configure the period for time sync events.
void
Root::timeSyncPeriod(Time newPeriod)
{
bool en = timeSyncEnabled();
_period = newPeriod;
_periodTick = _period.getTick();
timeSyncEnable(en);
}
/// Set the threshold for time remaining to spin wait.
void
Root::timeSyncSpinThreshold(Time newThreshold)
{
bool en = timeSyncEnabled();
_spinThreshold = newThreshold;
timeSyncEnable(en);
}
Root::Root(RootParams *p) : SimObject(p), _enabled(false),
_periodTick(p->time_sync_period), syncEvent(this)
{
_period.setTick(p->time_sync_period);
_spinThreshold.setTick(p->time_sync_spin_threshold);
assert(_root == NULL);
_root = this;
lastTime.setTimer();
timeSyncEnable(p->time_sync_enable);
}
Root *
RootParams::create()
{
static bool created = false;
if (created)
panic("only one root object allowed!");
created = true;
return new Root(this);
}
|
Use the new setTick and getTick functions.
|
TimeSync: Use the new setTick and getTick functions.
|
C++
|
bsd-3-clause
|
andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin
|
0dfa9c9e42380910de76c7a0e6fe601f741236fb
|
src/output.cxx
|
src/output.cxx
|
// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
// MIT License
#include "output.h"
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options/variables_map.hpp>
#include "event.h"
#include "hdf5_utils.h"
namespace trento {
namespace {
// These output functions are invoked by the Output class.
void write_stream(std::ostream& os, int width, int num, double impact_param,
int ncoll, const Event& event) {
using std::fixed;
using std::setprecision;
using std::setw;
using std::scientific;
// Write a nicely-formatted line of event properties.
os << setprecision(10)
<< setw(width) << num
<< setw(15) << fixed << impact_param
<< setw(5) << event.npart();
// Output ncoll if calculated
if (ncoll > 0) os << setw(6) << ncoll;
os << setw(18) << scientific << event.multiplicity()
<< fixed;
for (const auto& ecc : event.eccentricity())
os << setw(14) << ecc.second;
os << '\n';
}
void write_text_file(const fs::path& output_dir, int width, int num,
double impact_param, int ncoll, const Event& event, bool header) {
// Open a numbered file in the output directory.
// Pad the filename with zeros.
std::ostringstream padded_fname{};
padded_fname << std::setw(width) << std::setfill('0') << num << ".dat";
fs::ofstream ofs{output_dir / padded_fname.str()};
if (header) {
// Write a commented header of event properties as key = value pairs.
ofs << std::setprecision(10)
<< "# event " << num << '\n'
<< "# b = " << impact_param << '\n'
<< "# npart = " << event.npart() << '\n';
// Output ncoll if calculated
if (ncoll > 0) ofs << "# ncoll = " << ncoll << '\n';
ofs << "# mult = " << event.multiplicity() << '\n';
for (const auto& ecc : event.eccentricity())
ofs << "# e" << ecc.first << " = " << ecc.second << '\n';
}
// Write IC profile as a block grid. Use C++ default float format (not
// fixed-width) so that trailing zeros are omitted. This significantly
// increases output speed and saves disk space since many grid elements are
// zero.
for (const auto& row : event.reduced_thickness_grid()) {
auto&& iter = row.begin();
// Write all row elements except the last with a space delimiter afterwards.
do {
ofs << *iter << ' ';
} while (++iter != --row.end());
// Write the last element and a linebreak.
ofs << *iter << '\n';
}
}
#ifdef TRENTO_HDF5
/// Simple functor to write many events to an HDF5 file.
class HDF5Writer {
public:
/// Prepare an HDF5 file for writing.
HDF5Writer(const fs::path& filename);
/// Write an event.
void operator()(int num, double impact_param,
int ncoll, const Event& event) const;
private:
/// Internal storage of the file object.
H5::H5File file_;
};
// Add a simple scalar attribute to an HDF5 dataset.
template <typename T>
void hdf5_add_scalar_attr(
const H5::DataSet& dataset, const std::string& name, const T& value) {
const auto& datatype = hdf5::type<T>();
auto attr = dataset.createAttribute(name, datatype, H5::DataSpace{});
attr.write(datatype, &value);
}
HDF5Writer::HDF5Writer(const fs::path& filename)
: file_(filename.string(), H5F_ACC_TRUNC)
{}
void HDF5Writer::operator()(int num, double impact_param,
int ncoll, const Event& event) const {
// Prepare arguments for new HDF5 dataset.
// The dataset name is a prefix plus the event number.
const std::string name{"event_" + std::to_string(num)};
// Cache a reference to the event grid -- will need it several times.
const auto& grid = event.reduced_thickness_grid();
// Define HDF5 datatype and dataspace to match the grid.
const auto& datatype = hdf5::type<Event::Grid::element>();
std::array<hsize_t, Event::Grid::dimensionality> shape;
std::copy(grid.shape(), grid.shape() + shape.size(), shape.begin());
auto dataspace = hdf5::make_dataspace(shape);
// Set dataset storage properties.
H5::DSetCreatPropList proplist{};
// Set chunk size to the entire grid. For typical grid sizes (~100x100), this
// works out to ~80 KiB, which is pretty optimal. Anyway, it makes logical
// sense to chunk this way, since chunks must be read contiguously and there's
// no reason to read a partial grid.
proplist.setChunk(shape.size(), shape.data());
// Set gzip compression level. 4 is the default in h5py.
proplist.setDeflate(4);
// Create the new dataset and write the grid.
auto dataset = file_.createDataSet(name, datatype, dataspace, proplist);
dataset.write(grid.data(), datatype);
// Write event attributes.
hdf5_add_scalar_attr(dataset, "b", impact_param);
hdf5_add_scalar_attr(dataset, "npart", event.npart());
// Write ncoll if calculated
//if (ncoll > 0) hdf5_add_scalar_attr(dataset, "ncoll", ncoll);
hdf5_add_scalar_attr(dataset, "ncoll", ncoll);
hdf5_add_scalar_attr(dataset, "mult", event.multiplicity());
for (const auto& ecc : event.eccentricity())
hdf5_add_scalar_attr(dataset, "e" + std::to_string(ecc.first), ecc.second);
}
#endif // TRENTO_HDF5
} // unnamed namespace
Output::Output(const VarMap& var_map) {
// Determine the required width (padding) of the event number. For example if
// there are 10 events, the numbers are 0-9 and so no padding is necessary.
// However given 11 events, the numbers are 00-10 with padded 00, 01, ...
auto nevents = var_map["number-events"].as<int>();
auto width = static_cast<int>(std::ceil(std::log10(nevents)));
// Write to stdout unless the quiet option was specified.
if (!var_map["quiet"].as<bool>()) {
writers_.emplace_back(
[width](int num, double impact_param, int ncoll, const Event& event) {
write_stream(std::cout, width, num, impact_param, ncoll, event);
}
);
}
// Possibly write to text or HDF5 files.
if (var_map.count("output")) {
const auto& output_path = var_map["output"].as<fs::path>();
if (hdf5::filename_is_hdf5(output_path)) {
#ifdef TRENTO_HDF5
if (fs::exists(output_path) && !fs::is_empty(output_path))
throw std::runtime_error{"file '" + output_path.string() +
"' exists, will not overwrite"};
writers_.emplace_back(HDF5Writer{output_path});
#else
throw std::runtime_error{"HDF5 output was not compiled"};
#endif // TRENTO_HDF5
} else {
// Text files are all written into a single directory. Require the
// directory to be initially empty to avoid accidental overwriting and/or
// spewing files into an already-used location. If the directory does not
// exist, create it.
if (fs::exists(output_path)) {
if (!fs::is_empty(output_path)) {
throw std::runtime_error{"output directory '" + output_path.string() +
"' must be empty"};
}
} else {
fs::create_directories(output_path);
}
auto header = !var_map["no-header"].as<bool>();
writers_.emplace_back(
[output_path, width, header](int num, double impact_param,
int ncoll, const Event& event) {
write_text_file(output_path, width, num,
impact_param, ncoll, event, header);
}
);
}
}
}
} // namespace trento
|
// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
// MIT License
#include "output.h"
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options/variables_map.hpp>
#include "event.h"
#include "hdf5_utils.h"
namespace trento {
namespace {
// These output functions are invoked by the Output class.
void write_stream(std::ostream& os, int width, int num, double impact_param,
int ncoll, const Event& event) {
using std::fixed;
using std::setprecision;
using std::setw;
using std::scientific;
// Write a nicely-formatted line of event properties.
os << setprecision(10)
<< setw(width) << num
<< setw(15) << fixed << impact_param
<< setw(5) << event.npart();
// Output ncoll if calculated
if (ncoll > 0) os << setw(6) << ncoll;
os << setw(18) << scientific << event.multiplicity()
<< fixed;
for (const auto& ecc : event.eccentricity())
os << setw(14) << ecc.second;
os << '\n';
}
void write_text_file(const fs::path& output_dir, int width, int num,
double impact_param, int ncoll, const Event& event, bool header) {
// Open a numbered file in the output directory.
// Pad the filename with zeros.
std::ostringstream padded_fname{};
padded_fname << std::setw(width) << std::setfill('0') << num << ".dat";
fs::ofstream ofs{output_dir / padded_fname.str()};
if (header) {
// Write a commented header of event properties as key = value pairs.
ofs << std::setprecision(10)
<< "# event " << num << '\n'
<< "# b = " << impact_param << '\n'
<< "# npart = " << event.npart() << '\n';
// Output ncoll if calculated
if (ncoll > 0) ofs << "# ncoll = " << ncoll << '\n';
ofs << "# mult = " << event.multiplicity() << '\n';
for (const auto& ecc : event.eccentricity())
ofs << "# e" << ecc.first << " = " << ecc.second << '\n';
}
// Write IC profile as a block grid. Use C++ default float format (not
// fixed-width) so that trailing zeros are omitted. This significantly
// increases output speed and saves disk space since many grid elements are
// zero.
for (const auto& row : event.reduced_thickness_grid()) {
auto&& iter = row.begin();
// Write all row elements except the last with a space delimiter afterwards.
do {
ofs << *iter << ' ';
} while (++iter != --row.end());
// Write the last element and a linebreak.
ofs << *iter << '\n';
}
}
#ifdef TRENTO_HDF5
/// Simple functor to write many events to an HDF5 file.
class HDF5Writer {
public:
/// Prepare an HDF5 file for writing.
HDF5Writer(const fs::path& filename);
/// Write an event.
void operator()(int num, double impact_param,
int ncoll, const Event& event) const;
private:
/// Internal storage of the file object.
H5::H5File file_;
};
// Add a simple scalar attribute to an HDF5 dataset.
template <typename T>
void hdf5_add_scalar_attr(
const H5::DataSet& dataset, const std::string& name, const T& value) {
const auto& datatype = hdf5::type<T>();
auto attr = dataset.createAttribute(name, datatype, H5::DataSpace{});
attr.write(datatype, &value);
}
HDF5Writer::HDF5Writer(const fs::path& filename)
: file_(filename.string(), H5F_ACC_TRUNC)
{}
void HDF5Writer::operator()(int num, double impact_param,
int ncoll, const Event& event) const {
// Prepare arguments for new HDF5 dataset.
// The dataset name is a prefix plus the event number.
const std::string name{"event_" + std::to_string(num)};
// Cache a reference to the event grid -- will need it several times.
const auto& grid = event.reduced_thickness_grid();
// Define HDF5 datatype and dataspace to match the grid.
const auto& datatype = hdf5::type<Event::Grid::element>();
std::array<hsize_t, Event::Grid::dimensionality> shape;
std::copy(grid.shape(), grid.shape() + shape.size(), shape.begin());
auto dataspace = hdf5::make_dataspace(shape);
// Set dataset storage properties.
H5::DSetCreatPropList proplist{};
// Set chunk size to the entire grid. For typical grid sizes (~100x100), this
// works out to ~80 KiB, which is pretty optimal. Anyway, it makes logical
// sense to chunk this way, since chunks must be read contiguously and there's
// no reason to read a partial grid.
proplist.setChunk(shape.size(), shape.data());
// Set gzip compression level. 4 is the default in h5py.
proplist.setDeflate(4);
// Create the new dataset and write the grid.
auto dataset = file_.createDataSet(name, datatype, dataspace, proplist);
dataset.write(grid.data(), datatype);
// Write event attributes.
hdf5_add_scalar_attr(dataset, "b", impact_param);
hdf5_add_scalar_attr(dataset, "npart", event.npart());
// Write ncoll if calculated
if (ncoll > 0) hdf5_add_scalar_attr(dataset, "ncoll", ncoll);
hdf5_add_scalar_attr(dataset, "mult", event.multiplicity());
for (const auto& ecc : event.eccentricity())
hdf5_add_scalar_attr(dataset, "e" + std::to_string(ecc.first), ecc.second);
}
#endif // TRENTO_HDF5
} // unnamed namespace
Output::Output(const VarMap& var_map) {
// Determine the required width (padding) of the event number. For example if
// there are 10 events, the numbers are 0-9 and so no padding is necessary.
// However given 11 events, the numbers are 00-10 with padded 00, 01, ...
auto nevents = var_map["number-events"].as<int>();
auto width = static_cast<int>(std::ceil(std::log10(nevents)));
// Write to stdout unless the quiet option was specified.
if (!var_map["quiet"].as<bool>()) {
writers_.emplace_back(
[width](int num, double impact_param, int ncoll, const Event& event) {
write_stream(std::cout, width, num, impact_param, ncoll, event);
}
);
}
// Possibly write to text or HDF5 files.
if (var_map.count("output")) {
const auto& output_path = var_map["output"].as<fs::path>();
if (hdf5::filename_is_hdf5(output_path)) {
#ifdef TRENTO_HDF5
if (fs::exists(output_path) && !fs::is_empty(output_path))
throw std::runtime_error{"file '" + output_path.string() +
"' exists, will not overwrite"};
writers_.emplace_back(HDF5Writer{output_path});
#else
throw std::runtime_error{"HDF5 output was not compiled"};
#endif // TRENTO_HDF5
} else {
// Text files are all written into a single directory. Require the
// directory to be initially empty to avoid accidental overwriting and/or
// spewing files into an already-used location. If the directory does not
// exist, create it.
if (fs::exists(output_path)) {
if (!fs::is_empty(output_path)) {
throw std::runtime_error{"output directory '" + output_path.string() +
"' must be empty"};
}
} else {
fs::create_directories(output_path);
}
auto header = !var_map["no-header"].as<bool>();
writers_.emplace_back(
[output_path, width, header](int num, double impact_param,
int ncoll, const Event& event) {
write_text_file(output_path, width, num,
impact_param, ncoll, event, header);
}
);
}
}
}
} // namespace trento
|
revert hdf5 output
|
revert hdf5 output
|
C++
|
mit
|
Duke-QCD/trento,Duke-QCD/trento
|
c9b2decf0d3225a5e43539dd56c38a957452f7d0
|
include/libtorrent/config.hpp
|
include/libtorrent/config.hpp
|
/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _MSC_VER
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
// 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup
#pragma warning(disable: 4996)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 0
#endif
#endif
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_SYSCTL 1
#define TORRENT_USE_IFCONF 1
// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_NETLINK 1
#define TORRENT_USE_IFCONF 1
#define TORRENT_HAS_SALEN 0
// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_USE_NETLINK 0
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
#define TORRENT_USE_GETIPFORWARDTABLE 1
// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 1
#endif
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0
// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
#define TORRENT_USE_IFCONF 1
// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif
// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif
#ifndef TORRENT_HAS_SALEN
#define TORRENT_HAS_SALEN 1
#endif
#ifndef TORRENT_USE_GETADAPTERSADDRESSES
#define TORRENT_USE_GETADAPTERSADDRESSES 0
#endif
#ifndef TORRENT_USE_NETLINK
#define TORRENT_USE_NETLINK 0
#endif
#ifndef TORRENT_USE_SYSCTL
#define TORRENT_USE_SYSCTL 0
#endif
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 0
#endif
#ifndef TORRENT_USE_LOCALE
#define TORRENT_USE_LOCALE 0
#endif
#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif
#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif
#ifndef TORRENT_USE_IFADDRS
#define TORRENT_USE_IFADDRS 0
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif
#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif
#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif
#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif
#ifndef TORRENT_HAS_STRDUP
#define TORRENT_HAS_STRDUP 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_ECLOCK \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#if !TORRENT_HAS_STRDUP
inline char* strdup(char const* str)
{
if (str == 0) return 0;
char* tmp = (char*)malloc(strlen(str) + 1);
if (tmp == 0) return 0;
strcpy(tmp, str);
return tmp;
}
#endif
// for non-exception builds
#ifdef BOOST_NO_EXCEPTIONS
#define TORRENT_TRY if (true)
#define TORRENT_CATCH(x) else if (false)
#define TORRENT_DECLARE_DUMMY(x, y) x y
#else
#define TORRENT_TRY try
#define TORRENT_CATCH(x) catch(x)
#define TORRENT_DECLARE_DUMMY(x, y)
#endif // BOOST_NO_EXCEPTIONS
#endif // TORRENT_CONFIG_HPP_INCLUDED
|
/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _MSC_VER
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
// 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup
#pragma warning(disable: 4996)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 0
#endif
#endif
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_SYSCTL 1
#define TORRENT_USE_IFCONF 1
// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_NETLINK 1
#define TORRENT_USE_IFCONF 1
#define TORRENT_HAS_SALEN 0
// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_USE_NETLINK 0
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
#define TORRENT_USE_GETIPFORWARDTABLE 1
// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 1
#endif
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0
// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
#define TORRENT_USE_IFCONF 1
// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
// ==== GNU/Hurd ===
#elif defined __GNU__
#define TORRENT_HURD
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_IFCONF 1
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif
// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif
#ifndef TORRENT_HAS_SALEN
#define TORRENT_HAS_SALEN 1
#endif
#ifndef TORRENT_USE_GETADAPTERSADDRESSES
#define TORRENT_USE_GETADAPTERSADDRESSES 0
#endif
#ifndef TORRENT_USE_NETLINK
#define TORRENT_USE_NETLINK 0
#endif
#ifndef TORRENT_USE_SYSCTL
#define TORRENT_USE_SYSCTL 0
#endif
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 0
#endif
#ifndef TORRENT_USE_LOCALE
#define TORRENT_USE_LOCALE 0
#endif
#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif
#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif
#ifndef TORRENT_USE_IFADDRS
#define TORRENT_USE_IFADDRS 0
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif
#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif
#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif
#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif
#ifndef TORRENT_HAS_STRDUP
#define TORRENT_HAS_STRDUP 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_ECLOCK \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined __APPLE__ && defined __MACH__
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#if !TORRENT_HAS_STRDUP
inline char* strdup(char const* str)
{
if (str == 0) return 0;
char* tmp = (char*)malloc(strlen(str) + 1);
if (tmp == 0) return 0;
strcpy(tmp, str);
return tmp;
}
#endif
// for non-exception builds
#ifdef BOOST_NO_EXCEPTIONS
#define TORRENT_TRY if (true)
#define TORRENT_CATCH(x) else if (false)
#define TORRENT_DECLARE_DUMMY(x, y) x y
#else
#define TORRENT_TRY try
#define TORRENT_CATCH(x) catch(x)
#define TORRENT_DECLARE_DUMMY(x, y)
#endif // BOOST_NO_EXCEPTIONS
#endif // TORRENT_CONFIG_HPP_INCLUDED
|
apply patch to fix build on GNU hurd
|
apply patch to fix build on GNU hurd
|
C++
|
bsd-3-clause
|
snowyu/libtorrent,hamedramzi/libtorrent,hamedramzi/libtorrent,TeoTwawki/libtorrent,TeoTwawki/libtorrent,hamedramzi/libtorrent,TeoTwawki/libtorrent,hamedramzi/libtorrent,snowyu/libtorrent,TeoTwawki/libtorrent,snowyu/libtorrent,snowyu/libtorrent,hamedramzi/libtorrent,snowyu/libtorrent,TeoTwawki/libtorrent,hamedramzi/libtorrent,snowyu/libtorrent,TeoTwawki/libtorrent
|
4044886cc9bb5c10c79af52340676ae939006dd6
|
include/protocol/messages.hpp
|
include/protocol/messages.hpp
|
#ifndef MESSAGES_HPP_
#define MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x01 };
char data[255];
} __attribute__((packed));
struct attitude_message_t {
enum { ID = 0x02 };
float roll;
float pitch;
float yaw;
} __attribute__((packed));
std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
|
#ifndef MESSAGES_HPP_
#define MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x01 };
char data[255];
} __attribute__((packed));
struct attitude_message_t {
enum { ID = 0x02 };
float roll;
float pitch;
float yaw;
} __attribute__((packed));
std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
case attitude_message_t::ID:
return sizeof(attitude_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
|
Add length for attitude message.
|
Add length for attitude message.
|
C++
|
mit
|
OSURoboticsClub/aerial_protocol
|
66990867b8170e484e628ae01e68ab1dc1f98f22
|
mutation.cc
|
mutation.cc
|
/*
* Copyright (C) 2014 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mutation.hh"
#include "query-result-writer.hh"
#include "flat_mutation_reader.hh"
mutation::data::data(dht::decorated_key&& key, schema_ptr&& schema)
: _schema(std::move(schema))
, _dk(std::move(key))
, _p(_schema)
{ }
mutation::data::data(partition_key&& key_, schema_ptr&& schema)
: _schema(std::move(schema))
, _dk(dht::global_partitioner().decorate_key(*_schema, std::move(key_)))
, _p(_schema)
{ }
mutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, const mutation_partition& mp)
: _schema(std::move(schema))
, _dk(std::move(key))
, _p(mp)
{ }
mutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, mutation_partition&& mp)
: _schema(std::move(schema))
, _dk(std::move(key))
, _p(std::move(mp))
{ }
void mutation::set_static_cell(const column_definition& def, atomic_cell_or_collection&& value) {
partition().static_row().apply(def, std::move(value));
}
void mutation::set_static_cell(const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) {
auto column_def = schema()->get_column_definition(name);
if (!column_def) {
throw std::runtime_error(sprint("no column definition found for '%s'", name));
}
if (!column_def->is_static()) {
throw std::runtime_error(sprint("column '%s' is not static", name));
}
partition().static_row().apply(*column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));
}
void mutation::set_clustered_cell(const clustering_key& key, const bytes& name, const data_value& value,
api::timestamp_type timestamp, ttl_opt ttl) {
auto column_def = schema()->get_column_definition(name);
if (!column_def) {
throw std::runtime_error(sprint("no column definition found for '%s'", name));
}
return set_clustered_cell(key, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));
}
void mutation::set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection&& value) {
auto& row = partition().clustered_row(*schema(), key).cells();
row.apply(def, std::move(value));
}
void mutation::set_cell(const clustering_key_prefix& prefix, const bytes& name, const data_value& value,
api::timestamp_type timestamp, ttl_opt ttl) {
auto column_def = schema()->get_column_definition(name);
if (!column_def) {
throw std::runtime_error(sprint("no column definition found for '%s'", name));
}
return set_cell(prefix, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));
}
void mutation::set_cell(const clustering_key_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) {
if (def.is_static()) {
set_static_cell(def, std::move(value));
} else if (def.is_regular()) {
set_clustered_cell(prefix, def, std::move(value));
} else {
throw std::runtime_error("attemting to store into a key cell");
}
}
bool mutation::operator==(const mutation& m) const {
return decorated_key().equal(*schema(), m.decorated_key())
&& partition().equal(*schema(), m.partition(), *m.schema());
}
bool mutation::operator!=(const mutation& m) const {
return !(*this == m);
}
void
mutation::query(query::result::builder& builder,
const query::partition_slice& slice,
gc_clock::time_point now,
uint32_t row_limit) &&
{
auto pb = builder.add_partition(*schema(), key());
auto is_reversed = slice.options.contains<query::partition_slice::option::reversed>();
mutation_partition& p = partition();
auto limit = std::min(row_limit, slice.partition_row_limit());
p.compact_for_query(*schema(), now, slice.row_ranges(*schema(), key()), is_reversed, limit);
p.query_compacted(pb, *schema(), limit);
}
query::result
mutation::query(const query::partition_slice& slice,
query::result_request request,
gc_clock::time_point now, uint32_t row_limit) &&
{
query::result::builder builder(slice, request, { });
std::move(*this).query(builder, slice, now, row_limit);
return builder.build();
}
query::result
mutation::query(const query::partition_slice& slice,
query::result_request request,
gc_clock::time_point now, uint32_t row_limit) const&
{
return mutation(*this).query(slice, request, now, row_limit);
}
size_t
mutation::live_row_count(gc_clock::time_point query_time) const {
return partition().live_row_count(*schema(), query_time);
}
bool
mutation_decorated_key_less_comparator::operator()(const mutation& m1, const mutation& m2) const {
return m1.decorated_key().less_compare(*m1.schema(), m2.decorated_key());
}
boost::iterator_range<std::vector<mutation>::const_iterator>
slice(const std::vector<mutation>& partitions, const dht::partition_range& r) {
struct cmp {
bool operator()(const dht::ring_position& pos, const mutation& m) const {
return m.decorated_key().tri_compare(*m.schema(), pos) > 0;
};
bool operator()(const mutation& m, const dht::ring_position& pos) const {
return m.decorated_key().tri_compare(*m.schema(), pos) < 0;
};
};
return boost::make_iterator_range(
r.start()
? (r.start()->is_inclusive()
? std::lower_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp())
: std::upper_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp()))
: partitions.cbegin(),
r.end()
? (r.end()->is_inclusive()
? std::upper_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp())
: std::lower_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp()))
: partitions.cend());
}
void
mutation::upgrade(const schema_ptr& new_schema) {
if (_ptr->_schema != new_schema) {
schema_ptr s = new_schema;
partition().upgrade(*schema(), *new_schema);
_ptr->_schema = std::move(s);
}
}
void mutation::apply(mutation&& m) {
partition().apply(*schema(), std::move(m.partition()), *m.schema());
}
void mutation::apply(const mutation& m) {
partition().apply(*schema(), m.partition(), *m.schema());
}
void mutation::apply(const mutation_fragment& mf) {
partition().apply(*schema(), mf);
}
mutation& mutation::operator=(const mutation& m) {
return *this = mutation(m);
}
mutation mutation::operator+(const mutation& other) const {
auto m = *this;
m.apply(other);
return m;
}
mutation& mutation::operator+=(const mutation& other) {
apply(other);
return *this;
}
mutation& mutation::operator+=(mutation&& other) {
apply(std::move(other));
return *this;
}
mutation mutation::sliced(const query::clustering_row_ranges& ranges) const {
auto m = mutation(schema(), decorated_key(), mutation_partition(partition(), *schema(), ranges));
m.partition().row_tombstones().trim(*schema(), ranges);
return m;
}
class mutation_rebuilder {
mutation _m;
size_t _remaining_limit;
public:
mutation_rebuilder(dht::decorated_key dk, schema_ptr s)
: _m(std::move(dk), std::move(s)), _remaining_limit(0) {
}
stop_iteration consume(tombstone t) {
_m.partition().apply(t);
return stop_iteration::no;
}
stop_iteration consume(range_tombstone&& rt) {
_m.partition().apply_row_tombstone(*_m.schema(), std::move(rt));
return stop_iteration::no;
}
stop_iteration consume(static_row&& sr) {
_m.partition().static_row().apply(*_m.schema(), column_kind::static_column, std::move(sr.cells()));
return stop_iteration::no;
}
stop_iteration consume(clustering_row&& cr) {
auto& dr = _m.partition().clustered_row(*_m.schema(), std::move(cr.key()));
dr.apply(cr.tomb());
dr.apply(cr.marker());
dr.cells().apply(*_m.schema(), column_kind::regular_column, std::move(cr.cells()));
return stop_iteration::no;
}
mutation_opt consume_end_of_stream() {
return mutation_opt(std::move(_m));
}
};
future<mutation_opt> mutation_from_streamed_mutation(streamed_mutation_opt sm) {
if (!sm) {
return make_ready_future<mutation_opt>();
}
return do_with(std::move(*sm), [] (auto& sm) {
return consume(sm, mutation_rebuilder(sm.decorated_key(), sm.schema()));
});
}
future<mutation> mutation_from_streamed_mutation(streamed_mutation& sm) {
return consume(sm, mutation_rebuilder(sm.decorated_key(), sm.schema())).then([] (mutation_opt&& mo) {
return std::move(*mo);
});
}
future<mutation_opt> read_mutation_from_flat_mutation_reader(schema_ptr s, flat_mutation_reader& r) {
if (r.is_buffer_empty()) {
if (r.is_end_of_stream()) {
return make_ready_future<mutation_opt>();
}
return r.fill_buffer().then([&r, s = std::move(s)] {
return read_mutation_from_flat_mutation_reader(std::move(s), r);
});
}
// r.is_buffer_empty() is always false at this point
struct adapter {
schema_ptr _s;
stdx::optional<mutation_rebuilder> _builder;
adapter(schema_ptr s) : _s(std::move(s)) { }
void consume_new_partition(const dht::decorated_key& dk) {
_builder = mutation_rebuilder(dk, std::move(_s));
}
stop_iteration consume(tombstone t) {
assert(_builder);
return _builder->consume(t);
}
stop_iteration consume(range_tombstone&& rt) {
assert(_builder);
return _builder->consume(std::move(rt));
}
stop_iteration consume(static_row&& sr) {
assert(_builder);
return _builder->consume(std::move(sr));
}
stop_iteration consume(clustering_row&& cr) {
assert(_builder);
return _builder->consume(std::move(cr));
}
stop_iteration consume_end_of_partition() {
assert(_builder);
return stop_iteration::yes;
}
mutation_opt consume_end_of_stream() {
if (!_builder) {
return mutation_opt();
}
return _builder->consume_end_of_stream();
}
};
return r.consume(adapter(std::move(s)));
}
std::ostream& operator<<(std::ostream& os, const mutation& m) {
const ::schema& s = *m.schema();
fprint(os, "{%s.%s key %s data ", s.ks_name(), s.cf_name(), m.decorated_key());
os << m.partition() << "}";
return os;
}
|
/*
* Copyright (C) 2014 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mutation.hh"
#include "query-result-writer.hh"
#include "flat_mutation_reader.hh"
mutation::data::data(dht::decorated_key&& key, schema_ptr&& schema)
: _schema(std::move(schema))
, _dk(std::move(key))
, _p(_schema)
{ }
mutation::data::data(partition_key&& key_, schema_ptr&& schema)
: _schema(std::move(schema))
, _dk(dht::global_partitioner().decorate_key(*_schema, std::move(key_)))
, _p(_schema)
{ }
mutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, const mutation_partition& mp)
: _schema(std::move(schema))
, _dk(std::move(key))
, _p(mp)
{ }
mutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, mutation_partition&& mp)
: _schema(std::move(schema))
, _dk(std::move(key))
, _p(std::move(mp))
{ }
void mutation::set_static_cell(const column_definition& def, atomic_cell_or_collection&& value) {
partition().static_row().apply(def, std::move(value));
}
void mutation::set_static_cell(const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) {
auto column_def = schema()->get_column_definition(name);
if (!column_def) {
throw std::runtime_error(sprint("no column definition found for '%s'", name));
}
if (!column_def->is_static()) {
throw std::runtime_error(sprint("column '%s' is not static", name));
}
partition().static_row().apply(*column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));
}
void mutation::set_clustered_cell(const clustering_key& key, const bytes& name, const data_value& value,
api::timestamp_type timestamp, ttl_opt ttl) {
auto column_def = schema()->get_column_definition(name);
if (!column_def) {
throw std::runtime_error(sprint("no column definition found for '%s'", name));
}
return set_clustered_cell(key, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));
}
void mutation::set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection&& value) {
auto& row = partition().clustered_row(*schema(), key).cells();
row.apply(def, std::move(value));
}
void mutation::set_cell(const clustering_key_prefix& prefix, const bytes& name, const data_value& value,
api::timestamp_type timestamp, ttl_opt ttl) {
auto column_def = schema()->get_column_definition(name);
if (!column_def) {
throw std::runtime_error(sprint("no column definition found for '%s'", name));
}
return set_cell(prefix, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));
}
void mutation::set_cell(const clustering_key_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) {
if (def.is_static()) {
set_static_cell(def, std::move(value));
} else if (def.is_regular()) {
set_clustered_cell(prefix, def, std::move(value));
} else {
throw std::runtime_error("attemting to store into a key cell");
}
}
bool mutation::operator==(const mutation& m) const {
return decorated_key().equal(*schema(), m.decorated_key())
&& partition().equal(*schema(), m.partition(), *m.schema());
}
bool mutation::operator!=(const mutation& m) const {
return !(*this == m);
}
void
mutation::query(query::result::builder& builder,
const query::partition_slice& slice,
gc_clock::time_point now,
uint32_t row_limit) &&
{
auto pb = builder.add_partition(*schema(), key());
auto is_reversed = slice.options.contains<query::partition_slice::option::reversed>();
mutation_partition& p = partition();
auto limit = std::min(row_limit, slice.partition_row_limit());
p.compact_for_query(*schema(), now, slice.row_ranges(*schema(), key()), is_reversed, limit);
p.query_compacted(pb, *schema(), limit);
}
query::result
mutation::query(const query::partition_slice& slice,
query::result_request request,
gc_clock::time_point now, uint32_t row_limit) &&
{
query::result::builder builder(slice, request, { });
std::move(*this).query(builder, slice, now, row_limit);
return builder.build();
}
query::result
mutation::query(const query::partition_slice& slice,
query::result_request request,
gc_clock::time_point now, uint32_t row_limit) const&
{
return mutation(*this).query(slice, request, now, row_limit);
}
size_t
mutation::live_row_count(gc_clock::time_point query_time) const {
return partition().live_row_count(*schema(), query_time);
}
bool
mutation_decorated_key_less_comparator::operator()(const mutation& m1, const mutation& m2) const {
return m1.decorated_key().less_compare(*m1.schema(), m2.decorated_key());
}
boost::iterator_range<std::vector<mutation>::const_iterator>
slice(const std::vector<mutation>& partitions, const dht::partition_range& r) {
struct cmp {
bool operator()(const dht::ring_position& pos, const mutation& m) const {
return m.decorated_key().tri_compare(*m.schema(), pos) > 0;
};
bool operator()(const mutation& m, const dht::ring_position& pos) const {
return m.decorated_key().tri_compare(*m.schema(), pos) < 0;
};
};
return boost::make_iterator_range(
r.start()
? (r.start()->is_inclusive()
? std::lower_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp())
: std::upper_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp()))
: partitions.cbegin(),
r.end()
? (r.end()->is_inclusive()
? std::upper_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp())
: std::lower_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp()))
: partitions.cend());
}
void
mutation::upgrade(const schema_ptr& new_schema) {
if (_ptr->_schema != new_schema) {
schema_ptr s = new_schema;
partition().upgrade(*schema(), *new_schema);
_ptr->_schema = std::move(s);
}
}
void mutation::apply(mutation&& m) {
partition().apply(*schema(), std::move(m.partition()), *m.schema());
}
void mutation::apply(const mutation& m) {
partition().apply(*schema(), m.partition(), *m.schema());
}
void mutation::apply(const mutation_fragment& mf) {
partition().apply(*schema(), mf);
}
mutation& mutation::operator=(const mutation& m) {
return *this = mutation(m);
}
mutation mutation::operator+(const mutation& other) const {
auto m = *this;
m.apply(other);
return m;
}
mutation& mutation::operator+=(const mutation& other) {
apply(other);
return *this;
}
mutation& mutation::operator+=(mutation&& other) {
apply(std::move(other));
return *this;
}
mutation mutation::sliced(const query::clustering_row_ranges& ranges) const {
auto m = mutation(schema(), decorated_key(), mutation_partition(partition(), *schema(), ranges));
m.partition().row_tombstones().trim(*schema(), ranges);
return m;
}
class mutation_rebuilder {
mutation _m;
size_t _remaining_limit;
public:
mutation_rebuilder(dht::decorated_key dk, schema_ptr s)
: _m(std::move(dk), std::move(s)), _remaining_limit(0) {
}
stop_iteration consume(tombstone t) {
_m.partition().apply(t);
return stop_iteration::no;
}
stop_iteration consume(range_tombstone&& rt) {
_m.partition().apply_row_tombstone(*_m.schema(), std::move(rt));
return stop_iteration::no;
}
stop_iteration consume(static_row&& sr) {
_m.partition().static_row().apply(*_m.schema(), column_kind::static_column, std::move(sr.cells()));
return stop_iteration::no;
}
stop_iteration consume(clustering_row&& cr) {
auto& dr = _m.partition().clustered_row(*_m.schema(), std::move(cr.key()));
dr.apply(cr.tomb());
dr.apply(cr.marker());
dr.cells().apply(*_m.schema(), column_kind::regular_column, std::move(cr.cells()));
return stop_iteration::no;
}
mutation_opt consume_end_of_stream() {
return mutation_opt(std::move(_m));
}
};
future<mutation_opt> mutation_from_streamed_mutation(streamed_mutation_opt sm) {
if (!sm) {
return make_ready_future<mutation_opt>();
}
return do_with(std::move(*sm), [] (auto& sm) {
return consume(sm, mutation_rebuilder(sm.decorated_key(), sm.schema()));
});
}
future<mutation> mutation_from_streamed_mutation(streamed_mutation& sm) {
return consume(sm, mutation_rebuilder(sm.decorated_key(), sm.schema())).then([] (mutation_opt&& mo) {
return std::move(*mo);
});
}
future<mutation_opt> read_mutation_from_flat_mutation_reader(schema_ptr s, flat_mutation_reader& r) {
if (r.is_buffer_empty()) {
if (r.is_end_of_stream()) {
return make_ready_future<mutation_opt>();
}
return r.fill_buffer().then([&r, s = std::move(s)] {
return read_mutation_from_flat_mutation_reader(std::move(s), r);
});
}
// r.is_buffer_empty() is always false at this point
struct adapter {
schema_ptr _s;
stdx::optional<mutation_rebuilder> _builder;
adapter(schema_ptr s) : _s(std::move(s)) { }
void consume_new_partition(const dht::decorated_key& dk) {
_builder = mutation_rebuilder(dk, std::move(_s));
}
stop_iteration consume(tombstone t) {
assert(_builder);
return _builder->consume(t);
}
stop_iteration consume(range_tombstone&& rt) {
assert(_builder);
return _builder->consume(std::move(rt));
}
stop_iteration consume(static_row&& sr) {
assert(_builder);
return _builder->consume(std::move(sr));
}
stop_iteration consume(clustering_row&& cr) {
assert(_builder);
return _builder->consume(std::move(cr));
}
stop_iteration consume_end_of_partition() {
assert(_builder);
return stop_iteration::yes;
}
mutation_opt consume_end_of_stream() {
if (!_builder) {
return mutation_opt();
}
return _builder->consume_end_of_stream();
}
};
return r.consume(adapter(std::move(s)));
}
std::ostream& operator<<(std::ostream& os, const mutation& m) {
const ::schema& s = *m.schema();
fprint(os, "{%s.%s %s ", s.ks_name(), s.cf_name(), m.decorated_key());
os << m.partition() << "}";
return os;
}
|
Make printout more concise
|
mutation: Make printout more concise
Before:
{ks.cf key {key: pk{000c706b30303030303030303030}, token:-2018791535786252460} data {mutation_partition:
After:
{ks.cf {key: pk{000c706b30303030303030303030}, token:-2018791535786252460} {mutation_partition:
|
C++
|
agpl-3.0
|
duarten/scylla,scylladb/scylla,duarten/scylla,scylladb/scylla,scylladb/scylla,avikivity/scylla,avikivity/scylla,duarten/scylla,avikivity/scylla,scylladb/scylla
|
d1382a680d7af66720b2a30c57b32de77aa25623
|
doc/snippets/IOFormat.cpp
|
doc/snippets/IOFormat.cpp
|
std::string sep = "\n----------------------------------------\n";
Matrix3f m1;
m1 << 1.111111, 2, 3.33333, 4, 5, 6, 7, 8.888888, 9;
IOFormat CommaInitFmt(4, Raw, ", ", ", ", "", "", " << ", ";");
IOFormat CleanFmt(4, AlignCols, ", ", "\n", "[", "]");
IOFormat OctaveFmt(4, AlignCols, ", ", ";\n", "", "", "[", "]");
IOFormat HeavyFmt(4, AlignCols, ", ", ";\n", "[", "]", "[", "]");
std::cout << m1 << sep;
std::cout << m1.format(CommaInitFmt) << sep;
std::cout << m1.format(CleanFmt) << sep;
std::cout << m1.format(OctaveFmt) << sep;
std::cout << m1.format(HeavyFmt) << sep;
|
std::string sep = "\n----------------------------------------\n";
Matrix3d m1;
m1 << 1.111111, 2, 3.33333, 4, 5, 6, 7, 8.888888, 9;
IOFormat CommaInitFmt(StreamPrecision, DontAlignCols, ", ", ", ", "", "", " << ", ";");
IOFormat CleanFmt(4, 0, ", ", "\n", "[", "]");
IOFormat OctaveFmt(StreamPrecision, 0, ", ", ";\n", "", "", "[", "]");
IOFormat HeavyFmt(FullPrecision, 0, ", ", ";\n", "[", "]", "[", "]");
std::cout << m1 << sep;
std::cout << m1.format(CommaInitFmt) << sep;
std::cout << m1.format(CleanFmt) << sep;
std::cout << m1.format(OctaveFmt) << sep;
std::cout << m1.format(HeavyFmt) << sep;
|
update snippet
|
update snippet
|
C++
|
bsd-3-clause
|
mjbshaw/Eigen,madlib/eigen_backup,madlib/eigen_backup,rotorliu/eigen,mjbshaw/Eigen,mjbshaw/Eigen,rotorliu/eigen,rotorliu/eigen,mjbshaw/Eigen,rotorliu/eigen,madlib/eigen_backup,madlib/eigen_backup
|
eafc66fccd9b2dcf7d60ac15c18f3972b51445f1
|
Modules/DiffusionImaging/MiniApps/TensorReconstruction.cpp
|
Modules/DiffusionImaging/MiniApps/TensorReconstruction.cpp
|
/*===================================================================
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 "mitkDiffusionImage.h"
#include "mitkBaseData.h"
#include <mitkIOUtil.h>
#include <itkDiffusionTensor3DReconstructionImageFilter.h>
#include <itkDiffusionTensor3D.h>
#include <itkImageFileWriter.h>
#include <itkNrrdImageIO.h>
#include "mitkCommandLineParser.h"
#include <itksys/SystemTools.hxx>
using namespace mitk;
/**
* Convert files from one ending to the other
*/
int main(int argc, char* argv[])
{
std::cout << "TensorReconstruction";
mitkCommandLineParser parser;
parser.setArgumentPrefix("--", "-");
parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input file", "input raw dwi (.dwi or .fsl/.fslgz)", us::Any(), false);
parser.addArgument("outFile", "o", mitkCommandLineParser::OutputFile, "Output file", "output file", us::Any(), false);
parser.addArgument("b0Threshold", "t", mitkCommandLineParser::Int, "b0 threshold", "baseline image intensity threshold", 0, true);
parser.setCategory("Preprocessing Tools");
parser.setTitle("Tensor Reconstruction");
parser.setDescription("");
parser.setContributor("MBI");
map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0)
return EXIT_FAILURE;
std::string inFileName = us::any_cast<string>(parsedArgs["input"]);
std::string outfilename = us::any_cast<string>(parsedArgs["outFile"]);
outfilename = itksys::SystemTools::GetFilenamePath(outfilename)+"/"+itksys::SystemTools::GetFilenameWithoutExtension(outfilename);
outfilename += ".dti";
int threshold = 0;
if (parsedArgs.count("b0Threshold"))
threshold = us::any_cast<int>(parsedArgs["b0Threshold"]);
try
{
std::vector<BaseData::Pointer> infile = IOUtil::Load( inFileName );
DiffusionImage<short>::Pointer dwi = dynamic_cast<DiffusionImage<short>*>(infile.at(0).GetPointer());
typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, float > TensorReconstructionImageFilterType;
TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New();
filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() );
filter->SetBValue(dwi->GetReferenceBValue());
filter->SetThreshold(threshold);
filter->Update();
// Save tensor image
itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
io->SetFileType( itk::ImageIOBase::Binary );
io->UseCompressionOn();
itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::Pointer writer = itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName(outfilename);
writer->SetImageIO(io);
writer->UseCompressionOn();
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "Exception: " << err;
}
catch ( std::exception err)
{
std::cout << "Exception: " << err.what();
}
catch ( ... )
{
std::cout << "Exception!";
}
return EXIT_SUCCESS;
}
|
/*===================================================================
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 "mitkDiffusionImage.h"
#include "mitkBaseData.h"
#include <mitkIOUtil.h>
#include <itkDiffusionTensor3DReconstructionImageFilter.h>
#include <itkDiffusionTensor3D.h>
#include <itkImageFileWriter.h>
#include <itkNrrdImageIO.h>
#include "mitkCommandLineParser.h"
#include <itksys/SystemTools.hxx>
using namespace mitk;
/**
* Convert files from one ending to the other
*/
int main(int argc, char* argv[])
{
std::cout << "TensorReconstruction";
mitkCommandLineParser parser;
parser.setArgumentPrefix("--", "-");
parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input file", "input raw dwi (.dwi or .fsl/.fslgz)", us::Any(), false);
parser.addArgument("outFile", "o", mitkCommandLineParser::OutputFile, "Output file", "output file", us::Any(), false);
parser.addArgument("b0Threshold", "t", mitkCommandLineParser::Int, "b0 threshold", "baseline image intensity threshold", 0, true);
parser.setCategory("Preprocessing Tools");
parser.setTitle("Tensor Reconstruction");
parser.setDescription("");
parser.setContributor("MBI");
map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0)
return EXIT_FAILURE;
std::string inFileName = us::any_cast<string>(parsedArgs["input"]);
std::string outfilename = us::any_cast<string>(parsedArgs["outFile"]);
outfilename = itksys::SystemTools::GetFilenamePath(outfilename)+"/"+itksys::SystemTools::GetFilenameWithoutExtension(outfilename);
outfilename += ".dti";
int threshold = 0;
if (parsedArgs.count("b0Threshold"))
threshold = us::any_cast<int>(parsedArgs["b0Threshold"]);
try
{
std::vector<BaseData::Pointer> infile = IOUtil::Load( inFileName );
DiffusionImage<short>::Pointer dwi = dynamic_cast<DiffusionImage<short>*>(infile.at(0).GetPointer());
typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, float > TensorReconstructionImageFilterType;
TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New();
filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() );
filter->SetBValue(dwi->GetReferenceBValue());
filter->SetThreshold(threshold);
filter->Update();
// Save tensor image
itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
io->SetFileType( itk::ImageIOBase::Binary );
io->UseCompressionOn();
itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::Pointer writer = itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName(outfilename);
writer->SetImageIO(io);
writer->UseCompressionOn();
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "Exception: " << err;
}
catch ( std::exception err)
{
std::cout << "Exception: " << err.what();
}
catch ( ... )
{
std::cout << "Exception!";
}
return EXIT_SUCCESS;
}
|
Revert "COMP: Force continuous dartclients to run."
|
Revert "COMP: Force continuous dartclients to run."
This reverts commit c9709b3b694c0aa6687e3499e2b6302bd2508146.
|
C++
|
bsd-3-clause
|
fmilano/mitk,iwegner/MITK,danielknorr/MITK,NifTK/MITK,fmilano/mitk,RabadanLab/MITKats,MITK/MITK,MITK/MITK,fmilano/mitk,MITK/MITK,RabadanLab/MITKats,fmilano/mitk,danielknorr/MITK,iwegner/MITK,NifTK/MITK,RabadanLab/MITKats,RabadanLab/MITKats,NifTK/MITK,RabadanLab/MITKats,RabadanLab/MITKats,danielknorr/MITK,NifTK/MITK,iwegner/MITK,iwegner/MITK,danielknorr/MITK,NifTK/MITK,MITK/MITK,fmilano/mitk,danielknorr/MITK,fmilano/mitk,fmilano/mitk,MITK/MITK,iwegner/MITK,NifTK/MITK,MITK/MITK,danielknorr/MITK,danielknorr/MITK,iwegner/MITK
|
2bfb837c2624503b5c8899786c66fa137b2dd356
|
PWGLF/RESONANCES/macros/mini/AddAnalysisTaskTPCKStarTest.C
|
PWGLF/RESONANCES/macros/mini/AddAnalysisTaskTPCKStarTest.C
|
/***************************************************************************
[email protected] - last modified on 06/08/2012
//
// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
// 1) flag to know if running on MC or data
// 2) path where all configs are stored
// ---
// Returns:
// kTRUE --> initialization successful
// kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddAnalysisTaskTPCKStarTest
(
Bool_t isMC,
Bool_t isPP,
Float_t nsigmaPi = 2.0,
Float_t nsigmaKa = 2.0,
Bool_t enableMonitor = kTRUE,
Bool_t IsMcTrueOnly = kFALSE,
UInt_t triggerMask = AliVEvent::kMB,
Int_t PbPb2011CentFlat = 0,
Int_t nmix = 0,
Float_t maxDiffVzMix = 1.0,
Float_t maxDiffMultMix = 10.0,
Float_t maxDiffAngleMixDeg = 20.0,
TString outNameSuffix = "",
TString optSys = "Default"
)
{
//
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddAnalysisTaskTPCKStar_Test", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("TPCKStar%s%s_%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"), outNameSuffix.Data() );
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
//centrality flatening patch LHC11h
if(PbPb2011CentFlat)
task->SetUseCentralityPatchPbPb2011(PbPb2011CentFlat);
//task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
//task->SelectCollisionCandidates(triggerMask);
task->UseESDTriggerMask(triggerMask);
if (isPP)
task->UseMultiplicity("QUALITY");
else
task->UseCentrality("V0M");
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
if (!isPP) task->SetMaxDiffAngle(maxDiffAngleMixDeg*TMath::DegToRad()); //set angle diff in rad
::Info("AddAnalysisTaskTPCKStar_Test", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n max diff EP angle = %5.3f deg", nmix, maxDiffVzMix, maxDiffMultMix, (isPP ? 0.0 : maxDiffAngleMixDeg)));
mgr->AddTask(task);
//
// -- EVENT CUTS (same for all configs) ---------------------------------------------------------
//
// cut on primary vertex:
// - 2nd argument --> |Vz| range
// - 3rd argument --> minimum required number of contributors
// - 4th argument --> tells if TPC stand-alone vertexes must be accepted
AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", 100.0, 0, kFALSE);
if (isPP) cutVertex->SetCheckPileUp(kTRUE); // set the check for pileup
// define and fill cut set for event cut
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(cutVertex);
eventCuts->SetCutScheme(cutVertex->GetName());
// set cuts in task
task->SetEventCuts(eventCuts);
//
// -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//
//vertex
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 400, -20.0, 20.0);
//multiplicity or centrality
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
if (isPP)
outMult->AddAxis(multID, 400, 0.0, 400.0);
else
outMult->AddAxis(multID, 100, 0.0, 100.0);
//event plane (only for PbPb)
Int_t planeID = task->CreateValue(AliRsnMiniValue::kPlaneAngle, kFALSE);
AliRsnMiniOutput *outPlane = task->CreateOutput("eventPlane", "HIST", "EVENT");
if (!isPP)
outPlane->AddAxis(planeID, 180, 0.0, TMath::Pi());
//
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(-0.5, 0.5);
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
//
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
if(!isMC){
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigTPCanalysisKStarTest.C");
//gROOT->LoadMacro("ConfigTPCanalysisKStarTest.C");
if (!ConfigTPCanalysisKStarTest(task, isMC, isPP, "", cutsPair, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly,313,optSys.Data())) return 0x0;
}
else {
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigTPCanalysisKStarTest.C");
//gROOT->LoadMacro("ConfigTPCanalysisKStarTest.C");
if (!ConfigTPCanalysisKStarTest(task, isMC, isPP, "Part", cutsPair, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly, 313,optSys.Data())) return 0x0; //K*
if (!ConfigTPCanalysisKStarTest(task, isMC, isPP, "AntiPart", cutsPair, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly, -313,optSys.Data())) return 0x0; //anti-K*
}
//
// -- CONTAINERS --------------------------------------------------------------------------------
//
TString outputFileName = AliAnalysisManager::GetCommonFileName();
// outputFileName += ":Rsn";
Printf("AddAnalysisTaskTPCKStar_Test - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
|
/***************************************************************************
[email protected] - last modified on 06/08/2012
//
// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
// 1) flag to know if running on MC or data
// 2) path where all configs are stored
// ---
// Returns:
// kTRUE --> initialization successful
// kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddAnalysisTaskTPCKStarTest
(
Bool_t isMC,
Bool_t isPP,
Float_t nsigmaPi = 2.0,
Float_t nsigmaKa = 2.0,
Bool_t enableMonitor = kTRUE,
Bool_t IsMcTrueOnly = kFALSE,
UInt_t triggerMask = AliVEvent::kMB,
Int_t PbPb2011CentFlat = 0,
Int_t nmix = 0,
Float_t maxDiffVzMix = 1.0,
Float_t maxDiffMultMix = 10.0,
Float_t maxDiffAngleMixDeg = 20.0,
TString outNameSuffix = "",
TString optSys = "Default"
)
{
//
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddAnalysisTaskTPCKStar_Test", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("TPCKStar%s%s_%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"), outNameSuffix.Data() );
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
//centrality flatening patch LHC11h
if(PbPb2011CentFlat)
task->SetUseCentralityPatchPbPb2011(PbPb2011CentFlat);
//task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
//task->SelectCollisionCandidates(triggerMask);
task->UseESDTriggerMask(triggerMask);
if (isPP)
task->UseMultiplicity("QUALITY");
else
task->UseCentrality("V0M");
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
if (!isPP) task->SetMaxDiffAngle(maxDiffAngleMixDeg*TMath::DegToRad()); //set angle diff in rad
::Info("AddAnalysisTaskTPCKStar_Test", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n max diff EP angle = %5.3f deg", nmix, maxDiffVzMix, maxDiffMultMix, (isPP ? 0.0 : maxDiffAngleMixDeg)));
mgr->AddTask(task);
//
// -- EVENT CUTS (same for all configs) ---------------------------------------------------------
//
// cut on primary vertex:
// - 2nd argument --> |Vz| range
// - 3rd argument --> minimum required number of contributors
// - 4th argument --> tells if TPC stand-alone vertexes must be accepted
AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", 10.0, 0, kFALSE);
if (isPP) cutVertex->SetCheckPileUp(kTRUE); // set the check for pileup
// define and fill cut set for event cut
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(cutVertex);
eventCuts->SetCutScheme(cutVertex->GetName());
// set cuts in task
task->SetEventCuts(eventCuts);
//
// -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//
//vertex
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 400, -20.0, 20.0);
//multiplicity or centrality
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
if (isPP)
outMult->AddAxis(multID, 400, 0.0, 400.0);
else
outMult->AddAxis(multID, 100, 0.0, 100.0);
//event plane (only for PbPb)
Int_t planeID = task->CreateValue(AliRsnMiniValue::kPlaneAngle, kFALSE);
AliRsnMiniOutput *outPlane = task->CreateOutput("eventPlane", "HIST", "EVENT");
if (!isPP)
outPlane->AddAxis(planeID, 180, 0.0, TMath::Pi());
//
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(-0.5, 0.5);
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
//
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
if(!isMC){
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigTPCanalysisKStarTest.C");
//gROOT->LoadMacro("ConfigTPCanalysisKStarTest.C");
if (!ConfigTPCanalysisKStarTest(task, isMC, isPP, "", cutsPair, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly,313,optSys.Data())) return 0x0;
}
else {
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigTPCanalysisKStarTest.C");
//gROOT->LoadMacro("ConfigTPCanalysisKStarTest.C");
if (!ConfigTPCanalysisKStarTest(task, isMC, isPP, "Part", cutsPair, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly, 313,optSys.Data())) return 0x0; //K*
if (!ConfigTPCanalysisKStarTest(task, isMC, isPP, "AntiPart", cutsPair, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly, -313,optSys.Data())) return 0x0; //anti-K*
}
//
// -- CONTAINERS --------------------------------------------------------------------------------
//
TString outputFileName = AliAnalysisManager::GetCommonFileName();
// outputFileName += ":Rsn";
Printf("AddAnalysisTaskTPCKStar_Test - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
|
Fix vertex z cut (Kishora)
|
Fix vertex z cut (Kishora)
|
C++
|
bsd-3-clause
|
carstooon/AliPhysics,hzanoli/AliPhysics,mbjadhav/AliPhysics,fcolamar/AliPhysics,lfeldkam/AliPhysics,dmuhlhei/AliPhysics,preghenella/AliPhysics,carstooon/AliPhysics,yowatana/AliPhysics,lfeldkam/AliPhysics,hcab14/AliPhysics,mbjadhav/AliPhysics,ALICEHLT/AliPhysics,victor-gonzalez/AliPhysics,alisw/AliPhysics,dmuhlhei/AliPhysics,akubera/AliPhysics,mpuccio/AliPhysics,dstocco/AliPhysics,amaringarcia/AliPhysics,mvala/AliPhysics,hzanoli/AliPhysics,mpuccio/AliPhysics,jgronefe/AliPhysics,pchrista/AliPhysics,ALICEHLT/AliPhysics,mazimm/AliPhysics,pbatzing/AliPhysics,AudreyFrancisco/AliPhysics,AudreyFrancisco/AliPhysics,rihanphys/AliPhysics,dmuhlhei/AliPhysics,rbailhac/AliPhysics,aaniin/AliPhysics,jgronefe/AliPhysics,ppribeli/AliPhysics,AMechler/AliPhysics,akubera/AliPhysics,btrzecia/AliPhysics,ALICEHLT/AliPhysics,fbellini/AliPhysics,preghenella/AliPhysics,mvala/AliPhysics,lcunquei/AliPhysics,dlodato/AliPhysics,mvala/AliPhysics,kreisl/AliPhysics,SHornung1/AliPhysics,SHornung1/AliPhysics,nschmidtALICE/AliPhysics,hcab14/AliPhysics,kreisl/AliPhysics,pchrista/AliPhysics,jmargutt/AliPhysics,victor-gonzalez/AliPhysics,ppribeli/AliPhysics,sebaleh/AliPhysics,btrzecia/AliPhysics,yowatana/AliPhysics,dlodato/AliPhysics,jmargutt/AliPhysics,aaniin/AliPhysics,lfeldkam/AliPhysics,fbellini/AliPhysics,jgronefe/AliPhysics,lcunquei/AliPhysics,AudreyFrancisco/AliPhysics,lcunquei/AliPhysics,nschmidtALICE/AliPhysics,amatyja/AliPhysics,mpuccio/AliPhysics,kreisl/AliPhysics,yowatana/AliPhysics,AMechler/AliPhysics,fbellini/AliPhysics,SHornung1/AliPhysics,ALICEHLT/AliPhysics,amaringarcia/AliPhysics,dlodato/AliPhysics,mpuccio/AliPhysics,alisw/AliPhysics,ppribeli/AliPhysics,sebaleh/AliPhysics,lfeldkam/AliPhysics,dstocco/AliPhysics,AMechler/AliPhysics,hcab14/AliPhysics,lfeldkam/AliPhysics,nschmidtALICE/AliPhysics,carstooon/AliPhysics,amaringarcia/AliPhysics,dstocco/AliPhysics,sebaleh/AliPhysics,alisw/AliPhysics,AMechler/AliPhysics,yowatana/AliPhysics,mazimm/AliPhysics,pbatzing/AliPhysics,btrzecia/AliPhysics,btrzecia/AliPhysics,mpuccio/AliPhysics,mazimm/AliPhysics,mazimm/AliPhysics,rbailhac/AliPhysics,hzanoli/AliPhysics,rbailhac/AliPhysics,pbatzing/AliPhysics,hzanoli/AliPhysics,akubera/AliPhysics,fcolamar/AliPhysics,sebaleh/AliPhysics,mkrzewic/AliPhysics,victor-gonzalez/AliPhysics,fbellini/AliPhysics,adriansev/AliPhysics,amatyja/AliPhysics,preghenella/AliPhysics,mbjadhav/AliPhysics,nschmidtALICE/AliPhysics,jgronefe/AliPhysics,amaringarcia/AliPhysics,lcunquei/AliPhysics,pchrista/AliPhysics,ppribeli/AliPhysics,dmuhlhei/AliPhysics,btrzecia/AliPhysics,carstooon/AliPhysics,rderradi/AliPhysics,pbatzing/AliPhysics,aaniin/AliPhysics,victor-gonzalez/AliPhysics,yowatana/AliPhysics,alisw/AliPhysics,hzanoli/AliPhysics,mkrzewic/AliPhysics,jmargutt/AliPhysics,rderradi/AliPhysics,ALICEHLT/AliPhysics,sebaleh/AliPhysics,akubera/AliPhysics,SHornung1/AliPhysics,mbjadhav/AliPhysics,jmargutt/AliPhysics,rbailhac/AliPhysics,mbjadhav/AliPhysics,adriansev/AliPhysics,jmargutt/AliPhysics,dstocco/AliPhysics,SHornung1/AliPhysics,AMechler/AliPhysics,mkrzewic/AliPhysics,dlodato/AliPhysics,mkrzewic/AliPhysics,pchrista/AliPhysics,fbellini/AliPhysics,btrzecia/AliPhysics,pbuehler/AliPhysics,ppribeli/AliPhysics,akubera/AliPhysics,victor-gonzalez/AliPhysics,mbjadhav/AliPhysics,mazimm/AliPhysics,aaniin/AliPhysics,rihanphys/AliPhysics,kreisl/AliPhysics,rihanphys/AliPhysics,AudreyFrancisco/AliPhysics,dmuhlhei/AliPhysics,pbuehler/AliPhysics,rbailhac/AliPhysics,fcolamar/AliPhysics,aaniin/AliPhysics,rderradi/AliPhysics,adriansev/AliPhysics,fbellini/AliPhysics,mkrzewic/AliPhysics,pbatzing/AliPhysics,dstocco/AliPhysics,pbuehler/AliPhysics,alisw/AliPhysics,lfeldkam/AliPhysics,mkrzewic/AliPhysics,mazimm/AliPhysics,lcunquei/AliPhysics,ppribeli/AliPhysics,kreisl/AliPhysics,carstooon/AliPhysics,mpuccio/AliPhysics,rderradi/AliPhysics,rderradi/AliPhysics,nschmidtALICE/AliPhysics,rderradi/AliPhysics,alisw/AliPhysics,jgronefe/AliPhysics,amatyja/AliPhysics,amaringarcia/AliPhysics,adriansev/AliPhysics,fcolamar/AliPhysics,btrzecia/AliPhysics,hcab14/AliPhysics,fcolamar/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,pchrista/AliPhysics,hcab14/AliPhysics,aaniin/AliPhysics,fcolamar/AliPhysics,ppribeli/AliPhysics,mvala/AliPhysics,SHornung1/AliPhysics,victor-gonzalez/AliPhysics,dstocco/AliPhysics,AMechler/AliPhysics,yowatana/AliPhysics,preghenella/AliPhysics,pbuehler/AliPhysics,sebaleh/AliPhysics,rbailhac/AliPhysics,hcab14/AliPhysics,amatyja/AliPhysics,pbatzing/AliPhysics,pchrista/AliPhysics,lcunquei/AliPhysics,carstooon/AliPhysics,ALICEHLT/AliPhysics,jmargutt/AliPhysics,dmuhlhei/AliPhysics,preghenella/AliPhysics,akubera/AliPhysics,sebaleh/AliPhysics,nschmidtALICE/AliPhysics,dlodato/AliPhysics,mbjadhav/AliPhysics,rderradi/AliPhysics,mvala/AliPhysics,dlodato/AliPhysics,jgronefe/AliPhysics,pbuehler/AliPhysics,dlodato/AliPhysics,aaniin/AliPhysics,dstocco/AliPhysics,SHornung1/AliPhysics,AMechler/AliPhysics,jgronefe/AliPhysics,pchrista/AliPhysics,pbatzing/AliPhysics,mpuccio/AliPhysics,pbuehler/AliPhysics,akubera/AliPhysics,preghenella/AliPhysics,lfeldkam/AliPhysics,pbuehler/AliPhysics,preghenella/AliPhysics,victor-gonzalez/AliPhysics,kreisl/AliPhysics,AudreyFrancisco/AliPhysics,mvala/AliPhysics,mazimm/AliPhysics,amaringarcia/AliPhysics,mvala/AliPhysics,yowatana/AliPhysics,rihanphys/AliPhysics,carstooon/AliPhysics,fcolamar/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,AudreyFrancisco/AliPhysics,adriansev/AliPhysics,alisw/AliPhysics,amaringarcia/AliPhysics,hzanoli/AliPhysics,kreisl/AliPhysics,hcab14/AliPhysics,rihanphys/AliPhysics,jmargutt/AliPhysics,amatyja/AliPhysics,adriansev/AliPhysics,mkrzewic/AliPhysics,hzanoli/AliPhysics,dmuhlhei/AliPhysics,amatyja/AliPhysics,AudreyFrancisco/AliPhysics,ALICEHLT/AliPhysics,fbellini/AliPhysics,amatyja/AliPhysics,rihanphys/AliPhysics,lcunquei/AliPhysics
|
3d780ac3478c0863d9824f002731966c86180c38
|
lib/safestack/safestack.cc
|
lib/safestack/safestack.cc
|
//===-- safestack.cc ------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the runtime support for the safe stack protection
// mechanism. The runtime manages allocation/deallocation of the unsafe stack
// for the main thread, as well as all pthreads that are created/destroyed
// during program execution.
//
//===----------------------------------------------------------------------===//
#include "safestack_platform.h"
#include "safestack_util.h"
#include <errno.h>
#include <sys/resource.h>
#include "interception/interception.h"
using namespace safestack;
// TODO: To make accessing the unsafe stack pointer faster, we plan to
// eventually store it directly in the thread control block data structure on
// platforms where this structure is pointed to by %fs or %gs. This is exactly
// the same mechanism as currently being used by the traditional stack
// protector pass to store the stack guard (see getStackCookieLocation()
// function above). Doing so requires changing the tcbhead_t struct in glibc
// on Linux and tcb struct in libc on FreeBSD.
//
// For now, store it in a thread-local variable.
extern "C" {
__attribute__((visibility(
"default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
}
namespace {
// TODO: The runtime library does not currently protect the safe stack beyond
// relying on the system-enforced ASLR. The protection of the (safe) stack can
// be provided by three alternative features:
//
// 1) Protection via hardware segmentation on x86-32 and some x86-64
// architectures: the (safe) stack segment (implicitly accessed via the %ss
// segment register) can be separated from the data segment (implicitly
// accessed via the %ds segment register). Dereferencing a pointer to the safe
// segment would result in a segmentation fault.
//
// 2) Protection via software fault isolation: memory writes that are not meant
// to access the safe stack can be prevented from doing so through runtime
// instrumentation. One way to do it is to allocate the safe stack(s) in the
// upper half of the userspace and bitmask the corresponding upper bit of the
// memory addresses of memory writes that are not meant to access the safe
// stack.
//
// 3) Protection via information hiding on 64 bit architectures: the location
// of the safe stack(s) can be randomized through secure mechanisms, and the
// leakage of the stack pointer can be prevented. Currently, libc can leak the
// stack pointer in several ways (e.g. in longjmp, signal handling, user-level
// context switching related functions, etc.). These can be fixed in libc and
// in other low-level libraries, by either eliminating the escaping/dumping of
// the stack pointer (i.e., %rsp) when that's possible, or by using
// encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
// we control and protect better, as is already done for setjmp in glibc.)
// Furthermore, a static machine code level verifier can be ran after code
// generation to make sure that the stack pointer is never written to memory,
// or if it is, its written on the safe stack.
//
// Finally, while the Unsafe Stack pointer is currently stored in a thread
// local variable, with libc support it could be stored in the TCB (thread
// control block) as well, eliminating another level of indirection and making
// such accesses faster. Alternatively, dedicating a separate register for
// storing it would also be possible.
/// Minimum stack alignment for the unsafe stack.
const unsigned kStackAlign = 16;
/// Default size of the unsafe stack. This value is only used if the stack
/// size rlimit is set to infinity.
const unsigned kDefaultUnsafeStackSize = 0x2800000;
/// Runtime page size obtained through sysconf
unsigned pageSize;
// Per-thread unsafe stack information. It's not frequently accessed, so there
// it can be kept out of the tcb in normal thread-local variables.
__thread void *unsafe_stack_start = nullptr;
__thread size_t unsafe_stack_size = 0;
__thread size_t unsafe_stack_guard = 0;
inline void *unsafe_stack_alloc(size_t size, size_t guard) {
SFS_CHECK(size + guard >= size);
void *addr = Mmap(nullptr, RoundUpTo(size + guard, pageSize),
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
SFS_CHECK(MAP_FAILED != addr);
Mprotect(addr, guard, PROT_NONE);
return (char *)addr + guard;
}
inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
SFS_CHECK((char *)start + size >= (char *)start);
SFS_CHECK((char *)start + guard >= (char *)start);
void *stack_ptr = (char *)start + size;
SFS_CHECK((((size_t)stack_ptr) & (kStackAlign - 1)) == 0);
__safestack_unsafe_stack_ptr = stack_ptr;
unsafe_stack_start = start;
unsafe_stack_size = size;
unsafe_stack_guard = guard;
}
/// Thread data for the cleanup handler
pthread_key_t thread_cleanup_key;
/// Safe stack per-thread information passed to the thread_start function
struct tinfo {
void *(*start_routine)(void *);
void *start_routine_arg;
void *unsafe_stack_start;
size_t unsafe_stack_size;
size_t unsafe_stack_guard;
};
/// Wrap the thread function in order to deallocate the unsafe stack when the
/// thread terminates by returning from its main function.
void *thread_start(void *arg) {
struct tinfo *tinfo = (struct tinfo *)arg;
void *(*start_routine)(void *) = tinfo->start_routine;
void *start_routine_arg = tinfo->start_routine_arg;
// Setup the unsafe stack; this will destroy tinfo content
unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
tinfo->unsafe_stack_guard);
// Make sure out thread-specific destructor will be called
pthread_setspecific(thread_cleanup_key, (void *)1);
return start_routine(start_routine_arg);
}
/// Linked list used to store exiting threads stack/thread information.
struct thread_stack_ll {
struct thread_stack_ll *next;
void *stack_base;
size_t size;
pid_t pid;
ThreadId tid;
};
/// Linked list of unsafe stacks for threads that are exiting. We delay
/// unmapping them until the thread exits.
thread_stack_ll *thread_stacks = nullptr;
pthread_mutex_t thread_stacks_mutex = PTHREAD_MUTEX_INITIALIZER;
/// Thread-specific data destructor. We want to free the unsafe stack only after
/// this thread is terminated. libc can call functions in safestack-instrumented
/// code (like free) after thread-specific data destructors have run.
void thread_cleanup_handler(void *_iter) {
SFS_CHECK(unsafe_stack_start != nullptr);
pthread_setspecific(thread_cleanup_key, NULL);
pthread_mutex_lock(&thread_stacks_mutex);
// Temporary list to hold the previous threads stacks so we don't hold the
// thread_stacks_mutex for long.
thread_stack_ll *temp_stacks = thread_stacks;
thread_stacks = nullptr;
pthread_mutex_unlock(&thread_stacks_mutex);
pid_t pid = getpid();
ThreadId tid = GetTid();
// Free stacks for dead threads
thread_stack_ll **stackp = &temp_stacks;
while (*stackp) {
thread_stack_ll *stack = *stackp;
if (stack->pid != pid ||
(-1 == TgKill(stack->pid, stack->tid, 0) && errno == ESRCH)) {
Munmap(stack->stack_base, stack->size);
*stackp = stack->next;
free(stack);
} else
stackp = &stack->next;
}
thread_stack_ll *cur_stack =
(thread_stack_ll *)malloc(sizeof(thread_stack_ll));
cur_stack->stack_base = (char *)unsafe_stack_start - unsafe_stack_guard;
cur_stack->size = unsafe_stack_size + unsafe_stack_guard;
cur_stack->pid = pid;
cur_stack->tid = tid;
pthread_mutex_lock(&thread_stacks_mutex);
// Merge thread_stacks with the current thread's stack and any remaining
// temp_stacks
*stackp = thread_stacks;
cur_stack->next = temp_stacks;
thread_stacks = cur_stack;
pthread_mutex_unlock(&thread_stacks_mutex);
unsafe_stack_start = nullptr;
}
void EnsureInterceptorsInitialized();
/// Intercept thread creation operation to allocate and setup the unsafe stack
INTERCEPTOR(int, pthread_create, pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg) {
EnsureInterceptorsInitialized();
size_t size = 0;
size_t guard = 0;
if (attr) {
pthread_attr_getstacksize(attr, &size);
pthread_attr_getguardsize(attr, &guard);
} else {
// get pthread default stack size
pthread_attr_t tmpattr;
pthread_attr_init(&tmpattr);
pthread_attr_getstacksize(&tmpattr, &size);
pthread_attr_getguardsize(&tmpattr, &guard);
pthread_attr_destroy(&tmpattr);
}
SFS_CHECK(size);
size = RoundUpTo(size, kStackAlign);
SFS_CHECK((guard & (pageSize - 1)) == 0);
void *addr = unsafe_stack_alloc(size, guard);
struct tinfo *tinfo =
(struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
tinfo->start_routine = start_routine;
tinfo->start_routine_arg = arg;
tinfo->unsafe_stack_start = addr;
tinfo->unsafe_stack_size = size;
tinfo->unsafe_stack_guard = guard;
return REAL(pthread_create)(thread, attr, thread_start, tinfo);
}
pthread_mutex_t interceptor_init_mutex = PTHREAD_MUTEX_INITIALIZER;
bool interceptors_inited = false;
void EnsureInterceptorsInitialized() {
MutexLock lock(interceptor_init_mutex);
if (interceptors_inited)
return;
// Initialize pthread interceptors for thread allocation
INTERCEPT_FUNCTION(pthread_create);
interceptors_inited = true;
}
} // namespace
extern "C" __attribute__((visibility("default")))
#if !SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, the constructor is invoked using .preinit_array (see below)
__attribute__((constructor(0)))
#endif
void __safestack_init() {
pageSize = sysconf(_SC_PAGESIZE);
// Determine the stack size for the main thread.
size_t size = kDefaultUnsafeStackSize;
size_t guard = 4096;
struct rlimit limit;
if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
size = limit.rlim_cur;
// Allocate unsafe stack for main thread
void *addr = unsafe_stack_alloc(size, guard);
unsafe_stack_setup(addr, size, guard);
// Setup the cleanup handler
pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
}
#if SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, run safestack initialization before any other constructors.
// On other platforms we use the constructor attribute to arrange to run our
// initialization early.
extern "C" {
__attribute__((section(".preinit_array"),
used)) void (*__safestack_preinit)(void) = __safestack_init;
}
#endif
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_bottom() {
return unsafe_stack_start;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_top() {
return (char*)unsafe_stack_start + unsafe_stack_size;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
return unsafe_stack_start;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
return __safestack_unsafe_stack_ptr;
}
|
//===-- safestack.cc ------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the runtime support for the safe stack protection
// mechanism. The runtime manages allocation/deallocation of the unsafe stack
// for the main thread, as well as all pthreads that are created/destroyed
// during program execution.
//
//===----------------------------------------------------------------------===//
#include "safestack_platform.h"
#include "safestack_util.h"
#include <errno.h>
#include <sys/resource.h>
#include "interception/interception.h"
using namespace safestack;
// TODO: To make accessing the unsafe stack pointer faster, we plan to
// eventually store it directly in the thread control block data structure on
// platforms where this structure is pointed to by %fs or %gs. This is exactly
// the same mechanism as currently being used by the traditional stack
// protector pass to store the stack guard (see getStackCookieLocation()
// function above). Doing so requires changing the tcbhead_t struct in glibc
// on Linux and tcb struct in libc on FreeBSD.
//
// For now, store it in a thread-local variable.
extern "C" {
__attribute__((visibility(
"default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
}
namespace {
// TODO: The runtime library does not currently protect the safe stack beyond
// relying on the system-enforced ASLR. The protection of the (safe) stack can
// be provided by three alternative features:
//
// 1) Protection via hardware segmentation on x86-32 and some x86-64
// architectures: the (safe) stack segment (implicitly accessed via the %ss
// segment register) can be separated from the data segment (implicitly
// accessed via the %ds segment register). Dereferencing a pointer to the safe
// segment would result in a segmentation fault.
//
// 2) Protection via software fault isolation: memory writes that are not meant
// to access the safe stack can be prevented from doing so through runtime
// instrumentation. One way to do it is to allocate the safe stack(s) in the
// upper half of the userspace and bitmask the corresponding upper bit of the
// memory addresses of memory writes that are not meant to access the safe
// stack.
//
// 3) Protection via information hiding on 64 bit architectures: the location
// of the safe stack(s) can be randomized through secure mechanisms, and the
// leakage of the stack pointer can be prevented. Currently, libc can leak the
// stack pointer in several ways (e.g. in longjmp, signal handling, user-level
// context switching related functions, etc.). These can be fixed in libc and
// in other low-level libraries, by either eliminating the escaping/dumping of
// the stack pointer (i.e., %rsp) when that's possible, or by using
// encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
// we control and protect better, as is already done for setjmp in glibc.)
// Furthermore, a static machine code level verifier can be ran after code
// generation to make sure that the stack pointer is never written to memory,
// or if it is, its written on the safe stack.
//
// Finally, while the Unsafe Stack pointer is currently stored in a thread
// local variable, with libc support it could be stored in the TCB (thread
// control block) as well, eliminating another level of indirection and making
// such accesses faster. Alternatively, dedicating a separate register for
// storing it would also be possible.
/// Minimum stack alignment for the unsafe stack.
const unsigned kStackAlign = 16;
/// Default size of the unsafe stack. This value is only used if the stack
/// size rlimit is set to infinity.
const unsigned kDefaultUnsafeStackSize = 0x2800000;
// Per-thread unsafe stack information. It's not frequently accessed, so there
// it can be kept out of the tcb in normal thread-local variables.
__thread void *unsafe_stack_start = nullptr;
__thread size_t unsafe_stack_size = 0;
__thread size_t unsafe_stack_guard = 0;
inline void *unsafe_stack_alloc(size_t size, size_t guard) {
SFS_CHECK(size + guard >= size);
void *addr = Mmap(nullptr, size + guard, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
SFS_CHECK(MAP_FAILED != addr);
Mprotect(addr, guard, PROT_NONE);
return (char *)addr + guard;
}
inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
SFS_CHECK((char *)start + size >= (char *)start);
SFS_CHECK((char *)start + guard >= (char *)start);
void *stack_ptr = (char *)start + size;
SFS_CHECK((((size_t)stack_ptr) & (kStackAlign - 1)) == 0);
__safestack_unsafe_stack_ptr = stack_ptr;
unsafe_stack_start = start;
unsafe_stack_size = size;
unsafe_stack_guard = guard;
}
/// Thread data for the cleanup handler
pthread_key_t thread_cleanup_key;
/// Safe stack per-thread information passed to the thread_start function
struct tinfo {
void *(*start_routine)(void *);
void *start_routine_arg;
void *unsafe_stack_start;
size_t unsafe_stack_size;
size_t unsafe_stack_guard;
};
/// Wrap the thread function in order to deallocate the unsafe stack when the
/// thread terminates by returning from its main function.
void *thread_start(void *arg) {
struct tinfo *tinfo = (struct tinfo *)arg;
void *(*start_routine)(void *) = tinfo->start_routine;
void *start_routine_arg = tinfo->start_routine_arg;
// Setup the unsafe stack; this will destroy tinfo content
unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
tinfo->unsafe_stack_guard);
// Make sure out thread-specific destructor will be called
pthread_setspecific(thread_cleanup_key, (void *)1);
return start_routine(start_routine_arg);
}
/// Linked list used to store exiting threads stack/thread information.
struct thread_stack_ll {
struct thread_stack_ll *next;
void *stack_base;
size_t size;
pid_t pid;
ThreadId tid;
};
/// Linked list of unsafe stacks for threads that are exiting. We delay
/// unmapping them until the thread exits.
thread_stack_ll *thread_stacks = nullptr;
pthread_mutex_t thread_stacks_mutex = PTHREAD_MUTEX_INITIALIZER;
/// Thread-specific data destructor. We want to free the unsafe stack only after
/// this thread is terminated. libc can call functions in safestack-instrumented
/// code (like free) after thread-specific data destructors have run.
void thread_cleanup_handler(void *_iter) {
SFS_CHECK(unsafe_stack_start != nullptr);
pthread_setspecific(thread_cleanup_key, NULL);
pthread_mutex_lock(&thread_stacks_mutex);
// Temporary list to hold the previous threads stacks so we don't hold the
// thread_stacks_mutex for long.
thread_stack_ll *temp_stacks = thread_stacks;
thread_stacks = nullptr;
pthread_mutex_unlock(&thread_stacks_mutex);
pid_t pid = getpid();
ThreadId tid = GetTid();
// Free stacks for dead threads
thread_stack_ll **stackp = &temp_stacks;
while (*stackp) {
thread_stack_ll *stack = *stackp;
if (stack->pid != pid ||
(-1 == TgKill(stack->pid, stack->tid, 0) && errno == ESRCH)) {
Munmap(stack->stack_base, stack->size);
*stackp = stack->next;
free(stack);
} else
stackp = &stack->next;
}
thread_stack_ll *cur_stack =
(thread_stack_ll *)malloc(sizeof(thread_stack_ll));
cur_stack->stack_base = (char *)unsafe_stack_start - unsafe_stack_guard;
cur_stack->size = unsafe_stack_size + unsafe_stack_guard;
cur_stack->pid = pid;
cur_stack->tid = tid;
pthread_mutex_lock(&thread_stacks_mutex);
// Merge thread_stacks with the current thread's stack and any remaining
// temp_stacks
*stackp = thread_stacks;
cur_stack->next = temp_stacks;
thread_stacks = cur_stack;
pthread_mutex_unlock(&thread_stacks_mutex);
unsafe_stack_start = nullptr;
}
void EnsureInterceptorsInitialized();
/// Intercept thread creation operation to allocate and setup the unsafe stack
INTERCEPTOR(int, pthread_create, pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg) {
EnsureInterceptorsInitialized();
size_t size = 0;
size_t guard = 0;
if (attr) {
pthread_attr_getstacksize(attr, &size);
pthread_attr_getguardsize(attr, &guard);
} else {
// get pthread default stack size
pthread_attr_t tmpattr;
pthread_attr_init(&tmpattr);
pthread_attr_getstacksize(&tmpattr, &size);
pthread_attr_getguardsize(&tmpattr, &guard);
pthread_attr_destroy(&tmpattr);
}
SFS_CHECK(size);
size = RoundUpTo(size, kStackAlign);
void *addr = unsafe_stack_alloc(size, guard);
struct tinfo *tinfo =
(struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
tinfo->start_routine = start_routine;
tinfo->start_routine_arg = arg;
tinfo->unsafe_stack_start = addr;
tinfo->unsafe_stack_size = size;
tinfo->unsafe_stack_guard = guard;
return REAL(pthread_create)(thread, attr, thread_start, tinfo);
}
pthread_mutex_t interceptor_init_mutex = PTHREAD_MUTEX_INITIALIZER;
bool interceptors_inited = false;
void EnsureInterceptorsInitialized() {
MutexLock lock(interceptor_init_mutex);
if (interceptors_inited)
return;
// Initialize pthread interceptors for thread allocation
INTERCEPT_FUNCTION(pthread_create);
interceptors_inited = true;
}
} // namespace
extern "C" __attribute__((visibility("default")))
#if !SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, the constructor is invoked using .preinit_array (see below)
__attribute__((constructor(0)))
#endif
void __safestack_init() {
// Determine the stack size for the main thread.
size_t size = kDefaultUnsafeStackSize;
size_t guard = 4096;
struct rlimit limit;
if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
size = limit.rlim_cur;
// Allocate unsafe stack for main thread
void *addr = unsafe_stack_alloc(size, guard);
unsafe_stack_setup(addr, size, guard);
// Setup the cleanup handler
pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
}
#if SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, run safestack initialization before any other constructors.
// On other platforms we use the constructor attribute to arrange to run our
// initialization early.
extern "C" {
__attribute__((section(".preinit_array"),
used)) void (*__safestack_preinit)(void) = __safestack_init;
}
#endif
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_bottom() {
return unsafe_stack_start;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_top() {
return (char*)unsafe_stack_start + unsafe_stack_size;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
return unsafe_stack_start;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
return __safestack_unsafe_stack_ptr;
}
|
Remove pageSize
|
[safestack] Remove pageSize
Summary:
3rd party sysconf interceptor may crash if it's called before unsafe_stack_setup
However pageSize is not useful here. mmap should round up on it's own, SFS_CHECK can be removed.
Reviewers: eugenis, vlad.tsyrklevich
Subscribers: #sanitizers, llvm-commits
Tags: #sanitizers, #llvm
Differential Revision: https://reviews.llvm.org/D57924
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@353481 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
|
86d340264ca7cbe423b95b5b1dfc3562485f5b72
|
opencog/server/NetworkServer.cc
|
opencog/server/NetworkServer.cc
|
/*
* opencog/server/NetworkServer.cc
*
* Copyright (C) 2002-2007 Novamente LLC
* Copyright (C) 2008 by OpenCog Foundation
* All Rights Reserved
*
* Written by Andre Senna <[email protected]>
* Gustavo Gama <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "NetworkServer.h"
#include <boost/bind.hpp>
#include <opencog/util/Logger.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/platform.h>
using namespace opencog;
NetworkServer::NetworkServer()
: _started(false), _running(false), _thread(0)
{
logger().debug("[NetworkServer] constructor");
}
NetworkServer::~NetworkServer()
{
logger().debug("[NetworkServer] enter destructor");
if (_thread != 0)
pthread_join(_thread, NULL);
for (SocketPort* sp : _listeners) delete sp;
logger().debug("[NetworkServer] all threads joined, exit destructor");
}
extern "C" {
static void* _opencog_run_wrapper(void* arg)
{
logger().debug("[NetworkServer] run wrapper");
NetworkServer* ns = (NetworkServer*) arg;
ns->run();
return NULL;
}
}
void NetworkServer::start()
{
if (_running) {
logger().warn("server has already started");
return;
}
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
// create thread
int rc = pthread_create(&_thread, &attr, _opencog_run_wrapper, this);
if (rc != 0) {
logger().error("Unable to start network server thread: %d", rc);
_running = false;
_started = false;
return;
}
_started = true;
_running = true;
}
void NetworkServer::stop()
{
logger().debug("[NetworkServer] stop");
_running = false;
io_service.stop();
while (_started) { usleep(10000); }
}
void NetworkServer::run()
{
logger().debug("[NetworkServer] run");
while (_running) {
try {
io_service.run();
} catch (boost::system::system_error& e) {
logger().error("Error in boost::asio io_service::run() => %s", e.what());
}
usleep(50000); // avoids busy wait
}
logger().debug("[NetworkServer] end of run");
_started = false;
}
namespace opencog {
struct equal_to_port : public std::binary_function<const SocketPort*, const unsigned short &, bool>
{
bool operator()(const SocketPort* sock, const unsigned short &port) {
SocketPort* s = const_cast<SocketPort*>(sock);
return ((s->getPort()) == port);
}
};
}
bool NetworkServer::removeListener(const unsigned short port)
{
logger().debug("[NetworkServer] removing listener bound to port %d", port);
std::vector<SocketPort*>::iterator l =
std::find_if(_listeners.begin(), _listeners.end(),
boost::bind(equal_to_port(), _1, port));
if (l == _listeners.end()) {
logger().warn("unable to remove listener from port %d", port);
return false;
}
SocketPort* sp = *l;
_listeners.erase(l);
delete sp;
return true;
}
|
/*
* opencog/server/NetworkServer.cc
*
* Copyright (C) 2002-2007 Novamente LLC
* Copyright (C) 2008 by OpenCog Foundation
* All Rights Reserved
*
* Written by Andre Senna <[email protected]>
* Gustavo Gama <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "NetworkServer.h"
#include <boost/bind.hpp>
#include <opencog/util/Logger.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/platform.h>
using namespace opencog;
NetworkServer::NetworkServer()
: _started(false), _running(false), _thread(0)
{
logger().debug("[NetworkServer] constructor");
}
NetworkServer::~NetworkServer()
{
logger().debug("[NetworkServer] enter destructor");
for (SocketPort* sp : _listeners) delete sp;
logger().debug("[NetworkServer] all threads joined, exit destructor");
}
extern "C" {
static void* _opencog_run_wrapper(void* arg)
{
logger().debug("[NetworkServer] run wrapper");
NetworkServer* ns = (NetworkServer*) arg;
ns->run();
return NULL;
}
}
void NetworkServer::start()
{
if (_running) {
logger().warn("server has already started");
return;
}
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
// create thread
int rc = pthread_create(&_thread, &attr, _opencog_run_wrapper, this);
if (rc != 0) {
logger().error("Unable to start network server thread: %d", rc);
_running = false;
_started = false;
return;
}
_started = true;
_running = true;
}
void NetworkServer::stop()
{
logger().debug("[NetworkServer] stop");
_running = false;
io_service.stop();
if (_thread != 0)
pthread_join(_thread, NULL);
}
void NetworkServer::run()
{
logger().debug("[NetworkServer] run");
while (_running) {
try {
io_service.run();
} catch (boost::system::system_error& e) {
logger().error("Error in boost::asio io_service::run() => %s", e.what());
}
usleep(50000); // avoids busy wait
}
logger().debug("[NetworkServer] end of run");
_started = false;
}
namespace opencog {
struct equal_to_port : public std::binary_function<const SocketPort*, const unsigned short &, bool>
{
bool operator()(const SocketPort* sock, const unsigned short &port) {
SocketPort* s = const_cast<SocketPort*>(sock);
return ((s->getPort()) == port);
}
};
}
bool NetworkServer::removeListener(const unsigned short port)
{
logger().debug("[NetworkServer] removing listener bound to port %d", port);
std::vector<SocketPort*>::iterator l =
std::find_if(_listeners.begin(), _listeners.end(),
boost::bind(equal_to_port(), _1, port));
if (l == _listeners.end()) {
logger().warn("unable to remove listener from port %d", port);
return false;
}
SocketPort* sp = *l;
_listeners.erase(l);
delete sp;
return true;
}
|
Fix thread crash on CogServer destruction
|
Fix thread crash on CogServer destruction
|
C++
|
agpl-3.0
|
kim135797531/opencog,AmeBel/atomspace,jswiergo/atomspace,AmeBel/opencog,Tiggels/opencog,shujingke/opencog,misgeatgit/atomspace,rTreutlein/atomspace,ruiting/opencog,rohit12/opencog,iAMr00t/opencog,roselleebarle04/opencog,printedheart/opencog,eddiemonroe/opencog,Selameab/opencog,ceefour/opencog,ruiting/opencog,eddiemonroe/opencog,virneo/opencog,ArvinPan/atomspace,kinoc/opencog,misgeatgit/opencog,virneo/opencog,gavrieltal/opencog,shujingke/opencog,ArvinPan/atomspace,cosmoharrigan/opencog,Selameab/opencog,Tiggels/opencog,anitzkin/opencog,gaapt/opencog,AmeBel/opencog,inflector/atomspace,gavrieltal/opencog,sumitsourabh/opencog,ruiting/opencog,Allend575/opencog,yantrabuddhi/atomspace,ruiting/opencog,rodsol/opencog,gavrieltal/opencog,shujingke/opencog,AmeBel/atomspace,virneo/opencog,jswiergo/atomspace,misgeatgit/opencog,jlegendary/opencog,rohit12/opencog,ceefour/opencog,inflector/atomspace,roselleebarle04/opencog,rTreutlein/atomspace,sanuj/opencog,virneo/opencog,virneo/opencog,UIKit0/atomspace,iAMr00t/opencog,Allend575/opencog,AmeBel/opencog,kim135797531/opencog,rohit12/opencog,inflector/atomspace,cosmoharrigan/opencog,iAMr00t/opencog,anitzkin/opencog,misgeatgit/opencog,jlegendary/opencog,tim777z/opencog,shujingke/opencog,jlegendary/opencog,printedheart/atomspace,rodsol/atomspace,yantrabuddhi/atomspace,williampma/opencog,MarcosPividori/atomspace,kinoc/opencog,TheNameIsNigel/opencog,cosmoharrigan/atomspace,ArvinPan/opencog,MarcosPividori/atomspace,Selameab/atomspace,jlegendary/opencog,inflector/opencog,virneo/opencog,ceefour/atomspace,TheNameIsNigel/opencog,yantrabuddhi/opencog,tim777z/opencog,printedheart/atomspace,ArvinPan/atomspace,ArvinPan/opencog,sumitsourabh/opencog,kinoc/opencog,rodsol/opencog,Tiggels/opencog,inflector/atomspace,yantrabuddhi/atomspace,anitzkin/opencog,williampma/opencog,rohit12/opencog,misgeatgit/atomspace,rTreutlein/atomspace,rodsol/opencog,sumitsourabh/opencog,misgeatgit/atomspace,virneo/atomspace,tim777z/opencog,rohit12/atomspace,roselleebarle04/opencog,inflector/opencog,virneo/atomspace,williampma/opencog,cosmoharrigan/opencog,andre-senna/opencog,ceefour/opencog,AmeBel/atomspace,virneo/opencog,williampma/opencog,ceefour/atomspace,inflector/atomspace,yantrabuddhi/opencog,tim777z/opencog,eddiemonroe/opencog,misgeatgit/atomspace,jswiergo/atomspace,rohit12/opencog,AmeBel/opencog,ceefour/opencog,printedheart/opencog,gavrieltal/opencog,virneo/atomspace,misgeatgit/opencog,cosmoharrigan/opencog,ceefour/opencog,sanuj/opencog,anitzkin/opencog,andre-senna/opencog,MarcosPividori/atomspace,Selameab/opencog,ArvinPan/opencog,kim135797531/opencog,eddiemonroe/opencog,ruiting/opencog,misgeatgit/opencog,UIKit0/atomspace,gavrieltal/opencog,tim777z/opencog,sumitsourabh/opencog,prateeksaxena2809/opencog,jlegendary/opencog,tim777z/opencog,eddiemonroe/atomspace,printedheart/opencog,eddiemonroe/atomspace,kim135797531/opencog,AmeBel/opencog,Tiggels/opencog,sanuj/opencog,rohit12/atomspace,AmeBel/atomspace,cosmoharrigan/opencog,Allend575/opencog,sanuj/opencog,williampma/opencog,printedheart/atomspace,gaapt/opencog,yantrabuddhi/opencog,rodsol/atomspace,roselleebarle04/opencog,inflector/opencog,TheNameIsNigel/opencog,jlegendary/opencog,cosmoharrigan/opencog,prateeksaxena2809/opencog,rodsol/atomspace,yantrabuddhi/opencog,Tiggels/opencog,rTreutlein/atomspace,yantrabuddhi/atomspace,inflector/opencog,rodsol/atomspace,anitzkin/opencog,misgeatgit/atomspace,anitzkin/opencog,AmeBel/opencog,rohit12/opencog,misgeatgit/opencog,ceefour/atomspace,rodsol/opencog,andre-senna/opencog,yantrabuddhi/opencog,yantrabuddhi/atomspace,gavrieltal/opencog,Selameab/atomspace,prateeksaxena2809/opencog,Allend575/opencog,virneo/atomspace,ArvinPan/atomspace,Allend575/opencog,cosmoharrigan/atomspace,roselleebarle04/opencog,inflector/opencog,williampma/atomspace,gaapt/opencog,Selameab/atomspace,eddiemonroe/opencog,eddiemonroe/opencog,sumitsourabh/opencog,eddiemonroe/atomspace,gaapt/opencog,misgeatgit/opencog,prateeksaxena2809/opencog,AmeBel/opencog,ceefour/opencog,UIKit0/atomspace,andre-senna/opencog,eddiemonroe/atomspace,jlegendary/opencog,eddiemonroe/atomspace,kinoc/opencog,kinoc/opencog,roselleebarle04/opencog,Selameab/opencog,rodsol/opencog,AmeBel/atomspace,eddiemonroe/opencog,UIKit0/atomspace,williampma/atomspace,ArvinPan/opencog,ArvinPan/opencog,Tiggels/opencog,sanuj/opencog,jswiergo/atomspace,shujingke/opencog,printedheart/opencog,kim135797531/opencog,inflector/opencog,gavrieltal/opencog,Allend575/opencog,ruiting/opencog,rohit12/atomspace,yantrabuddhi/opencog,ArvinPan/opencog,TheNameIsNigel/opencog,Selameab/atomspace,Selameab/opencog,williampma/opencog,iAMr00t/opencog,inflector/opencog,misgeatgit/opencog,gaapt/opencog,andre-senna/opencog,roselleebarle04/opencog,ruiting/opencog,misgeatgit/opencog,iAMr00t/opencog,prateeksaxena2809/opencog,ceefour/atomspace,Allend575/opencog,iAMr00t/opencog,Selameab/opencog,prateeksaxena2809/opencog,andre-senna/opencog,gaapt/opencog,anitzkin/opencog,TheNameIsNigel/opencog,andre-senna/opencog,rohit12/atomspace,TheNameIsNigel/opencog,rTreutlein/atomspace,williampma/atomspace,printedheart/opencog,williampma/atomspace,shujingke/opencog,yantrabuddhi/opencog,cosmoharrigan/atomspace,cosmoharrigan/atomspace,sumitsourabh/opencog,ceefour/opencog,sanuj/opencog,gaapt/opencog,kim135797531/opencog,kinoc/opencog,sumitsourabh/opencog,printedheart/atomspace,rodsol/opencog,printedheart/opencog,kinoc/opencog,kim135797531/opencog,inflector/opencog,shujingke/opencog,MarcosPividori/atomspace,prateeksaxena2809/opencog
|
0fab51f39ac0498024c9629daa235e1189c7f0de
|
src/summary.cpp
|
src/summary.cpp
|
//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <numeric>
#include <unordered_map>
#include <unordered_set>
#include "cpp_utils/assert.hpp"
#include "summary.hpp"
#include "console.hpp"
#include "accounts.hpp"
#include "compute.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "fortune.hpp"
#include "objectives.hpp"
#include "budget_exception.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "writer.hpp"
using namespace budget;
namespace {
std::string account_summary(budget::month month, budget::year year){
std::vector<std::string> columns;
std::vector<std::vector<std::string>> contents;
auto sm = start_month(year);
columns.push_back("Account");
columns.push_back("Expenses");
columns.push_back("Earnings");
columns.push_back("Balance");
columns.push_back("Local");
std::unordered_map<std::string, budget::money> account_previous;
//Fill the table
budget::money tot_expenses;
budget::money tot_earnings;
budget::money tot_balance;
budget::money tot_local;
budget::money prev_expenses;
budget::money prev_earnings;
budget::money prev_balance;
budget::money prev_local;
for (unsigned short i = sm; i <= month; ++i) {
budget::month m = i;
for (auto& account : all_accounts(year, m)) {
auto total_expenses = accumulate_amount_if(all_expenses(), [account, year, m](budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; });
auto total_earnings = accumulate_amount_if(all_earnings(), [account, year, m](budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; });
auto balance = account_previous[account.name] + account.amount - total_expenses + total_earnings;
auto local_balance = account.amount - total_expenses + total_earnings;
if (i == month) {
contents.push_back({account.name});
contents.back().push_back(format_money(total_expenses));
contents.back().push_back(format_money(total_earnings));
contents.back().push_back(format_money(balance));
contents.back().push_back(format_money(local_balance));
tot_expenses += total_expenses;
tot_earnings += total_earnings;
tot_balance += balance;
tot_local += local_balance;
} else if(month > 1 && m == month - 1){
prev_expenses = total_expenses;
prev_earnings = total_earnings;
prev_balance = balance;
prev_local = local_balance;
}
account_previous[account.name] = balance;
}
}
contents.push_back({"Total"});
contents.back().push_back(format_money(tot_expenses));
contents.back().push_back(format_money(tot_earnings));
contents.back().push_back(format_money(tot_balance));
contents.back().push_back(format_money(tot_local));
if(month > 1){
contents.push_back({"Previous"});
contents.back().push_back(format_money(prev_expenses));
contents.back().push_back(format_money(prev_earnings));
contents.back().push_back(format_money(prev_balance));
contents.back().push_back(format_money(prev_local));
contents.push_back({"Average"});
contents.back().push_back(format_money(tot_expenses / month.value));
contents.back().push_back(format_money(tot_earnings / month.value));
contents.back().push_back(format_money(tot_balance / month.value));
contents.back().push_back(format_money(tot_local / month.value));
}
std::stringstream ss;
console_writer w(ss);
w.display_table(columns, contents, 1, {}, 1);
return ss.str();
}
std::string objectives_summary(){
std::stringstream ss;
console_writer w(ss);
budget::yearly_objective_status(w, false, true);
ss << std::endl;
budget::current_monthly_objective_status(w, true);
return ss.str();
}
std::string fortune_summary(){
std::stringstream ss;
budget::status_fortunes(ss, true);
return ss.str();
}
void print_columns(const std::vector<std::string>& columns){
std::vector<std::vector<std::string>> split_columns;
for(auto& column : columns){
split_columns.push_back(budget::split(column, '\n'));
}
std::vector<std::string> composed_columns;
// Compute the total width
size_t total_max_width = composed_columns.size() * 2;
for(auto& column : split_columns){
size_t max_width = 0;
for(auto& row : column){
max_width = std::max(max_width, rsize_after(row));
}
total_max_width += max_width;
}
if (terminal_width() - 3 > total_max_width) {
// By default, print the columns side by side
for (auto& column : split_columns) {
size_t max_width = 0;
for (auto& row : column) {
max_width = std::max(max_width, rsize_after(row));
}
for (size_t i = 0; i < column.size(); ++i) {
auto& row = column[i];
if (i >= composed_columns.size()) {
composed_columns.emplace_back();
}
composed_columns[i] += row;
auto length = rsize_after(row);
if (length < max_width) {
composed_columns[i] += std::string(max_width - length, ' ');
}
}
for (size_t i = column.size(); i < composed_columns.size(); ++i) {
composed_columns[i] += std::string(max_width, ' ');
}
// Add some spacing from previous column
for (auto& row : composed_columns) {
row += " ";
}
}
for (auto& row : composed_columns) {
std::cout << row << std::endl;
}
} else {
// If the columns cannot be printed side by side
// print them one after another
for (auto& column : split_columns) {
for(auto& row : column){
std::cout << row << std::endl;
}
std::cout << std::endl;
}
}
}
void month_overview(budget::month month, budget::year year) {
// First display overview of the accounts
auto m_summary = account_summary(month, year);
// Second display a summary of the objectives
auto m_objectives_summary = objectives_summary();
// Third display a summary of the fortune
auto m_fortune_summary = fortune_summary();
print_columns({m_summary, m_objectives_summary, m_fortune_summary});
}
void month_overview(budget::month m) {
month_overview(m, local_day().year());
}
void month_overview() {
month_overview(local_day().month(), local_day().year());
}
} // end of anonymous namespace
constexpr const std::array<std::pair<const char*, const char*>, 1> budget::module_traits<budget::summary_module>::aliases;
void budget::summary_module::load() {
load_accounts();
load_expenses();
load_earnings();
load_objectives();
load_fortunes();
}
void budget::summary_module::handle(std::vector<std::string>& args) {
if (all_accounts().empty()) {
throw budget_exception("No accounts defined, you should start by defining some of them");
}
if (args.empty() || args.size() == 1) {
month_overview();
} else {
auto& subcommand = args[1];
if (subcommand == "month") {
auto today = local_day();
if (args.size() == 2) {
month_overview();
} else if (args.size() == 3) {
auto m = budget::month(to_number<unsigned short>(args[2]));
if (m > today.month()) {
throw budget_exception("Cannot compute the summary of the future");
}
month_overview(m);
} else if (args.size() == 4) {
auto m = budget::month(to_number<unsigned short>(args[2]));
auto y = budget::year(to_number<unsigned short>(args[3]));
if (y > today.year()) {
throw budget_exception("Cannot compute the summary of the future");
}
if (y == today.year() && m > today.month()) {
throw budget_exception("Cannot compute the summary of the future");
}
month_overview(m, y);
} else {
throw budget_exception("Too many arguments to overview month");
}
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
|
//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <numeric>
#include <unordered_map>
#include <unordered_set>
#include "cpp_utils/assert.hpp"
#include "summary.hpp"
#include "console.hpp"
#include "accounts.hpp"
#include "compute.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "fortune.hpp"
#include "objectives.hpp"
#include "budget_exception.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "writer.hpp"
using namespace budget;
namespace {
std::string account_summary(budget::month month, budget::year year){
std::vector<std::string> columns;
std::vector<std::vector<std::string>> contents;
auto sm = start_month(year);
columns.push_back("Account");
columns.push_back("Expenses");
columns.push_back("Earnings");
columns.push_back("Balance");
columns.push_back("Local");
std::unordered_map<std::string, budget::money> account_previous;
//Fill the table
budget::money tot_expenses;
budget::money tot_earnings;
budget::money tot_balance;
budget::money tot_local;
budget::money prev_expenses;
budget::money prev_earnings;
budget::money prev_balance;
budget::money prev_local;
for (unsigned short i = sm; i <= month; ++i) {
budget::month m = i;
for (auto& account : all_accounts(year, m)) {
auto total_expenses = accumulate_amount_if(all_expenses(), [account, year, m](budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; });
auto total_earnings = accumulate_amount_if(all_earnings(), [account, year, m](budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; });
auto balance = account_previous[account.name] + account.amount - total_expenses + total_earnings;
auto local_balance = account.amount - total_expenses + total_earnings;
if (i == month) {
contents.push_back({account.name});
contents.back().push_back(format_money(total_expenses));
contents.back().push_back(format_money(total_earnings));
contents.back().push_back(format_money(balance));
contents.back().push_back(format_money(local_balance));
tot_expenses += total_expenses;
tot_earnings += total_earnings;
tot_balance += balance;
tot_local += local_balance;
} else if(month > 1 && m == month - 1){
prev_expenses = total_expenses;
prev_earnings = total_earnings;
prev_balance = balance;
prev_local = local_balance;
}
account_previous[account.name] = balance;
}
}
contents.push_back({"Total"});
contents.back().push_back(format_money(tot_expenses));
contents.back().push_back(format_money(tot_earnings));
contents.back().push_back(format_money(tot_balance));
contents.back().push_back(format_money(tot_local));
if(month > 1){
contents.push_back({"Previous"});
contents.back().push_back(format_money(prev_expenses));
contents.back().push_back(format_money(prev_earnings));
contents.back().push_back(format_money(prev_balance));
contents.back().push_back(format_money(prev_local));
contents.push_back({"Average"});
contents.back().push_back(format_money(tot_expenses / month.value));
contents.back().push_back(format_money(tot_earnings / month.value));
contents.back().push_back(format_money(tot_balance / month.value));
contents.back().push_back(format_money(tot_local / month.value));
}
std::stringstream ss;
console_writer w(ss);
w.display_table(columns, contents, 1, {}, 1);
return ss.str();
}
std::string objectives_summary(){
std::stringstream ss;
console_writer w(ss);
budget::yearly_objective_status(w, false, true);
ss << std::endl;
budget::current_monthly_objective_status(w, true);
return ss.str();
}
std::string fortune_summary(){
std::stringstream ss;
budget::status_fortunes(ss, true);
return ss.str();
}
void print_columns(const std::vector<std::string>& columns){
std::vector<std::vector<std::string>> split_columns;
for(auto& column : columns){
split_columns.push_back(budget::split(column, '\n'));
}
std::vector<std::string> composed_columns;
// Compute the total width
size_t total_max_width = composed_columns.size() * 2;
size_t max_length = 0;
for(auto& column : split_columns){
size_t max_width = 0;
for(auto& row : column){
max_width = std::max(max_width, rsize_after(row));
}
total_max_width += max_width;
max_length = std::max(max_length, column.size());
}
if (terminal_width() - 3 > total_max_width) {
// By default, print the columns side by side
for (auto& column : split_columns) {
size_t max_width = 0;
for (auto& row : column) {
max_width = std::max(max_width, rsize_after(row));
}
for (size_t i = 0; i < column.size(); ++i) {
auto& row = column[i];
if (i >= composed_columns.size()) {
composed_columns.emplace_back();
}
composed_columns[i] += row;
auto length = rsize_after(row);
if (length < max_width) {
composed_columns[i] += std::string(max_width - length, ' ');
}
}
for (size_t i = column.size(); i < max_length; ++i) {
if (i >= composed_columns.size()) {
composed_columns.emplace_back();
}
composed_columns[i] += std::string(max_width, ' ');
}
// Add some spacing from previous column
for (auto& row : composed_columns) {
row += " ";
}
}
for (auto& row : composed_columns) {
std::cout << row << std::endl;
}
} else {
// If the columns cannot be printed side by side
// print them one after another
for (auto& column : split_columns) {
for(auto& row : column){
std::cout << row << std::endl;
}
std::cout << std::endl;
}
}
}
void month_overview(budget::month month, budget::year year) {
// First display overview of the accounts
auto m_summary = account_summary(month, year);
// Second display a summary of the objectives
auto m_objectives_summary = objectives_summary();
// Third display a summary of the fortune
auto m_fortune_summary = fortune_summary();
print_columns({m_summary, m_objectives_summary, m_fortune_summary});
}
void month_overview(budget::month m) {
month_overview(m, local_day().year());
}
void month_overview() {
month_overview(local_day().month(), local_day().year());
}
} // end of anonymous namespace
constexpr const std::array<std::pair<const char*, const char*>, 1> budget::module_traits<budget::summary_module>::aliases;
void budget::summary_module::load() {
load_accounts();
load_expenses();
load_earnings();
load_objectives();
load_fortunes();
}
void budget::summary_module::handle(std::vector<std::string>& args) {
if (all_accounts().empty()) {
throw budget_exception("No accounts defined, you should start by defining some of them");
}
if (args.empty() || args.size() == 1) {
month_overview();
} else {
auto& subcommand = args[1];
if (subcommand == "month") {
auto today = local_day();
if (args.size() == 2) {
month_overview();
} else if (args.size() == 3) {
auto m = budget::month(to_number<unsigned short>(args[2]));
if (m > today.month()) {
throw budget_exception("Cannot compute the summary of the future");
}
month_overview(m);
} else if (args.size() == 4) {
auto m = budget::month(to_number<unsigned short>(args[2]));
auto y = budget::year(to_number<unsigned short>(args[3]));
if (y > today.year()) {
throw budget_exception("Cannot compute the summary of the future");
}
if (y == today.year() && m > today.month()) {
throw budget_exception("Cannot compute the summary of the future");
}
month_overview(m, y);
} else {
throw budget_exception("Too many arguments to overview month");
}
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
|
Fix print_columns
|
Fix print_columns
|
C++
|
mit
|
wichtounet/budgetwarrior,wichtounet/budgetwarrior,wichtounet/budgetwarrior
|
92739af6c52c2f7baf1574a1ac38d0cd245488e5
|
TableGen/DAGISelMatcherOpt.cpp
|
TableGen/DAGISelMatcherOpt.cpp
|
//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the DAG Matcher optimizer.
//
//===----------------------------------------------------------------------===//
#include "DAGISelMatcher.h"
using namespace llvm;
static void ContractNodes(OwningPtr<MatcherNode> &MatcherPtr) {
// If we reached the end of the chain, we're done.
MatcherNode *N = MatcherPtr.get();
if (N == 0) return;
// If we have a scope node, walk down both edges.
if (ScopeMatcherNode *Push = dyn_cast<ScopeMatcherNode>(N))
ContractNodes(Push->getCheckPtr());
// If we found a movechild node with a node that comes in a 'foochild' form,
// transform it.
if (MoveChildMatcherNode *MC = dyn_cast<MoveChildMatcherNode>(N)) {
MatcherNode *New = 0;
if (RecordMatcherNode *RM = dyn_cast<RecordMatcherNode>(MC->getNext()))
New = new RecordChildMatcherNode(MC->getChildNo(), RM->getWhatFor());
if (CheckTypeMatcherNode *CT= dyn_cast<CheckTypeMatcherNode>(MC->getNext()))
New = new CheckChildTypeMatcherNode(MC->getChildNo(), CT->getType());
if (New) {
// Insert the new node.
New->setNext(MatcherPtr.take());
MatcherPtr.reset(New);
// Remove the old one.
MC->setNext(MC->getNext()->takeNext());
return ContractNodes(MatcherPtr);
}
}
if (MoveChildMatcherNode *MC = dyn_cast<MoveChildMatcherNode>(N))
if (MoveParentMatcherNode *MP =
dyn_cast<MoveParentMatcherNode>(MC->getNext())) {
MatcherPtr.reset(MP->takeNext());
return ContractNodes(MatcherPtr);
}
ContractNodes(N->getNextPtr());
}
MatcherNode *llvm::OptimizeMatcher(MatcherNode *Matcher) {
OwningPtr<MatcherNode> MatcherPtr(Matcher);
ContractNodes(MatcherPtr);
return MatcherPtr.take();
}
|
//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the DAG Matcher optimizer.
//
//===----------------------------------------------------------------------===//
#include "DAGISelMatcher.h"
using namespace llvm;
static void ContractNodes(OwningPtr<MatcherNode> &MatcherPtr) {
// If we reached the end of the chain, we're done.
MatcherNode *N = MatcherPtr.get();
if (N == 0) return;
// If we have a scope node, walk down both edges.
if (ScopeMatcherNode *Push = dyn_cast<ScopeMatcherNode>(N))
ContractNodes(Push->getCheckPtr());
// If we found a movechild node with a node that comes in a 'foochild' form,
// transform it.
if (MoveChildMatcherNode *MC = dyn_cast<MoveChildMatcherNode>(N)) {
MatcherNode *New = 0;
if (RecordMatcherNode *RM = dyn_cast<RecordMatcherNode>(MC->getNext()))
New = new RecordChildMatcherNode(MC->getChildNo(), RM->getWhatFor());
if (CheckTypeMatcherNode *CT= dyn_cast<CheckTypeMatcherNode>(MC->getNext()))
New = new CheckChildTypeMatcherNode(MC->getChildNo(), CT->getType());
if (New) {
// Insert the new node.
New->setNext(MatcherPtr.take());
MatcherPtr.reset(New);
// Remove the old one.
MC->setNext(MC->getNext()->takeNext());
return ContractNodes(MatcherPtr);
}
}
if (MoveChildMatcherNode *MC = dyn_cast<MoveChildMatcherNode>(N))
if (MoveParentMatcherNode *MP =
dyn_cast<MoveParentMatcherNode>(MC->getNext())) {
MatcherPtr.reset(MP->takeNext());
return ContractNodes(MatcherPtr);
}
ContractNodes(N->getNextPtr());
}
static void FactorNodes(OwningPtr<MatcherNode> &MatcherPtr) {
// If we reached the end of the chain, we're done.
MatcherNode *N = MatcherPtr.get();
if (N == 0) return;
// If this is not a push node, just scan for one.
if (!isa<ScopeMatcherNode>(N))
return FactorNodes(N->getNextPtr());
// Okay, pull together the series of linear push nodes into a vector so we can
// inspect it more easily.
SmallVector<MatcherNode*, 32> OptionsToMatch;
MatcherNode *CurNode = N;
for (; ScopeMatcherNode *PMN = dyn_cast<ScopeMatcherNode>(CurNode);
CurNode = PMN->getNext())
OptionsToMatch.push_back(PMN->getCheck());
OptionsToMatch.push_back(CurNode);
}
MatcherNode *llvm::OptimizeMatcher(MatcherNode *Matcher) {
OwningPtr<MatcherNode> MatcherPtr(Matcher);
ContractNodes(MatcherPtr);
FactorNodes(MatcherPtr);
return MatcherPtr.take();
}
|
add some noop code to push it out of my tree.
|
add some noop code to push it out of my tree.
git-svn-id: a4a6f32337ebd29ad4763b423022f00f68d1c7b7@97094 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-3-clause
|
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
|
7d2de2b9d3a1799cec2d9943147583f7301be632
|
jubatus/client.hpp
|
jubatus/client.hpp
|
// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Networks 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
#ifndef JUBATUS_CLIENT_HPP_
#define JUBATUS_CLIENT_HPP_
//=============================================================//
// //
// _________ ___ //
// \____ _| | / ___I_I___ //
// | | | | \__^ ^__/ ____ //
// | | | | ___ ___ __ | | / __/ //
// | | |-| |-|| |/ \ / \| | | | |^| |^|| (__ //
// | | | | | || ^ || ^ | | | | | | | \__ \ //
// | | | \_/ || O || O | | |_| \_/ | ___) | //
// | | \__/|_||_|\___/ \___/|_| |__/ \__/|_| \___/ //
// | / //
// / / //
// |/ //
// //
//=============================================================//
#include <jubatus/client/classifier_client.hpp>
#include <jubatus/client/recommender_client.hpp>
#include <jubatus/client/stat_client.hpp>
#include <jubatus/client/regression_client.hpp>
#include <jubatus/client/graph_client.hpp>
#include <jubatus/client/anomaly_client.hpp>
#include <jubatus/client/burst_client.hpp>
#include <jubatus/client/nearest_neighbor_client.hpp>
#include <jubatus/client/clustering_client.hpp>
#include <jubatus/client/bandit_client.hpp>
#endif // JUBATUS_CLIENT_HPP_
|
// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Networks 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
#ifndef JUBATUS_CLIENT_HPP_
#define JUBATUS_CLIENT_HPP_
//=============================================================//
// //
// _________ ___ //
// \____ _| | / ___I_I___ //
// | | | | \__^ ^__/ ____ //
// | | | | ___ ___ __ | | / __/ //
// | | |-| |-|| |/ \ / \| | | | |^| |^|| (__ //
// | | | | | || ^ || ^ | | | | | | | \__ \ //
// | | | \_/ || O || O | | |_| \_/ | ___) | //
// | | \__/|_||_|\___/ \___/|_| |__/ \__/|_| \___/ //
// | / //
// / / //
// |/ //
// //
//=============================================================//
#include <jubatus/client/classifier_client.hpp>
#include <jubatus/client/recommender_client.hpp>
#include <jubatus/client/stat_client.hpp>
#include <jubatus/client/regression_client.hpp>
#include <jubatus/client/graph_client.hpp>
#include <jubatus/client/anomaly_client.hpp>
#include <jubatus/client/burst_client.hpp>
#include <jubatus/client/nearest_neighbor_client.hpp>
#include <jubatus/client/clustering_client.hpp>
#include <jubatus/client/bandit_client.hpp>
#include <jubatus/client/weight_client.hpp>
#endif // JUBATUS_CLIENT_HPP_
|
fix missing weight_client.hpp in client.hpp (fix #1127)
|
fix missing weight_client.hpp in client.hpp (fix #1127)
|
C++
|
lgpl-2.1
|
jubatus/jubatus,jubatus/jubatus,jubatus/jubatus
|
2f03fd4eeff5f01c241cbc7d9e51fb2f536e88f7
|
curiosity_animation/src/ofApp.cpp
|
curiosity_animation/src/ofApp.cpp
|
#include "ofApp.h"
#include "ofxXmlSettings.h"
//--------------------------------------------------------------
void ofApp::setup(){
// start logging
ofLogToFile("app.log");
// start recoding events
if (!eventLog.open(ofToDataPath("events.txt"), ofFile::WriteOnly)) {
ofLogError() << "Error opening events.txt - !!!DATA WILL BE LOST!!!";
}
if (!configuration.Read()) {
ofLogError() << "Error reading configuration";
}
if (!gameStats.Read()) {
ofLogError() << "Error reading game stats.";
}
ofSetFrameRate(configuration.FrameRate);
ofSetFullscreen(configuration.Fullscreen);
#ifdef TARGET_OSX
ofSetDataPathRoot("../Resources/data/");
#endif
// Distance reading
serialPort.listDevices();
vector<ofSerialDeviceInfo> deviceList = serialPort.getDeviceList();
if (configuration.ActiveSerialPort < deviceList.size()) {
if (!serialPort.setup(configuration.ActiveSerialPort, 9600)) {
ofLogError() << "Failed to connect to serial device! "
<< deviceList[configuration.ActiveSerialPort].getDeviceName();
}
}
currentDistance = configuration.MaxDistance;
previousDistanceChangeAt = ofGetElapsedTimeMillis();
// HUD
if (!f.loadFont("verdana.ttf", 16, true, true)) {
ofLogError() << "Error loading font";
}
f.setLineHeight(18.0f);
f.setLetterSpacing(1.037);
// Audio
if (!backgroundSound.loadSound("1.mp3")) {
ofLogError() << "Error loading background sound";
}
backgroundSound.setLoop(true);
if (!heartbeatSound.loadSound("2.mp3")) {
ofLogError() << "Error loading heartbeat sound";
}
heartbeatSound.setLoop(true);
}
bool Configuration::Read() {
// Read configuration or create default
ofxXmlSettings xml;
if (!xml.loadFile("configuration.xml")) {
xml.setValue("configuration:ImageCount", ImageCount);
xml.setValue("configuration:Fullscreen", Fullscreen);
xml.setValue("configuration:MinDistance", MinDistance);
xml.setValue("configuration:MaxDistance", MaxDistance);
xml.setValue("configuration:DeathZone", DeathZone);
xml.setValue("configuration:RestartIntervalSeconds", RestartIntervalSeconds);
xml.setValue("configuration:ActiveSerialPort", ActiveSerialPort);
xml.setValue("configuration:StartingFramesPerSecond", StartingFramesPerSecond);
xml.setValue("configuration:FinishingFramesPerSecond", FinishingFramesPerSecond);
xml.setValue("configuration:StartingVolume", StartingVolume);
xml.setValue("configuration:FinishingVolume", FinishingVolume);
xml.setValue("configuration:StartingHeartBeatSpeed", StartingHeartBeatSpeed);
xml.setValue("configuration:FinishingHeartBeatSpeed", FinishingHeartBeatSpeed);
xml.setValue("configuration:FrameRate", FrameRate);
if (!xml.saveFile("configuration.xml")) {
ofLogError() << "Error saving configuration file";
return false;
}
} else {
ImageCount = xml.getValue("configuration:ImageCount", ImageCount);
Fullscreen = xml.getValue("configuration:Fullscreen", Fullscreen);
MinDistance = xml.getValue("configuration:MinDistance", MinDistance);
MaxDistance = xml.getValue("configuration:MaxDistance", MaxDistance);
DeathZone = xml.getValue("configuration:DeathZone", DeathZone);
RestartIntervalSeconds = xml.getValue("configuration:RestartIntervalSeconds", RestartIntervalSeconds);
ActiveSerialPort = xml.getValue("configuration:ActiveSerialPort", ActiveSerialPort);
StartingFramesPerSecond = xml.getValue("configuration:StartingFramesPerSecond", StartingFramesPerSecond);
FinishingFramesPerSecond = xml.getValue("configuration:FinishingFramesPerSecond", FinishingFramesPerSecond);
StartingVolume = xml.getValue("configuration:StartingVolume", StartingVolume);
FinishingVolume = xml.getValue("configuration:FinishingVolume", FinishingVolume);
StartingHeartBeatSpeed = xml.getValue("configuration:StartingHeartBeatSpeed", StartingHeartBeatSpeed);
FinishingHeartBeatSpeed = xml.getValue("configuration:FinishingHeartBeatSpeed", FinishingHeartBeatSpeed);
FrameRate = xml.getValue("configuration:FrameRate", FrameRate);
}
return true;
}
bool GameStats::Read() {
// Read game stats or create default
ofxXmlSettings xml;
if (!xml.loadFile("gamestats.xml")) {
if (!Write()) {
return false;
}
} else {
Saves = xml.getValue("gamestats:Saves", Saves);
Kills = xml.getValue("gamestats:Kills", Kills);
}
return true;
}
bool GameStats::Write() const {
ofxXmlSettings xml;
xml.setValue("gamestats:Saves", Saves);
xml.setValue("gamestats:Kills", Kills);
return xml.saveFile();
}
//--------------------------------------------------------------
void ofApp::update(){
long now = ofGetElapsedTimeMillis();
// Determine if user is now in the death zone
if (!finishedAt && (currentDistance < configuration.MinDistance + configuration.DeathZone)) {
finishedAt = now;
ofLogNotice() << "Game finished at " << now;
eventLog << "finished=" << now << std::endl;
gameStats.Kills++;
if (!gameStats.Write()) {
ofLogError() << "Error writing game stats";
}
}
// Restart if needed
if (finishedAt && (finishedAt < now - (configuration.RestartIntervalSeconds*1000))) {
finishedAt = 0;
setFrame(0);
setDistance("restart", configuration.MaxDistance);
ofLogNotice() << "Game restarted";
eventLog << "started=" << now << std::endl;
}
// Read serial
if (serialPort.isInitialized()) {
if (serialPort.available()) {
char c = serialPort.readByte();
if ('\n' == c) {
std::string input = serialbuf.str();
serialbuf.str("");
ofLogNotice() << "Serial input: " << input << std::endl;
} else {
serialbuf << c;
}
}
}
// Update visual
long timePassed = now - previousFrameDrawnAt;
int millis = ofMap(currentDistance,
configuration.MaxDistance, configuration.MinDistance,
1000 / configuration.StartingFramesPerSecond, 1000 / configuration.FinishingFramesPerSecond);
fps = 1000 / millis;
if (timePassed >= millis) {
// move towards destination
if (destinationFrame > frame) {
setFrame(frame + 1);
} else if (destinationFrame < frame) {
setFrame(frame - 1);
}
previousFrameDrawnAt = now;
}
// Update audio
if (!backgroundSound.getIsPlaying()) {
backgroundSound.play();
}
backgroundSound.setVolume(ofMap(currentDistance,
configuration.MaxDistance, configuration.MinDistance,
configuration.StartingVolume, configuration.FinishingVolume));
if (!finishedAt) {
if (!heartbeatSound.getIsPlaying()) {
heartbeatSound.play();
}
heartbeatSound.setSpeed(ofMap(currentDistance,
configuration.MaxDistance, configuration.MinDistance,
configuration.StartingHeartBeatSpeed, configuration.FinishingHeartBeatSpeed));
} else {
if (heartbeatSound.getIsPlaying()) {
heartbeatSound.stop();
}
}
ofSoundUpdate();
}
ofTexture *ofApp::getImage(const int i) {
if (images.end() == images.find(i)) {
ofTexture img;
if (!ofLoadImage(img, ofToString(i) + ".jpg")) {
ofLogError() << "Error loading image";
return 0;
}
images[i] = img;
}
return &images[i];
}
// Frame for current distance
// Note that this is not the actual frame that will be animated.
// Instead will start to animate towards this frame.
int ofApp::frameForDistance() const {
return ofMap(currentDistance, configuration.MinDistance, configuration.MaxDistance, configuration.ImageCount, 0);
}
void ofApp::setFrame(const int i) {
frame = ofClamp(i, 0, configuration.ImageCount - 1);
}
void ofApp::setDestinationFrame(const int i) {
destinationFrame = ofClamp(i, 0, configuration.ImageCount - 1);
}
void ofApp::clearImage(const int i) {
images.erase(images.find(i));
}
//--------------------------------------------------------------
void ofApp::draw(){
// Update HUD
int y = 40;
f.drawString("dist=" + ofToString(currentDistance), 10, y);
f.drawString("f=" + ofToString(frame) + "/" + ofToString(configuration.ImageCount), 160, y);
f.drawString("dest.f=" + ofToString(destinationFrame), 310, y);
f.drawString("fps=" + ofToString(fps), 460, y);
f.drawString("saves=" + ofToString(gameStats.Saves), 610, y);
f.drawString("kills=" + ofToString(gameStats.Kills), 760, y);
// Draw the current animation frame
ofTexture *img = getImage(frame);
img->draw( 0, 60, ofGetWidth(), ofGetHeight() - 60 );
clearImage(frame);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
ofLogNotice() << "keyPressed key=" << key;
if (finishedAt) {
return;
}
if (OF_KEY_UP == key) {
// distance decreases as viewer approaches
setDistance("keyboard up", currentDistance - 50 - int(ofRandom(100)));
} else if (OF_KEY_DOWN == key) {
// distance incrases as viewer steps back
setDistance("keyboar down", currentDistance + 50 + int(ofRandom(100)));
}
}
void ofApp::setDistance(const std::string reason, const int value) {
currentDistance = ofClamp(value, configuration.MinDistance, configuration.MaxDistance);
// Start animating towards this new distance
setDestinationFrame(frameForDistance());
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
|
#include "ofApp.h"
#include "ofxXmlSettings.h"
//--------------------------------------------------------------
void ofApp::setup(){
// start logging
ofLogToFile("app.log");
// start recoding events
if (!eventLog.open(ofToDataPath("events.txt"), ofFile::WriteOnly)) {
ofLogError() << "Error opening events.txt - !!!DATA WILL BE LOST!!!";
}
if (!configuration.Read()) {
ofLogError() << "Error reading configuration";
}
if (!gameStats.Read()) {
ofLogError() << "Error reading game stats.";
}
ofSetFrameRate(configuration.FrameRate);
ofSetFullscreen(configuration.Fullscreen);
#ifdef TARGET_OSX
ofSetDataPathRoot("../Resources/data/");
#endif
// Distance reading
serialPort.listDevices();
vector<ofSerialDeviceInfo> deviceList = serialPort.getDeviceList();
if (configuration.ActiveSerialPort < deviceList.size()) {
if (!serialPort.setup(configuration.ActiveSerialPort, 9600)) {
ofLogError() << "Failed to connect to serial device! "
<< deviceList[configuration.ActiveSerialPort].getDeviceName();
}
}
currentDistance = configuration.MaxDistance;
previousDistanceChangeAt = ofGetElapsedTimeMillis();
// HUD
if (!f.loadFont("verdana.ttf", 16, true, true)) {
ofLogError() << "Error loading font";
}
f.setLineHeight(18.0f);
f.setLetterSpacing(1.037);
// Audio
if (!backgroundSound.loadSound("1.mp3")) {
ofLogError() << "Error loading background sound";
}
backgroundSound.setLoop(true);
if (!heartbeatSound.loadSound("2.mp3")) {
ofLogError() << "Error loading heartbeat sound";
}
heartbeatSound.setLoop(true);
}
bool Configuration::Read() {
// Read configuration or create default
ofxXmlSettings xml;
if (!xml.loadFile("configuration.xml")) {
xml.setValue("configuration:ImageCount", ImageCount);
xml.setValue("configuration:Fullscreen", Fullscreen);
xml.setValue("configuration:MinDistance", MinDistance);
xml.setValue("configuration:MaxDistance", MaxDistance);
xml.setValue("configuration:DeathZone", DeathZone);
xml.setValue("configuration:RestartIntervalSeconds", RestartIntervalSeconds);
xml.setValue("configuration:ActiveSerialPort", ActiveSerialPort);
xml.setValue("configuration:StartingFramesPerSecond", StartingFramesPerSecond);
xml.setValue("configuration:FinishingFramesPerSecond", FinishingFramesPerSecond);
xml.setValue("configuration:StartingVolume", StartingVolume);
xml.setValue("configuration:FinishingVolume", FinishingVolume);
xml.setValue("configuration:StartingHeartBeatSpeed", StartingHeartBeatSpeed);
xml.setValue("configuration:FinishingHeartBeatSpeed", FinishingHeartBeatSpeed);
xml.setValue("configuration:FrameRate", FrameRate);
if (!xml.saveFile("configuration.xml")) {
ofLogError() << "Error saving configuration file";
return false;
}
} else {
ImageCount = xml.getValue("configuration:ImageCount", ImageCount);
Fullscreen = xml.getValue("configuration:Fullscreen", Fullscreen);
MinDistance = xml.getValue("configuration:MinDistance", MinDistance);
MaxDistance = xml.getValue("configuration:MaxDistance", MaxDistance);
DeathZone = xml.getValue("configuration:DeathZone", DeathZone);
RestartIntervalSeconds = xml.getValue("configuration:RestartIntervalSeconds", RestartIntervalSeconds);
ActiveSerialPort = xml.getValue("configuration:ActiveSerialPort", ActiveSerialPort);
StartingFramesPerSecond = xml.getValue("configuration:StartingFramesPerSecond", StartingFramesPerSecond);
FinishingFramesPerSecond = xml.getValue("configuration:FinishingFramesPerSecond", FinishingFramesPerSecond);
StartingVolume = xml.getValue("configuration:StartingVolume", StartingVolume);
FinishingVolume = xml.getValue("configuration:FinishingVolume", FinishingVolume);
StartingHeartBeatSpeed = xml.getValue("configuration:StartingHeartBeatSpeed", StartingHeartBeatSpeed);
FinishingHeartBeatSpeed = xml.getValue("configuration:FinishingHeartBeatSpeed", FinishingHeartBeatSpeed);
FrameRate = xml.getValue("configuration:FrameRate", FrameRate);
}
return true;
}
bool GameStats::Read() {
// Read game stats or create default
ofxXmlSettings xml;
if (!xml.loadFile("gamestats.xml")) {
if (!Write()) {
return false;
}
} else {
Saves = xml.getValue("gamestats:Saves", Saves);
Kills = xml.getValue("gamestats:Kills", Kills);
}
return true;
}
bool GameStats::Write() const {
ofFile f(ofToDataPath("gamestats.xml"));
f.moveTo("gamestats_backup.xml");
ofxXmlSettings xml;
xml.setValue("gamestats:Saves", Saves);
xml.setValue("gamestats:Kills", Kills);
return xml.saveFile("gamestats.xml");
}
//--------------------------------------------------------------
void ofApp::update(){
long now = ofGetElapsedTimeMillis();
// Determine if user is now in the death zone
if (!finishedAt && (currentDistance < configuration.MinDistance + configuration.DeathZone)) {
finishedAt = now;
ofLogNotice() << "Game finished at " << now;
eventLog << "finished=" << now << std::endl;
gameStats.Kills++;
if (!gameStats.Write()) {
ofLogError() << "Error writing game stats";
}
}
// Restart if needed
if (finishedAt && (finishedAt < now - (configuration.RestartIntervalSeconds*1000))) {
finishedAt = 0;
setFrame(0);
setDistance("restart", configuration.MaxDistance);
ofLogNotice() << "Game restarted";
eventLog << "started=" << now << std::endl;
}
// Read serial
if (serialPort.isInitialized()) {
if (serialPort.available()) {
char c = serialPort.readByte();
if ('\n' == c) {
std::string input = serialbuf.str();
serialbuf.str("");
ofLogNotice() << "Serial input: " << input << std::endl;
} else {
serialbuf << c;
}
}
}
// Update visual
long timePassed = now - previousFrameDrawnAt;
int millis = ofMap(currentDistance,
configuration.MaxDistance, configuration.MinDistance,
1000 / configuration.StartingFramesPerSecond, 1000 / configuration.FinishingFramesPerSecond);
fps = 1000 / millis;
if (timePassed >= millis) {
// move towards destination
if (destinationFrame > frame) {
setFrame(frame + 1);
} else if (destinationFrame < frame) {
setFrame(frame - 1);
}
previousFrameDrawnAt = now;
}
// Update audio
if (!backgroundSound.getIsPlaying()) {
backgroundSound.play();
}
backgroundSound.setVolume(ofMap(currentDistance,
configuration.MaxDistance, configuration.MinDistance,
configuration.StartingVolume, configuration.FinishingVolume));
if (!finishedAt) {
if (!heartbeatSound.getIsPlaying()) {
heartbeatSound.play();
}
heartbeatSound.setSpeed(ofMap(currentDistance,
configuration.MaxDistance, configuration.MinDistance,
configuration.StartingHeartBeatSpeed, configuration.FinishingHeartBeatSpeed));
} else {
if (heartbeatSound.getIsPlaying()) {
heartbeatSound.stop();
}
}
ofSoundUpdate();
}
ofTexture *ofApp::getImage(const int i) {
if (images.end() == images.find(i)) {
ofTexture img;
if (!ofLoadImage(img, ofToString(i) + ".jpg")) {
ofLogError() << "Error loading image";
return 0;
}
images[i] = img;
}
return &images[i];
}
// Frame for current distance
// Note that this is not the actual frame that will be animated.
// Instead will start to animate towards this frame.
int ofApp::frameForDistance() const {
return ofMap(currentDistance, configuration.MinDistance, configuration.MaxDistance, configuration.ImageCount, 0);
}
void ofApp::setFrame(const int i) {
frame = ofClamp(i, 0, configuration.ImageCount - 1);
}
void ofApp::setDestinationFrame(const int i) {
destinationFrame = ofClamp(i, 0, configuration.ImageCount - 1);
}
void ofApp::clearImage(const int i) {
images.erase(images.find(i));
}
//--------------------------------------------------------------
void ofApp::draw(){
// Update HUD
int y = 40;
f.drawString("dist=" + ofToString(currentDistance), 10, y);
f.drawString("f=" + ofToString(frame) + "/" + ofToString(configuration.ImageCount), 160, y);
f.drawString("dest.f=" + ofToString(destinationFrame), 310, y);
f.drawString("fps=" + ofToString(fps), 460, y);
f.drawString("saves=" + ofToString(gameStats.Saves), 610, y);
f.drawString("kills=" + ofToString(gameStats.Kills), 760, y);
// Draw the current animation frame
ofTexture *img = getImage(frame);
img->draw( 0, 60, ofGetWidth(), ofGetHeight() - 60 );
clearImage(frame);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
ofLogNotice() << "keyPressed key=" << key;
if (finishedAt) {
return;
}
if (OF_KEY_UP == key) {
// distance decreases as viewer approaches
setDistance("keyboard up", currentDistance - 50 - int(ofRandom(100)));
} else if (OF_KEY_DOWN == key) {
// distance incrases as viewer steps back
setDistance("keyboar down", currentDistance + 50 + int(ofRandom(100)));
}
}
void ofApp::setDistance(const std::string reason, const int value) {
currentDistance = ofClamp(value, configuration.MinDistance, configuration.MaxDistance);
// Start animating towards this new distance
setDestinationFrame(frameForDistance());
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
|
save gamestats
|
save gamestats
|
C++
|
mit
|
tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation
|
812c590d821353f48548858df6fed16b20b8d60a
|
chrome/browser/errorpage_browsertest.cc
|
chrome/browser/errorpage_browsertest.cc
|
// 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 "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/net/url_request_mock_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/net/url_request_failed_dns_job.h"
#include "content/browser/net/url_request_mock_http_job.h"
#include "content/public/browser/web_contents.h"
#include "content/test/test_navigation_observer.h"
using content::BrowserThread;
using content::NavigationController;
class ErrorPageTest : public InProcessBrowserTest {
public:
enum HistoryNavigationDirection {
HISTORY_NAVIGATE_BACK,
HISTORY_NAVIGATE_FORWARD,
};
// Navigates the active tab to a mock url created for the file at |file_path|.
void NavigateToFileURL(const FilePath::StringType& file_path) {
ui_test_utils::NavigateToURL(
browser(),
URLRequestMockHTTPJob::GetMockUrl(FilePath(file_path)));
}
// Navigates to the given URL and waits for |num_navigations| to occur, and
// the title to change to |expected_title|.
void NavigateToURLAndWaitForTitle(const GURL& url,
const std::string& expected_title,
int num_navigations) {
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(),
ASCIIToUTF16(expected_title));
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), url, num_navigations);
EXPECT_EQ(title_watcher.WaitAndGetTitle(), ASCIIToUTF16(expected_title));
}
// Navigates back in the history and waits for |num_navigations| to occur, and
// the title to change to |expected_title|.
void GoBackAndWaitForTitle(const std::string& expected_title,
int num_navigations) {
NavigateHistoryAndWaitForTitle(expected_title,
num_navigations,
HISTORY_NAVIGATE_BACK);
}
// Navigates forward in the history and waits for |num_navigations| to occur,
// and the title to change to |expected_title|.
void GoForwardAndWaitForTitle(const std::string& expected_title,
int num_navigations) {
NavigateHistoryAndWaitForTitle(expected_title,
num_navigations,
HISTORY_NAVIGATE_FORWARD);
}
protected:
void SetUpOnMainThread() OVERRIDE {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
}
private:
// Navigates the browser the indicated direction in the history and waits for
// |num_navigations| to occur and the title to change to |expected_title|.
void NavigateHistoryAndWaitForTitle(const std::string& expected_title,
int num_navigations,
HistoryNavigationDirection direction) {
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(),
ASCIIToUTF16(expected_title));
TestNavigationObserver test_navigation_observer(
content::Source<NavigationController>(
&browser()->GetSelectedTabContentsWrapper()->web_contents()->
GetController()),
NULL,
num_navigations);
if (direction == HISTORY_NAVIGATE_BACK) {
browser()->GoBack(CURRENT_TAB);
} else if (direction == HISTORY_NAVIGATE_FORWARD) {
browser()->GoForward(CURRENT_TAB);
} else {
FAIL();
}
test_navigation_observer.WaitForObservation(
base::Bind(&ui_test_utils::RunMessageLoop),
base::Bind(&MessageLoop::Quit,
base::Unretained(MessageLoopForUI::current())));
EXPECT_EQ(title_watcher.WaitAndGetTitle(), ASCIIToUTF16(expected_title));
}
};
// Test that a DNS error occuring in the main frame redirects to an error page.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, DNSError_Basic) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
}
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, DNSError_GoBack1) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
}
// See crbug.com/109669
#if defined(USE_AURA)
#define MAYBE_DNSError_GoBack2 FLAKY_DNSError_GoBack2
#else
#define MAYBE_DNSError_GoBack2 DNSError_GoBack2
#endif
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
NavigateToFileURL(FILE_PATH_LITERAL("title3.html"));
GoBackAndWaitForTitle("Mock Link Doctor", 2);
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
}
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, DNSError_GoBack2AndForward) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
NavigateToFileURL(FILE_PATH_LITERAL("title3.html"));
GoBackAndWaitForTitle("Mock Link Doctor", 2);
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
GoForwardAndWaitForTitle("Mock Link Doctor", 2);
}
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, DNSError_GoBack2Forward2) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToFileURL(FILE_PATH_LITERAL("title3.html"));
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
GoBackAndWaitForTitle("Mock Link Doctor", 2);
GoBackAndWaitForTitle("Title Of More Awesomeness", 1);
GoForwardAndWaitForTitle("Mock Link Doctor", 2);
GoForwardAndWaitForTitle("Title Of Awesomeness", 1);
}
// Test that a DNS error occuring in an iframe.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
NavigateToURLAndWaitForTitle(
URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))),
"Blah",
1);
}
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToFileURL(FILE_PATH_LITERAL("iframe_dns_error.html"));
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
}
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToFileURL(FILE_PATH_LITERAL("iframe_dns_error.html"));
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
GoForwardAndWaitForTitle("Blah", 1);
}
// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, Page404) {
NavigateToURLAndWaitForTitle(
URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))),
"SUCCESS",
1);
}
|
// 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 "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/net/url_request_mock_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/net/url_request_failed_dns_job.h"
#include "content/browser/net/url_request_mock_http_job.h"
#include "content/public/browser/web_contents.h"
#include "content/test/test_navigation_observer.h"
using content::BrowserThread;
using content::NavigationController;
class ErrorPageTest : public InProcessBrowserTest {
public:
enum HistoryNavigationDirection {
HISTORY_NAVIGATE_BACK,
HISTORY_NAVIGATE_FORWARD,
};
// Navigates the active tab to a mock url created for the file at |file_path|.
void NavigateToFileURL(const FilePath::StringType& file_path) {
ui_test_utils::NavigateToURL(
browser(),
URLRequestMockHTTPJob::GetMockUrl(FilePath(file_path)));
}
// Navigates to the given URL and waits for |num_navigations| to occur, and
// the title to change to |expected_title|.
void NavigateToURLAndWaitForTitle(const GURL& url,
const std::string& expected_title,
int num_navigations) {
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(),
ASCIIToUTF16(expected_title));
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), url, num_navigations);
EXPECT_EQ(title_watcher.WaitAndGetTitle(), ASCIIToUTF16(expected_title));
}
// Navigates back in the history and waits for |num_navigations| to occur, and
// the title to change to |expected_title|.
void GoBackAndWaitForTitle(const std::string& expected_title,
int num_navigations) {
NavigateHistoryAndWaitForTitle(expected_title,
num_navigations,
HISTORY_NAVIGATE_BACK);
}
// Navigates forward in the history and waits for |num_navigations| to occur,
// and the title to change to |expected_title|.
void GoForwardAndWaitForTitle(const std::string& expected_title,
int num_navigations) {
NavigateHistoryAndWaitForTitle(expected_title,
num_navigations,
HISTORY_NAVIGATE_FORWARD);
}
protected:
void SetUpOnMainThread() OVERRIDE {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
}
private:
// Navigates the browser the indicated direction in the history and waits for
// |num_navigations| to occur and the title to change to |expected_title|.
void NavigateHistoryAndWaitForTitle(const std::string& expected_title,
int num_navigations,
HistoryNavigationDirection direction) {
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(),
ASCIIToUTF16(expected_title));
TestNavigationObserver test_navigation_observer(
content::Source<NavigationController>(
&browser()->GetSelectedTabContentsWrapper()->web_contents()->
GetController()),
NULL,
num_navigations);
if (direction == HISTORY_NAVIGATE_BACK) {
browser()->GoBack(CURRENT_TAB);
} else if (direction == HISTORY_NAVIGATE_FORWARD) {
browser()->GoForward(CURRENT_TAB);
} else {
FAIL();
}
test_navigation_observer.WaitForObservation(
base::Bind(&ui_test_utils::RunMessageLoop),
base::Bind(&MessageLoop::Quit,
base::Unretained(MessageLoopForUI::current())));
EXPECT_EQ(title_watcher.WaitAndGetTitle(), ASCIIToUTF16(expected_title));
}
};
// See crbug.com/109669
#if defined(USE_AURA)
#define MAYBE_DNSError_Basic FLAKY_DNSError_Basic
#else
#define MAYBE_DNSError_Basic DNSError_Basic
#endif
// Test that a DNS error occuring in the main frame redirects to an error page.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, MAYBE_DNSError_Basic) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
}
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, DNSError_GoBack1) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
}
// See crbug.com/109669
#if defined(USE_AURA)
#define MAYBE_DNSError_GoBack2 FLAKY_DNSError_GoBack2
#else
#define MAYBE_DNSError_GoBack2 DNSError_GoBack2
#endif
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
NavigateToFileURL(FILE_PATH_LITERAL("title3.html"));
GoBackAndWaitForTitle("Mock Link Doctor", 2);
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
}
// See crbug.com/109669
#if defined(USE_AURA)
#define MAYBE_DNSError_GoBack2AndForward FLAKY_DNSError_GoBack2AndForward
#else
#define MAYBE_DNSError_GoBack2AndForward DNSError_GoBack2AndForward
#endif
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2AndForward) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
NavigateToFileURL(FILE_PATH_LITERAL("title3.html"));
GoBackAndWaitForTitle("Mock Link Doctor", 2);
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
GoForwardAndWaitForTitle("Mock Link Doctor", 2);
}
// See crbug.com/109669
#if defined(USE_AURA)
#define MAYBE_DNSError_GoBack2AndForward2 FLAKY_DNSError_GoBack2AndForward2
#else
#define MAYBE_DNSError_GoBack2AndForward2 DNSError_GoBack2AndForward2
#endif
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2Forward2) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToFileURL(FILE_PATH_LITERAL("title3.html"));
NavigateToURLAndWaitForTitle(test_url, "Mock Link Doctor", 2);
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
GoBackAndWaitForTitle("Mock Link Doctor", 2);
GoBackAndWaitForTitle("Title Of More Awesomeness", 1);
GoForwardAndWaitForTitle("Mock Link Doctor", 2);
GoForwardAndWaitForTitle("Title Of Awesomeness", 1);
}
// Test that a DNS error occuring in an iframe.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
NavigateToURLAndWaitForTitle(
URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))),
"Blah",
1);
}
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToFileURL(FILE_PATH_LITERAL("iframe_dns_error.html"));
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
}
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
NavigateToFileURL(FILE_PATH_LITERAL("title2.html"));
NavigateToFileURL(FILE_PATH_LITERAL("iframe_dns_error.html"));
GoBackAndWaitForTitle("Title Of Awesomeness", 1);
GoForwardAndWaitForTitle("Blah", 1);
}
// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
IN_PROC_BROWSER_TEST_F(ErrorPageTest, Page404) {
NavigateToURLAndWaitForTitle(
URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))),
"SUCCESS",
1);
}
|
Mark more ErrorPageTest.DNSError* tests as flaky
|
Mark more ErrorPageTest.DNSError* tests as flaky
[email protected]
BUG=109669
TEST=ErrorPageTest.DNSError_[Basic|GoBack2AndForward|GoBack2AndForward2]
Review URL: http://codereview.chromium.org/9114058
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@117140 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium
|
ad27ecb3b6378ddd38fca1268054b6d564461571
|
chrome/browser/process_singleton_mac.cc
|
chrome/browser/process_singleton_mac.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include "chrome/browser/process_singleton.h"
#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/metrics/histogram.h"
#include "chrome/common/chrome_constants.h"
namespace {
// From "man 2 intro".
const int kMaxErrno = EOPNOTSUPP;
} // namespace
// This class is used to funnel messages to a single instance of the browser
// process. This is needed for several reasons on other platforms.
//
// On Windows, when the user re-opens the application from the shell (e.g. an
// explicit double-click, a shortcut that opens a webpage, etc.) we need to send
// the message to the currently-existing copy of the browser.
//
// On Linux, opening a URL is done by creating an instance of the web browser
// process and passing it the URL to go to on its commandline.
//
// Neither of those cases apply on the Mac. Launch Services ensures that there
// is only one instance of the process, and we get URLs to open via AppleEvents
// and, once again, the Launch Services system. We have no need to manage this
// ourselves. An exclusive lock is used to flush out anyone making incorrect
// assumptions.
ProcessSingleton::ProcessSingleton(const FilePath& user_data_dir)
: locked_(false),
foreground_window_(NULL),
lock_path_(user_data_dir.Append(chrome::kSingletonLockFilename)),
lock_fd_(-1) {
}
ProcessSingleton::~ProcessSingleton() {
// Make sure the lock is released. Process death will also release
// it, even if this is not called.
Cleanup();
}
ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
// This space intentionally left blank.
return PROCESS_NONE;
}
ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
// Windows tries NotifyOtherProcess() first.
return Create() ? PROCESS_NONE : PROFILE_IN_USE;
}
// Attempt to acquire an exclusive lock on an empty file in the
// profile directory. Returns |true| if it gets the lock.
// TODO(shess): The older code always returned |true|. Monitor the
// histograms and convert the marked failure cases to |false| once
// it's clear that it is safe to do. http://crbug.com/58986
// TODO(shess): Rather than logging failures, popup an alert. Punting
// that for now because it would require confidence that this code is
// never called in a situation where an alert wouldn't work.
// http://crbug.com/59061
bool ProcessSingleton::Create() {
DCHECK_EQ(-1, lock_fd_) << "lock_path_ is already open.";
lock_fd_ = HANDLE_EINTR(open(lock_path_.value().c_str(),
O_RDONLY | O_CREAT, 0644));
if (lock_fd_ == -1) {
const int capture_errno = errno;
DPCHECK(lock_fd_ != -1) << "Unexpected failure opening profile lockfile";
UMA_HISTOGRAM_ENUMERATION("ProcessSingleton.OpenError",
capture_errno, kMaxErrno);
// TODO(shess): Change to |false|.
return true;
}
// Acquire an exclusive lock in non-blocking fashion. If the lock
// is already held, this will return |EWOULDBLOCK|.
int rc = HANDLE_EINTR(flock(lock_fd_, LOCK_EX|LOCK_NB));
if (rc == -1) {
const int capture_errno = errno;
DPCHECK(errno == EWOULDBLOCK)
<< "Unexpected failure locking profile lockfile";
Cleanup();
// Other errors indicate something crazy is happening.
if (capture_errno != EWOULDBLOCK) {
UMA_HISTOGRAM_ENUMERATION("ProcessSingleton.LockError",
capture_errno, kMaxErrno);
// TODO(shess): Change to |false|.
return true;
}
// The file is open by another process and locked.
LOG(ERROR) << "Unable to obtain profile lock.";
return false;
}
return true;
}
void ProcessSingleton::Cleanup() {
// Closing the file also releases the lock.
if (lock_fd_ != -1)
HANDLE_EINTR(close(lock_fd_));
lock_fd_ = -1;
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include "chrome/browser/process_singleton.h"
#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/metrics/histogram.h"
#include "chrome/common/chrome_constants.h"
namespace {
// From "man 2 intro", the largest errno is |EOPNOTSUPP|, which is
// |102|. Since the histogram memory usage is proportional to this
// number, using the |102| directly rather than the macro.
const int kMaxErrno = 102;
} // namespace
// This class is used to funnel messages to a single instance of the browser
// process. This is needed for several reasons on other platforms.
//
// On Windows, when the user re-opens the application from the shell (e.g. an
// explicit double-click, a shortcut that opens a webpage, etc.) we need to send
// the message to the currently-existing copy of the browser.
//
// On Linux, opening a URL is done by creating an instance of the web browser
// process and passing it the URL to go to on its commandline.
//
// Neither of those cases apply on the Mac. Launch Services ensures that there
// is only one instance of the process, and we get URLs to open via AppleEvents
// and, once again, the Launch Services system. We have no need to manage this
// ourselves. An exclusive lock is used to flush out anyone making incorrect
// assumptions.
ProcessSingleton::ProcessSingleton(const FilePath& user_data_dir)
: locked_(false),
foreground_window_(NULL),
lock_path_(user_data_dir.Append(chrome::kSingletonLockFilename)),
lock_fd_(-1) {
}
ProcessSingleton::~ProcessSingleton() {
// Make sure the lock is released. Process death will also release
// it, even if this is not called.
Cleanup();
}
ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
// This space intentionally left blank.
return PROCESS_NONE;
}
ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
// Windows tries NotifyOtherProcess() first.
return Create() ? PROCESS_NONE : PROFILE_IN_USE;
}
// Attempt to acquire an exclusive lock on an empty file in the
// profile directory. Returns |true| if it gets the lock.
// TODO(shess): The older code always returned |true|. Monitor the
// histograms and convert the marked failure cases to |false| once
// it's clear that it is safe to do. http://crbug.com/58986
// TODO(shess): Rather than logging failures, popup an alert. Punting
// that for now because it would require confidence that this code is
// never called in a situation where an alert wouldn't work.
// http://crbug.com/59061
bool ProcessSingleton::Create() {
DCHECK_EQ(-1, lock_fd_) << "lock_path_ is already open.";
lock_fd_ = HANDLE_EINTR(open(lock_path_.value().c_str(),
O_RDONLY | O_CREAT, 0644));
if (lock_fd_ == -1) {
const int capture_errno = errno;
DPCHECK(lock_fd_ != -1) << "Unexpected failure opening profile lockfile";
UMA_HISTOGRAM_ENUMERATION("ProcessSingleton.OpenError",
capture_errno, kMaxErrno);
// TODO(shess): Change to |false|.
return true;
}
// Acquire an exclusive lock in non-blocking fashion. If the lock
// is already held, this will return |EWOULDBLOCK|.
int rc = HANDLE_EINTR(flock(lock_fd_, LOCK_EX|LOCK_NB));
if (rc == -1) {
const int capture_errno = errno;
DPCHECK(errno == EWOULDBLOCK)
<< "Unexpected failure locking profile lockfile";
Cleanup();
// Other errors indicate something crazy is happening.
if (capture_errno != EWOULDBLOCK) {
UMA_HISTOGRAM_ENUMERATION("ProcessSingleton.LockError",
capture_errno, kMaxErrno);
// TODO(shess): Change to |false|.
return true;
}
// The file is open by another process and locked.
LOG(ERROR) << "Unable to obtain profile lock.";
return false;
}
return true;
}
void ProcessSingleton::Cleanup() {
// Closing the file also releases the lock.
if (lock_fd_ != -1) {
int rc = HANDLE_EINTR(close(lock_fd_));
DPCHECK(!rc) << "Closing lock_fd_:";
}
lock_fd_ = -1;
}
|
Fix clang breakage in process_singleton_mac.cc.
|
[Mac] Fix clang breakage in process_singleton_mac.cc.
Not using the return value from close() is verboten. Use the return
value.
Additionally, a late addition to the original CL asked for
clarification that kMaxErrno wasn't "too big". Make it so.
BUG=none
TEST=clang builds. histograms don't take up megabytes.
Review URL: http://codereview.chromium.org/3760005
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@62681 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
bbdb8d37f859a07348d4548f760513f1602eb85d
|
wb-homa-modbus/modbus_client.cpp
|
wb-homa-modbus/modbus_client.cpp
|
#include <iostream>
#include <unistd.h>
#include "modbus_client.h"
class TModbusHandler
{
public:
TModbusHandler(const TModbusParameter& _param): param(_param) {}
virtual ~TModbusHandler() {}
virtual int Read(modbus_t* ctx) = 0;
virtual void Write(modbus_t* ctx, int v);
const TModbusParameter& Parameter() const { return param; }
bool Poll(modbus_t* ctx);
void Flush(modbus_t* ctx);
int Value() const { return value; }
void SetValue(int v);
private:
int value = 0;
TModbusParameter param;
bool dirty = false;
bool did_read = false;
};
void TModbusHandler::Write(modbus_t*, int)
{
throw TModbusException("trying to write read-only parameter");
};
bool TModbusHandler::Poll(modbus_t* ctx)
{
bool first_poll = !did_read;
int new_value;
modbus_set_slave(ctx, param.slave);
try {
new_value = Read(ctx);
} catch (const TModbusException& e) {
std::cerr << "TModbusHandler::Poll(): warning: " << e.what() << std::endl;
return false;
}
did_read = true;
if (value != new_value) {
value = new_value;
std::cout << "new val for " << param.str() << ": " << new_value << std::endl;
return true;
}
return first_poll;
}
void TModbusHandler::Flush(modbus_t* ctx)
{
if (dirty) {
modbus_set_slave(ctx, param.slave);
try {
Write(ctx, value);
} catch (const TModbusException& e) {
std::cerr << "TModbusHandler::Flush(): warning: " << e.what() << std::endl;
return;
}
dirty = false;
}
}
void TModbusHandler::SetValue(int v)
{
value = v;
dirty = true;
}
class TCoilHandler: public TModbusHandler
{
public:
TCoilHandler(const TModbusParameter& _param): TModbusHandler(_param) {}
int Read(modbus_t* ctx) {
unsigned char b;
if (modbus_read_bits(ctx, Parameter().address, 1, &b) < 1)
throw TModbusException("failed to read coil");
return b & 1;
}
void Write(modbus_t* ctx, int v) {
if (modbus_write_bit(ctx, Parameter().address, v) < 0)
throw TModbusException("failed to write coil");
}
};
class TDiscreteInputHandler: public TModbusHandler
{
public:
TDiscreteInputHandler(const TModbusParameter& _param): TModbusHandler(_param) {}
int Read(modbus_t* ctx) {
uint8_t b;
if (modbus_read_input_bits(ctx, Parameter().address, 1, &b) < 1)
throw TModbusException("failed to read discrete input");
return b & 1;
}
};
class THoldingRegisterHandler: public TModbusHandler
{
public:
THoldingRegisterHandler(const TModbusParameter& _param): TModbusHandler(_param) {}
int Read(modbus_t* ctx) {
uint16_t v;
if (modbus_read_registers(ctx, Parameter().address, 1, &v) < 1)
throw TModbusException("failed to read holding register");
return v;
}
void Write(modbus_t* ctx, int v) {
// FIXME: the following code causes an error:
// if (modbus_write_register(ctx, Parameter().address, v) < 0)
// throw TModbusException("failed to write holding register");
// setting modbus register: <1:holding: 1> <- 30146
// <01><03><02><5A><1C><83><2D>
// [01][06][00][01][75][C2][7F][0B]
// Waiting for a confirmation...
// <01><03><02><00><00><B8><44>
// Message length not corresponding to the computed length (7 != 8)
// Fatal: Modbus error: failed to write holding register
// Exiting...
uint16_t d = (uint16_t)v;
std::cout << "write: " << Parameter().str() << std::endl;
if (modbus_write_registers(ctx, Parameter().address, 1, &d) < 1)
throw TModbusException("failed to write holding register");
}
};
class TInputRegisterHandler: public TModbusHandler
{
public:
TInputRegisterHandler(const TModbusParameter& _param): TModbusHandler(_param) {}
int Read(modbus_t* ctx) {
uint16_t v;
if (modbus_read_input_registers(ctx, Parameter().address, 1, &v) < 1)
throw TModbusException("failed to read input register");
return v;
}
};
TModbusClient::TModbusClient(std::string device,
int baud_rate,
char parity,
int data_bits,
int stop_bits)
: active(false)
{
ctx = modbus_new_rtu(device.c_str(), baud_rate, parity, data_bits, stop_bits);
if (!ctx)
throw TModbusException("failed to create modbus context");
// modbus_set_debug(ctx, 1);
modbus_set_error_recovery(ctx, MODBUS_ERROR_RECOVERY_PROTOCOL); // FIXME
}
TModbusClient::~TModbusClient()
{
if (active)
Disconnect();
modbus_free(ctx);
}
void TModbusClient::AddParam(const TModbusParameter& param)
{
if (active)
throw TModbusException("can't add parameters to the active client");
if (handlers.find(param) != handlers.end())
throw TModbusException("duplicate parameter");
handlers[param] = std::unique_ptr<TModbusHandler>(CreateParameterHandler(param));
}
void TModbusClient::Connect()
{
if (active)
return;
if (modbus_connect(ctx) != 0)
throw TModbusException("couldn't initialize the serial port");
modbus_flush(ctx);
active = true;
}
void TModbusClient::Disconnect()
{
modbus_close(ctx);
active = false;
}
void TModbusClient::Loop()
{
if (!handlers.size())
throw TModbusException("no parameters defined");
Connect();
// FIXME: that's suboptimal polling implementation.
// Need to implement bunching of Modbus registers.
// Note that for multi-register values, all values
// corresponding to single parameter should be retrieved
// by single query.
for (;;) {
for (const auto& p: handlers) {
p.second->Flush(ctx);
if (p.second->Poll(ctx) && callback)
callback(p.first, p.second->Value());
usleep(100000); // FIXME
}
}
}
void TModbusClient::SetValue(const TModbusParameter& param, int value)
{
auto it = handlers.find(param);
if (it == handlers.end())
throw TModbusException("parameter not found");
it->second->SetValue(value);
}
void TModbusClient::SetCallback(const TModbusCallback& _callback)
{
callback = _callback;
}
TModbusHandler* TModbusClient::CreateParameterHandler(const TModbusParameter& param)
{
switch (param.type) {
case TModbusParameter::Type::COIL:
return new TCoilHandler(param);
case TModbusParameter::Type::DISCRETE_INPUT:
return new TDiscreteInputHandler(param);
case TModbusParameter::Type::HOLDING_REGITER:
return new THoldingRegisterHandler(param);
case TModbusParameter::Type::INPUT_REGISTER:
return new THoldingRegisterHandler(param);
default:
throw TModbusException("bad parameter type");
}
}
|
#include <iostream>
#include <unistd.h>
#include "modbus_client.h"
class TModbusHandler
{
public:
TModbusHandler(const TModbusParameter& _param): param(_param) {}
virtual ~TModbusHandler() {}
virtual int Read(modbus_t* ctx) = 0;
virtual void Write(modbus_t* ctx, int v);
const TModbusParameter& Parameter() const { return param; }
bool Poll(modbus_t* ctx);
void Flush(modbus_t* ctx);
int Value() const { return value; }
void SetValue(int v);
private:
int value = 0;
TModbusParameter param;
bool dirty = false;
bool did_read = false;
};
void TModbusHandler::Write(modbus_t*, int)
{
throw TModbusException("trying to write read-only parameter");
};
bool TModbusHandler::Poll(modbus_t* ctx)
{
bool first_poll = !did_read;
int new_value;
modbus_set_slave(ctx, param.slave);
try {
new_value = Read(ctx);
} catch (const TModbusException& e) {
std::cerr << "TModbusHandler::Poll(): warning: " << e.what() << std::endl;
return false;
}
did_read = true;
if (value != new_value) {
value = new_value;
std::cout << "new val for " << param.str() << ": " << new_value << std::endl;
return true;
}
return first_poll;
}
void TModbusHandler::Flush(modbus_t* ctx)
{
if (dirty) {
modbus_set_slave(ctx, param.slave);
try {
Write(ctx, value);
} catch (const TModbusException& e) {
std::cerr << "TModbusHandler::Flush(): warning: " << e.what() << std::endl;
return;
}
dirty = false;
}
}
void TModbusHandler::SetValue(int v)
{
value = v;
dirty = true;
}
class TCoilHandler: public TModbusHandler
{
public:
TCoilHandler(const TModbusParameter& _param): TModbusHandler(_param) {}
int Read(modbus_t* ctx) {
unsigned char b;
if (modbus_read_bits(ctx, Parameter().address, 1, &b) < 1)
throw TModbusException("failed to read coil");
return b & 1;
}
void Write(modbus_t* ctx, int v) {
if (modbus_write_bit(ctx, Parameter().address, v) < 0)
throw TModbusException("failed to write coil");
}
};
class TDiscreteInputHandler: public TModbusHandler
{
public:
TDiscreteInputHandler(const TModbusParameter& _param): TModbusHandler(_param) {}
int Read(modbus_t* ctx) {
uint8_t b;
if (modbus_read_input_bits(ctx, Parameter().address, 1, &b) < 1)
throw TModbusException("failed to read discrete input");
return b & 1;
}
};
class THoldingRegisterHandler: public TModbusHandler
{
public:
THoldingRegisterHandler(const TModbusParameter& _param): TModbusHandler(_param) {}
int Read(modbus_t* ctx) {
uint16_t v;
if (modbus_read_registers(ctx, Parameter().address, 1, &v) < 1)
throw TModbusException("failed to read holding register");
return v;
}
void Write(modbus_t* ctx, int v) {
// FIXME: the following code causes an error:
// if (modbus_write_register(ctx, Parameter().address, v) < 0)
// throw TModbusException("failed to write holding register");
// setting modbus register: <1:holding: 1> <- 30146
// <01><03><02><5A><1C><83><2D>
// [01][06][00][01][75][C2][7F][0B]
// Waiting for a confirmation...
// <01><03><02><00><00><B8><44>
// Message length not corresponding to the computed length (7 != 8)
// Fatal: Modbus error: failed to write holding register
// Exiting...
uint16_t d = (uint16_t)v;
std::cout << "write: " << Parameter().str() << std::endl;
if (modbus_write_registers(ctx, Parameter().address, 1, &d) < 1)
throw TModbusException("failed to write holding register");
}
};
class TInputRegisterHandler: public TModbusHandler
{
public:
TInputRegisterHandler(const TModbusParameter& _param): TModbusHandler(_param) {}
int Read(modbus_t* ctx) {
uint16_t v;
if (modbus_read_input_registers(ctx, Parameter().address, 1, &v) < 1)
throw TModbusException("failed to read input register");
return v;
}
};
TModbusClient::TModbusClient(std::string device,
int baud_rate,
char parity,
int data_bits,
int stop_bits)
: active(false)
{
ctx = modbus_new_rtu(device.c_str(), baud_rate, parity, data_bits, stop_bits);
if (!ctx)
throw TModbusException("failed to create modbus context");
// modbus_set_debug(ctx, 1);
modbus_set_error_recovery(ctx, MODBUS_ERROR_RECOVERY_PROTOCOL); // FIXME
}
TModbusClient::~TModbusClient()
{
if (active)
Disconnect();
modbus_free(ctx);
}
void TModbusClient::AddParam(const TModbusParameter& param)
{
if (active)
throw TModbusException("can't add parameters to the active client");
if (handlers.find(param) != handlers.end())
throw TModbusException("duplicate parameter");
handlers[param] = std::unique_ptr<TModbusHandler>(CreateParameterHandler(param));
}
void TModbusClient::Connect()
{
if (active)
return;
if (modbus_connect(ctx) != 0)
throw TModbusException("couldn't initialize the serial port");
modbus_flush(ctx);
active = true;
}
void TModbusClient::Disconnect()
{
modbus_close(ctx);
active = false;
}
void TModbusClient::Loop()
{
if (!handlers.size())
throw TModbusException("no parameters defined");
Connect();
// FIXME: that's suboptimal polling implementation.
// Need to implement bunching of Modbus registers.
// Note that for multi-register values, all values
// corresponding to single parameter should be retrieved
// by single query.
for (;;) {
for (const auto& p: handlers) {
p.second->Flush(ctx);
if (p.second->Poll(ctx) && callback)
callback(p.first, p.second->Value());
usleep(100000); // FIXME
}
}
}
void TModbusClient::SetValue(const TModbusParameter& param, int value)
{
auto it = handlers.find(param);
if (it == handlers.end())
throw TModbusException("parameter not found");
it->second->SetValue(value);
}
void TModbusClient::SetCallback(const TModbusCallback& _callback)
{
callback = _callback;
}
TModbusHandler* TModbusClient::CreateParameterHandler(const TModbusParameter& param)
{
switch (param.type) {
case TModbusParameter::Type::COIL:
return new TCoilHandler(param);
case TModbusParameter::Type::DISCRETE_INPUT:
return new TDiscreteInputHandler(param);
case TModbusParameter::Type::HOLDING_REGITER:
return new THoldingRegisterHandler(param);
case TModbusParameter::Type::INPUT_REGISTER:
return new TInputRegisterHandler(param);
default:
throw TModbusException("bad parameter type");
}
}
|
fix input register handling.
|
modbus: fix input register handling.
|
C++
|
mit
|
vasvlad/wb-homa-drivers,vasvlad/wb-homa-drivers,vasvlad/wb-homa-drivers,vasvlad/wb-homa-drivers
|
feb738b7a046ace499034f3a26c988ef78f5fac9
|
engine/core/linux/NativeWindowLinux.hpp
|
engine/core/linux/NativeWindowLinux.hpp
|
// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_CORE_NATIVEWINDOWLINUX_HPP
#define OUZEL_CORE_NATIVEWINDOWLINUX_HPP
#include "../Setup.h"
#include <cstdint>
#if OUZEL_SUPPORTS_X11
# include <X11/Xlib.h>
# include <X11/Xutil.h>
#elif OUZEL_SUPPORTS_DISPMANX
# include <bcm_host.h>
typedef struct
{
DISPMANX_ELEMENT_HANDLE_T element;
int width; /* This is necessary because dispmanx elements are not queriable. */
int height;
} EGL_DISPMANX_WINDOW_T;
#endif
#include "../NativeWindow.hpp"
#include "../../graphics/Graphics.hpp"
namespace ouzel::core::linux
{
class Engine;
class NativeWindow final: public core::NativeWindow
{
friend Engine;
public:
NativeWindow(const std::function<void(const Event&)>& initCallback,
const Size2U& newSize,
bool newResizable,
bool newFullscreen,
bool newExclusiveFullscreen,
const std::string& newTitle);
~NativeWindow() override;
void executeCommand(const Command& command) final;
void close();
void setSize(const Size2U& newSize);
void setFullscreen(bool newFullscreen);
void setTitle(const std::string& newTitle);
void bringToFront();
void show();
void hide();
void minimize();
void maximize();
void restore();
auto& getNativeWindow() const noexcept { return window; }
#if OUZEL_SUPPORTS_X11
auto& getDisplay() const noexcept { return display; }
auto getProtocolsAtom() const noexcept { return protocolsAtom; }
auto getDeleteAtom() const noexcept { return deleteAtom; }
#endif
private:
#if OUZEL_SUPPORTS_X11
void handleFocusIn();
void handleFocusOut();
void handleResize(const Size2U& newSize);
void handleMap();
void handleUnmap();
bool isMapped() const;
Display* display = nullptr;
int screenNumber = 0;
::Window window = None;
Atom deleteAtom = None;
Atom protocolsAtom = None;
Atom stateAtom = None;
Atom stateFullscreenAtom = None;
Atom activateWindowAtom = None;
#elif OUZEL_SUPPORTS_DISPMANX
EGL_DISPMANX_WINDOW_T window;
#endif
};
}
#endif // OUZEL_CORE_NATIVEWINDOWLINUX_HPP
|
// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_CORE_NATIVEWINDOWLINUX_HPP
#define OUZEL_CORE_NATIVEWINDOWLINUX_HPP
#include "../Setup.h"
#include <cstdint>
#if OUZEL_SUPPORTS_X11
# include <X11/Xlib.h>
# include <X11/Xutil.h>
#elif OUZEL_SUPPORTS_DISPMANX
# include <bcm_host.h>
typedef struct
{
DISPMANX_ELEMENT_HANDLE_T element;
int width; /* This is necessary because dispmanx elements are not queriable. */
int height;
} EGL_DISPMANX_WINDOW_T;
#endif
#include "../NativeWindow.hpp"
namespace ouzel::core::linux
{
class Engine;
class NativeWindow final: public core::NativeWindow
{
friend Engine;
public:
NativeWindow(const std::function<void(const Event&)>& initCallback,
const Size2U& newSize,
bool newResizable,
bool newFullscreen,
bool newExclusiveFullscreen,
const std::string& newTitle);
~NativeWindow() override;
void executeCommand(const Command& command) final;
void close();
void setSize(const Size2U& newSize);
void setFullscreen(bool newFullscreen);
void setTitle(const std::string& newTitle);
void bringToFront();
void show();
void hide();
void minimize();
void maximize();
void restore();
auto& getNativeWindow() const noexcept { return window; }
#if OUZEL_SUPPORTS_X11
auto& getDisplay() const noexcept { return display; }
auto getProtocolsAtom() const noexcept { return protocolsAtom; }
auto getDeleteAtom() const noexcept { return deleteAtom; }
#endif
private:
#if OUZEL_SUPPORTS_X11
void handleFocusIn();
void handleFocusOut();
void handleResize(const Size2U& newSize);
void handleMap();
void handleUnmap();
bool isMapped() const;
Display* display = nullptr;
int screenNumber = 0;
::Window window = None;
Atom deleteAtom = None;
Atom protocolsAtom = None;
Atom stateAtom = None;
Atom stateFullscreenAtom = None;
Atom activateWindowAtom = None;
#elif OUZEL_SUPPORTS_DISPMANX
EGL_DISPMANX_WINDOW_T window;
#endif
};
}
#endif // OUZEL_CORE_NATIVEWINDOWLINUX_HPP
|
Remove unneeded include
|
Remove unneeded include
|
C++
|
unlicense
|
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
|
aa10e9b61d3b42c94a36defd6d259e4f6b314d2d
|
EMCAL/EMCALUtils/AliEMCALTriggerMappingV1.cxx
|
EMCAL/EMCALUtils/AliEMCALTriggerMappingV1.cxx
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
Author: R. GUERNANE LPSC Grenoble CNRS/IN2P3
*/
#include "AliEMCALTriggerMapping.h"
#include "AliEMCALTriggerMappingV1.h"
#include "AliEMCALGeometry.h"
#include "AliLog.h"
ClassImp(AliEMCALTriggerMappingV1)
//________________________________________________________________________________________________
AliEMCALTriggerMappingV1::AliEMCALTriggerMappingV1() : AliEMCALTriggerMapping()
{
// Ctor
SetUniqueID(1);
}
//________________________________________________________________________________________________
AliEMCALTriggerMappingV1::AliEMCALTriggerMappingV1(const Int_t ntru, const AliEMCALGeometry* geo) : AliEMCALTriggerMapping(ntru, geo)
{
// Ctor
SetUniqueID(1);
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetAbsFastORIndexFromTRU(const Int_t iTRU, const Int_t iADC, Int_t& id) const
{
//Trigger mapping method, get FastOr Index from TRU
if (iTRU > fNTRU - 1 || iTRU < 0 || iADC > 95 || iADC < 0) {
AliError("TRU out of range!");
return kFALSE;
}
id = ( iTRU % 2 ) ? iADC%4 + 4 * (23 - int(iADC/4)) : (3 - iADC%4) + 4 * int(iADC/4);
id += iTRU * 96;
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetTRUFromAbsFastORIndex(const Int_t id, Int_t& iTRU, Int_t& iADC) const
{
// Trigger mapping method, get TRU number from FastOr Index
if (id > fNTRU * 96 - 1 || id < 0) {
AliError("Fast-OR ID is out of range!");
return kFALSE;
}
iTRU = id / 96;
iADC = id % 96;
iADC = ( iTRU % 2 ) ? iADC%4 + 4 * (23 - int(iADC/4)) : (3 - iADC%4) + 4 * int(iADC/4);
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetPositionInTRUFromAbsFastORIndex(const Int_t id, Int_t& iTRU, Int_t& iEta, Int_t& iPhi) const
{
// Trigger mapping method, get position in TRU from FasOr Index
Int_t iADC = -1;
if (!GetTRUFromAbsFastORIndex(id, iTRU, iADC)) return kFALSE;
Int_t x = iADC / 4;
Int_t y = iADC % 4;
if ( iTRU % 2 ) { // C side
iEta = 23 - x;
iPhi = y;
}
else { // A side
iEta = x;
iPhi = 3 - y;
}
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetPositionInSMFromAbsFastORIndex(const Int_t id, Int_t& iSM, Int_t& iEta, Int_t& iPhi) const
{
//Trigger mapping method, get position in Super Module from FasOr Index
Int_t iTRU = -1;
if (!GetPositionInTRUFromAbsFastORIndex(id, iTRU, iEta, iPhi)) return kFALSE;
if (iTRU % 2) { // C side
iSM = 2 * (int(int(iTRU / 2) / 3)) + 1;
} else { // A side
iSM = 2 * (int(int(iTRU / 2) / 3));
}
iPhi += 4 * int((iTRU % 6) / 2);
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetPositionInEMCALFromAbsFastORIndex(const Int_t id, Int_t& iEta, Int_t& iPhi) const
{
//Trigger mapping method, get position in EMCAL from FastOR index
Int_t iSM = -1;
if (GetPositionInSMFromAbsFastORIndex(id, iSM, iEta, iPhi)) {
if (iSM % 2) iEta += 24;
iPhi += 12 * int(iSM / 2);
return kTRUE;
}
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetAbsFastORIndexFromPositionInTRU(const Int_t iTRU, const Int_t iEta, const Int_t iPhi, Int_t& id) const
{
//Trigger mapping method, get Index if FastOr from Position in TRU
if (iTRU < 0 || iTRU > fNTRU - 1 || iEta < 0 || iEta > 23 || iPhi < 0 || iPhi > 3) {
AliError(Form("Out of range! iTRU=%d, iEta=%d, iPhi=%d", iTRU, iEta, iPhi));
return kFALSE;
}
id = iPhi + 4 * iEta + iTRU * 96;
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetAbsFastORIndexFromPositionInSM(const Int_t iSM, const Int_t iEta, const Int_t iPhi, Int_t& id) const
{
// Trigger mapping method, from position in SM Index get FastOR index
if (iSM < 0 || iSM >= 12 || iEta < 0 || iEta > 23 || iPhi < 0 || iPhi > 11) {
AliError(Form("Out of range! iSM=%d, iEta=%d, iPhi=%d", iSM, iEta, iPhi));
return kFALSE;
}
Int_t x = iEta;
Int_t y = iPhi % 4;
Int_t iOff = (iSM % 2) ? 1 : 0;
Int_t iTRU = 2 * int(iPhi / 4) + 6 * int(iSM / 2) + iOff;
if (GetAbsFastORIndexFromPositionInTRU(iTRU, x, y, id)) {
return kTRUE;
}
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetAbsFastORIndexFromPositionInEMCAL(const Int_t iEta, const Int_t iPhi, Int_t& id) const
{
// Trigger mapping method, from position in EMCAL Index get FastOR index
if (iEta < 0 || iEta > 47 || iPhi < 0 || iPhi > 63) {
AliError(Form("Out of range! iEta: %2d iPhi: %2d", iEta, iPhi));
return kFALSE;
}
id = iEta * 48 + iPhi;
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetFastORIndexFromCellIndex(const Int_t id, Int_t& idx) const
{
// Trigger mapping method, from cell index get FastOR index
Int_t iSupMod, nModule, nIphi, nIeta, iphim, ietam;
Bool_t isOK = fGeometry->GetCellIndex( id, iSupMod, nModule, nIphi, nIeta );
fGeometry->GetModulePhiEtaIndexInSModule( iSupMod, nModule, iphim, ietam );
if (isOK && GetAbsFastORIndexFromPositionInSM(iSupMod, ietam, iphim, idx)) return kTRUE;
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetCellIndexFromFastORIndex(const Int_t id, Int_t idx[4]) const
{
// Trigger mapping method, from FASTOR index get cell index
Int_t iSM=-1, iEta=-1, iPhi=-1;
if (GetPositionInSMFromAbsFastORIndex(id, iSM, iEta, iPhi)) {
Int_t ix = 2 * iEta;
Int_t iy = 2 * iPhi;
for (Int_t i = 0; i < 2; i++) {
for (Int_t j = 0; j < 2; j++) {
idx[2 * i + j] = fGeometry->GetAbsCellIdFromCellIndexes(iSM, iy + i, ix + j);
}
}
return kTRUE;
}
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetTRUIndexFromSTUIndex(const Int_t id, Int_t& idx) const
{
// STU mapping: TRU# 0 and 16 are missing
if (id > 31 || id < 0) {
AliError(Form("TRU index out of range: %d",id));
return kFALSE;
}
idx = GetTRUIndexFromSTUIndex(id);
return kTRUE;
}
//________________________________________________________________________________________________
Int_t AliEMCALTriggerMappingV1::GetTRUIndexFromSTUIndex(const Int_t id) const
{
// STU mapping: TRU# 0 and 16 are missing
if (id > 31 || id < 0) {
AliError(Form("TRU index out of range: %d",id));
}
return (id > 15) ? 2 * (31 - id) : 2 * (15 - id) + 1;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetTRUIndexFromOnlineIndex(const Int_t id, Int_t& idx) const
{
//Trigger mapping method, from STU index get TRU index
idx = GetOnlineIndexFromTRUIndex(id);
if (idx > fNTRU - 1 || idx < 0) {
AliError(Form("TRU index out of range: %d",idx));
return kFALSE;
}
return kTRUE;
}
//________________________________________________________________________________________________
Int_t AliEMCALTriggerMappingV1::GetTRUIndexFromOnlineIndex(const Int_t id) const
{
//Trigger mapping method, from STU index get TRU index
if (id > fNTRU - 1 || id < 0) {
AliError(Form("TRU index out of range: %d",id));
}
if (id == 31) {
return 31;
}
//jump 4 TRUs for DCAL
Int_t tmp=0;
if(id > 31) tmp = id+4;
else tmp = id;
Int_t idx = ((tmp% 6) < 3) ? 6 * int(tmp/ 6) + 2 * (tmp% 3) : 6 * int(tmp/ 6) + 2 * (2 - (tmp% 3)) + 1;
if(id > 31) idx-=4;
return idx;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetOnlineIndexFromTRUIndex(const Int_t id, Int_t& idx) const
{
//Trigger mapping method, from STU index get TRU index
idx = GetOnlineIndexFromTRUIndex(id);
if (idx > fNTRU-1 || idx < 0)
{
AliError(Form("TRU index out of range: %d",idx));
return kFALSE;
}
return kTRUE;
}
//________________________________________________________________________________________________
Int_t AliEMCALTriggerMappingV1::GetOnlineIndexFromTRUIndex(const Int_t id) const
{
//Trigger mapping method, from STU index get TRU index
if (id > fNTRU-1 || id < 0)
{
AliError(Form("TRU index out of range: %d",id));
}
if (id == 31) {
return 31;
}
//jump 4 TRUs for DCAL
Int_t tmp=0;
if(id > 31) tmp = id+4;
else tmp = id;
Int_t idx = (tmp % 2) ? int((6 - (tmp % 6)) / 2) + 3 * (2 * int(tmp / 6) + 1) : 3 * int(tmp / 6) + int(tmp / 2);
if(id > 31) idx-=4;
return idx;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetFastORIndexFromL0Index(const Int_t iTRU, const Int_t id, Int_t idx[], const Int_t size) const
{
//Trigger mapping method, from L0 index get FastOR index
if (size <= 0 || size > 4) {
AliError("Size not supported!");
return kFALSE;
}
Int_t motif[4] = {0, 1, 4, 5};
switch (size) {
case 1: // Cosmic trigger
if (!GetAbsFastORIndexFromTRU(iTRU, id, idx[1])) return kFALSE;
break;
case 4: // 4 x 4
for (Int_t k = 0; k < 4; k++) {
Int_t iADC = motif[k] + 4 * int(id / 3) + (id % 3);
if (!GetAbsFastORIndexFromTRU(iTRU, iADC, idx[k])) return kFALSE;
}
break;
default:
break;
}
return kTRUE;
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
Author: R. GUERNANE LPSC Grenoble CNRS/IN2P3
*/
#include "AliEMCALTriggerMapping.h"
#include "AliEMCALTriggerMappingV1.h"
#include "AliEMCALGeometry.h"
#include "AliLog.h"
ClassImp(AliEMCALTriggerMappingV1)
//________________________________________________________________________________________________
AliEMCALTriggerMappingV1::AliEMCALTriggerMappingV1() : AliEMCALTriggerMapping()
{
// Ctor
SetUniqueID(1);
}
//________________________________________________________________________________________________
AliEMCALTriggerMappingV1::AliEMCALTriggerMappingV1(const Int_t ntru, const AliEMCALGeometry* geo) : AliEMCALTriggerMapping(ntru, geo)
{
// Ctor
SetUniqueID(1);
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetAbsFastORIndexFromTRU(const Int_t iTRU, const Int_t iADC, Int_t& id) const
{
//Trigger mapping method, get FastOr Index from TRU
if (iTRU > fNTRU - 1 || iTRU < 0 || iADC > 95 || iADC < 0) {
AliError("TRU out of range!");
return kFALSE;
}
id = ( iTRU % 2 ) ? iADC%4 + 4 * (23 - int(iADC/4)) : (3 - iADC%4) + 4 * int(iADC/4);
id += iTRU * 96;
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetTRUFromAbsFastORIndex(const Int_t id, Int_t& iTRU, Int_t& iADC) const
{
// Trigger mapping method, get TRU number from FastOr Index
if (id > fNTRU * 96 - 1 || id < 0) {
AliError("Fast-OR ID is out of range!");
return kFALSE;
}
iTRU = id / 96;
iADC = id % 96;
iADC = ( iTRU % 2 ) ? iADC%4 + 4 * (23 - int(iADC/4)) : (3 - iADC%4) + 4 * int(iADC/4);
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetPositionInTRUFromAbsFastORIndex(const Int_t id, Int_t& iTRU, Int_t& iEta, Int_t& iPhi) const
{
// Trigger mapping method, get position in TRU from FasOr Index
Int_t iADC = -1;
if (!GetTRUFromAbsFastORIndex(id, iTRU, iADC)) return kFALSE;
Int_t x = iADC / 4;
Int_t y = iADC % 4;
if ( iTRU % 2 ) { // C side
iEta = 23 - x;
iPhi = y;
}
else { // A side
iEta = x;
iPhi = 3 - y;
}
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetPositionInSMFromAbsFastORIndex(const Int_t id, Int_t& iSM, Int_t& iEta, Int_t& iPhi) const
{
//Trigger mapping method, get position in Super Module from FasOr Index
Int_t iTRU = -1;
if (!GetPositionInTRUFromAbsFastORIndex(id, iTRU, iEta, iPhi)) return kFALSE;
if (iTRU % 2) { // C side
iSM = 2 * (int(int(iTRU / 2) / 3)) + 1;
} else { // A side
iSM = 2 * (int(int(iTRU / 2) / 3));
}
iPhi += 4 * int((iTRU % 6) / 2);
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetPositionInEMCALFromAbsFastORIndex(const Int_t id, Int_t& iEta, Int_t& iPhi) const
{
//Trigger mapping method, get position in EMCAL from FastOR index
Int_t iSM = -1;
if (GetPositionInSMFromAbsFastORIndex(id, iSM, iEta, iPhi)) {
if (iSM % 2) iEta += 24;
iPhi += 12 * int(iSM / 2);
return kTRUE;
}
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetAbsFastORIndexFromPositionInTRU(const Int_t iTRU, const Int_t iEta, const Int_t iPhi, Int_t& id) const
{
//Trigger mapping method, get Index if FastOr from Position in TRU
if (iTRU < 0 || iTRU > fNTRU - 1 || iEta < 0 || iEta > 23 || iPhi < 0 || iPhi > 3) {
AliError(Form("Out of range! iTRU=%d, iEta=%d, iPhi=%d", iTRU, iEta, iPhi));
return kFALSE;
}
id = iPhi + 4 * iEta + iTRU * 96;
return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetAbsFastORIndexFromPositionInSM(const Int_t iSM, const Int_t iEta, const Int_t iPhi, Int_t& id) const
{
// Trigger mapping method, from position in SM Index get FastOR index
if (iSM < 0 || iSM >= 12 || iEta < 0 || iEta > 23 || iPhi < 0 || iPhi > 11) {
AliError(Form("Out of range! iSM=%d, iEta=%d, iPhi=%d", iSM, iEta, iPhi));
return kFALSE;
}
Int_t x = iEta;
Int_t y = iPhi % 4;
Int_t iOff = (iSM % 2) ? 1 : 0;
Int_t iTRU = 2 * int(iPhi / 4) + 6 * int(iSM / 2) + iOff;
if (GetAbsFastORIndexFromPositionInTRU(iTRU, x, y, id)) {
return kTRUE;
}
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetAbsFastORIndexFromPositionInEMCAL(const Int_t iEta, const Int_t iPhi, Int_t& id) const
{
// Trigger mapping method, from position in EMCAL Index get FastOR index
if (iEta < 0 || iEta > 47 || iPhi < 0 || iPhi > 63) {
AliError(Form("Out of range! iEta: %2d iPhi: %2d", iEta, iPhi));
return kFALSE;
}
Int_t s = int(iEta / 24) + 2 * int(iPhi / 4);
Int_t x = iEta % 24;
Int_t y = iPhi % 4;
if (GetAbsFastORIndexFromPositionInSM(s, x, y, id)) {
return kTRUE;
}
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetFastORIndexFromCellIndex(const Int_t id, Int_t& idx) const
{
// Trigger mapping method, from cell index get FastOR index
Int_t iSupMod, nModule, nIphi, nIeta, iphim, ietam;
Bool_t isOK = fGeometry->GetCellIndex( id, iSupMod, nModule, nIphi, nIeta );
fGeometry->GetModulePhiEtaIndexInSModule( iSupMod, nModule, iphim, ietam );
if (isOK && GetAbsFastORIndexFromPositionInSM(iSupMod, ietam, iphim, idx)) return kTRUE;
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetCellIndexFromFastORIndex(const Int_t id, Int_t idx[4]) const
{
// Trigger mapping method, from FASTOR index get cell index
Int_t iSM=-1, iEta=-1, iPhi=-1;
if (GetPositionInSMFromAbsFastORIndex(id, iSM, iEta, iPhi)) {
Int_t ix = 2 * iEta;
Int_t iy = 2 * iPhi;
for (Int_t i = 0; i < 2; i++) {
for (Int_t j = 0; j < 2; j++) {
idx[2 * i + j] = fGeometry->GetAbsCellIdFromCellIndexes(iSM, iy + i, ix + j);
}
}
return kTRUE;
}
return kFALSE;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetTRUIndexFromSTUIndex(const Int_t id, Int_t& idx) const
{
// STU mapping: TRU# 0 and 16 are missing
if (id > 31 || id < 0) {
AliError(Form("TRU index out of range: %d",id));
return kFALSE;
}
idx = GetTRUIndexFromSTUIndex(id);
return kTRUE;
}
//________________________________________________________________________________________________
Int_t AliEMCALTriggerMappingV1::GetTRUIndexFromSTUIndex(const Int_t id) const
{
// STU mapping: TRU# 0 and 16 are missing
if (id > 31 || id < 0) {
AliError(Form("TRU index out of range: %d",id));
}
return (id > 15) ? 2 * (31 - id) : 2 * (15 - id) + 1;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetTRUIndexFromOnlineIndex(const Int_t id, Int_t& idx) const
{
//Trigger mapping method, from STU index get TRU index
idx = GetOnlineIndexFromTRUIndex(id);
if (idx > fNTRU - 1 || idx < 0) {
AliError(Form("TRU index out of range: %d",idx));
return kFALSE;
}
return kTRUE;
}
//________________________________________________________________________________________________
Int_t AliEMCALTriggerMappingV1::GetTRUIndexFromOnlineIndex(const Int_t id) const
{
//Trigger mapping method, from STU index get TRU index
if (id > fNTRU - 1 || id < 0) {
AliError(Form("TRU index out of range: %d",id));
}
if (id == 31) {
return 31;
}
//jump 4 TRUs for DCAL
Int_t tmp=0;
if(id > 31) tmp = id+4;
else tmp = id;
Int_t idx = ((tmp% 6) < 3) ? 6 * int(tmp/ 6) + 2 * (tmp% 3) : 6 * int(tmp/ 6) + 2 * (2 - (tmp% 3)) + 1;
if(id > 31) idx-=4;
return idx;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetOnlineIndexFromTRUIndex(const Int_t id, Int_t& idx) const
{
//Trigger mapping method, from STU index get TRU index
idx = GetOnlineIndexFromTRUIndex(id);
if (idx > fNTRU-1 || idx < 0)
{
AliError(Form("TRU index out of range: %d",idx));
return kFALSE;
}
return kTRUE;
}
//________________________________________________________________________________________________
Int_t AliEMCALTriggerMappingV1::GetOnlineIndexFromTRUIndex(const Int_t id) const
{
//Trigger mapping method, from STU index get TRU index
if (id > fNTRU-1 || id < 0)
{
AliError(Form("TRU index out of range: %d",id));
}
if (id == 31) {
return 31;
}
//jump 4 TRUs for DCAL
Int_t tmp=0;
if(id > 31) tmp = id+4;
else tmp = id;
Int_t idx = (tmp % 2) ? int((6 - (tmp % 6)) / 2) + 3 * (2 * int(tmp / 6) + 1) : 3 * int(tmp / 6) + int(tmp / 2);
if(id > 31) idx-=4;
return idx;
}
//________________________________________________________________________________________________
Bool_t AliEMCALTriggerMappingV1::GetFastORIndexFromL0Index(const Int_t iTRU, const Int_t id, Int_t idx[], const Int_t size) const
{
//Trigger mapping method, from L0 index get FastOR index
if (size <= 0 || size > 4) {
AliError("Size not supported!");
return kFALSE;
}
Int_t motif[4] = {0, 1, 4, 5};
switch (size) {
case 1: // Cosmic trigger
if (!GetAbsFastORIndexFromTRU(iTRU, id, idx[1])) return kFALSE;
break;
case 4: // 4 x 4
for (Int_t k = 0; k < 4; k++) {
Int_t iADC = motif[k] + 4 * int(id / 3) + (id % 3);
if (!GetAbsFastORIndexFromTRU(iTRU, iADC, idx[k])) return kFALSE;
}
break;
default:
break;
}
return kTRUE;
}
|
Fix global mapping
|
Fix global mapping
|
C++
|
bsd-3-clause
|
miranov25/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,miranov25/AliRoot,alisw/AliRoot,alisw/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,alisw/AliRoot,miranov25/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,coppedis/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,jgrosseo/AliRoot
|
872c47a960eb51299401fa093ffb2b4c25a78b58
|
src/test/vm.cpp
|
src/test/vm.cpp
|
#include <imq/vm.h>
#include <imq/expressions.h>
#include <imq/mathexpr.h>
#include <imq/image.h>
#include <gtest/gtest.h>
using namespace imq;
TEST(VMachine, CallFunctionExpr)
{
VMachine vm;
bool functionCalled = false;
QValue func = QValue::Function(&vm, [&](VMachine* vm, int32_t argCount, QValue* args, QValue* result) -> Result {
if (argCount == 1)
{
*result = args[0];
}
else if (argCount == 2)
{
*result = QValue::Float(3.f);
}
else
{
*result = QValue::Integer(argCount);
}
functionCalled = true;
return true;
});
CallFunctionExpr* expr = new CallFunctionExpr(new ConstantExpr(func, { 0, 0 }), 0, nullptr, { 0, 0 });
QValue value;
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Integer(0));
functionCalled = false;
delete expr;
VExpression** args = new VExpression*[1]{ new ConstantExpr(QValue::Integer(321), {0,0}) };
expr = new CallFunctionExpr(new ConstantExpr(func, { 0, 0 }), 1, args, { 0, 0 });
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Integer(321));
functionCalled = false;
delete expr;
args = new VExpression*[2]{ new ConstantExpr(QValue::Integer(321), {0,0}), new ConstantExpr(QValue::Integer(123), {0,0}) };
expr = new CallFunctionExpr(new ConstantExpr(func, { 0,0 }), 2, args, { 0, 0 });
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Float(3.f));
delete expr;
}
TEST(VMachine, Variables)
{
VMachine vm;
QValue value;
VExpression* expr = new RetrieveVariableExpr("foo", { 1, 2 });
Result result = expr->execute(vm.getRootContext(), &value);
ASSERT_FALSE(result);
ASSERT_EQ(result.getErr(), "line 1:2: Unknown variable \"foo\"");
VStatement* stm = new SetVariableStm("foo", new ConstantExpr(QValue::Integer(345), { 0, 0 }), { 0, 0 });
ASSERT_TRUE(stm->execute(vm.getRootContext()));
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Integer(345));
delete expr;
delete stm;
}
TEST(VMachine, Fields)
{
VMachine vm;
QValue obj = QValue::Object(new QColor(&vm, 1.f, 0.3f, 0.4f, 1.f));
QValue value;
VExpression* expr = new RetrieveFieldExpr(new ConstantExpr(obj, { 0, 0 }), "foo", { 0, 0 });
ASSERT_FALSE(expr->execute(vm.getRootContext(), &value));
delete expr;
expr = new RetrieveFieldExpr(new ConstantExpr(obj, { 0, 0 }), "g", { 0, 0 });
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Float(0.3f));
VStatement* stm = new SetFieldStm(new ConstantExpr(obj, { 0, 0 }), "green", new ConstantExpr(QValue::Float(0.89f), { 0,0 }), { 0, 0 });
ASSERT_FALSE(stm->execute(vm.getRootContext()));
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Float(0.3f));
delete expr;
delete stm;
}
TEST(VMachine, Indices)
{
VMachine vm;
QValue obj = QValue::Object(new QColor(&vm, 1.f, 0.3f, 0.4f, 1.f));
QValue value;
VExpression* expr = new RetrieveIndexExpr(new ConstantExpr(obj, { 0,0 }), new ConstantExpr(QValue::Integer(-1), { 0,0 }), { 0, 0 });
ASSERT_FALSE(expr->execute(vm.getRootContext(), &value));
delete expr;
expr = new RetrieveIndexExpr(new ConstantExpr(obj, { 0,0 }), new ConstantExpr(QValue::Integer(2), { 0,0 }), { 0, 0 });
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Float(0.4f));
VStatement* stm = new SetIndexStm(new ConstantExpr(obj, { 0, 0 }), new ConstantExpr(QValue::Integer(2), { 0,0 }), new ConstantExpr(QValue::Float(0.132f), { 0,0 }), { 0,0 });
ASSERT_FALSE(stm->execute(vm.getRootContext()));
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Float(0.4f));
delete expr;
delete stm;
}
TEST(VMachine, Select)
{
VMachine vm;
QImage* imageA = new QImage(&vm, 100, 100, QColor(&vm, 1.f, 1.f, 1.f, 1.f));
QImage* imageB = new QImage(&vm, 100, 100, QColor(&vm, 0.f, 0.f, 0.f, 0.f));
VStatement* stm = new SelectStm(
new ConstantExpr(QValue::Object(imageB), { 0, 0 }),
new ConstantExpr(QValue::Object(imageA), { 0, 0 }),
new RetrieveVariableExpr("color", { 0, 0 }),
nullptr,
nullptr,
0,
nullptr,
{ 0, 0 }
);
ASSERT_TRUE(stm->execute(vm.getRootContext()));
QColor color(&vm);
for (int32_t y = 0; y < 100; ++y)
{
for (int32_t x = 0; x < 100; ++x)
{
ASSERT_TRUE(imageB->getPixel(x, y, &color));
ASSERT_EQ(color, QColor(&vm, 1.f, 1.f, 1.f, 1.f));
}
}
delete stm;
}
TEST(VMachine, MathExpressions)
{
VMachine vm;
// (8 + (5 - 3)) / 2 * 4
VExpression* expr = new MulExpr(
new DivExpr(
new AddExpr(
new ConstantExpr(QValue::Integer(8), { 0,0 }),
new SubExpr(
new ConstantExpr(QValue::Integer(5), { 0,0 }),
new ConstantExpr(QValue::Integer(3), { 0,0 }),
{ 0,0 }
),
{ 0,0 }
),
new ConstantExpr(QValue::Integer(2), { 0,0 }),
{ 0,0 }
),
new ConstantExpr(QValue::Integer(4), { 0,0 }),
{ 0,0 }
);
QValue value;
int32_t i;
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(value.getInteger(&i));
ASSERT_EQ(i, 20);
delete expr;
// 25.8 / 2
expr = new DivExpr(
new ConstantExpr(QValue::Float(25.8f), { 0,0 }),
new ConstantExpr(QValue::Integer(2), { 0,0 }),
{ 0,0 }
);
float f;
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(value.getFloat(&f));
ASSERT_FLOAT_EQ(f, 12.9f);
delete expr;
// true || (false && !(5 == 5))
expr = new OrExpr(
new ConstantExpr(QValue::Bool(true), { 0,0 }),
new AndExpr(
new ConstantExpr(QValue::Bool(false), { 0,0 }),
new NotExpr(
new EqualExpr(
new ConstantExpr(QValue::Integer(5), { 0,0 }),
new ConstantExpr(QValue::Integer(5), { 0,0 }),
{ 0,0 }
),
{ 0,0 }
),
{ 0,0 }
),
{ 0,0 }
);
bool b;
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(value.getBool(&b));
ASSERT_TRUE(b);
delete expr;
}
TEST(VMachine, DefineInput)
{
VMachine vm;
Context* ctx = new SimpleContext(&vm);
VStatement* stm = new DefineInputStm("foo", new ConstantExpr(QValue::Nil(), { 0,0 }), { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Inputs/outputs must be defined in the root context.");
delete stm;
RootContext* rootCtx = new RootContext(&vm);
stm = new DefineInputStm("foo", new ConstantExpr(QValue::Nil(), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("foo"));
QValue value;
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Nil());
rootCtx->setInput("foo", QValue::Integer(123));
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Integer(123));
res = stm->execute(rootCtx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Input foo has the wrong type.");
delete stm;
stm = new DefineInputStm("bar", new ConstantExpr(QValue::Float(1.34f), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("bar"));
ASSERT_TRUE(rootCtx->getValue("bar", &value));
ASSERT_EQ(value, QValue::Float(1.34f));
delete stm;
}
TEST(VMachine, DefineOutput)
{
VMachine vm;
Context* ctx = new SimpleContext(&vm);
VStatement* stm = new DefineOutputStm("foo", nullptr, { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Inputs/outputs must be defined in the root context.");
delete stm;
RootContext* rootCtx = new RootContext(&vm);
stm = new DefineOutputStm("foo", nullptr, { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("foo"));
QValue value;
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Nil());
rootCtx->setOutput("foo", QValue::Integer(123));
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Integer(123));
res = stm->execute(rootCtx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Outputs may not be redefined.");
delete stm;
stm = new DefineOutputStm("bar", new ConstantExpr(QValue::Float(1.34f), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("bar"));
ASSERT_TRUE(rootCtx->getValue("bar", &value));
ASSERT_EQ(value, QValue::Float(1.34f));
delete stm;
}
TEST(VMachine, Branch)
{
VMachine vm;
bool trueCalled = false;
bool falseCalled = false;
QValue trueFunc = QValue::Function(&vm, [&](VMachine* vm, int32_t argCount, QValue* args, QValue* result) -> Result {
trueCalled = true;
*result = QValue::Nil();
return true;
});
QValue falseFunc = QValue::Function(&vm, [&](VMachine* vm, int32_t argCount, QValue* args, QValue* result) -> Result {
falseCalled = true;
*result = QValue::Nil();
return true;
});
VStatement* stm = new BranchStm(new ConstantExpr(QValue::Integer(123), { 0,0 }), nullptr, nullptr, { 0,0 });
Result res = stm->execute(vm.getRootContext());
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Subexpression must return a boolean within a Branch");
delete stm;
stm = new BranchStm(
new ConstantExpr(QValue::Bool(false), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(trueFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(falseFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
{ 0,0 }
);
ASSERT_TRUE(stm->execute(vm.getRootContext()));
EXPECT_FALSE(trueCalled);
EXPECT_TRUE(falseCalled);
trueCalled = false;
falseCalled = false;
delete stm;
stm = new BranchStm(
new ConstantExpr(QValue::Bool(true), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(trueFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(falseFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
{ 0,0 }
);
ASSERT_TRUE(stm->execute(vm.getRootContext()));
EXPECT_TRUE(trueCalled);
EXPECT_FALSE(falseCalled);
delete stm;
}
|
#include <imq/vm.h>
#include <imq/expressions.h>
#include <imq/mathexpr.h>
#include <imq/image.h>
#include <gtest/gtest.h>
using namespace imq;
TEST(VMachine, CallFunctionExpr)
{
VMachine vm;
bool functionCalled = false;
QValue func = QValue::Function(&vm, [&](VMachine* vm, int32_t argCount, QValue* args, QValue* result) -> Result {
if (argCount == 1)
{
*result = args[0];
}
else if (argCount == 2)
{
*result = QValue::Float(3.f);
}
else
{
*result = QValue::Integer(argCount);
}
functionCalled = true;
return true;
});
CallFunctionExpr* expr = new CallFunctionExpr(new ConstantExpr(func, { 0, 0 }), 0, nullptr, { 0, 0 });
QValue value;
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Integer(0));
functionCalled = false;
delete expr;
VExpression** args = new VExpression*[1]{ new ConstantExpr(QValue::Integer(321), {0,0}) };
expr = new CallFunctionExpr(new ConstantExpr(func, { 0, 0 }), 1, args, { 0, 0 });
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Integer(321));
functionCalled = false;
delete expr;
args = new VExpression*[2]{ new ConstantExpr(QValue::Integer(321), {0,0}), new ConstantExpr(QValue::Integer(123), {0,0}) };
expr = new CallFunctionExpr(new ConstantExpr(func, { 0,0 }), 2, args, { 0, 0 });
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Float(3.f));
delete expr;
}
TEST(VMachine, Variables)
{
VMachine vm;
QValue value;
VExpression* expr = new RetrieveVariableExpr("foo", { 1, 2 });
Result result = expr->execute(vm.getRootContext(), &value);
ASSERT_FALSE(result);
ASSERT_EQ(result.getErr(), "line 1:2: Unknown variable \"foo\"");
VStatement* stm = new SetVariableStm("foo", new ConstantExpr(QValue::Integer(345), { 0, 0 }), { 0, 0 });
ASSERT_TRUE(stm->execute(vm.getRootContext()));
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Integer(345));
delete expr;
delete stm;
}
TEST(VMachine, Fields)
{
VMachine vm;
QValue obj = QValue::Object(new QColor(&vm, 1.f, 0.3f, 0.4f, 1.f));
QValue value;
VExpression* expr = new RetrieveFieldExpr(new ConstantExpr(obj, { 0, 0 }), "foo", { 0, 0 });
ASSERT_FALSE(expr->execute(vm.getRootContext(), &value));
delete expr;
expr = new RetrieveFieldExpr(new ConstantExpr(obj, { 0, 0 }), "g", { 0, 0 });
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Float(0.3f));
VStatement* stm = new SetFieldStm(new ConstantExpr(obj, { 0, 0 }), "green", new ConstantExpr(QValue::Float(0.89f), { 0,0 }), { 0, 0 });
ASSERT_FALSE(stm->execute(vm.getRootContext()));
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Float(0.3f));
delete expr;
delete stm;
}
TEST(VMachine, Indices)
{
VMachine vm;
QValue obj = QValue::Object(new QColor(&vm, 1.f, 0.3f, 0.4f, 1.f));
QValue value;
VExpression* expr = new RetrieveIndexExpr(new ConstantExpr(obj, { 0,0 }), new ConstantExpr(QValue::Integer(-1), { 0,0 }), { 0, 0 });
ASSERT_FALSE(expr->execute(vm.getRootContext(), &value));
delete expr;
expr = new RetrieveIndexExpr(new ConstantExpr(obj, { 0,0 }), new ConstantExpr(QValue::Integer(2), { 0,0 }), { 0, 0 });
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Float(0.4f));
VStatement* stm = new SetIndexStm(new ConstantExpr(obj, { 0, 0 }), new ConstantExpr(QValue::Integer(2), { 0,0 }), new ConstantExpr(QValue::Float(0.132f), { 0,0 }), { 0,0 });
ASSERT_FALSE(stm->execute(vm.getRootContext()));
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_EQ(value, QValue::Float(0.4f));
delete expr;
delete stm;
}
TEST(VMachine, Select)
{
VMachine vm;
QImage* imageA = new QImage(&vm, 100, 100, QColor(&vm, 1.f, 1.f, 1.f, 1.f));
QImage* imageB = new QImage(&vm, 100, 100, QColor(&vm, 0.f, 0.f, 0.f, 0.f));
VStatement* stm = new SelectStm(
new ConstantExpr(QValue::Object(imageB), { 0, 0 }),
new ConstantExpr(QValue::Object(imageA), { 0, 0 }),
new RetrieveVariableExpr("color", { 0, 0 }),
nullptr,
nullptr,
0,
nullptr,
{ 0, 0 }
);
ASSERT_TRUE(stm->execute(vm.getRootContext()));
QColor color(&vm);
for (int32_t y = 0; y < 100; ++y)
{
for (int32_t x = 0; x < 100; ++x)
{
ASSERT_TRUE(imageB->getPixel(x, y, &color));
ASSERT_EQ(color, QColor(&vm, 1.f, 1.f, 1.f, 1.f));
}
}
delete stm;
}
TEST(VMachine, MathExpressions)
{
VMachine vm;
// (8 + (5 - 3)) / 2 * 4
VExpression* expr = new MulExpr(
new DivExpr(
new AddExpr(
new ConstantExpr(QValue::Integer(8), { 0,0 }),
new SubExpr(
new ConstantExpr(QValue::Integer(5), { 0,0 }),
new ConstantExpr(QValue::Integer(3), { 0,0 }),
{ 0,0 }
),
{ 0,0 }
),
new ConstantExpr(QValue::Integer(2), { 0,0 }),
{ 0,0 }
),
new ConstantExpr(QValue::Integer(4), { 0,0 }),
{ 0,0 }
);
QValue value;
int32_t i;
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(value.getInteger(&i));
ASSERT_EQ(i, 20);
delete expr;
// 25.8 / 2
expr = new DivExpr(
new ConstantExpr(QValue::Float(25.8f), { 0,0 }),
new ConstantExpr(QValue::Integer(2), { 0,0 }),
{ 0,0 }
);
float f;
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(value.getFloat(&f));
ASSERT_FLOAT_EQ(f, 12.9f);
delete expr;
// true || (false && !(5 == 5))
expr = new OrExpr(
new ConstantExpr(QValue::Bool(true), { 0,0 }),
new AndExpr(
new ConstantExpr(QValue::Bool(false), { 0,0 }),
new NotExpr(
new EqualExpr(
new ConstantExpr(QValue::Integer(5), { 0,0 }),
new ConstantExpr(QValue::Integer(5), { 0,0 }),
{ 0,0 }
),
{ 0,0 }
),
{ 0,0 }
),
{ 0,0 }
);
bool b;
ASSERT_TRUE(expr->execute(vm.getRootContext(), &value));
ASSERT_TRUE(value.getBool(&b));
ASSERT_TRUE(b);
delete expr;
}
TEST(VMachine, DefineInput)
{
VMachine vm;
Context* ctx = new SimpleContext(&vm);
VStatement* stm = new DefineInputStm("foo", new ConstantExpr(QValue::Nil(), { 0,0 }), { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Inputs/outputs must be defined in the root context.");
delete stm;
RootContext* rootCtx = new RootContext(&vm);
stm = new DefineInputStm("foo", new ConstantExpr(QValue::Nil(), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("foo"));
QValue value;
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Nil());
rootCtx->setInput("foo", QValue::Integer(123));
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Integer(123));
res = stm->execute(rootCtx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Input foo has the wrong type.");
delete stm;
stm = new DefineInputStm("bar", new ConstantExpr(QValue::Float(1.34f), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("bar"));
ASSERT_TRUE(rootCtx->getValue("bar", &value));
ASSERT_EQ(value, QValue::Float(1.34f));
delete stm;
}
TEST(VMachine, DefineOutput)
{
VMachine vm;
Context* ctx = new SimpleContext(&vm);
VStatement* stm = new DefineOutputStm("foo", nullptr, { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Inputs/outputs must be defined in the root context.");
delete stm;
RootContext* rootCtx = new RootContext(&vm);
stm = new DefineOutputStm("foo", nullptr, { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("foo"));
QValue value;
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Nil());
rootCtx->setOutput("foo", QValue::Integer(123));
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Integer(123));
res = stm->execute(rootCtx);
ASSERT_TRUE(res);
// outputs may be redefined as of 0.5.0
//ASSERT_EQ(res.getErr(), "line 0:0: Outputs may not be redefined.");
delete stm;
stm = new DefineOutputStm("bar", new ConstantExpr(QValue::Float(1.34f), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("bar"));
ASSERT_TRUE(rootCtx->getValue("bar", &value));
ASSERT_EQ(value, QValue::Float(1.34f));
delete stm;
}
TEST(VMachine, Branch)
{
VMachine vm;
bool trueCalled = false;
bool falseCalled = false;
QValue trueFunc = QValue::Function(&vm, [&](VMachine* vm, int32_t argCount, QValue* args, QValue* result) -> Result {
trueCalled = true;
*result = QValue::Nil();
return true;
});
QValue falseFunc = QValue::Function(&vm, [&](VMachine* vm, int32_t argCount, QValue* args, QValue* result) -> Result {
falseCalled = true;
*result = QValue::Nil();
return true;
});
VStatement* stm = new BranchStm(new ConstantExpr(QValue::Integer(123), { 0,0 }), nullptr, nullptr, { 0,0 });
Result res = stm->execute(vm.getRootContext());
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Subexpression must return a boolean within a Branch");
delete stm;
stm = new BranchStm(
new ConstantExpr(QValue::Bool(false), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(trueFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(falseFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
{ 0,0 }
);
ASSERT_TRUE(stm->execute(vm.getRootContext()));
EXPECT_FALSE(trueCalled);
EXPECT_TRUE(falseCalled);
trueCalled = false;
falseCalled = false;
delete stm;
stm = new BranchStm(
new ConstantExpr(QValue::Bool(true), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(trueFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(falseFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
{ 0,0 }
);
ASSERT_TRUE(stm->execute(vm.getRootContext()));
EXPECT_TRUE(trueCalled);
EXPECT_FALSE(falseCalled);
delete stm;
}
|
fix VMachine.DefineOutput test as outputs may now be redefined
|
fix VMachine.DefineOutput test as outputs may now be redefined
|
C++
|
mit
|
redxdev/imquery,redxdev/imquery,redxdev/imquery
|
5a36bfe017b8c4408b8816246e07abcec96e0781
|
chrome/browser/ui/views/elevation_icon_setter.cc
|
chrome/browser/ui/views/elevation_icon_setter.cc
|
// 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 "chrome/browser/ui/views/elevation_icon_setter.h"
#include "base/task_runner_util.h"
#include "content/public/browser/browser_thread.h"
#include "ui/views/controls/button/label_button.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include "base/win/win_util.h"
#include "base/win/windows_version.h"
#include "ui/gfx/icon_util.h"
#endif
// Helpers --------------------------------------------------------------------
namespace {
scoped_ptr<SkBitmap> GetElevationIcon() {
scoped_ptr<SkBitmap> icon;
#if defined(OS_WIN)
if ((base::win::GetVersion() < base::win::VERSION_VISTA) ||
!base::win::UserAccountControlIsEnabled())
return icon.Pass();
SHSTOCKICONINFO icon_info = { sizeof(SHSTOCKICONINFO) };
typedef HRESULT (STDAPICALLTYPE *GetStockIconInfo)(SHSTOCKICONID,
UINT,
SHSTOCKICONINFO*);
// Even with the runtime guard above, we have to use GetProcAddress()
// here, because otherwise the loader will try to resolve the function
// address on startup, which will break on XP.
GetStockIconInfo func = reinterpret_cast<GetStockIconInfo>(
GetProcAddress(GetModuleHandle(L"shell32.dll"), "SHGetStockIconInfo"));
// TODO(pkasting): Run on a background thread since this call spins a nested
// message loop.
if (FAILED((*func)(SIID_SHIELD, SHGSI_ICON | SHGSI_SMALLICON, &icon_info)))
return icon.Pass();
icon.reset(IconUtil::CreateSkBitmapFromHICON(
icon_info.hIcon,
gfx::Size(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON))));
DestroyIcon(icon_info.hIcon);
#endif
return icon.Pass();
}
} // namespace
// ElevationIconSetter --------------------------------------------------------
ElevationIconSetter::ElevationIconSetter(views::LabelButton* button)
: button_(button),
weak_factory_(this) {
base::PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&GetElevationIcon),
base::Bind(&ElevationIconSetter::SetButtonIcon,
weak_factory_.GetWeakPtr()));
}
ElevationIconSetter::~ElevationIconSetter() {
}
void ElevationIconSetter::SetButtonIcon(scoped_ptr<SkBitmap> icon) {
if (icon) {
button_->SetImage(views::Button::STATE_NORMAL,
gfx::ImageSkia::CreateFrom1xBitmap(*icon));
button_->SizeToPreferredSize();
if (button_->parent())
button_->parent()->Layout();
}
}
|
// 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 "chrome/browser/ui/views/elevation_icon_setter.h"
#include "base/task_runner_util.h"
#include "content/public/browser/browser_thread.h"
#include "ui/views/controls/button/label_button.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include "base/win/win_util.h"
#include "base/win/windows_version.h"
#include "ui/gfx/icon_util.h"
#include "ui/gfx/win/dpi.h"
#endif
// Helpers --------------------------------------------------------------------
namespace {
scoped_ptr<SkBitmap> GetElevationIcon() {
scoped_ptr<SkBitmap> icon;
#if defined(OS_WIN)
if ((base::win::GetVersion() < base::win::VERSION_VISTA) ||
!base::win::UserAccountControlIsEnabled())
return icon.Pass();
SHSTOCKICONINFO icon_info = { sizeof(SHSTOCKICONINFO) };
typedef HRESULT (STDAPICALLTYPE *GetStockIconInfo)(SHSTOCKICONID,
UINT,
SHSTOCKICONINFO*);
// Even with the runtime guard above, we have to use GetProcAddress()
// here, because otherwise the loader will try to resolve the function
// address on startup, which will break on XP.
GetStockIconInfo func = reinterpret_cast<GetStockIconInfo>(
GetProcAddress(GetModuleHandle(L"shell32.dll"), "SHGetStockIconInfo"));
// TODO(pkasting): Run on a background thread since this call spins a nested
// message loop.
if (FAILED((*func)(SIID_SHIELD, SHGSI_ICON | SHGSI_SMALLICON, &icon_info)))
return icon.Pass();
icon.reset(IconUtil::CreateSkBitmapFromHICON(
icon_info.hIcon,
gfx::Size(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON))));
DestroyIcon(icon_info.hIcon);
#endif
return icon.Pass();
}
} // namespace
// ElevationIconSetter --------------------------------------------------------
ElevationIconSetter::ElevationIconSetter(views::LabelButton* button)
: button_(button),
weak_factory_(this) {
base::PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&GetElevationIcon),
base::Bind(&ElevationIconSetter::SetButtonIcon,
weak_factory_.GetWeakPtr()));
}
ElevationIconSetter::~ElevationIconSetter() {
}
void ElevationIconSetter::SetButtonIcon(scoped_ptr<SkBitmap> icon) {
if (icon) {
float device_scale_factor = 1.0f;
#if defined(OS_WIN)
// Windows gives us back a correctly-scaled image for the current DPI, so
// mark this image as having been scaled for the current DPI already.
device_scale_factor = gfx::GetDPIScale();
#endif
button_->SetImage(
views::Button::STATE_NORMAL,
gfx::ImageSkia(gfx::ImageSkiaRep(*icon, device_scale_factor)));
button_->SizeToPreferredSize();
if (button_->parent())
button_->parent()->Layout();
}
}
|
Make elevation icon size correct in different DPI settings
|
Make elevation icon size correct in different DPI settings
BUG=449731
Review URL: https://codereview.chromium.org/849543003
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#312458}
|
C++
|
bsd-3-clause
|
chuan9/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,chuan9/chromium-crosswalk,ltilve/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium
|
948d55c179e7b9fea28c84d5b1fc2040120db730
|
Caprica/main.cpp
|
Caprica/main.cpp
|
#include <ostream>
#include <string>
#include <ppl.h>
#include <boost/filesystem.hpp>
#include <common/CapricaConfig.h>
#include <papyrus/PapyrusResolutionContext.h>
#include <papyrus/PapyrusScript.h>
#include <papyrus/parser/PapyrusParser.h>
#include <pex/PexAsmWriter.h>
#include <pex/PexReader.h>
#include <pex/PexWriter.h>
#include <pex/parser/PexAsmParser.h>
void compileScript(std::string filename) {
printf("Compiling %s\n", filename.c_str());
auto baseName = boost::filesystem::basename(filename);
auto ext = boost::filesystem::extension(filename);
if (ext == ".psc") {
auto parser = new caprica::papyrus::parser::PapyrusParser(filename);
auto a = parser->parseScript();
caprica::CapricaError::exitIfErrors();
delete parser;
auto ctx = new caprica::papyrus::PapyrusResolutionContext();
a->semantic(ctx);
caprica::CapricaError::exitIfErrors();
auto pex = a->buildPex();
caprica::CapricaError::exitIfErrors();
delete ctx;
delete a;
std::ofstream strm(baseName + ".pex", std::ofstream::binary);
caprica::pex::PexWriter wtr(strm);
pex->write(wtr);
if (caprica::CapricaConfig::dumpPexAsm) {
std::ofstream asmStrm(baseName + ".pas", std::ofstream::binary);
caprica::pex::PexAsmWriter asmWtr(asmStrm);
pex->writeAsm(asmWtr);
}
delete pex;
} else if (ext == ".pas") {
auto parser = new caprica::pex::parser::PexAsmParser(filename);
auto pex = parser->parseFile();
caprica::CapricaError::exitIfErrors();
delete parser;
std::ofstream strm(baseName + ".pex", std::ofstream::binary);
caprica::pex::PexWriter wtr(strm);
pex->write(wtr);
delete pex;
} else if (ext == ".pex") {
caprica::pex::PexReader rdr(filename);
auto pex = caprica::pex::PexFile::read(rdr);
caprica::CapricaError::exitIfErrors();
std::ofstream asmStrm(baseName + ".pas", std::ofstream::binary);
caprica::pex::PexAsmWriter asmWtr(asmStrm);
pex->writeAsm(asmWtr);
delete pex;
} else {
printf("Don't know how to compile %s!\n", filename.c_str());
}
}
int main(int argc, char* argv[])
{
if (argc != 2) {
printf("Invoke like: caprica.exe myFile.psc");
}
printf("Caprica Papyrus Compiler v0.0.7\n");
#ifdef NDEBUG
try {
#endif
std::string file = argv[1];
if (boost::filesystem::is_directory(file)) {
caprica::CapricaConfig::importDirectories.push_back(boost::filesystem::absolute(file).string());
std::vector<std::string> files;
boost::system::error_code ec;
for (auto e : boost::filesystem::directory_iterator(file, ec)) {
if (boost::filesystem::extension(e.path()) == ".psc" || boost::filesystem::extension(e.path()) == ".pas")
files.push_back(e.path().string());
}
if (caprica::CapricaConfig::compileInParallel) {
concurrency::parallel_for_each(files.begin(), files.end(), [](std::string fl) {
compileScript(fl);
});
} else {
for (auto& file : files)
compileScript(file);
}
} else {
caprica::CapricaConfig::importDirectories.push_back(boost::filesystem::path(boost::filesystem::absolute(file)).parent_path().string());
compileScript(file);
}
#ifdef NDEBUG
} catch (std::runtime_error err) {
printf("%s", err.what());
getchar();
}
#endif
return 0;
}
|
#include <ostream>
#include <string>
#include <ppl.h>
#include <boost/filesystem.hpp>
#include <common/CapricaConfig.h>
#include <papyrus/PapyrusResolutionContext.h>
#include <papyrus/PapyrusScript.h>
#include <papyrus/parser/PapyrusParser.h>
#include <pex/PexAsmWriter.h>
#include <pex/PexReader.h>
#include <pex/PexWriter.h>
#include <pex/parser/PexAsmParser.h>
void compileScript(std::string filename) {
printf("Compiling %s\n", filename.c_str());
auto baseName = boost::filesystem::basename(filename);
auto ext = boost::filesystem::extension(filename);
if (ext == ".psc") {
auto parser = new caprica::papyrus::parser::PapyrusParser(filename);
auto a = parser->parseScript();
caprica::CapricaError::exitIfErrors();
delete parser;
auto ctx = new caprica::papyrus::PapyrusResolutionContext();
a->semantic(ctx);
caprica::CapricaError::exitIfErrors();
auto pex = a->buildPex();
caprica::CapricaError::exitIfErrors();
delete ctx;
delete a;
std::ofstream strm(baseName + ".pex", std::ofstream::binary);
caprica::pex::PexWriter wtr(strm);
pex->write(wtr);
if (caprica::CapricaConfig::dumpPexAsm) {
std::ofstream asmStrm(baseName + ".pas", std::ofstream::binary);
caprica::pex::PexAsmWriter asmWtr(asmStrm);
pex->writeAsm(asmWtr);
}
delete pex;
} else if (ext == ".pas") {
auto parser = new caprica::pex::parser::PexAsmParser(filename);
auto pex = parser->parseFile();
caprica::CapricaError::exitIfErrors();
delete parser;
std::ofstream strm(baseName + ".pex", std::ofstream::binary);
caprica::pex::PexWriter wtr(strm);
pex->write(wtr);
delete pex;
} else if (ext == ".pex") {
caprica::pex::PexReader rdr(filename);
auto pex = caprica::pex::PexFile::read(rdr);
caprica::CapricaError::exitIfErrors();
std::ofstream asmStrm(baseName + ".pas", std::ofstream::binary);
caprica::pex::PexAsmWriter asmWtr(asmStrm);
pex->writeAsm(asmWtr);
delete pex;
} else {
printf("Don't know how to compile %s!\n", filename.c_str());
}
}
int main(int argc, char* argv[])
{
if (argc != 2) {
printf("Invoke like: caprica.exe myFile.psc");
}
printf("Caprica Papyrus Compiler v0.0.8\n");
#ifdef NDEBUG
try {
#endif
std::string file = argv[1];
if (boost::filesystem::is_directory(file)) {
caprica::CapricaConfig::importDirectories.push_back(boost::filesystem::absolute(file).string());
std::vector<std::string> files;
boost::system::error_code ec;
for (auto e : boost::filesystem::directory_iterator(file, ec)) {
if (boost::filesystem::extension(e.path()) == ".psc" || boost::filesystem::extension(e.path()) == ".pas")
files.push_back(e.path().string());
}
if (caprica::CapricaConfig::compileInParallel) {
concurrency::parallel_for_each(files.begin(), files.end(), [](std::string fl) {
compileScript(fl);
});
} else {
for (auto& file : files)
compileScript(file);
}
} else {
caprica::CapricaConfig::importDirectories.push_back(boost::filesystem::path(boost::filesystem::absolute(file)).parent_path().string());
compileScript(file);
}
#ifdef NDEBUG
} catch (std::runtime_error err) {
printf("%s", err.what());
getchar();
}
#endif
return 0;
}
|
Bump version number to v0.0.8
|
Bump version number to v0.0.8
|
C++
|
mit
|
Orvid/Caprica,Orvid/Caprica
|
568a0a731a5f692f3a995a82b37a3f4fd4562a72
|
dynd/src/wrapper.cpp
|
dynd/src/wrapper.cpp
|
//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#include "wrapper.hpp"
using namespace std;
template <typename T>
PyTypeObject *&DyND_PyWrapper_Type()
{
static PyTypeObject *type = NULL;
return type;
}
template PyTypeObject *&DyND_PyWrapper_Type<dynd::nd::array>();
template PyTypeObject *&DyND_PyWrapper_Type<dynd::nd::callable>();
template PyTypeObject *&DyND_PyWrapper_Type<dynd::ndt::type>();
|
//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#include "wrapper.hpp"
using namespace std;
template <typename T>
inline PyTypeObject *&DyND_PyWrapper_Type()
{
static PyTypeObject *type = NULL;
return type;
}
template PyTypeObject *&DyND_PyWrapper_Type<dynd::nd::array>();
template PyTypeObject *&DyND_PyWrapper_Type<dynd::nd::callable>();
template PyTypeObject *&DyND_PyWrapper_Type<dynd::ndt::type>();
|
Update wrapper.cpp
|
Update wrapper.cpp
|
C++
|
bsd-2-clause
|
insertinterestingnamehere/dynd-python,cpcloud/dynd-python,izaid/dynd-python,ContinuumIO/dynd-python,ContinuumIO/dynd-python,ContinuumIO/dynd-python,cpcloud/dynd-python,pombredanne/dynd-python,ContinuumIO/dynd-python,izaid/dynd-python,pombredanne/dynd-python,cpcloud/dynd-python,mwiebe/dynd-python,pombredanne/dynd-python,pombredanne/dynd-python,insertinterestingnamehere/dynd-python,mwiebe/dynd-python,insertinterestingnamehere/dynd-python,izaid/dynd-python,izaid/dynd-python,michaelpacer/dynd-python,michaelpacer/dynd-python,michaelpacer/dynd-python,cpcloud/dynd-python,mwiebe/dynd-python,michaelpacer/dynd-python,mwiebe/dynd-python,insertinterestingnamehere/dynd-python
|
1f31001f2b86e805cf19826f2eb1685c51966e34
|
packages/applications/defmap.cc
|
packages/applications/defmap.cc
|
/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#ifdef HAS_VTK
#include <irtkRegistration.h>
// Default filenames
char *target_name = NULL, *output_name = NULL, *mask_name = NULL;
char **dof_name = NULL;
#define MAX_DOFS 10
#define MAX_PTS_PAREG 10000
void usage()
{
cerr << " Usage: defmap [target] [output] <options>" << endl;
cerr << " " << endl;
cerr << " Map of distances that voxels in the target move under the effect" << endl;
cerr << " of one or more transformations." << endl;
cerr << " " << endl;
cerr << " where <options> is one or more of the following: \n" << endl;
cerr << " -dofin file Transformation. Can be repeated to give multiple dofs" << endl;
cerr << " (i.e. \"-dofin file1 -dofin file2 ...\") which are applied" << endl;
cerr << " in order given (Max 10)." << endl;
cerr << " -Tp value Padding value in target." << endl;
cerr << " -mask file Image mask to define a region of interest." << endl;
cerr << " -removeGlobal Estimate a global affine transformation based on a sampled" << endl;
cerr << " subset of voxel locations and their transformed coordinates." << endl;
cerr << " Remove the effect of this global transformation before " << endl;
cerr << " estimating the distances." << endl;
cerr << " " << endl;
exit(1);
}
int main(int argc, char **argv)
{
irtkTransformation **transformation = NULL;
int ok, x, y, z, regressAffine;
double Tp, val;
int i, noOfDofs;
int noOfPoints, ptID;
// Check command line
if (argc < 3){
usage();
}
// Parse source and target images
target_name = argv[1];
argc--;
argv++;
output_name = argv[1];
argc--;
argv++;
// Read target image
cout << "Reading target ... ";
cout.flush();
irtkRealImage target(target_name);
cout << "done" << endl;
Tp = -1.0 * FLT_MAX;
// Fix number of dofs
noOfDofs = 0;
dof_name = new char*[MAX_DOFS];
regressAffine = false;
while (argc > 1){
ok = false;
if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)){
argc--;
argv++;
dof_name[noOfDofs] = argv[1];
noOfDofs++;
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tp") == 0)){
argc--;
argv++;
Tp = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-removeGlobal") == 0)){
argc--;
argv++;
regressAffine = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-mask") == 0)){
argc--;
argv++;
mask_name = argv[1];
argc--;
argv++;
ok = true;
}
if (ok == false){
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
if (noOfDofs == 0){
cout << "No transformations specified: Using a single identity transformation!" << endl;
noOfDofs = 1;
transformation = new irtkTransformation*[noOfDofs];
transformation[0] = new irtkRigidTransformation;
} else {
cout << "Reading dof(s) ... ";
cout.flush();
transformation = new irtkTransformation*[noOfDofs];
for (i = 0; i < noOfDofs; i++){
transformation[i] = irtkTransformation::New(dof_name[i]);
}
cout << "done." << endl;
}
cout << "Setting up mask ... ";
cout.flush();
irtkGreyImage mask;
if (mask_name == NULL){
mask.Read(target_name);
irtkGreyPixel *ptr2mask = mask.GetPointerToVoxels();
irtkRealPixel *ptr2tgt = target.GetPointerToVoxels();
noOfPoints = target.GetNumberOfVoxels();
for (i = 0; i < noOfPoints; i++){
if (*ptr2tgt > Tp)
*ptr2mask = 1;
else
*ptr2mask = 0;
++ptr2tgt;
++ptr2mask;
}
} else {
mask.Read(mask_name);
}
cout << "done." << endl;
// Make an identity global transformation.
irtkAffineTransformation *trAffine = new irtkAffineTransformation;
if (regressAffine == true){
// Estimate the global affine transformation.
irtkPointSet targetPts;
irtkPointSet sourcePts;
// Collect point data.
cout << "Collecting point data." << endl;
noOfPoints = target.GetNumberOfVoxels();
cout << "Number of voxels : " << noOfPoints << endl;
int incr;
incr = 1;
while ((noOfPoints / incr) > MAX_PTS_PAREG){
incr++;
}
cout << "Subsampling uniformly by increments of " << incr << " ... ";
cout.flush();
noOfPoints = 0;
ptID = -1;
// Loop over all voxels.
for (z = 0; z < target.GetZ(); z++){
for (y = 0; y < target.GetY(); y++){
for (x = 0; x < target.GetX(); x++){
ptID++;
// Should we sample it or not?
if ((ptID % incr) != 0)
continue;
// Get two copies of current image coordinates.
irtkPoint p(x, y, z);
irtkPoint q(x, y, z);
// Transform points into target world coordinates.
target.ImageToWorld(p);
target.ImageToWorld(q);
targetPts.Add(p);
// Transform one point to source coordinates.
for (i = 0; i < noOfDofs; i++){
transformation[i]->Transform(q);
}
sourcePts.Add(q);
noOfPoints++;
}
}
}
cout << "done." << endl;
cout << "Sampled point count : " << noOfPoints << endl;
cout << "Estimating global affine component ... (Error = ";
cout.flush();
irtkPointAffineRegistration *pareg = new irtkPointAffineRegistration;
// Set input and output for the registration filter
irtkPointSet tmp1 = targetPts;
irtkPointSet tmp2 = sourcePts;
pareg->SetInput(&tmp1, &tmp2);
pareg->SetOutput(trAffine);
// Run registration filter
pareg->Run();
cout << ") done." << endl;
cout << "Estimated global affine transformation: " << endl;
trAffine->Print();
cout << endl;
cout << "Calculating displacements after removing affine component ... ";
} else {
// No affine regression
cout << "Calculating full displacements of transformations ... ";
}
cout.flush();
for (z = 0; z < target.GetZ(); z++){
for (y = 0; y < target.GetY(); y++){
for (x = 0; x < target.GetX(); x++){
if (mask(x,y,z) > 0){
irtkPoint p(x, y, z);
irtkPoint q(x, y, z);
// Transform points into target world coordinates
target.ImageToWorld(p);
target.ImageToWorld(q);
// Apply global Affine to one copy of the target
// points (this is the identity if no regression was done).
trAffine->irtkTransformation::Transform(p);
// Transform the other copy by the input dofs.
for (i = 0; i < noOfDofs; i++){
transformation[i]->Transform(q);
}
// Calculate distance.
val = p.Distance(q);
} else {
val = 0;
}
target.Put(x, y, z, val);
}
}
}
target.Write(output_name);
cout << "done." << endl;
}
#else
#include <irtkImage.h>
int main( int argc, char *argv[] ){
cerr << argv[0] << " needs to be compiled with the VTK library " << endl;
}
#endif
|
/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#ifdef HAS_VTK
#include <irtkRegistration.h>
// Default filenames
char *target_name = NULL, *output_name = NULL, *mask_name = NULL;
char **dof_name = NULL;
#define MAX_DOFS 10
#define MAX_PTS_PAREG 10000
void usage()
{
cerr << " Usage: defmap [target] [output] <options>" << endl;
cerr << " " << endl;
cerr << " Map of distances that voxels in the target move under the effect" << endl;
cerr << " of one or more transformations." << endl;
cerr << " " << endl;
cerr << " where <options> is one or more of the following: \n" << endl;
cerr << " -dofin file Transformation. Can be repeated to give multiple dofs" << endl;
cerr << " (i.e. \"-dofin file1 -dofin file2 ...\") which are applied" << endl;
cerr << " in order given (Max 10)." << endl;
cerr << " -Tp value Padding value in target." << endl;
cerr << " -mask file Image mask to define a region of interest." << endl;
cerr << " -removeGlobal Estimate a global affine transformation based on a sampled" << endl;
cerr << " subset of voxel locations and their transformed coordinates." << endl;
cerr << " Remove the effect of this global transformation before " << endl;
cerr << " estimating the distances." << endl;
cerr << " -square Provide map of squared distances." << endl;
cerr << " " << endl;
exit(1);
}
int main(int argc, char **argv)
{
irtkTransformation **transformation = NULL;
int x, y, z;
bool regressAffine, ok, squaredDistance;
double Tp, val;
int i, noOfDofs;
int noOfPoints, ptID;
// Check command line
if (argc < 3){
usage();
}
// Parse source and target images
target_name = argv[1];
argc--;
argv++;
output_name = argv[1];
argc--;
argv++;
// Read target image
cout << "Reading target ... ";
cout.flush();
irtkRealImage target(target_name);
cout << "done" << endl;
Tp = -1.0 * FLT_MAX;
// Fix number of dofs
noOfDofs = 0;
dof_name = new char*[MAX_DOFS];
regressAffine = false;
squaredDistance = false;
while (argc > 1){
ok = false;
if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)){
argc--;
argv++;
dof_name[noOfDofs] = argv[1];
noOfDofs++;
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tp") == 0)){
argc--;
argv++;
Tp = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-removeGlobal") == 0)){
argc--;
argv++;
regressAffine = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-square") == 0)){
argc--;
argv++;
squaredDistance = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-mask") == 0)){
argc--;
argv++;
mask_name = argv[1];
argc--;
argv++;
ok = true;
}
if (ok == false){
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
if (noOfDofs == 0){
cout << "No transformations specified: Using a single identity transformation!" << endl;
noOfDofs = 1;
transformation = new irtkTransformation*[noOfDofs];
transformation[0] = new irtkRigidTransformation;
} else {
cout << "Reading dof(s) ... ";
cout.flush();
transformation = new irtkTransformation*[noOfDofs];
for (i = 0; i < noOfDofs; i++){
transformation[i] = irtkTransformation::New(dof_name[i]);
}
cout << "done." << endl;
}
cout << "Setting up mask ... ";
cout.flush();
irtkGreyImage mask;
if (mask_name == NULL){
mask.Read(target_name);
irtkGreyPixel *ptr2mask = mask.GetPointerToVoxels();
irtkRealPixel *ptr2tgt = target.GetPointerToVoxels();
noOfPoints = target.GetNumberOfVoxels();
for (i = 0; i < noOfPoints; i++){
if (*ptr2tgt > Tp)
*ptr2mask = 1;
else
*ptr2mask = 0;
++ptr2tgt;
++ptr2mask;
}
} else {
mask.Read(mask_name);
}
cout << "done." << endl;
// Make an identity global transformation.
irtkAffineTransformation *trAffine = new irtkAffineTransformation;
if (regressAffine == true){
// Estimate the global affine transformation.
irtkPointSet targetPts;
irtkPointSet sourcePts;
// Collect point data.
cout << "Collecting point data." << endl;
noOfPoints = target.GetNumberOfVoxels();
cout << "Number of voxels : " << noOfPoints << endl;
int incr;
incr = 1;
while ((noOfPoints / incr) > MAX_PTS_PAREG){
incr++;
}
cout << "Subsampling uniformly by increments of " << incr << " ... ";
cout.flush();
noOfPoints = 0;
ptID = -1;
// Loop over all voxels.
for (z = 0; z < target.GetZ(); z++){
for (y = 0; y < target.GetY(); y++){
for (x = 0; x < target.GetX(); x++){
ptID++;
// Should we sample it or not?
if ((ptID % incr) != 0)
continue;
// Get two copies of current image coordinates.
irtkPoint p(x, y, z);
irtkPoint q(x, y, z);
// Transform points into target world coordinates.
target.ImageToWorld(p);
target.ImageToWorld(q);
targetPts.Add(p);
// Transform one point to source coordinates.
for (i = 0; i < noOfDofs; i++){
transformation[i]->Transform(q);
}
sourcePts.Add(q);
noOfPoints++;
}
}
}
cout << "done." << endl;
cout << "Sampled point count : " << noOfPoints << endl;
cout << "Estimating global affine component ... (Error = ";
cout.flush();
irtkPointAffineRegistration *pareg = new irtkPointAffineRegistration;
// Set input and output for the registration filter
irtkPointSet tmp1 = targetPts;
irtkPointSet tmp2 = sourcePts;
pareg->SetInput(&tmp1, &tmp2);
pareg->SetOutput(trAffine);
// Run registration filter
pareg->Run();
cout << ") done." << endl;
cout << "Estimated global affine transformation: " << endl;
trAffine->Print();
cout << endl;
cout << "Calculating displacements after removing affine component ... ";
} else {
// No affine regression
cout << "Calculating full displacements of transformations ... ";
}
cout.flush();
for (z = 0; z < target.GetZ(); z++){
for (y = 0; y < target.GetY(); y++){
for (x = 0; x < target.GetX(); x++){
if (mask(x,y,z) > 0){
irtkPoint p(x, y, z);
irtkPoint q(x, y, z);
// Transform points into target world coordinates
target.ImageToWorld(p);
target.ImageToWorld(q);
// Apply global Affine to one copy of the target
// points (this is the identity if no regression was done).
trAffine->irtkTransformation::Transform(p);
// Transform the other copy by the input dofs.
for (i = 0; i < noOfDofs; i++){
transformation[i]->Transform(q);
}
// Calculate distance.
val = p.Distance(q);
if (squaredDistance == true){
val = val * val;
}
} else {
val = 0;
}
target.Put(x, y, z, val);
}
}
}
target.Write(output_name);
cout << "done." << endl;
}
#else
#include <irtkImage.h>
int main( int argc, char *argv[] ){
cerr << argv[0] << " needs to be compiled with the VTK library " << endl;
}
#endif
|
Allow a map of squared distances.
|
Allow a map of squared distances.
|
C++
|
unknown
|
sk1712/IRTK,sk1712/IRTK,ghisvail/irtk-legacy,BioMedIA/irtk-legacy,BioMedIA/IRTK,BioMedIA/IRTK,ghisvail/irtk-legacy,sk1712/IRTK,BioMedIA/IRTK,ghisvail/irtk-legacy,BioMedIA/irtk-legacy,BioMedIA/irtk-legacy,BioMedIA/irtk-legacy,sk1712/IRTK,BioMedIA/IRTK,ghisvail/irtk-legacy
|
afd3599a9c86244d572f6c3281be335d96dec11a
|
Extractor/XMLParser.cpp
|
Extractor/XMLParser.cpp
|
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
*/
#include "XMLParser.h"
#include "ExtractionWay.h"
#include "ExtractorCallbacks.h"
#include "../DataStructures/HashTable.h"
#include "../DataStructures/ImportNode.h"
#include "../DataStructures/InputReaderFactory.h"
#include "../DataStructures/Restriction.h"
#include "../Util/SimpleLogger.h"
#include "../Util/StringUtil.h"
#include "../typedefs.h"
#include <osrm/Coordinate.h>
XMLParser::XMLParser(const char *filename, ExtractorCallbacks *ec, ScriptingEnvironment &se)
: BaseParser(ec, se)
{
inputReader = inputReaderFactory(filename);
}
bool XMLParser::ReadHeader() { return xmlTextReaderRead(inputReader) == 1; }
bool XMLParser::Parse()
{
while (xmlTextReaderRead(inputReader) == 1)
{
const int type = xmlTextReaderNodeType(inputReader);
// 1 is Element
if (type != 1)
{
continue;
}
xmlChar *currentName = xmlTextReaderName(inputReader);
if (currentName == NULL)
{
continue;
}
if (xmlStrEqual(currentName, (const xmlChar *)"node") == 1)
{
ImportNode n = ReadXMLNode();
ParseNodeInLua(n, lua_state);
extractor_callbacks->ProcessNode(n);
}
if (xmlStrEqual(currentName, (const xmlChar *)"way") == 1)
{
ExtractionWay way = ReadXMLWay();
ParseWayInLua(way, lua_state);
extractor_callbacks->ProcessWay(way);
}
if (use_turn_restrictions && xmlStrEqual(currentName, (const xmlChar *)"relation") == 1)
{
InputRestrictionContainer r = ReadXMLRestriction();
if ((UINT_MAX != r.fromWay) && !extractor_callbacks->ProcessRestriction(r))
{
std::cerr << "[XMLParser] restriction not parsed" << std::endl;
}
}
xmlFree(currentName);
}
return true;
}
InputRestrictionContainer XMLParser::ReadXMLRestriction()
{
InputRestrictionContainer restriction;
std::string except_tag_string;
if (xmlTextReaderIsEmptyElement(inputReader) != 1)
{
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
if (child_type != 1 && child_type != 15)
{
continue;
}
const int childDepth = xmlTextReaderDepth(inputReader);
xmlChar *childName = xmlTextReaderName(inputReader);
if (childName == NULL)
{
continue;
}
if (depth == childDepth && child_type == 15 &&
xmlStrEqual(childName, (const xmlChar *)"relation") == 1)
{
xmlFree(childName);
break;
}
if (child_type != 1)
{
xmlFree(childName);
continue;
}
if (xmlStrEqual(childName, (const xmlChar *)"tag") == 1)
{
xmlChar *k = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (k != NULL && value != NULL)
{
if (xmlStrEqual(k, (const xmlChar *)"restriction") &&
(0 == std::string((const char *)value).find("only_")))
{
restriction.restriction.flags.isOnly = true;
}
if (xmlStrEqual(k, (const xmlChar *)"except"))
{
except_tag_string = (const char *)value;
}
}
if (k != NULL)
{
xmlFree(k);
}
if (value != NULL)
{
xmlFree(value);
}
}
else if (xmlStrEqual(childName, (const xmlChar *)"member") == 1)
{
xmlChar *ref = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"ref");
if (ref != NULL)
{
xmlChar *role = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"role");
xmlChar *type = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"type");
if (xmlStrEqual(role, (const xmlChar *)"to") &&
xmlStrEqual(type, (const xmlChar *)"way"))
{
restriction.toWay = stringToUint((const char *)ref);
}
if (xmlStrEqual(role, (const xmlChar *)"from") &&
xmlStrEqual(type, (const xmlChar *)"way"))
{
restriction.fromWay = stringToUint((const char *)ref);
}
if (xmlStrEqual(role, (const xmlChar *)"via") &&
xmlStrEqual(type, (const xmlChar *)"node"))
{
restriction.restriction.viaNode = stringToUint((const char *)ref);
}
if (NULL != type)
{
xmlFree(type);
}
if (NULL != role)
{
xmlFree(role);
}
if (NULL != ref)
{
xmlFree(ref);
}
}
}
xmlFree(childName);
}
}
if (ShouldIgnoreRestriction(except_tag_string))
{
restriction.fromWay = UINT_MAX; // workaround to ignore the restriction
}
return restriction;
}
ExtractionWay XMLParser::ReadXMLWay()
{
ExtractionWay way;
if (xmlTextReaderIsEmptyElement(inputReader) == 1)
{
return way;
}
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
if (child_type != 1 && child_type != 15)
{
continue;
}
const int childDepth = xmlTextReaderDepth(inputReader);
xmlChar *childName = xmlTextReaderName(inputReader);
if (childName == NULL)
{
continue;
}
if (depth == childDepth && child_type == 15 &&
xmlStrEqual(childName, (const xmlChar *)"way") == 1)
{
xmlChar *id = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id");
way.id = stringToUint((char *)id);
xmlFree(id);
xmlFree(childName);
break;
}
if (child_type != 1)
{
xmlFree(childName);
continue;
}
if (xmlStrEqual(childName, (const xmlChar *)"tag") == 1)
{
xmlChar *k = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (k != NULL && value != NULL)
{
way.keyVals.Add(std::string((char *)k), std::string((char *)value));
}
if (k != NULL)
{
xmlFree(k);
}
if (value != NULL)
{
xmlFree(value);
}
}
else if (xmlStrEqual(childName, (const xmlChar *)"nd") == 1)
{
xmlChar *ref = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"ref");
if (ref != NULL)
{
way.path.push_back(stringToUint((const char *)ref));
xmlFree(ref);
}
}
xmlFree(childName);
}
return way;
}
ImportNode XMLParser::ReadXMLNode()
{
ImportNode node;
xmlChar *attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lat");
if (attribute != NULL)
{
node.lat = COORDINATE_PRECISION * StringToDouble((const char *)attribute);
xmlFree(attribute);
}
attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lon");
if (attribute != NULL)
{
node.lon = COORDINATE_PRECISION * StringToDouble((const char *)attribute);
xmlFree(attribute);
}
attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id");
if (attribute != NULL)
{
node.node_id = stringToUint((const char *)attribute);
xmlFree(attribute);
}
if (xmlTextReaderIsEmptyElement(inputReader) == 1)
{
return node;
}
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
// 1 = Element, 15 = EndElement
if (child_type != 1 && child_type != 15)
{
continue;
}
const int childDepth = xmlTextReaderDepth(inputReader);
xmlChar *childName = xmlTextReaderName(inputReader);
if (childName == NULL)
{
continue;
}
if (depth == childDepth && child_type == 15 &&
xmlStrEqual(childName, (const xmlChar *)"node") == 1)
{
xmlFree(childName);
break;
}
if (child_type != 1)
{
xmlFree(childName);
continue;
}
if (xmlStrEqual(childName, (const xmlChar *)"tag") == 1)
{
xmlChar *k = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (k != NULL && value != NULL)
{
node.keyVals.emplace(std::string((char *)(k)), std::string((char *)(value)));
}
if (k != NULL)
{
xmlFree(k);
}
if (value != NULL)
{
xmlFree(value);
}
}
xmlFree(childName);
}
return node;
}
|
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
*/
#include "XMLParser.h"
#include "ExtractionWay.h"
#include "ExtractorCallbacks.h"
#include "../DataStructures/HashTable.h"
#include "../DataStructures/ImportNode.h"
#include "../DataStructures/InputReaderFactory.h"
#include "../DataStructures/Restriction.h"
#include "../Util/SimpleLogger.h"
#include "../Util/StringUtil.h"
#include "../typedefs.h"
#include <osrm/Coordinate.h>
XMLParser::XMLParser(const char *filename, ExtractorCallbacks *ec, ScriptingEnvironment &se)
: BaseParser(ec, se)
{
inputReader = inputReaderFactory(filename);
}
bool XMLParser::ReadHeader() { return xmlTextReaderRead(inputReader) == 1; }
bool XMLParser::Parse()
{
while (xmlTextReaderRead(inputReader) == 1)
{
const int type = xmlTextReaderNodeType(inputReader);
// 1 is Element
if (type != 1)
{
continue;
}
xmlChar *currentName = xmlTextReaderName(inputReader);
if (currentName == NULL)
{
continue;
}
if (xmlStrEqual(currentName, (const xmlChar *)"node") == 1)
{
ImportNode n = ReadXMLNode();
ParseNodeInLua(n, lua_state);
extractor_callbacks->ProcessNode(n);
}
if (xmlStrEqual(currentName, (const xmlChar *)"way") == 1)
{
ExtractionWay way = ReadXMLWay();
ParseWayInLua(way, lua_state);
extractor_callbacks->ProcessWay(way);
}
if (use_turn_restrictions && xmlStrEqual(currentName, (const xmlChar *)"relation") == 1)
{
InputRestrictionContainer r = ReadXMLRestriction();
if ((UINT_MAX != r.fromWay) && !extractor_callbacks->ProcessRestriction(r))
{
std::cerr << "[XMLParser] restriction not parsed" << std::endl;
}
}
xmlFree(currentName);
}
return true;
}
InputRestrictionContainer XMLParser::ReadXMLRestriction()
{
InputRestrictionContainer restriction;
if (xmlTextReaderIsEmptyElement(inputReader) == 1)
{
return restriction;
}
std::string except_tag_string;
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
if (child_type != 1 && child_type != 15)
{
continue;
}
const int child_depth = xmlTextReaderDepth(inputReader);
xmlChar *child_name = xmlTextReaderName(inputReader);
if (child_name == NULL)
{
continue;
}
if (depth == child_depth && child_type == 15 &&
xmlStrEqual(child_name, (const xmlChar *)"relation") == 1)
{
xmlFree(child_name);
break;
}
if (child_type != 1)
{
xmlFree(child_name);
continue;
}
if (xmlStrEqual(child_name, (const xmlChar *)"tag") == 1)
{
xmlChar *k = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (k != NULL && value != NULL)
{
if (xmlStrEqual(k, (const xmlChar *)"restriction") &&
(0 == std::string((const char *)value).find("only_")))
{
restriction.restriction.flags.isOnly = true;
}
if (xmlStrEqual(k, (const xmlChar *)"except"))
{
except_tag_string = (const char *)value;
}
}
if (k != NULL)
{
xmlFree(k);
}
if (value != NULL)
{
xmlFree(value);
}
}
else if (xmlStrEqual(child_name, (const xmlChar *)"member") == 1)
{
xmlChar *ref = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"ref");
if (ref != NULL)
{
xmlChar *role = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"role");
xmlChar *type = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"type");
if (xmlStrEqual(role, (const xmlChar *)"to") &&
xmlStrEqual(type, (const xmlChar *)"way"))
{
restriction.toWay = stringToUint((const char *)ref);
}
if (xmlStrEqual(role, (const xmlChar *)"from") &&
xmlStrEqual(type, (const xmlChar *)"way"))
{
restriction.fromWay = stringToUint((const char *)ref);
}
if (xmlStrEqual(role, (const xmlChar *)"via") &&
xmlStrEqual(type, (const xmlChar *)"node"))
{
restriction.restriction.viaNode = stringToUint((const char *)ref);
}
if (NULL != type)
{
xmlFree(type);
}
if (NULL != role)
{
xmlFree(role);
}
if (NULL != ref)
{
xmlFree(ref);
}
}
}
xmlFree(child_name);
}
if (ShouldIgnoreRestriction(except_tag_string))
{
restriction.fromWay = UINT_MAX; // workaround to ignore the restriction
}
return restriction;
}
ExtractionWay XMLParser::ReadXMLWay()
{
ExtractionWay way;
if (xmlTextReaderIsEmptyElement(inputReader) == 1)
{
return way;
}
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
if (child_type != 1 && child_type != 15)
{
continue;
}
const int child_depth = xmlTextReaderDepth(inputReader);
xmlChar *child_name = xmlTextReaderName(inputReader);
if (child_name == NULL)
{
continue;
}
if (depth == child_depth && child_type == 15 &&
xmlStrEqual(child_name, (const xmlChar *)"way") == 1)
{
xmlChar *id = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id");
way.id = stringToUint((char *)id);
xmlFree(id);
xmlFree(child_name);
break;
}
if (child_type != 1)
{
xmlFree(child_name);
continue;
}
if (xmlStrEqual(child_name, (const xmlChar *)"tag") == 1)
{
xmlChar *k = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (k != NULL && value != NULL)
{
way.keyVals.Add(std::string((char *)k), std::string((char *)value));
}
if (k != NULL)
{
xmlFree(k);
}
if (value != NULL)
{
xmlFree(value);
}
}
else if (xmlStrEqual(child_name, (const xmlChar *)"nd") == 1)
{
xmlChar *ref = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"ref");
if (ref != NULL)
{
way.path.push_back(stringToUint((const char *)ref));
xmlFree(ref);
}
}
xmlFree(child_name);
}
return way;
}
ImportNode XMLParser::ReadXMLNode()
{
ImportNode node;
xmlChar *attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lat");
if (attribute != NULL)
{
node.lat = COORDINATE_PRECISION * StringToDouble((const char *)attribute);
xmlFree(attribute);
}
attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lon");
if (attribute != NULL)
{
node.lon = COORDINATE_PRECISION * StringToDouble((const char *)attribute);
xmlFree(attribute);
}
attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id");
if (attribute != NULL)
{
node.node_id = stringToUint((const char *)attribute);
xmlFree(attribute);
}
if (xmlTextReaderIsEmptyElement(inputReader) == 1)
{
return node;
}
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
// 1 = Element, 15 = EndElement
if (child_type != 1 && child_type != 15)
{
continue;
}
const int child_depth = xmlTextReaderDepth(inputReader);
xmlChar *child_name = xmlTextReaderName(inputReader);
if (child_name == NULL)
{
continue;
}
if (depth == child_depth && child_type == 15 &&
xmlStrEqual(child_name, (const xmlChar *)"node") == 1)
{
xmlFree(child_name);
break;
}
if (child_type != 1)
{
xmlFree(child_name);
continue;
}
if (xmlStrEqual(child_name, (const xmlChar *)"tag") == 1)
{
xmlChar *k = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (k != NULL && value != NULL)
{
node.keyVals.emplace(std::string((char *)(k)), std::string((char *)(value)));
}
if (k != NULL)
{
xmlFree(k);
}
if (value != NULL)
{
xmlFree(value);
}
}
xmlFree(child_name);
}
return node;
}
|
remove depth of nested block
|
remove depth of nested block
|
C++
|
bsd-2-clause
|
neilbu/osrm-backend,neilbu/osrm-backend,skyborla/osrm-backend,ammeurer/osrm-backend,raymond0/osrm-backend,skyborla/osrm-backend,raymond0/osrm-backend,agruss/osrm-backend,bjtaylor1/Project-OSRM-Old,Conggge/osrm-backend,ammeurer/osrm-backend,raymond0/osrm-backend,neilbu/osrm-backend,duizendnegen/osrm-backend,agruss/osrm-backend,jpizarrom/osrm-backend,frodrigo/osrm-backend,jpizarrom/osrm-backend,bjtaylor1/osrm-backend,Tristramg/osrm-backend,bjtaylor1/Project-OSRM-Old,bjtaylor1/osrm-backend,yuryleb/osrm-backend,duizendnegen/osrm-backend,hydrays/osrm-backend,duizendnegen/osrm-backend,Conggge/osrm-backend,antoinegiret/osrm-backend,Conggge/osrm-backend,antoinegiret/osrm-geovelo,Tristramg/osrm-backend,arnekaiser/osrm-backend,felixguendling/osrm-backend,duizendnegen/osrm-backend,antoinegiret/osrm-geovelo,ramyaragupathy/osrm-backend,oxidase/osrm-backend,bjtaylor1/osrm-backend,prembasumatary/osrm-backend,frodrigo/osrm-backend,Project-OSRM/osrm-backend,atsuyim/osrm-backend,oxidase/osrm-backend,nagyistoce/osrm-backend,tkhaxton/osrm-backend,KnockSoftware/osrm-backend,beemogmbh/osrm-backend,prembasumatary/osrm-backend,alex85k/Project-OSRM,stevevance/Project-OSRM,bjtaylor1/Project-OSRM-Old,chaupow/osrm-backend,alex85k/Project-OSRM,stevevance/Project-OSRM,nagyistoce/osrm-backend,Conggge/osrm-backend,skyborla/osrm-backend,ammeurer/osrm-backend,prembasumatary/osrm-backend,arnekaiser/osrm-backend,frodrigo/osrm-backend,yuryleb/osrm-backend,frodrigo/osrm-backend,ramyaragupathy/osrm-backend,ammeurer/osrm-backend,KnockSoftware/osrm-backend,ammeurer/osrm-backend,arnekaiser/osrm-backend,antoinegiret/osrm-backend,KnockSoftware/osrm-backend,arnekaiser/osrm-backend,tkhaxton/osrm-backend,Tristramg/osrm-backend,ramyaragupathy/osrm-backend,agruss/osrm-backend,Project-OSRM/osrm-backend,beemogmbh/osrm-backend,bitsteller/osrm-backend,Project-OSRM/osrm-backend,Project-OSRM/osrm-backend,stevevance/Project-OSRM,beemogmbh/osrm-backend,chaupow/osrm-backend,deniskoronchik/osrm-backend,stevevance/Project-OSRM,antoinegiret/osrm-backend,felixguendling/osrm-backend,bitsteller/osrm-backend,neilbu/osrm-backend,felixguendling/osrm-backend,yuryleb/osrm-backend,raymond0/osrm-backend,tkhaxton/osrm-backend,yuryleb/osrm-backend,chaupow/osrm-backend,atsuyim/osrm-backend,hydrays/osrm-backend,oxidase/osrm-backend,bitsteller/osrm-backend,bjtaylor1/osrm-backend,jpizarrom/osrm-backend,hydrays/osrm-backend,antoinegiret/osrm-geovelo,beemogmbh/osrm-backend,ammeurer/osrm-backend,KnockSoftware/osrm-backend,oxidase/osrm-backend,nagyistoce/osrm-backend,hydrays/osrm-backend,bjtaylor1/Project-OSRM-Old,deniskoronchik/osrm-backend,atsuyim/osrm-backend,ammeurer/osrm-backend,deniskoronchik/osrm-backend,deniskoronchik/osrm-backend,alex85k/Project-OSRM
|
3a114e1570ce483f6a659148131112dd634a0f47
|
MergeTwoSortListUseMultiCore/mergeTwoList.cpp
|
MergeTwoSortListUseMultiCore/mergeTwoList.cpp
|
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <pthread.h>
#include <sys/time.h>
#include <stdint.h>
#include <fstream>
struct arg_struct {
const std::vector<int> *first;
uint32_t first_size_begin;
uint32_t first_size_end;
const std::vector<int> *second;
uint32_t second_size_begin;
uint32_t second_size_end;
std::vector<int> value;
};
typedef struct arg_struct ARG ;
void* merge(void *arg) {
ARG *p = (ARG *) arg;
int first_size = p->first_size_end;
int second_size = p->second_size_end;
int begin = p->first_size_begin;
int end = p->second_size_begin;
p->value.resize((first_size - begin) + (second_size - end));
//std::cout << "first begin size: " << begin << " first end size: " << first_size << " second begin size: " << end << " second end size: " << second_size << std::endl;
while (begin < first_size && end < second_size) {
if ((*p->first)[begin] < (*p->second)[end]) {
p->value.push_back((*p->first)[begin]);
begin++;
} else if ((*p->first)[begin] > (*p->second)[end]){
p->value.push_back((*p->second)[end]);
end++;
} else {
p->value.push_back((*p->second)[begin]);
begin++;
end++;
}
}
while (begin < first_size) {
p->value.push_back((*p->first)[begin]);
begin++;
}
while (end < second_size) {
p->value.push_back((*p->second)[end]);
end++;
}
//std::cout << "value size is " << p->value.size() << std::endl;
return NULL;
}
void create_n_thread(const std::vector<int> &first, const std::vector<int> &second, uint32_t thread_count)
{
pthread_t thr[thread_count];
ARG arg[thread_count];
int pos = 0;
for (size_t i = 0; i < thread_count; i++) {
//std::cout << "pos is " << pos << " value is " << second[pos] << std::endl;
arg[i].first = &first;
arg[i].first_size_begin = first.size() * i / thread_count;
arg[i].first_size_end = first.size() * (i + 1) / thread_count;
arg[i].second = &second;
arg[i].second_size_begin = pos;
if (i == thread_count - 1) {
arg[i].second_size_end = second.size();
} else {
pos = lower_bound(second.begin(), second.end(), first[first.size() * (i + 1) / thread_count]) - second.begin();
arg[i].second_size_end = pos; // + 1
}
}
for (size_t i = 0; i < thread_count; i++) {
if (pthread_create(&thr[i], NULL, merge, (void*)&arg[i]) !=0) {
std::cout << "create " << i << " thread failed!" << std::endl;
return;
}
}
for (size_t i = 0; i < thread_count; i++) {
pthread_join(thr[i], NULL);
}
}
void load_data(std::vector<int> &first, std::vector<int> &second) {
std::ifstream fin("first.txt", std::ios::in);
char line[256]={0};
while (fin.getline(line, sizeof(line))) {
first.push_back(atoi(line));
}
std::ifstream fin2("second.txt", std::ios::in);
while (fin2.getline(line, sizeof(line))) {
second.push_back(atoi(line));
}
}
void common(const std::vector<int> &first, const std::vector<int> &second) {
struct timeval t1, t2;
gettimeofday(&t1, NULL);
ARG arg;
arg.first = &first;
arg.first_size_begin = 0;
arg.first_size_end = first.size();
arg.second = &second;
arg.second_size_begin = 0;
arg.second_size_end = second.size();
merge((void*)&arg);
gettimeofday(&t2, NULL);
std::cout << "一个进程merge耗时 " << ((t2.tv_sec - t1.tv_sec) * 1000000 + t2.tv_usec - t1.tv_usec) <<" 微秒"<< std::endl; //微秒
}
void use_four_thread(const std::vector<int> &first, const std::vector<int> &second, uint32_t thread_count) {
struct timeval t1, t2;
gettimeofday(&t1, NULL);
create_n_thread(first, second, thread_count);
gettimeofday(&t2, NULL);
std::cout << "四个线程merge耗时 " << ((t2.tv_sec - t1.tv_sec) * 1000000 + t2.tv_usec - t1.tv_usec) <<" 微秒"<< std::endl; //微秒
}
void use_two_thread(const std::vector<int> &first, const std::vector<int> &second, uint32_t thread_count) {
struct timeval t1, t2;
gettimeofday(&t1, NULL);
create_n_thread(first, second, thread_count);
gettimeofday(&t2, NULL);
std::cout << "两个线程merge耗时 " << ((t2.tv_sec - t1.tv_sec) * 1000000 + t2.tv_usec - t1.tv_usec) <<" 微秒"<< std::endl; //微秒
}
int main() {
std::vector<int> first;
std::vector<int> second;
load_data(first, second);
// 单线程merge时间统计
//common(first, second);
// 2个线程merge时间统计
//use_two_thread(first, second, 2);
// 4个线程merge时间统计
use_four_thread(first, second, 4);
return 0;
}
|
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <pthread.h>
#include <sys/time.h>
#include <stdint.h>
#include <fstream>
struct arg_struct {
const std::vector<int> *first;
uint32_t first_size_begin;
uint32_t first_size_end;
const std::vector<int> *second;
uint32_t second_size_begin;
uint32_t second_size_end;
std::vector<int> value;
};
typedef struct arg_struct ARG ;
void* merge(void *arg) {
ARG *p = (ARG *) arg;
int first_size = p->first_size_end;
int second_size = p->second_size_end;
int begin = p->first_size_begin;
int end = p->second_size_begin;
p->value.reserve((first_size - begin) + (second_size - end));
//std::cout << "first begin size: " << begin << " first end size: " << first_size << " second begin size: " << end << " second end size: " << second_size << std::endl;
while (begin < first_size && end < second_size) {
if ((*p->first)[begin] < (*p->second)[end]) {
p->value.push_back((*p->first)[begin]);
begin++;
} else if ((*p->first)[begin] > (*p->second)[end]){
p->value.push_back((*p->second)[end]);
end++;
} else {
p->value.push_back((*p->second)[begin]);
begin++;
end++;
}
}
while (begin < first_size) {
p->value.push_back((*p->first)[begin]);
begin++;
}
while (end < second_size) {
p->value.push_back((*p->second)[end]);
end++;
}
//std::cout << "value size is " << p->value.size() << std::endl;
return NULL;
}
void create_n_thread(const std::vector<int> &first, const std::vector<int> &second, uint32_t thread_count)
{
pthread_t thr[thread_count];
ARG arg[thread_count];
int pos = 0;
for (size_t i = 0; i < thread_count; i++) {
//std::cout << "pos is " << pos << " value is " << second[pos] << std::endl;
arg[i].first = &first;
arg[i].first_size_begin = first.size() * i / thread_count;
arg[i].first_size_end = first.size() * (i + 1) / thread_count;
arg[i].second = &second;
arg[i].second_size_begin = pos;
if (i == thread_count - 1) {
arg[i].second_size_end = second.size();
} else {
pos = lower_bound(second.begin(), second.end(), first[first.size() * (i + 1) / thread_count]) - second.begin();
arg[i].second_size_end = pos; // + 1
}
}
for (size_t i = 0; i < thread_count; i++) {
if (pthread_create(&thr[i], NULL, merge, (void*)&arg[i]) !=0) {
std::cout << "create " << i << " thread failed!" << std::endl;
return;
}
}
for (size_t i = 0; i < thread_count; i++) {
pthread_join(thr[i], NULL);
}
}
void load_data(std::vector<int> &first, std::vector<int> &second) {
std::ifstream fin("first.txt", std::ios::in);
char line[256]={0};
while (fin.getline(line, sizeof(line))) {
first.push_back(atoi(line));
}
std::ifstream fin2("second.txt", std::ios::in);
while (fin2.getline(line, sizeof(line))) {
second.push_back(atoi(line));
}
}
void common(const std::vector<int> &first, const std::vector<int> &second) {
struct timeval t1, t2;
gettimeofday(&t1, NULL);
ARG arg;
arg.first = &first;
arg.first_size_begin = 0;
arg.first_size_end = first.size();
arg.second = &second;
arg.second_size_begin = 0;
arg.second_size_end = second.size();
merge((void*)&arg);
gettimeofday(&t2, NULL);
std::cout << "一个进程merge耗时 " << ((t2.tv_sec - t1.tv_sec) * 1000000 + t2.tv_usec - t1.tv_usec) <<" 微秒"<< std::endl; //微秒
}
void use_four_thread(const std::vector<int> &first, const std::vector<int> &second, uint32_t thread_count) {
struct timeval t1, t2;
gettimeofday(&t1, NULL);
create_n_thread(first, second, thread_count);
gettimeofday(&t2, NULL);
std::cout << "四个线程merge耗时 " << ((t2.tv_sec - t1.tv_sec) * 1000000 + t2.tv_usec - t1.tv_usec) <<" 微秒"<< std::endl; //微秒
}
void use_two_thread(const std::vector<int> &first, const std::vector<int> &second, uint32_t thread_count) {
struct timeval t1, t2;
gettimeofday(&t1, NULL);
create_n_thread(first, second, thread_count);
gettimeofday(&t2, NULL);
std::cout << "两个线程merge耗时 " << ((t2.tv_sec - t1.tv_sec) * 1000000 + t2.tv_usec - t1.tv_usec) <<" 微秒"<< std::endl; //微秒
}
int main() {
std::vector<int> first;
std::vector<int> second;
load_data(first, second);
// 单线程merge时间统计
common(first, second);
// 2个线程merge时间统计
use_two_thread(first, second, 2);
// 4个线程merge时间统计
//use_four_thread(first, second, 4);
return 0;
}
|
fix bug
|
fix bug
|
C++
|
mit
|
armsword/snippet,armsword/snippet
|
9df792c199473ac1bd012b8018373680ac00c309
|
test/CodeGenCXX/global-init.cpp
|
test/CodeGenCXX/global-init.cpp
|
// RUN: %clang_cc1 -triple=x86_64-apple-darwin10 -emit-llvm %s -o - |FileCheck %s
struct A {
A();
~A();
};
struct B { B(); ~B(); };
struct C { void *field; };
struct D { ~D(); };
// CHECK: @c = global %struct.C zeroinitializer, align 8
// CHECK: call void @_ZN1AC1Ev(%struct.A* @a)
// CHECK: call i32 @__cxa_atexit(void (i8*)* bitcast (void (%struct.A*)* @_ZN1AD1Ev to void (i8*)*), i8* getelementptr inbounds (%struct.A* @a, i32 0, i32 0), i8* bitcast (i8** @__dso_handle to i8*))
A a;
// CHECK: call void @_ZN1BC1Ev(%struct.A* @b)
// CHECK: call i32 @__cxa_atexit(void (i8*)* bitcast (void (%struct.A*)* @_ZN1BD1Ev to void (i8*)*), i8* getelementptr inbounds (%struct.A* @b, i32 0, i32 0), i8* bitcast (i8** @__dso_handle to i8*))
B b;
// PR6205: this should not require a global initializer
// CHECK-NOT: call void @_ZN1CC1Ev(%struct.C* @c)
C c;
// CHECK: call i32 @__cxa_atexit(void (i8*)* bitcast (void (%struct.A*)* @_ZN1DD1Ev to void (i8*)*), i8* getelementptr inbounds (%struct.A* @d, i32 0, i32 0), i8* bitcast (i8** @__dso_handle to i8*))
D d;
// CHECK: define internal void @_GLOBAL__I_a() {
|
// RUN: %clang_cc1 -triple=x86_64-apple-darwin10 -emit-llvm %s -o - |FileCheck %s
struct A {
A();
~A();
};
struct B { B(); ~B(); };
struct C { void *field; };
struct D { ~D(); };
// CHECK: @c = global %struct.C zeroinitializer, align 8
// CHECK: call void @_ZN1AC1Ev(%struct.A* @a)
// CHECK: call i32 @__cxa_atexit(void (i8*)* bitcast (void (%struct.A*)* @_ZN1AD1Ev to void (i8*)*), i8* getelementptr inbounds (%struct.A* @a, i32 0, i32 0), i8* bitcast (i8** @__dso_handle to i8*))
A a;
// CHECK: call void @_ZN1BC1Ev(%struct.A* @b)
// CHECK: call i32 @__cxa_atexit(void (i8*)* bitcast (void (%struct.A*)* @_ZN1BD1Ev to void (i8*)*), i8* getelementptr inbounds (%struct.A* @b, i32 0, i32 0), i8* bitcast (i8** @__dso_handle to i8*))
B b;
// PR6205: this should not require a global initializer
// CHECK-NOT: call void @_ZN1CC1Ev(%struct.C* @c)
C c;
// CHECK: call i32 @__cxa_atexit(void (i8*)* bitcast (void (%struct.A*)* @_ZN1DD1Ev to void (i8*)*), i8* getelementptr inbounds (%struct.A* @d, i32 0, i32 0), i8* bitcast (i8** @__dso_handle to i8*))
D d;
// CHECK: define internal void @_GLOBAL__I_a() section "__TEXT,__StaticInit,regular,pure_instructions" {
|
Fix test.
|
Fix test.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@105668 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang
|
c42f0a5fe7641f565d1061f45258ef37f1a5499a
|
ui/src/inputoutputmanager.cpp
|
ui/src/inputoutputmanager.cpp
|
/*
Q Light Controller
inputoutputmanager.cpp
Copyright (c) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <QListWidgetItem>
#include <QListWidget>
#include <QHeaderView>
#include <QStringList>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QSettings>
#include <QSplitter>
#include <QLineEdit>
#include <QCheckBox>
#include <QToolBar>
#include <QAction>
#include <QTimer>
#include <QDebug>
#include <QLabel>
#include <QIcon>
#include "inputoutputpatcheditor.h"
#include "universeitemwidget.h"
#include "inputoutputmanager.h"
#include "inputoutputmap.h"
#include "outputpatch.h"
#include "inputpatch.h"
#include "apputil.h"
#include "doc.h"
#define KColumnUniverse 0
#define KColumnInput 1
#define KColumnOutput 2
#define KColumnFeedback 3
#define KColumnProfile 4
#define KColumnInputNum 5
#define KColumnOutputNum 6
#define SETTINGS_SPLITTER "inputmanager/splitter"
InputOutputManager* InputOutputManager::s_instance = NULL;
InputOutputManager::InputOutputManager(QWidget* parent, Doc* doc)
: QWidget(parent)
, m_doc(doc)
, m_toolbar(NULL)
, m_addUniverseAction(NULL)
, m_deleteUniverseAction(NULL)
, m_uniNameEdit(NULL)
, m_uniPassthroughCheck(NULL)
, m_editor(NULL)
, m_editorUniverse(UINT_MAX)
{
Q_ASSERT(s_instance == NULL);
s_instance = this;
Q_ASSERT(doc != NULL);
m_ioMap = doc->inputOutputMap();
/* Create a new layout for this widget */
new QVBoxLayout(this);
layout()->setContentsMargins(0, 0, 0, 0);
layout()->setSpacing(0);
m_splitter = new QSplitter(Qt::Horizontal, this);
layout()->addWidget(m_splitter);
m_addUniverseAction = new QAction(QIcon(":/edit_add.png"),
tr("Add U&niverse"), this);
m_addUniverseAction->setShortcut(QKeySequence("CTRL+N"));
connect(m_addUniverseAction, SIGNAL(triggered(bool)),
this, SLOT(slotAddUniverse()));
m_deleteUniverseAction = new QAction(QIcon(":/edit_remove.png"),
tr("&Delete Universe"), this);
m_deleteUniverseAction->setShortcut(QKeySequence("CTRL+D"));
connect(m_deleteUniverseAction, SIGNAL(triggered(bool)),
this, SLOT(slotDeleteUniverse()));
QWidget* ucontainer = new QWidget(this);
m_splitter->addWidget(ucontainer);
ucontainer->setLayout(new QVBoxLayout);
ucontainer->layout()->setContentsMargins(0, 0, 0, 0);
// Add a toolbar to the dock area
m_toolbar = new QToolBar("Input Output Manager", this);
m_toolbar->setFloatable(false);
m_toolbar->setMovable(false);
m_toolbar->setIconSize(QSize(32, 32));
m_toolbar->addAction(m_addUniverseAction);
m_toolbar->addAction(m_deleteUniverseAction);
m_toolbar->addSeparator();
QLabel *uniLabel = new QLabel(tr("Universe name:"));
m_uniNameEdit = new QLineEdit(this);
QFont font = QApplication::font();
//font.setBold(true);
font.setPixelSize(18);
uniLabel->setFont(font);
m_uniNameEdit->setFont(font);
m_toolbar->addWidget(uniLabel);
m_toolbar->addWidget(m_uniNameEdit);
m_uniPassthroughCheck = new QCheckBox(tr("Passthrough"), this);
m_uniPassthroughCheck->setLayoutDirection(Qt::RightToLeft);
m_uniPassthroughCheck->setFont(font);
m_toolbar->addWidget(m_uniPassthroughCheck);
m_splitter->widget(0)->layout()->addWidget(m_toolbar);
connect(m_uniNameEdit, SIGNAL(textChanged(QString)),
this, SLOT(slotUniverseNameChanged(QString)));
connect(m_uniPassthroughCheck, SIGNAL(toggled(bool)),
this, SLOT(slotPassthroughChanged(bool)));
/* Universes list */
m_list = new QListWidget(this);
m_list->setItemDelegate(new UniverseItemWidget(m_list));
m_splitter->widget(0)->layout()->addWidget(m_list);
QWidget* gcontainer = new QWidget(this);
m_splitter->addWidget(gcontainer);
gcontainer->setLayout(new QVBoxLayout);
gcontainer->layout()->setContentsMargins(0, 0, 0, 0);
connect(m_list, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
this, SLOT(slotCurrentItemChanged()));
/* Timer that clears the input data icon after a while */
m_icon = QIcon(":/input.png");
m_timer = new QTimer(this);
m_timer->setSingleShot(true);
connect(m_timer, SIGNAL(timeout()), this, SLOT(slotTimerTimeout()));
/* Listen to input map's input data signals */
connect(m_ioMap, SIGNAL(inputValueChanged(quint32,quint32,uchar)),
this, SLOT(slotInputValueChanged(quint32,quint32,uchar)));
/* Listen to plugin configuration changes */
connect(m_ioMap, SIGNAL(pluginConfigurationChanged(const QString&, bool)),
this, SLOT(updateList()));
connect(m_ioMap, SIGNAL(universeAdded(quint32)),
this, SLOT(slotUniverseAdded(quint32)));
updateList();
m_list->setCurrentItem(m_list->item(0));
QSettings settings;
QVariant var = settings.value(SETTINGS_SPLITTER);
if (var.isValid() == true)
m_splitter->restoreState(var.toByteArray());
}
InputOutputManager::~InputOutputManager()
{
QSettings settings;
settings.setValue(SETTINGS_SPLITTER, m_splitter->saveState());
s_instance = NULL;
}
InputOutputManager* InputOutputManager::instance()
{
return s_instance;
}
/*****************************************************************************
* Tree widget
*****************************************************************************/
void InputOutputManager::updateList()
{
m_list->blockSignals(true);
m_list->clear();
for (quint32 uni = 0; uni < m_ioMap->universesCount(); uni++)
updateItem(new QListWidgetItem(m_list), uni);
m_list->blockSignals(false);
if (m_ioMap->universesCount() == 0)
{
if (m_editor != NULL)
{
m_splitter->widget(1)->layout()->removeWidget(m_editor);
m_editor->deleteLater();
m_editor = NULL;
}
m_deleteUniverseAction->setEnabled(false);
m_uniNameEdit->setText("");
m_uniNameEdit->setEnabled(false);
}
else
{
m_deleteUniverseAction->setEnabled(true);
m_list->setCurrentItem(m_list->item(0));
m_uniNameEdit->setEnabled(true);
m_uniNameEdit->setText(m_ioMap->getUniverseNameByIndex(0));
m_uniPassthroughCheck->setChecked(m_ioMap->getUniversePassthrough(0));
}
}
void InputOutputManager::updateItem(QListWidgetItem* item, quint32 universe)
{
Q_ASSERT(item != NULL);
InputPatch* ip = m_ioMap->inputPatch(universe);
OutputPatch* op = m_ioMap->outputPatch(universe);
OutputPatch* fp = m_ioMap->feedbackPatch(universe);
QString uniName = m_ioMap->getUniverseNameByIndex(universe);
if (uniName.isEmpty())
{
QString defUniName = tr("Universe %1").arg(universe + 1);
m_ioMap->setUniverseName(universe, defUniName);
item->setData(Qt::DisplayRole, defUniName);
}
else
item->setData(Qt::DisplayRole, uniName);
item->setSizeHint(QSize(m_list->width(), 50));
item->setData(Qt::UserRole, universe);
if (ip != NULL)
{
item->setData(Qt::UserRole + 1, ip->inputName());
item->setData(Qt::UserRole + 2, ip->profileName());
}
else
{
item->setData(Qt::UserRole + 1, KInputNone);
item->setData(Qt::UserRole + 2, KInputNone);
}
if (op != NULL)
item->setData(Qt::UserRole + 3, op->outputName());
else
item->setData(Qt::UserRole + 3, KOutputNone);
if (fp != NULL)
item->setData(Qt::UserRole + 4, fp->outputName());
else
item->setData(Qt::UserRole + 4, KOutputNone);
}
void InputOutputManager::slotInputValueChanged(quint32 universe, quint32 channel, uchar value)
{
Q_UNUSED(channel);
Q_UNUSED(value);
// If the manager is not visible, don't even waste CPU
if (isVisible() == false)
return;
QListWidgetItem *item = m_list->item(universe);
if (item == NULL)
return;
/* Show an icon on a universe row that received input data */
item->setData(Qt::DecorationRole, m_icon);
/* Restart the timer */
m_timer->start(300);
}
void InputOutputManager::slotTimerTimeout()
{
for (int i = 0; i < m_list->count(); i++)
{
QListWidgetItem *item = m_list->item(i);
item->setData(Qt::DecorationRole, QIcon());
}
}
void InputOutputManager::slotCurrentItemChanged()
{
QListWidgetItem* item = m_list->currentItem();
if (item == NULL)
{
if (m_ioMap->universesCount() == 0)
return;
m_list->setCurrentItem(m_list->item(0));
item = m_list->currentItem();
}
if (item == NULL)
return;
quint32 universe = item->data(Qt::UserRole).toInt();
if (m_editorUniverse == universe)
return;
if (m_editor != NULL)
{
m_splitter->widget(1)->layout()->removeWidget(m_editor);
m_editor->deleteLater();
m_editor = NULL;
}
m_editor = new InputOutputPatchEditor(this, universe, m_ioMap, m_doc);
m_editorUniverse = universe;
m_splitter->widget(1)->layout()->addWidget(m_editor);
connect(m_editor, SIGNAL(mappingChanged()), this, SLOT(slotMappingChanged()));
connect(m_editor, SIGNAL(audioInputDeviceChanged()), this, SLOT(slotAudioInputChanged()));
m_editor->show();
int uniIdx = m_list->currentRow();
m_uniNameEdit->setText(m_ioMap->getUniverseNameByIndex(uniIdx));
m_uniPassthroughCheck->setChecked(m_ioMap->getUniversePassthrough(uniIdx));
}
void InputOutputManager::slotMappingChanged()
{
QListWidgetItem* item = m_list->currentItem();
if (item != NULL)
{
uint universe = item->data(Qt::UserRole).toInt();
updateItem(item, universe);
m_doc->inputOutputMap()->saveDefaults();
}
}
void InputOutputManager::slotAudioInputChanged()
{
m_doc->destroyAudioCapture();
}
void InputOutputManager::slotAddUniverse()
{
m_ioMap->addUniverse();
m_doc->setModified();
}
void InputOutputManager::slotDeleteUniverse()
{
int uniIdx = m_list->currentRow();
if ((uniIdx + 1) != (int)(m_ioMap->universesCount()))
{
QMessageBox::information(this,
tr("Unable to remove universe"),
tr("You can only remove universes starting from the last one"));
return;
}
// Check if the universe is patched
if (m_ioMap->isUniversePatched(uniIdx) == true)
{
// Ask for user's confirmation
if (QMessageBox::question(
this, tr("Delete Universe"),
tr("The universe you are trying to delete is patched. Are you sure you want to delete it ?"),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
}
// Check if there are fixtures using this universe
quint32 uniID = m_ioMap->getUniverseID(uniIdx);
if (uniID == m_ioMap->invalidUniverse())
return;
foreach(Fixture *fx, m_doc->fixtures())
{
if (fx->universe() == uniID)
{
// Ask for user's confirmation
if (QMessageBox::question(
this, tr("Delete Universe"),
tr("There are some fixtures using the universe you are trying to delete. Are you sure you want to delete it ?"),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
break;
}
}
m_ioMap->removeUniverse(uniIdx);
m_doc->setModified();
updateList();
}
void InputOutputManager::slotUniverseNameChanged(QString name)
{
QListWidgetItem *currItem = m_list->currentItem();
if (currItem == NULL)
return;
int uniIdx = m_list->currentRow();
if (name.isEmpty())
name = tr("Universe %1").arg(uniIdx + 1);
m_ioMap->setUniverseName(uniIdx, name);
currItem->setData(Qt::DisplayRole, name);
}
void InputOutputManager::slotUniverseAdded(quint32 universe)
{
QListWidgetItem *item = new QListWidgetItem(m_list);
updateItem(item, universe);
}
void InputOutputManager::slotPassthroughChanged(bool checked)
{
QListWidgetItem *currItem = m_list->currentItem();
if (currItem == NULL)
return;
int uniIdx = m_list->currentRow();
m_ioMap->setUniversePassthrough(uniIdx, checked);
m_doc->inputOutputMap()->saveDefaults();
}
void InputOutputManager::showEvent(QShowEvent *ev)
{
Q_UNUSED(ev);
// force the recreation of the selected universe editor
m_editorUniverse = UINT_MAX;
updateList();
}
|
/*
Q Light Controller
inputoutputmanager.cpp
Copyright (c) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <QListWidgetItem>
#include <QListWidget>
#include <QHeaderView>
#include <QStringList>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QSettings>
#include <QSplitter>
#include <QLineEdit>
#include <QCheckBox>
#include <QToolBar>
#include <QAction>
#include <QTimer>
#include <QDebug>
#include <QLabel>
#include <QIcon>
#include "inputoutputpatcheditor.h"
#include "universeitemwidget.h"
#include "inputoutputmanager.h"
#include "inputoutputmap.h"
#include "outputpatch.h"
#include "inputpatch.h"
#include "apputil.h"
#include "doc.h"
#define KColumnUniverse 0
#define KColumnInput 1
#define KColumnOutput 2
#define KColumnFeedback 3
#define KColumnProfile 4
#define KColumnInputNum 5
#define KColumnOutputNum 6
#define SETTINGS_SPLITTER "inputmanager/splitter"
InputOutputManager* InputOutputManager::s_instance = NULL;
InputOutputManager::InputOutputManager(QWidget* parent, Doc* doc)
: QWidget(parent)
, m_doc(doc)
, m_toolbar(NULL)
, m_addUniverseAction(NULL)
, m_deleteUniverseAction(NULL)
, m_uniNameEdit(NULL)
, m_uniPassthroughCheck(NULL)
, m_editor(NULL)
, m_editorUniverse(UINT_MAX)
{
Q_ASSERT(s_instance == NULL);
s_instance = this;
Q_ASSERT(doc != NULL);
m_ioMap = doc->inputOutputMap();
/* Create a new layout for this widget */
new QVBoxLayout(this);
layout()->setContentsMargins(0, 0, 0, 0);
layout()->setSpacing(0);
m_splitter = new QSplitter(Qt::Horizontal, this);
layout()->addWidget(m_splitter);
m_addUniverseAction = new QAction(QIcon(":/edit_add.png"),
tr("Add U&niverse"), this);
m_addUniverseAction->setShortcut(QKeySequence("CTRL+N"));
connect(m_addUniverseAction, SIGNAL(triggered(bool)),
this, SLOT(slotAddUniverse()));
m_deleteUniverseAction = new QAction(QIcon(":/edit_remove.png"),
tr("&Delete Universe"), this);
m_deleteUniverseAction->setShortcut(QKeySequence("CTRL+D"));
connect(m_deleteUniverseAction, SIGNAL(triggered(bool)),
this, SLOT(slotDeleteUniverse()));
QWidget* ucontainer = new QWidget(this);
m_splitter->addWidget(ucontainer);
ucontainer->setLayout(new QVBoxLayout);
ucontainer->layout()->setContentsMargins(0, 0, 0, 0);
// Add a toolbar to the dock area
m_toolbar = new QToolBar("Input Output Manager", this);
m_toolbar->setFloatable(false);
m_toolbar->setMovable(false);
m_toolbar->setIconSize(QSize(32, 32));
m_toolbar->addAction(m_addUniverseAction);
m_toolbar->addAction(m_deleteUniverseAction);
m_toolbar->addSeparator();
QLabel *uniLabel = new QLabel(tr("Universe name:"));
m_uniNameEdit = new QLineEdit(this);
QFont font = QApplication::font();
//font.setBold(true);
font.setPixelSize(18);
uniLabel->setFont(font);
m_uniNameEdit->setFont(font);
m_toolbar->addWidget(uniLabel);
m_toolbar->addWidget(m_uniNameEdit);
m_uniPassthroughCheck = new QCheckBox(tr("Passthrough"), this);
m_uniPassthroughCheck->setLayoutDirection(Qt::RightToLeft);
m_uniPassthroughCheck->setFont(font);
m_toolbar->addWidget(m_uniPassthroughCheck);
m_splitter->widget(0)->layout()->addWidget(m_toolbar);
connect(m_uniNameEdit, SIGNAL(textChanged(QString)),
this, SLOT(slotUniverseNameChanged(QString)));
connect(m_uniPassthroughCheck, SIGNAL(toggled(bool)),
this, SLOT(slotPassthroughChanged(bool)));
/* Universes list */
m_list = new QListWidget(this);
m_list->setItemDelegate(new UniverseItemWidget(m_list));
m_splitter->widget(0)->layout()->addWidget(m_list);
QWidget* gcontainer = new QWidget(this);
m_splitter->addWidget(gcontainer);
gcontainer->setLayout(new QVBoxLayout);
gcontainer->layout()->setContentsMargins(0, 0, 0, 0);
connect(m_list, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
this, SLOT(slotCurrentItemChanged()));
/* Timer that clears the input data icon after a while */
m_icon = QIcon(":/input.png");
m_timer = new QTimer(this);
m_timer->setSingleShot(true);
connect(m_timer, SIGNAL(timeout()), this, SLOT(slotTimerTimeout()));
/* Listen to input map's input data signals */
connect(m_ioMap, SIGNAL(inputValueChanged(quint32,quint32,uchar)),
this, SLOT(slotInputValueChanged(quint32,quint32,uchar)));
/* Listen to plugin configuration changes */
connect(m_ioMap, SIGNAL(pluginConfigurationChanged(const QString&, bool)),
this, SLOT(updateList()));
connect(m_ioMap, SIGNAL(universeAdded(quint32)),
this, SLOT(slotUniverseAdded(quint32)));
updateList();
m_list->setCurrentItem(m_list->item(0));
QSettings settings;
QVariant var = settings.value(SETTINGS_SPLITTER);
if (var.isValid() == true)
m_splitter->restoreState(var.toByteArray());
}
InputOutputManager::~InputOutputManager()
{
QSettings settings;
settings.setValue(SETTINGS_SPLITTER, m_splitter->saveState());
s_instance = NULL;
}
InputOutputManager* InputOutputManager::instance()
{
return s_instance;
}
/*****************************************************************************
* Tree widget
*****************************************************************************/
void InputOutputManager::updateList()
{
m_list->blockSignals(true);
m_list->clear();
for (quint32 uni = 0; uni < m_ioMap->universesCount(); uni++)
updateItem(new QListWidgetItem(m_list), uni);
m_list->blockSignals(false);
if (m_ioMap->universesCount() == 0)
{
if (m_editor != NULL)
{
m_splitter->widget(1)->layout()->removeWidget(m_editor);
m_editor->deleteLater();
m_editor = NULL;
}
m_deleteUniverseAction->setEnabled(false);
m_uniNameEdit->setText("");
m_uniNameEdit->setEnabled(false);
}
else
{
m_list->setCurrentItem(m_list->item(0));
m_uniNameEdit->setEnabled(true);
m_uniNameEdit->setText(m_ioMap->getUniverseNameByIndex(0));
m_uniPassthroughCheck->setChecked(m_ioMap->getUniversePassthrough(0));
}
}
void InputOutputManager::updateItem(QListWidgetItem* item, quint32 universe)
{
Q_ASSERT(item != NULL);
InputPatch* ip = m_ioMap->inputPatch(universe);
OutputPatch* op = m_ioMap->outputPatch(universe);
OutputPatch* fp = m_ioMap->feedbackPatch(universe);
QString uniName = m_ioMap->getUniverseNameByIndex(universe);
if (uniName.isEmpty())
{
QString defUniName = tr("Universe %1").arg(universe + 1);
m_ioMap->setUniverseName(universe, defUniName);
item->setData(Qt::DisplayRole, defUniName);
}
else
item->setData(Qt::DisplayRole, uniName);
item->setSizeHint(QSize(m_list->width(), 50));
item->setData(Qt::UserRole, universe);
if (ip != NULL)
{
item->setData(Qt::UserRole + 1, ip->inputName());
item->setData(Qt::UserRole + 2, ip->profileName());
}
else
{
item->setData(Qt::UserRole + 1, KInputNone);
item->setData(Qt::UserRole + 2, KInputNone);
}
if (op != NULL)
item->setData(Qt::UserRole + 3, op->outputName());
else
item->setData(Qt::UserRole + 3, KOutputNone);
if (fp != NULL)
item->setData(Qt::UserRole + 4, fp->outputName());
else
item->setData(Qt::UserRole + 4, KOutputNone);
}
void InputOutputManager::slotInputValueChanged(quint32 universe, quint32 channel, uchar value)
{
Q_UNUSED(channel);
Q_UNUSED(value);
// If the manager is not visible, don't even waste CPU
if (isVisible() == false)
return;
QListWidgetItem *item = m_list->item(universe);
if (item == NULL)
return;
/* Show an icon on a universe row that received input data */
item->setData(Qt::DecorationRole, m_icon);
/* Restart the timer */
m_timer->start(300);
}
void InputOutputManager::slotTimerTimeout()
{
for (int i = 0; i < m_list->count(); i++)
{
QListWidgetItem *item = m_list->item(i);
item->setData(Qt::DecorationRole, QIcon());
}
}
void InputOutputManager::slotCurrentItemChanged()
{
QListWidgetItem* item = m_list->currentItem();
if (item == NULL)
{
if (m_ioMap->universesCount() == 0)
return;
m_list->setCurrentItem(m_list->item(0));
item = m_list->currentItem();
}
if (item == NULL)
return;
quint32 universe = item->data(Qt::UserRole).toInt();
if (m_editorUniverse == universe)
return;
if ((universe + 1) != m_ioMap->universesCount())
m_deleteUniverseAction->setEnabled(false);
else
m_deleteUniverseAction->setEnabled(true);
if (m_editor != NULL)
{
m_splitter->widget(1)->layout()->removeWidget(m_editor);
m_editor->deleteLater();
m_editor = NULL;
}
m_editor = new InputOutputPatchEditor(this, universe, m_ioMap, m_doc);
m_editorUniverse = universe;
m_splitter->widget(1)->layout()->addWidget(m_editor);
connect(m_editor, SIGNAL(mappingChanged()), this, SLOT(slotMappingChanged()));
connect(m_editor, SIGNAL(audioInputDeviceChanged()), this, SLOT(slotAudioInputChanged()));
m_editor->show();
int uniIdx = m_list->currentRow();
m_uniNameEdit->setText(m_ioMap->getUniverseNameByIndex(uniIdx));
m_uniPassthroughCheck->setChecked(m_ioMap->getUniversePassthrough(uniIdx));
}
void InputOutputManager::slotMappingChanged()
{
QListWidgetItem* item = m_list->currentItem();
if (item != NULL)
{
uint universe = item->data(Qt::UserRole).toInt();
updateItem(item, universe);
m_doc->inputOutputMap()->saveDefaults();
}
}
void InputOutputManager::slotAudioInputChanged()
{
m_doc->destroyAudioCapture();
}
void InputOutputManager::slotAddUniverse()
{
m_ioMap->addUniverse();
m_doc->setModified();
}
void InputOutputManager::slotDeleteUniverse()
{
int uniIdx = m_list->currentRow();
if ((uniIdx + 1) != (int)(m_ioMap->universesCount()))
{
QMessageBox::information(this,
tr("Unable to remove universe"),
tr("You can only remove universes starting from the last one"));
return;
}
// Check if the universe is patched
if (m_ioMap->isUniversePatched(uniIdx) == true)
{
// Ask for user's confirmation
if (QMessageBox::question(
this, tr("Delete Universe"),
tr("The universe you are trying to delete is patched. Are you sure you want to delete it ?"),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
}
// Check if there are fixtures using this universe
quint32 uniID = m_ioMap->getUniverseID(uniIdx);
if (uniID == m_ioMap->invalidUniverse())
return;
foreach(Fixture *fx, m_doc->fixtures())
{
if (fx->universe() == uniID)
{
// Ask for user's confirmation
if (QMessageBox::question(
this, tr("Delete Universe"),
tr("There are some fixtures using the universe you are trying to delete. Are you sure you want to delete it ?"),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
break;
}
}
m_ioMap->removeUniverse(uniIdx);
m_doc->setModified();
updateList();
}
void InputOutputManager::slotUniverseNameChanged(QString name)
{
QListWidgetItem *currItem = m_list->currentItem();
if (currItem == NULL)
return;
int uniIdx = m_list->currentRow();
if (name.isEmpty())
name = tr("Universe %1").arg(uniIdx + 1);
m_ioMap->setUniverseName(uniIdx, name);
currItem->setData(Qt::DisplayRole, name);
}
void InputOutputManager::slotUniverseAdded(quint32 universe)
{
QListWidgetItem *item = new QListWidgetItem(m_list);
updateItem(item, universe);
}
void InputOutputManager::slotPassthroughChanged(bool checked)
{
QListWidgetItem *currItem = m_list->currentItem();
if (currItem == NULL)
return;
int uniIdx = m_list->currentRow();
m_ioMap->setUniversePassthrough(uniIdx, checked);
m_doc->inputOutputMap()->saveDefaults();
}
void InputOutputManager::showEvent(QShowEvent *ev)
{
Q_UNUSED(ev);
// force the recreation of the selected universe editor
m_editorUniverse = UINT_MAX;
updateList();
}
|
disable removeUniverse button
|
InputOutputManager: disable removeUniverse button
when the last universe is not selected.
|
C++
|
apache-2.0
|
nedmech/qlcplus,kripton/qlcplus,plugz/qlcplus,plugz/qlcplus,nedmech/qlcplus,kripton/qlcplus,nedmech/qlcplus,mcallegari/qlcplus,mcallegari/qlcplus,sbenejam/qlcplus,plugz/qlcplus,sbenejam/qlcplus,sbenejam/qlcplus,kripton/qlcplus,kripton/qlcplus,kripton/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,plugz/qlcplus,nedmech/qlcplus,nedmech/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,mcallegari/qlcplus,plugz/qlcplus,sbenejam/qlcplus,kripton/qlcplus,plugz/qlcplus,mcallegari/qlcplus,sbenejam/qlcplus,kripton/qlcplus,plugz/qlcplus,nedmech/qlcplus,mcallegari/qlcplus
|
57798768a705446f09ec306b84f7b4161f421b08
|
src/translate.C
|
src/translate.C
|
#include "run_submission.h"
#include <stdio.h>
#include <string.h>
const char * safe_get(Table& t, const char* key, const char* defaultValue)
{
Table::const_iterator got = t.find(key);
if (got == t.end())
return defaultValue;
return got->second.c_str();
}
void translate(Table& envT, Table& userT, DTable& userDT)
{
enum QueueType { UNKNOWN = -1, SLURM = 1, SGE, PBS, LSF };
QueueType queueType = UNKNOWN;
// Pick type of queuing system.
if (envT.count("SGE_ACCOUNT"))
queueType = SGE;
else if (envT.count("SLURM_JOB_ID"))
queueType = SLURM;
else if (envT.count("PBS_JOBID"))
queueType = PBS;
else if (envT.count("LSF_VERSION"))
queueType = LSF;
// userDT["num_tasks"] has a safe default value of 1 if not overridden by the run.
userDT["num_cores"] = userDT["num_tasks"];
// Now fill in num_cores, num_nodes, account, job_id, queue, submit_host in userT from the environment
if (queueType == SGE)
{
userT["account"] = safe_get(envT, "SGE_ACCOUNT", "unknown");
userT["job_id"] = safe_get(envT, "JOB_ID", "unknown");
userT["queue"] = safe_get(envT, "QUEUE", "unknown");
userT["submit_host"] = "unknown";
userDT["num_nodes"] = strtod(safe_get(envT, "NHOSTS", "1"), (char **) NULL);
}
else if (queueType == SLURM )
{
userT["job_id"] = safe_get(envT, "SLURM_JOB_ID", "unknown");
userT["queue"] = safe_get(envT, "SLURM_QUEUE", "unknown");
userT["submit_host"] = safe_get(envT, "SLURM_SUBMIT_HOST", "unknown");
userT["account"] = safe_get(envT, "SLURM_TACC_ACCOUNT", "unknown");
userDT["num_nodes"] = strtod(safe_get(envT, "SLURM_NNODES", "1"), (char **) NULL);
}
else if (queueType == PBS)
{
std::string job_id = safe_get(envT, "PBS_JOBID", "unknown");
std::size_t idx = job_id.find_first_not_of("0123456789[]");
userT["job_id"] = job_id.substr(0,idx);
userT["queue"] = safe_get(envT, "PBS_QUEUE", "unknown");
userT["submit_host"] = safe_get(envT, "PBS_O_HOST", "unknown");
userT["account"] = safe_get(envT, "PBS_ACCOUNT", "unknown");
userDT["num_nodes"] = strtod(safe_get(envT, "PBS_NUM_NODES", "1"), (char **) NULL);;
}
else if (queueType == LSF)
{
// We must count the number of "words" in mcpuA.
// We find the number of words by counting space blocks and add 1;
// then divide by 2. then convert to a string.
std::string mcpuA = safe_get(envT, "LSB_MCPU_HOSTS", "a 1");
std::string::size_type idx;
int count = 1;
idx = 0;
while (1)
{
idx = mcpuA.find(" ",idx);
if (idx == std::string::npos)
break;
count++;
idx = mcpuA.find_first_not_of(" ",idx+1);
}
count /= 2;
userT["job_id"] = safe_get(envT, "LSB_JOBID", "unknown");
userT["queue"] = safe_get(envT, "LSB_QUEUE", "unknown");
userT["submit_host"] = safe_get(envT, "LSB_EXEC_CLUSTER", "unknown");
userT["account"] = "unknown";
userDT["num_nodes"] = (double) count;
}
else
{
userT["job_id"] = "unknown";
userT["queue"] = "unknown";
userT["submit_host"] = "unknown";
userT["account"] = "unknown";
userDT["num_nodes"] = 1.0;
}
}
|
#include "run_submission.h"
#include <stdio.h>
#include <string.h>
const char * safe_get(Table& t, const char* key, const char* defaultValue)
{
Table::const_iterator got = t.find(key);
if (got == t.end())
return defaultValue;
return got->second.c_str();
}
void translate(Table& envT, Table& userT, DTable& userDT)
{
enum QueueType { UNKNOWN = -1, SLURM = 1, SGE, PBS, LSF };
QueueType queueType = UNKNOWN;
// Pick type of queuing system.
if (envT.count("SGE_ACCOUNT"))
queueType = SGE;
else if (envT.count("SLURM_JOB_ID"))
queueType = SLURM;
else if (envT.count("PBS_JOBID"))
queueType = PBS;
else if (envT.count("LSF_VERSION"))
queueType = LSF;
// userDT["num_tasks"] has a safe default value of 1 if not overridden by the run.
userDT["num_cores"] = userDT["num_tasks"];
// Now fill in num_cores, num_nodes, account, job_id, queue, submit_host in userT from the environment
if (queueType == SGE)
{
userT["account"] = safe_get(envT, "SGE_ACCOUNT", "unknown");
userT["job_id"] = safe_get(envT, "JOB_ID", "unknown");
userT["queue"] = safe_get(envT, "QUEUE", "unknown");
userT["submit_host"] = "unknown";
userDT["num_nodes"] = strtod(safe_get(envT, "NHOSTS", "1"), (char **) NULL);
}
else if (queueType == SLURM )
{
userT["job_id"] = safe_get(envT, "SLURM_JOB_ID", "unknown");
userT["queue"] = safe_get(envT, "SLURM_JOB_PARTITION", "unknown");
userT["submit_host"] = safe_get(envT, "SLURM_SUBMIT_HOST", "unknown");
userT["account"] = safe_get(envT, "SLURM_JOB_ACCOUNT", "unknown");
userDT["num_nodes"] = strtod(safe_get(envT, "SLURM_NNODES", "1"), (char **) NULL);
}
else if (queueType == PBS)
{
std::string job_id = safe_get(envT, "PBS_JOBID", "unknown");
std::size_t idx = job_id.find_first_not_of("0123456789[]");
userT["job_id"] = job_id.substr(0,idx);
userT["queue"] = safe_get(envT, "PBS_QUEUE", "unknown");
userT["submit_host"] = safe_get(envT, "PBS_O_HOST", "unknown");
userT["account"] = safe_get(envT, "PBS_ACCOUNT", "unknown");
userDT["num_nodes"] = strtod(safe_get(envT, "PBS_NUM_NODES", "1"), (char **) NULL);;
}
else if (queueType == LSF)
{
// We must count the number of "words" in mcpuA.
// We find the number of words by counting space blocks and add 1;
// then divide by 2. then convert to a string.
std::string mcpuA = safe_get(envT, "LSB_MCPU_HOSTS", "a 1");
std::string::size_type idx;
int count = 1;
idx = 0;
while (1)
{
idx = mcpuA.find(" ",idx);
if (idx == std::string::npos)
break;
count++;
idx = mcpuA.find_first_not_of(" ",idx+1);
}
count /= 2;
userT["job_id"] = safe_get(envT, "LSB_JOBID", "unknown");
userT["queue"] = safe_get(envT, "LSB_QUEUE", "unknown");
userT["submit_host"] = safe_get(envT, "LSB_EXEC_CLUSTER", "unknown");
userT["account"] = "unknown";
userDT["num_nodes"] = (double) count;
}
else
{
userT["job_id"] = "unknown";
userT["queue"] = "unknown";
userT["submit_host"] = "unknown";
userT["account"] = "unknown";
userDT["num_nodes"] = 1.0;
}
}
|
use more SLURM generic names for queue and account names in translate.C
|
use more SLURM generic names for queue and account names in translate.C
|
C++
|
lgpl-2.1
|
xalt/xalt,xalt/xalt,xalt/xalt,xalt/xalt,xalt/xalt,xalt/xalt,xalt/xalt
|
3afad2f9e1e7e2f007ef220a3da0151b66a75abe
|
data-student.cpp
|
data-student.cpp
|
#include "data-student.hpp"
using namespace std;
Semester::Semester() {
period = 0;
}
Semester::Semester(int p) {
period = p;
}
void Student::init(string n, int s, int g, string m) {
name = n;
startingYear = s;
gradutationYear = g;
parseMajors(m);
}
Student::Student() {
init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
int startYear = stringToInt(s), endYear = stringToInt(e);
init(n, startYear, endYear, m);
}
Student::Student(string fn) {
ifstream infile;
infile.open(fn.c_str());
}
void Student::parseMajors(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
string s = removeStartingText(*i, " ");
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
Major m = Major(s);
majors.push_back(m);
}
}
bool Student::hasTakenCourse(string str) {
bool userHasTaken = false;
Course checkAgainst = getCourse(str);
for (std::vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
if (*i == checkAgainst)
userHasTaken = true;
return userHasTaken;
}
void Student::addCourse(const Course& c) {
// cout << "Hi! I'm addCourse (not courses!!)!" << endl;
courses.push_back(c);
// cout << courses.at(courses.size()-1) << endl;
}
void Student::addCourses(string str) {
// cout << "Hi! I'm addCourses!" << endl;
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
// cout << *i << endl;
addCourse(Course(*i));
}
}
ostream& Student::getData(ostream &os) {
os << name << ", ";
os << "you are majoring in ";
for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
if (i!=majors.end()-1)
os << *i << ", ";
else
os << "and "<< *i;
}
os << ", while taking:" << endl;
for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
os << *i << endl;
return os;
}
void Student::display() {
cout << *this << endl;
};
ostream& operator<<(ostream& os, Student& item) {
os << item.getData(os);
return os;
}
|
#include "data-student.hpp"
using namespace std;
Semester::Semester() {
period = 0;
}
Semester::Semester(int p) {
period = p;
}
void Student::init(string n, int s, int g, string m) {
name = n;
startingYear = s;
gradutationYear = g;
parseMajors(m);
}
Student::Student() {
init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
int startYear = stringToInt(s), endYear = stringToInt(e);
init(n, startYear, endYear, m);
}
Student::Student(string fn) {
ifstream infile;
infile.open(fn.c_str());
}
void Student::parseMajors(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
string s = removeStartingText(*i, " ");
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
Major m = Major(s);
majors.push_back(m);
}
}
bool Student::hasTakenCourse(string str) {
bool userHasTaken = false;
Course checkAgainst = getCourse(str);
for (std::vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
if (*i == checkAgainst)
userHasTaken = true;
return userHasTaken;
}
void Student::addCourse(const Course& c) {
// cout << "Hi! I'm addCourse (not courses!!)!" << endl;
courses.push_back(c);
// cout << courses.at(courses.size()-1) << endl;
}
void Student::addCourses(string str) {
// cout << "Hi! I'm addCourses!" << endl;
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
// cout << *i << endl;
addCourse(Course(*i));
}
}
ostream& Student::getData(ostream &os) {
os << name << ", ";
os << "you are majoring in ";
for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
if (majors.size() == 2) {
if (i != majors.end()-1)
os << *i << " and ";
else
os << *i << " ";
}
else {
if (i != majors.end()-1)
os << *i << ", ";
else
os << "and " << *i << ", ";
}
}
os << "while taking:" << endl;
for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
os << *i << endl;
return os;
}
void Student::display() {
cout << *this << endl;
};
ostream& operator<<(ostream& os, Student& item) {
os << item.getData(os);
return os;
}
|
Update the formatting of the returned data from Student::getData
|
Update the formatting of the returned data from Student::getData
|
C++
|
agpl-3.0
|
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
|
54c6c33f04103de0d40b2dd085af61a6e765d2ff
|
test/bin_test_process_output.cc
|
test/bin_test_process_output.cc
|
/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib 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.
**
** Centreon Clib 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 Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <cstring>
#include <exception>
#include <iostream>
#include <unistd.h>
/**
* Find line into the environement.
*
* @param[in] data line on form key=value.
* @param[in] env The environment.
*
* @return True if data is find into env, otherwise false.
*/
static bool find(char const* data, char** env) {
for (unsigned int i(0); env[i]; ++i)
if (!strcmp(data, env[i]))
return (true);
return (false);
}
/**
* Check if the content of ref is in env array.
*
* @param[in] ref The content reference.
* @param[in] env The content to check.
*
* @return EXIT_SUCCESS on success, otherwise EXIT_FAILURE.
*/
static int check_env(char** ref, char** env) {
for (unsigned int i(0); ref[i]; ++i)
if (!find(ref[i], env))
return (EXIT_FAILURE);
return (EXIT_SUCCESS);
}
/**
* Read stdin and write into the stdout.
*
* @param[in] type If type if "err" write data on stderr,
* otherwise write on stdout.
*
* @return The total bytes written.
*/
static int check_output(char const* type) {
int output(strcmp(type, "err") ? 1 : 2);
int total(0);
int size(0);
char buffer[1024];
while ((size = read(0, buffer, sizeof(buffer))) > 0)
total += write(output, buffer, size);
return (EXIT_SUCCESS);
}
/**
* Usage of the application.
*
* @param[in] appname The application name.
*/
static void usage(char const* appname) {
std::cerr
<< "usage: " << appname << std::endl
<< " check_env key1=value1 keyx=valuex..." << std::endl
<< " check_output err|out" << std::endl
<< " check_return value" << std::endl
<< " check_sleep value" << std::endl;
exit(EXIT_FAILURE);
}
/**
* This main test the class process.
*/
int main(int argc, char** argv, char** env) {
try {
if (argc != 1) {
if (!strcmp(argv[1], "check_env"))
return (check_env(argv + 2, env));
if (argc == 3) {
if (!strcmp(argv[1], "check_output"))
return (check_output(argv[2]));
if (!strcmp(argv[1], "check_return"))
return (atoi(argv[2]));
if (!strcmp(argv[1], "check_sleep")) {
int timeout(atoi(argv[2]));
sleep(timeout);
return (timeout);
}
}
}
usage(argv[0]);
}
catch (std::exception const& e) {
std::cerr << "error:" << e.what() << std::endl;
return (EXIT_FAILURE);
}
}
|
/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib 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.
**
** Centreon Clib 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 Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <cstring>
#include <exception>
#include <iostream>
#ifdef _WIN32
# include <windows.h>
#else
# include <unistd.h>
#endif // Win32 or POSIX
/**
* Find line into the environement.
*
* @param[in] data line on form key=value.
* @param[in] env The environment.
*
* @return True if data is find into env, otherwise false.
*/
static bool find(char const* data, char** env) {
for (unsigned int i(0); env[i]; ++i)
if (!strcmp(data, env[i]))
return (true);
return (false);
}
/**
* Check if the content of ref is in env array.
*
* @param[in] ref The content reference.
* @param[in] env The content to check.
*
* @return EXIT_SUCCESS on success, otherwise EXIT_FAILURE.
*/
static int check_env(char** ref, char** env) {
for (unsigned int i(0); ref[i]; ++i)
if (!find(ref[i], env))
return (EXIT_FAILURE);
return (EXIT_SUCCESS);
}
/**
* Read stdin and write into the stdout.
*
* @param[in] type If type if "err" write data on stderr,
* otherwise write on stdout.
*
* @return The total bytes written.
*/
static int check_output(char const* type) {
int output(strcmp(type, "err") ? 1 : 2);
int total(0);
int size(0);
char buffer[1024];
while ((size = read(0, buffer, sizeof(buffer))) > 0)
total += write(output, buffer, size);
return (EXIT_SUCCESS);
}
/**
* Usage of the application.
*
* @param[in] appname The application name.
*/
static void usage(char const* appname) {
std::cerr
<< "usage: " << appname << std::endl
<< " check_env key1=value1 keyx=valuex..." << std::endl
<< " check_output err|out" << std::endl
<< " check_return value" << std::endl
<< " check_sleep value" << std::endl;
exit(EXIT_FAILURE);
}
/**
* This main test the class process.
*/
int main(int argc, char** argv, char** env) {
try {
if (argc != 1) {
if (!strcmp(argv[1], "check_env"))
return (check_env(argv + 2, env));
if (argc == 3) {
if (!strcmp(argv[1], "check_output"))
return (check_output(argv[2]));
if (!strcmp(argv[1], "check_return"))
return (atoi(argv[2]));
if (!strcmp(argv[1], "check_sleep")) {
int timeout(atoi(argv[2]));
#ifdef _WIN32
Sleep(timeout * 1000);
#else
sleep(timeout);
#endif // Win32 or POSIX
return (timeout);
}
}
}
usage(argv[0]);
}
catch (std::exception const& e) {
std::cerr << "error:" << e.what() << std::endl;
return (EXIT_FAILURE);
}
}
|
Fix compatibility of a unit test with Win32.
|
Fix compatibility of a unit test with Win32.
|
C++
|
apache-2.0
|
centreon/centreon-clib,centreon/centreon-clib,centreon/centreon-clib
|
2ad4d8ef22e19643dd758e43671161c7aebe6ee5
|
modules/vectorfieldvisualization/processors/datageneration/rbfvectorfieldgenerator2d.cpp
|
modules/vectorfieldvisualization/processors/datageneration/rbfvectorfieldgenerator2d.cpp
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "rbfvectorfieldgenerator2d.h"
#include <inviwo/core/datastructures/volume/volumeram.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
#include <warn/push>
#include <warn/ignore/all>
#include <Eigen/Dense>
#include <warn/pop>
namespace inviwo {
const ProcessorInfo RBFVectorFieldGenerator2D::processorInfo_{
"org.inviwo.RBFVectorFieldGenerator2D", // Class identifier
"RBF Based 2D Vector Field Generator", // Display name
"Data Creation", // Category
CodeState::Experimental, // Code state
Tags::CPU, // Tags
};
const ProcessorInfo RBFVectorFieldGenerator2D::getProcessorInfo() const {
return processorInfo_;
}
RBFVectorFieldGenerator2D::RBFVectorFieldGenerator2D()
: Processor()
, vectorField_("vectorField", DataVec4Float32::get(), false)
, size_("size", "Volume size", ivec2(700, 700), ivec2(1, 1), ivec2(1024, 1024))
, seeds_("seeds", "Number of seeds", 9, 1, 100)
, shape_("shape", "Shape Parameter", 1.2f, 0.0001f, 10.0f, 0.0001f)
, gaussian_("gaussian", "Gaussian")
, randomness_("randomness", "Randomness")
, useSameSeed_("useSameSeed", "Use same seed", true)
, seed_("seed", "Seed", 1, 0, std::numeric_limits<int>::max())
, rd_()
, mt_(rd_())
, theta_(0, 2 * M_PI)
, x_(-1.0, 1.0) {
addPort(vectorField_);
addProperty(size_);
addProperty(seeds_);
addProperty(shape_);
addProperty(gaussian_);
addProperty(randomness_);
randomness_.addProperty(useSameSeed_);
randomness_.addProperty(seed_);
useSameSeed_.onChange([&]() { seed_.setVisible(useSameSeed_.get()); samples_.clear(); });
seed_.onChange([&]() { samples_.clear(); });
}
RBFVectorFieldGenerator2D::~RBFVectorFieldGenerator2D() {}
void RBFVectorFieldGenerator2D::process() {
if (samples_.size() != seeds_.get()) {
createSamples();
}
Eigen::MatrixXd A(seeds_.get(), seeds_.get());
Eigen::VectorXd bx(seeds_.get()), by(seeds_.get());
Eigen::VectorXd xx(seeds_.get()), xy(seeds_.get());
int row = 0;
for (auto &a : samples_) {
int col = 0;
for (auto &b : samples_) {
auto r = glm::distance(a.first, b.first);
A(row, col++) = shape_.get() + gaussian_.evaluate(r);
}
bx(row) = a.second.x;
by(row++) = a.second.y;
}
auto solverX = A.llt();
auto solverY = A.llt();
xx = solverX.solve(bx);
xy = solverY.solve(by);
auto img = std::make_shared<Image>(size_.get(), DataVec4Float32::get());
vec4 *data =
static_cast<vec4 *>(img->getColorLayer()->getEditableRepresentation<LayerRAM>()->getData());
int i = 0;
for (int y = 0; y < size_.get().y; y++) {
for (int x = 0; x < size_.get().x; x++) {
dvec2 p(x, y);
p /= size_.get();
p *= 2;
p -= 1;
vec3 v(0, 0, 0);
int s = 0;
for (; s < seeds_.get(); s++) {
double r = glm::distance(p, samples_[s].first);
auto w = gaussian_.evaluate(r);
v.x += static_cast<float>(xx(s) * w);
v.y += static_cast<float>(xy(s) * w);
}
data[i++] = vec4(v, 1.0f);
}
}
vectorField_.setData(img);
}
dvec2 RBFVectorFieldGenerator2D::randomVector() {
dvec2 v(1, 0);
auto d = theta_(mt_);
auto c = std::cos(d);
auto s = std::sin(d);
return (mat2(c, s, -s, c) * v) * static_cast<float>((x_(mt_) * 2 - 1));
}
void RBFVectorFieldGenerator2D::createSamples()
{
LogInfo("Crating samples");
samples_.clear();
if (useSameSeed_.get()) {
mt_.seed(seed_.get());
}
samples_.resize(seeds_.get());
std::generate(samples_.begin(), samples_.end(),
[&]() { return std::make_pair(dvec2(x_(mt_), x_(mt_)), randomVector()); });
}
void RBFVectorFieldGenerator2D::serialize(Serializer& s) const {
std::vector<dvec2> sx;
std::vector<dvec2> sy;
for (auto s : samples_) {
sx.push_back(s.first);
sy.push_back(s.second);
}
s.serialize("samplesx", sx, "samplex");
s.serialize("samplesy", sy, "sampley");
Processor::serialize(s);
}
void RBFVectorFieldGenerator2D::deserialize(Deserializer& d) {
LogInfo("deserialize");
std::vector<dvec2> sx;
std::vector<dvec2> sy;
d.deserialize("samplesx", sx, "samplex");
d.deserialize("samplesy", sy, "sampley");
Processor::deserialize(d);
for (size_t i = 0; i < sx.size(); i++) {
samples_.emplace_back(sx[i], sy[i]);
}
LogInfo("deserialize done");
}
} // namespace
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "rbfvectorfieldgenerator2d.h"
#include <inviwo/core/datastructures/volume/volumeram.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
#include <warn/push>
#include <warn/ignore/all>
#include <Eigen/Dense>
#include <warn/pop>
namespace inviwo {
const ProcessorInfo RBFVectorFieldGenerator2D::processorInfo_{
"org.inviwo.RBFVectorFieldGenerator2D", // Class identifier
"RBF Based 2D Vector Field Generator", // Display name
"Data Creation", // Category
CodeState::Experimental, // Code state
Tags::CPU, // Tags
};
const ProcessorInfo RBFVectorFieldGenerator2D::getProcessorInfo() const {
return processorInfo_;
}
RBFVectorFieldGenerator2D::RBFVectorFieldGenerator2D()
: Processor()
, vectorField_("vectorField", DataVec4Float32::get(), false)
, size_("size", "Volume size", ivec2(700, 700), ivec2(1, 1), ivec2(1024, 1024))
, seeds_("seeds", "Number of seeds", 9, 1, 100)
, shape_("shape", "Shape Parameter", 1.2f, 0.0001f, 10.0f, 0.0001f)
, gaussian_("gaussian", "Gaussian")
, randomness_("randomness", "Randomness")
, useSameSeed_("useSameSeed", "Use same seed", true)
, seed_("seed", "Seed", 1, 0, std::numeric_limits<int>::max())
, rd_()
, mt_(rd_())
, theta_(0, 2 * M_PI)
, x_(-1.0, 1.0) {
addPort(vectorField_);
addProperty(size_);
addProperty(seeds_);
addProperty(shape_);
addProperty(gaussian_);
addProperty(randomness_);
randomness_.addProperty(useSameSeed_);
randomness_.addProperty(seed_);
useSameSeed_.onChange([&]() { seed_.setVisible(useSameSeed_.get()); samples_.clear(); });
seed_.onChange([&]() { samples_.clear(); });
}
RBFVectorFieldGenerator2D::~RBFVectorFieldGenerator2D() {}
void RBFVectorFieldGenerator2D::process() {
if (samples_.size() != seeds_.get()) {
createSamples();
}
Eigen::MatrixXd A(seeds_.get(), seeds_.get());
Eigen::VectorXd bx(seeds_.get()), by(seeds_.get());
Eigen::VectorXd xx(seeds_.get()), xy(seeds_.get());
int row = 0;
for (auto &a : samples_) {
int col = 0;
for (auto &b : samples_) {
auto r = glm::distance(a.first, b.first);
A(row, col++) = shape_.get() + gaussian_.evaluate(r);
}
bx(row) = a.second.x;
by(row++) = a.second.y;
}
auto solverX = A.llt();
auto solverY = A.llt();
xx = solverX.solve(bx);
xy = solverY.solve(by);
auto img = std::make_shared<Image>(size_.get(), DataVec4Float32::get());
vec4 *data =
static_cast<vec4 *>(img->getColorLayer()->getEditableRepresentation<LayerRAM>()->getData());
int i = 0;
for (int y = 0; y < size_.get().y; y++) {
for (int x = 0; x < size_.get().x; x++) {
dvec2 p(x, y);
p /= size_.get();
p *= 2;
p -= 1;
vec3 v(0, 0, 0);
int s = 0;
for (; s < seeds_.get(); s++) {
double r = glm::distance(p, samples_[s].first);
auto w = gaussian_.evaluate(r);
v.x += static_cast<float>(xx(s) * w);
v.y += static_cast<float>(xy(s) * w);
}
data[i++] = vec4(v, 1.0f);
}
}
vectorField_.setData(img);
}
dvec2 RBFVectorFieldGenerator2D::randomVector() {
dvec2 v(1, 0);
auto d = theta_(mt_);
auto c = std::cos(d);
auto s = std::sin(d);
return (mat2(c, s, -s, c) * v) * static_cast<float>((x_(mt_) * 2 - 1));
}
void RBFVectorFieldGenerator2D::createSamples()
{
samples_.clear();
if (useSameSeed_.get()) {
mt_.seed(seed_.get());
}
samples_.resize(seeds_.get());
std::generate(samples_.begin(), samples_.end(),
[&]() { return std::make_pair(dvec2(x_(mt_), x_(mt_)), randomVector()); });
}
void RBFVectorFieldGenerator2D::serialize(Serializer& s) const {
std::vector<dvec2> sx;
std::vector<dvec2> sy;
for (auto s : samples_) {
sx.push_back(s.first);
sy.push_back(s.second);
}
s.serialize("samplesx", sx, "samplex");
s.serialize("samplesy", sy, "sampley");
Processor::serialize(s);
}
void RBFVectorFieldGenerator2D::deserialize(Deserializer& d) {
std::vector<dvec2> sx;
std::vector<dvec2> sy;
d.deserialize("samplesx", sx, "samplex");
d.deserialize("samplesy", sy, "sampley");
Processor::deserialize(d);
for (size_t i = 0; i < sx.size(); i++) {
samples_.emplace_back(sx[i], sy[i]);
}
}
} // namespace
|
Revert "VectorFieldVisualization: RBF2D VF Generator: Some log info for debuging (jenkins)"
|
Revert "VectorFieldVisualization: RBF2D VF Generator: Some log info for debuging (jenkins)"
This reverts commit fb32a125876af8226a91ec364fdb38b4317c0ba4.
|
C++
|
bsd-2-clause
|
inviwo/inviwo,inviwo/inviwo,Sparkier/inviwo,Sparkier/inviwo,inviwo/inviwo,Sparkier/inviwo,inviwo/inviwo,inviwo/inviwo,Sparkier/inviwo,inviwo/inviwo,Sparkier/inviwo
|
e3f0fb881f05e322e98f9732442a96e366c9a4b7
|
external/vulkancts/framework/vulkan/vkRenderDocUtil.cpp
|
external/vulkancts/framework/vulkan/vkRenderDocUtil.cpp
|
/*-------------------------------------------------------------------------
* Vulkan CTS Framework
* --------------------
*
* Copyright (c) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief RenderDoc utility
*//*--------------------------------------------------------------------*/
#include "vkRenderDocUtil.hpp"
#include "deDynamicLibrary.hpp"
#include "deUniquePtr.hpp"
#include "tcuDefs.hpp"
#include "renderdoc_app.h"
#include <stdexcept>
#if (DE_OS == DE_OS_WIN32)
# define RENDERDOC_LIBRARY_NAME "renderdoc.dll"
#else
# define RENDERDOC_LIBRARY_NAME "librenderdoc.so"
#endif
namespace vk
{
struct RenderDocPrivate
{
RenderDocPrivate (void) : m_api(DE_NULL), m_valid(false) {}
de::MovePtr<de::DynamicLibrary> m_library;
::RENDERDOC_API_1_1_2* m_api;
bool m_valid;
};
RenderDocUtil::RenderDocUtil (void)
: m_priv (new RenderDocPrivate)
{
try
{
m_priv->m_library = de::MovePtr<de::DynamicLibrary>(new de::DynamicLibrary(RENDERDOC_LIBRARY_NAME));
}
catch (const std::runtime_error& e)
{
tcu::print("Library %s not loaded: %s, RenderDoc API not available", e.what(), RENDERDOC_LIBRARY_NAME);
}
if (m_priv->m_library)
{
::pRENDERDOC_GetAPI pGetApi = (::pRENDERDOC_GetAPI)m_priv->m_library->getFunction("RENDERDOC_GetAPI");
const int ret = pGetApi(eRENDERDOC_API_Version_1_1_2, (void **)&m_priv->m_api);
if (ret == 1)
{
m_priv->m_api->TriggerCapture();
m_priv->m_valid = true;
}
else
{
tcu::print("RENDERDOC_GetAPI returned %d status, RenderDoc API not available", ret);
}
}
}
RenderDocUtil::~RenderDocUtil (void)
{
if (m_priv)
{
delete m_priv;
}
}
bool RenderDocUtil::isValid (void)
{
return m_priv != DE_NULL && m_priv->m_valid;
}
void RenderDocUtil::startFrame (vk::VkInstance instance)
{
if (!isValid()) return;
m_priv->m_api->StartFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(instance), DE_NULL);
}
void RenderDocUtil::endFrame (vk::VkInstance instance)
{
if (!isValid()) return;
m_priv->m_api->EndFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(instance), DE_NULL);
}
} // vk
|
/*-------------------------------------------------------------------------
* Vulkan CTS Framework
* --------------------
*
* Copyright (c) 2018 The Khronos Group Inc.
* Copyright (c) 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief RenderDoc utility
*//*--------------------------------------------------------------------*/
#include "vkRenderDocUtil.hpp"
#include "deDynamicLibrary.hpp"
#include "deUniquePtr.hpp"
#include "tcuDefs.hpp"
#include "renderdoc_app.h"
#include <stdexcept>
#if (DE_OS == DE_OS_WIN32)
# define RENDERDOC_LIBRARY_NAME "renderdoc.dll"
#else
# define RENDERDOC_LIBRARY_NAME "librenderdoc.so"
#endif
namespace vk
{
struct RenderDocPrivate
{
RenderDocPrivate (void) : m_api(DE_NULL), m_valid(false) {}
de::MovePtr<de::DynamicLibrary> m_library;
::RENDERDOC_API_1_1_2* m_api;
bool m_valid;
};
RenderDocUtil::RenderDocUtil (void)
: m_priv (new RenderDocPrivate)
{
try
{
m_priv->m_library = de::MovePtr<de::DynamicLibrary>(new de::DynamicLibrary(RENDERDOC_LIBRARY_NAME));
}
catch (const std::runtime_error& e)
{
tcu::print("Library %s not loaded: %s, RenderDoc API not available", e.what(), RENDERDOC_LIBRARY_NAME);
}
if (m_priv->m_library)
{
::pRENDERDOC_GetAPI pGetApi = (::pRENDERDOC_GetAPI)m_priv->m_library->getFunction("RENDERDOC_GetAPI");
const int ret = pGetApi(eRENDERDOC_API_Version_1_1_2, (void **)&m_priv->m_api);
if (ret == 1)
{
m_priv->m_api->TriggerCapture();
m_priv->m_valid = true;
}
else
{
tcu::print("RENDERDOC_GetAPI returned %d status, RenderDoc API not available", ret);
}
}
}
RenderDocUtil::~RenderDocUtil (void)
{
if (m_priv)
{
delete m_priv;
}
}
bool RenderDocUtil::isValid (void)
{
return m_priv != DE_NULL && m_priv->m_valid;
}
void RenderDocUtil::startFrame (vk::VkInstance instance)
{
if (!isValid()) return;
m_priv->m_api->StartFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(instance), DE_NULL);
}
void RenderDocUtil::endFrame (vk::VkInstance instance)
{
if (!isValid()) return;
m_priv->m_api->EndFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(instance), DE_NULL);
}
} // vk
|
Correct copyright header
|
Correct copyright header
Components: Vulkan, Framework
Change-Id: I58107231871c5997d2feaf38e6633ed426288c00
Affects: None
|
C++
|
apache-2.0
|
KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,googlestadia/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,googlestadia/VK-GL-CTS,googlestadia/VK-GL-CTS,googlestadia/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,googlestadia/VK-GL-CTS,googlestadia/VK-GL-CTS
|
956244b3373766b31ff1ac7e5c95d9182d0683d0
|
utils/TableGen/ClangDiagnosticsEmitter.cpp
|
utils/TableGen/ClangDiagnosticsEmitter.cpp
|
//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang diagnostics tables.
//
//===----------------------------------------------------------------------===//
#include "ClangDiagnosticsEmitter.h"
#include "Record.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Streams.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/VectorExtras.h"
#include <set>
#include <map>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Warning Tables (.inc file) generation.
//===----------------------------------------------------------------------===//
void ClangDiagsDefsEmitter::run(std::ostream &OS) {
// Write the #if guard
if (!Component.empty()) {
std::string ComponentName = UppercaseString(Component);
OS << "#ifdef " << ComponentName << "START\n";
OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
<< ",\n";
OS << "#undef " << ComponentName << "START\n";
OS << "#endif\n";
}
const std::vector<Record*> &Diags =
Records.getAllDerivedDefinitions("Diagnostic");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
const Record &R = *Diags[i];
// Filter by component.
if (!Component.empty() && Component != R.getValueAsString("Component"))
continue;
OS << "DIAG(" << R.getName() << ", ";
OS << R.getValueAsDef("Class")->getName();
OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName();
// Description string.
OS << ", \"";
std::string S = R.getValueAsString("Text");
EscapeString(S);
OS << S << "\"";
// Warning associated with the diagnostic.
if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group"))) {
S = DI->getDef()->getValueAsString("GroupName");
EscapeString(S);
OS << ", \"" << S << "\"";
} else {
OS << ", 0";
}
OS << ")\n";
}
}
//===----------------------------------------------------------------------===//
// Warning Group Tables generation
//===----------------------------------------------------------------------===//
struct GroupInfo {
std::vector<const Record*> DiagsInGroup;
std::vector<std::string> SubGroups;
unsigned IDNo;
};
void ClangDiagGroupsEmitter::run(std::ostream &OS) {
// Invert the 1-[0/1] mapping of diags to group into a one to many mapping of
// groups to diags in the group.
std::map<std::string, GroupInfo> DiagsInGroup;
std::vector<Record*> Diags =
Records.getAllDerivedDefinitions("Diagnostic");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
const Record *R = Diags[i];
DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group"));
if (DI == 0) continue;
std::string GroupName = DI->getDef()->getValueAsString("GroupName");
DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
}
// Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
// groups (these are warnings that GCC supports that clang never produces).
Diags = Records.getAllDerivedDefinitions("DiagGroup");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
Record *Group = Diags[i];
GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
}
// Assign unique ID numbers to the groups.
unsigned IDNo = 0;
for (std::map<std::string, GroupInfo>::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)
I->second.IDNo = IDNo;
// Walk through the groups emitting an array for each diagnostic of the diags
// that are mapped to.
OS << "\n#ifdef GET_DIAG_ARRAYS\n";
unsigned MaxLen = 0;
for (std::map<std::string, GroupInfo>::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
MaxLen = std::max(MaxLen, (unsigned)I->first.size());
std::vector<const Record*> &V = I->second.DiagsInGroup;
if (!V.empty()) {
OS << "static const short DiagArray" << I->second.IDNo << "[] = { ";
for (unsigned i = 0, e = V.size(); i != e; ++i)
OS << "diag::" << V[i]->getName() << ", ";
OS << "-1 };\n";
}
const std::vector<std::string> &SubGroups = I->second.SubGroups;
if (!SubGroups.empty()) {
OS << "static const char DiagSubGroup" << I->second.IDNo << "[] = { ";
for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) {
std::map<std::string, GroupInfo>::iterator RI =
DiagsInGroup.find(SubGroups[i]);
assert(RI != DiagsInGroup.end() && "Referenced without existing?");
OS << RI->second.IDNo << ", ";
}
OS << "-1 };\n";
}
}
OS << "#endif // GET_DIAG_ARRAYS\n\n";
// Emit the table now.
OS << "\n#ifdef GET_DIAG_TABLE\n";
for (std::map<std::string, GroupInfo>::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
std::string S = I->first;
EscapeString(S);
// Group option string.
OS << " { \"" << S << "\","
<< std::string(MaxLen-I->first.size()+1, ' ');
// Diagnostics in the group.
if (I->second.DiagsInGroup.empty())
OS << "0, ";
else
OS << "DiagArray" << I->second.IDNo << ", ";
// Subgroups.
if (I->second.SubGroups.empty())
OS << 0;
else
OS << "DiagSubGroup" << I->second.IDNo;
OS << " },\n";
}
OS << "#endif // GET_DIAG_TABLE\n\n";
}
|
//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang diagnostics tables.
//
//===----------------------------------------------------------------------===//
#include "ClangDiagnosticsEmitter.h"
#include "Record.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Streams.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/VectorExtras.h"
#include <set>
#include <map>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Warning Tables (.inc file) generation.
//===----------------------------------------------------------------------===//
void ClangDiagsDefsEmitter::run(std::ostream &OS) {
// Write the #if guard
if (!Component.empty()) {
std::string ComponentName = UppercaseString(Component);
OS << "#ifdef " << ComponentName << "START\n";
OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
<< ",\n";
OS << "#undef " << ComponentName << "START\n";
OS << "#endif\n";
}
const std::vector<Record*> &Diags =
Records.getAllDerivedDefinitions("Diagnostic");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
const Record &R = *Diags[i];
// Filter by component.
if (!Component.empty() && Component != R.getValueAsString("Component"))
continue;
OS << "DIAG(" << R.getName() << ", ";
OS << R.getValueAsDef("Class")->getName();
OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName();
// Description string.
OS << ", \"";
std::string S = R.getValueAsString("Text");
EscapeString(S);
OS << S << "\"";
// Warning associated with the diagnostic.
if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group"))) {
S = DI->getDef()->getValueAsString("GroupName");
EscapeString(S);
OS << ", \"" << S << "\"";
} else {
OS << ", 0";
}
// SFINAE bit
if (R.getValueAsBit("SFINAE"))
OS << ", true";
else
OS << ", false";
OS << ")\n";
}
}
//===----------------------------------------------------------------------===//
// Warning Group Tables generation
//===----------------------------------------------------------------------===//
struct GroupInfo {
std::vector<const Record*> DiagsInGroup;
std::vector<std::string> SubGroups;
unsigned IDNo;
};
void ClangDiagGroupsEmitter::run(std::ostream &OS) {
// Invert the 1-[0/1] mapping of diags to group into a one to many mapping of
// groups to diags in the group.
std::map<std::string, GroupInfo> DiagsInGroup;
std::vector<Record*> Diags =
Records.getAllDerivedDefinitions("Diagnostic");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
const Record *R = Diags[i];
DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group"));
if (DI == 0) continue;
std::string GroupName = DI->getDef()->getValueAsString("GroupName");
DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
}
// Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
// groups (these are warnings that GCC supports that clang never produces).
Diags = Records.getAllDerivedDefinitions("DiagGroup");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
Record *Group = Diags[i];
GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
}
// Assign unique ID numbers to the groups.
unsigned IDNo = 0;
for (std::map<std::string, GroupInfo>::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)
I->second.IDNo = IDNo;
// Walk through the groups emitting an array for each diagnostic of the diags
// that are mapped to.
OS << "\n#ifdef GET_DIAG_ARRAYS\n";
unsigned MaxLen = 0;
for (std::map<std::string, GroupInfo>::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
MaxLen = std::max(MaxLen, (unsigned)I->first.size());
std::vector<const Record*> &V = I->second.DiagsInGroup;
if (!V.empty()) {
OS << "static const short DiagArray" << I->second.IDNo << "[] = { ";
for (unsigned i = 0, e = V.size(); i != e; ++i)
OS << "diag::" << V[i]->getName() << ", ";
OS << "-1 };\n";
}
const std::vector<std::string> &SubGroups = I->second.SubGroups;
if (!SubGroups.empty()) {
OS << "static const char DiagSubGroup" << I->second.IDNo << "[] = { ";
for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) {
std::map<std::string, GroupInfo>::iterator RI =
DiagsInGroup.find(SubGroups[i]);
assert(RI != DiagsInGroup.end() && "Referenced without existing?");
OS << RI->second.IDNo << ", ";
}
OS << "-1 };\n";
}
}
OS << "#endif // GET_DIAG_ARRAYS\n\n";
// Emit the table now.
OS << "\n#ifdef GET_DIAG_TABLE\n";
for (std::map<std::string, GroupInfo>::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
std::string S = I->first;
EscapeString(S);
// Group option string.
OS << " { \"" << S << "\","
<< std::string(MaxLen-I->first.size()+1, ' ');
// Diagnostics in the group.
if (I->second.DiagsInGroup.empty())
OS << "0, ";
else
OS << "DiagArray" << I->second.IDNo << ", ";
// Subgroups.
if (I->second.SubGroups.empty())
OS << 0;
else
OS << "DiagSubGroup" << I->second.IDNo;
OS << " },\n";
}
OS << "#endif // GET_DIAG_TABLE\n\n";
}
|
Add output of the SFINAE bit for Clang's diagnostics
|
Add output of the SFINAE bit for Clang's diagnostics
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@73331 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-2-clause
|
chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm
|
b678809c6ce7d3451e56ad5b74e25310281bc604
|
SceneStructureModule/SceneStructureModule.cpp
|
SceneStructureModule/SceneStructureModule.cpp
|
/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file SceneStructureModule.cpp
* @brief Provides Scene Structure window and raycast drag-and-drop import of
* .mesh, .scene, .xml and .nbf files to the main window.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "SceneStructureModule.h"
#include "SceneStructureWindow.h"
#include "SupportedFileTypes.h"
#include "AddContentWindow.h"
#include "Console.h"
#include "UiServiceInterface.h"
#include "Input.h"
#include "RenderServiceInterface.h"
#include "SceneImporter.h"
#include "EC_OgreCamera.h"
#include "EC_Placeable.h"
#include "NaaliUi.h"
#include "NaaliGraphicsView.h"
#include "NaaliMainWindow.h"
#include "LoggingFunctions.h"
#include "SceneDesc.h"
DEFINE_POCO_LOGGING_FUNCTIONS("SceneStructure");
#ifdef ASSIMP_ENABLED
#include <OpenAssetImport.h>
#endif
//#include <OgreCamera.h>
#include "MemoryLeakCheck.h"
SceneStructureModule::SceneStructureModule() :
IModule("SceneStructure"),
sceneWindow(0)
{
}
SceneStructureModule::~SceneStructureModule()
{
SAFE_DELETE(sceneWindow);
}
void SceneStructureModule::PostInitialize()
{
framework_->Console()->RegisterCommand("scenestruct", "Shows the Scene Structure window.", this, SLOT(ShowSceneStructureWindow()));
inputContext = framework_->GetInput()->RegisterInputContext("SceneStructureInput", 90);
//input->SetTakeKeyboardEventsOverQt(true);
connect(inputContext.get(), SIGNAL(KeyPressed(KeyEvent *)), this, SLOT(HandleKeyPressed(KeyEvent *)));
connect(framework_->Ui()->GraphicsView(), SIGNAL(DragEnterEvent(QDragEnterEvent *)), SLOT(HandleDragEnterEvent(QDragEnterEvent *)));
connect(framework_->Ui()->GraphicsView(), SIGNAL(DragMoveEvent(QDragMoveEvent *)), SLOT(HandleDragMoveEvent(QDragMoveEvent *)));
connect(framework_->Ui()->GraphicsView(), SIGNAL(DropEvent(QDropEvent *)), SLOT(HandleDropEvent(QDropEvent *)));
}
QList<Scene::Entity *> SceneStructureModule::InstantiateContent(const QString &filename, Vector3df worldPos, bool clearScene, bool queryPosition)
{
return InstantiateContent(filename, worldPos, SceneDesc(), clearScene, queryPosition);
}
QList<Scene::Entity *> SceneStructureModule::InstantiateContent(const QString &filename, Vector3df worldPos, const SceneDesc &desc,
bool clearScene, bool queryPosition)
{
QList<Scene::Entity *> ret;
SceneDesc sceneDesc;
if (!IsSupportedFileType(filename))
{
LogError("Unsupported file extension: " + filename.toStdString());
return ret;
}
const Scene::ScenePtr &scene = framework_->GetDefaultWorldScene();
if (!scene)
return ret;
if (queryPosition)
{
bool ok;
QString posString = QInputDialog::getText(0, tr("Position"), tr("position (x;y;z):"), QLineEdit::Normal, "0.00;0.00;0.00", &ok);
posString = posString.trimmed();
if (!ok)
return ret;
if (posString.isEmpty())
posString = "0;0;0";
posString.replace(',', '.');
QStringList pos = posString.split(';');
if (pos.size() > 0)
worldPos.x = pos[0].toFloat();
if (pos.size() > 1)
worldPos.y = pos[1].toFloat();
if (pos.size() > 2)
worldPos.z = pos[2].toFloat();
}
if (filename.endsWith(cOgreSceneFileExtension, Qt::CaseInsensitive))
{
//boost::filesystem::path path(filename.toStdString());
//std::string dirname = path.branch_path().string();
TundraLogic::SceneImporter importer(scene);
sceneDesc = importer.GetSceneDescForScene(filename);
///\todo Take into account asset sources.
/*
ret = importer.Import(filename.toStdString(), dirname, "./data/assets",
Transform(worldPos, Vector3df(), Vector3df(1,1,1)), AttributeChange::Default, clearScene, true, false);
if (ret.empty())
LogError("Import failed");
else
LogInfo("Import successful. " + ToString(ret.size()) + " entities created.");
*/
}
else if (filename.endsWith(cOgreMeshFileExtension, Qt::CaseInsensitive))
{
boost::filesystem::path path(filename.toStdString());
std::string dirname = path.branch_path().string();
TundraLogic::SceneImporter importer(scene);
sceneDesc = importer.GetSceneDescForMesh(filename);
/*
Scene::EntityPtr entity = importer.ImportMesh(filename.toStdString(), dirname, "./data/assets",
Transform(worldPos, Vector3df(), Vector3df(1,1,1)), std::string(), AttributeChange::Default, true);
if (entity)
ret << entity.get();
return ret;
*/
}
else if (filename.toLower().indexOf(cTundraXmlFileExtension) != -1 && filename.toLower().indexOf(cOgreMeshFileExtension) == -1)
{
ret = scene->LoadSceneXML(filename.toStdString(), clearScene, false, AttributeChange::Replicate);
// sceneDesc = scene->GetSceneDescription(filename);
}
else if (filename.toLower().indexOf(cTundraBinFileExtension) != -1)
{
ret = scene->CreateContentFromBinary(filename, true, AttributeChange::Replicate);
// sceneDesc = scene->GetSceneDescription(filename);
}
else
{
#ifdef ASSIMP_ENABLED
boost::filesystem::path path(filename.toStdString());
AssImp::OpenAssetImport assimporter;
QString extension = QString(path.extension().c_str()).toLower();
if (assimporter.IsSupportedExtension(extension))
{
std::string dirname = path.branch_path().string();
std::vector<AssImp::MeshData> meshNames;
assimporter.GetMeshData(filename, meshNames);
TundraLogic::SceneImporter sceneimporter(scene);
for (size_t i=0 ; i<meshNames.size() ; ++i)
{
Scene::EntityPtr entity = sceneimporter.ImportMesh(meshNames[i].file_.toStdString(), dirname, meshNames[i].transform_,
std::string(), "file://", AttributeChange::Default, false, meshNames[i].name_.toStdString());
if (entity)
ret.append(entity.get());
}
return ret;
}
#endif
}
if (!sceneDesc.IsEmpty())
{
AddContentWindow *addContent = new AddContentWindow(framework_, scene);
addContent->AddDescription(sceneDesc);
if (worldPos != Vector3df())
addContent->AddPosition(worldPos);
addContent->move((framework_->Ui()->MainWindow()->pos()) + QPoint(400, 200));
addContent->show();
}
return ret;
}
void SceneStructureModule::CentralizeEntitiesTo(const Vector3df &pos, const QList<Scene::Entity *> &entities)
{
Vector3df minPos(1e9f, 1e9f, 1e9f);
Vector3df maxPos(-1e9f, -1e9f, -1e9f);
foreach(Scene::Entity *e, entities)
{
EC_Placeable *p = e->GetComponent<EC_Placeable>().get();
if (p)
{
Vector3df pos = p->transform.Get().position;
minPos.x = std::min(minPos.x, pos.x);
minPos.y = std::min(minPos.y, pos.y);
minPos.z = std::min(minPos.z, pos.z);
maxPos.x = std::max(maxPos.x, pos.x);
maxPos.y = std::max(maxPos.y, pos.y);
maxPos.z = std::max(maxPos.z, pos.z);
}
}
// We assume that world's up axis is Z-coordinate axis.
Vector3df importPivotPos = Vector3df((minPos.x + maxPos.x) / 2, (minPos.y + maxPos.y) / 2, minPos.z);
Vector3df offset = pos - importPivotPos;
foreach(Scene::Entity *e, entities)
{
EC_Placeable *p = e->GetComponent<EC_Placeable>().get();
if (p)
{
Transform t = p->transform.Get();
t.position += offset;
p->transform.Set(t, AttributeChange::Default);
}
}
}
bool SceneStructureModule::IsSupportedFileType(const QString &filename)
{
if (filename.endsWith(cTundraXmlFileExtension, Qt::CaseInsensitive) ||
filename.endsWith(cTundraBinFileExtension, Qt::CaseInsensitive) ||
filename.endsWith(cOgreMeshFileExtension, Qt::CaseInsensitive) ||
filename.endsWith(cOgreSceneFileExtension, Qt::CaseInsensitive))
{
return true;
}
else
{
#ifdef ASSIMP_ENABLED
boost::filesystem::path path(filename.toStdString());
AssImp::OpenAssetImport assimporter;
QString extension = QString(path.extension().c_str()).toLower();
if (assimporter.IsSupportedExtension(extension))
return true;
#endif
return false;
}
}
void SceneStructureModule::ShowSceneStructureWindow()
{
/*UiServiceInterface *ui = framework_->GetService<UiServiceInterface>();
if (!ui)
return;*/
if (sceneWindow)
{
//ui->ShowWidget(sceneWindow);
sceneWindow->show();
return;
}
NaaliUi *ui = GetFramework()->Ui();
if (!ui)
return;
sceneWindow = new SceneStructureWindow(framework_);
//sceneWindow->move(200,200);
sceneWindow->SetScene(framework_->GetDefaultWorldScene());
sceneWindow->setParent(ui->MainWindow());
sceneWindow->setWindowFlags(Qt::Tool);
sceneWindow->show();
//ui->AddWidgetToScene(sceneWindow);
//ui->ShowWidget(sceneWindow);
}
void SceneStructureModule::HandleKeyPressed(KeyEvent *e)
{
if (e->eventType != KeyEvent::KeyPressed || e->keyPressCount > 1)
return;
Input &input = *framework_->GetInput();
const QKeySequence showSceneStruct = input.KeyBinding("ShowSceneStructureWindow", QKeySequence(Qt::ShiftModifier + Qt::Key_S));
if (QKeySequence(e->keyCode | e->modifiers) == showSceneStruct)
ShowSceneStructureWindow();
}
void SceneStructureModule::HandleDragEnterEvent(QDragEnterEvent *e)
{
// If at least one file is supported, accept.
if (e->mimeData()->hasUrls())
foreach(QUrl url, e->mimeData()->urls())
if (IsSupportedFileType(url.path()))
e->accept();
}
void SceneStructureModule::HandleDragMoveEvent(QDragMoveEvent *e)
{
// If at least one file is supported, accept.
if (e->mimeData()->hasUrls())
foreach(QUrl url, e->mimeData()->urls())
if (IsSupportedFileType(url.path()))
e->accept();
}
void SceneStructureModule::HandleDropEvent(QDropEvent *e)
{
if (e->mimeData()->hasUrls())
{
QList<Scene::Entity *> importedEntities;
Foundation::RenderServiceInterface *renderer = framework_->GetService<Foundation::RenderServiceInterface>();
if (!renderer)
return;
Vector3df worldPos;
RaycastResult* res = renderer->Raycast(e->pos().x(), e->pos().y());
if (!res->entity_)
{
// No entity hit, use camera's position with hard-coded offset.
const Scene::ScenePtr &scene = framework_->GetDefaultWorldScene();
if (!scene)
return;
foreach(Scene::EntityPtr cam, scene->GetEntitiesWithComponent(EC_OgreCamera::TypeNameStatic()))
if (cam->GetComponent<EC_OgreCamera>()->IsActive())
{
EC_Placeable *placeable = cam->GetComponent<EC_Placeable>().get();
if (placeable)
{
//Ogre::Ray ray = cam->GetComponent<EC_OgreCamera>()->GetCamera()->getCameraToViewportRay(e->pos().x(), e->pos().y());
Quaternion q = placeable->GetOrientation();
Vector3df v = q * -Vector3df::UNIT_Z;
//Ogre::Vector3 oV = ray.getPoint(20);
worldPos = /*Vector3df(oV.x, oV.y, oV.z);*/ placeable->GetPosition() + v * 20;
break;
}
}
}
else
worldPos = res->pos_;
foreach (QUrl url, e->mimeData()->urls())
{
QString filename = url.path();
#ifdef _WINDOWS
// We have '/' as the first char on windows and the filename
// is not identified as a file properly. But on other platforms the '/' is valid/required.
filename = filename.mid(1);
#endif
importedEntities.append(InstantiateContent(filename, worldPos/*Vector3df()*/, false));
}
// Calculate import pivot and offset for new content
//if (importedEntities.size())
// CentralizeEntitiesTo(worldPos, importedEntities);
e->acceptProposedAction();
}
}
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
POCO_BEGIN_MANIFEST(IModule)
POCO_EXPORT_CLASS(SceneStructureModule)
POCO_END_MANIFEST
|
/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file SceneStructureModule.cpp
* @brief Provides Scene Structure window and raycast drag-and-drop import of
* .mesh, .scene, .xml and .nbf files to the main window.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "SceneStructureModule.h"
#include "SceneStructureWindow.h"
#include "SupportedFileTypes.h"
#include "AddContentWindow.h"
#include "Console.h"
#include "UiServiceInterface.h"
#include "Input.h"
#include "RenderServiceInterface.h"
#include "SceneImporter.h"
#include "EC_OgreCamera.h"
#include "EC_Placeable.h"
#include "NaaliUi.h"
#include "NaaliGraphicsView.h"
#include "NaaliMainWindow.h"
#include "LoggingFunctions.h"
#include "SceneDesc.h"
DEFINE_POCO_LOGGING_FUNCTIONS("SceneStructure");
#ifdef ASSIMP_ENABLED
#include <OpenAssetImport.h>
#endif
//#include <OgreCamera.h>
#include "MemoryLeakCheck.h"
SceneStructureModule::SceneStructureModule() :
IModule("SceneStructure"),
sceneWindow(0)
{
}
SceneStructureModule::~SceneStructureModule()
{
SAFE_DELETE(sceneWindow);
}
void SceneStructureModule::PostInitialize()
{
framework_->Console()->RegisterCommand("scenestruct", "Shows the Scene Structure window.", this, SLOT(ShowSceneStructureWindow()));
inputContext = framework_->GetInput()->RegisterInputContext("SceneStructureInput", 90);
//input->SetTakeKeyboardEventsOverQt(true);
connect(inputContext.get(), SIGNAL(KeyPressed(KeyEvent *)), this, SLOT(HandleKeyPressed(KeyEvent *)));
connect(framework_->Ui()->GraphicsView(), SIGNAL(DragEnterEvent(QDragEnterEvent *)), SLOT(HandleDragEnterEvent(QDragEnterEvent *)));
connect(framework_->Ui()->GraphicsView(), SIGNAL(DragMoveEvent(QDragMoveEvent *)), SLOT(HandleDragMoveEvent(QDragMoveEvent *)));
connect(framework_->Ui()->GraphicsView(), SIGNAL(DropEvent(QDropEvent *)), SLOT(HandleDropEvent(QDropEvent *)));
}
QList<Scene::Entity *> SceneStructureModule::InstantiateContent(const QString &filename, Vector3df worldPos, bool clearScene, bool queryPosition)
{
return InstantiateContent(filename, worldPos, SceneDesc(), clearScene, queryPosition);
}
QList<Scene::Entity *> SceneStructureModule::InstantiateContent(const QString &filename, Vector3df worldPos, const SceneDesc &desc,
bool clearScene, bool queryPosition)
{
QList<Scene::Entity *> ret;
SceneDesc sceneDesc;
if (!IsSupportedFileType(filename))
{
LogError("Unsupported file extension: " + filename.toStdString());
return ret;
}
const Scene::ScenePtr &scene = framework_->GetDefaultWorldScene();
if (!scene)
return ret;
if (queryPosition)
{
bool ok;
QString posString = QInputDialog::getText(0, tr("Position"), tr("position (x;y;z):"), QLineEdit::Normal, "0.00;0.00;0.00", &ok);
posString = posString.trimmed();
if (!ok)
return ret;
if (posString.isEmpty())
posString = "0;0;0";
posString.replace(',', '.');
QStringList pos = posString.split(';');
if (pos.size() > 0)
worldPos.x = pos[0].toFloat();
if (pos.size() > 1)
worldPos.y = pos[1].toFloat();
if (pos.size() > 2)
worldPos.z = pos[2].toFloat();
}
if (filename.endsWith(cOgreSceneFileExtension, Qt::CaseInsensitive))
{
//boost::filesystem::path path(filename.toStdString());
//std::string dirname = path.branch_path().string();
TundraLogic::SceneImporter importer(scene);
sceneDesc = importer.GetSceneDescForScene(filename);
///\todo Take into account asset sources.
/*
ret = importer.Import(filename.toStdString(), dirname, "./data/assets",
Transform(worldPos, Vector3df(), Vector3df(1,1,1)), AttributeChange::Default, clearScene, true, false);
if (ret.empty())
LogError("Import failed");
else
LogInfo("Import successful. " + ToString(ret.size()) + " entities created.");
*/
}
else if (filename.endsWith(cOgreMeshFileExtension, Qt::CaseInsensitive))
{
boost::filesystem::path path(filename.toStdString());
std::string dirname = path.branch_path().string();
TundraLogic::SceneImporter importer(scene);
sceneDesc = importer.GetSceneDescForMesh(filename);
/*
Scene::EntityPtr entity = importer.ImportMesh(filename.toStdString(), dirname, "./data/assets",
Transform(worldPos, Vector3df(), Vector3df(1,1,1)), std::string(), AttributeChange::Default, true);
if (entity)
ret << entity.get();
return ret;
*/
}
else if (filename.toLower().indexOf(cTundraXmlFileExtension) != -1 && filename.toLower().indexOf(cOgreMeshFileExtension) == -1)
{
// ret = scene->LoadSceneXML(filename.toStdString(), clearScene, false, AttributeChange::Replicate);
sceneDesc = scene->GetSceneDescFromXml(filename);
}
else if (filename.toLower().indexOf(cTundraBinFileExtension) != -1)
{
// ret = scene->CreateContentFromBinary(filename, true, AttributeChange::Replicate);
sceneDesc = scene->GetSceneDescFromBinary(filename);
}
else
{
#ifdef ASSIMP_ENABLED
boost::filesystem::path path(filename.toStdString());
AssImp::OpenAssetImport assimporter;
QString extension = QString(path.extension().c_str()).toLower();
if (assimporter.IsSupportedExtension(extension))
{
std::string dirname = path.branch_path().string();
std::vector<AssImp::MeshData> meshNames;
assimporter.GetMeshData(filename, meshNames);
TundraLogic::SceneImporter sceneimporter(scene);
for (size_t i=0 ; i<meshNames.size() ; ++i)
{
Scene::EntityPtr entity = sceneimporter.ImportMesh(meshNames[i].file_.toStdString(), dirname, meshNames[i].transform_,
std::string(), "file://", AttributeChange::Default, false, meshNames[i].name_.toStdString());
if (entity)
ret.append(entity.get());
}
return ret;
}
#endif
}
if (!sceneDesc.IsEmpty())
{
AddContentWindow *addContent = new AddContentWindow(framework_, scene);
addContent->AddDescription(sceneDesc);
if (worldPos != Vector3df())
addContent->AddPosition(worldPos);
addContent->move((framework_->Ui()->MainWindow()->pos()) + QPoint(400, 200));
addContent->show();
}
return ret;
}
void SceneStructureModule::CentralizeEntitiesTo(const Vector3df &pos, const QList<Scene::Entity *> &entities)
{
Vector3df minPos(1e9f, 1e9f, 1e9f);
Vector3df maxPos(-1e9f, -1e9f, -1e9f);
foreach(Scene::Entity *e, entities)
{
EC_Placeable *p = e->GetComponent<EC_Placeable>().get();
if (p)
{
Vector3df pos = p->transform.Get().position;
minPos.x = std::min(minPos.x, pos.x);
minPos.y = std::min(minPos.y, pos.y);
minPos.z = std::min(minPos.z, pos.z);
maxPos.x = std::max(maxPos.x, pos.x);
maxPos.y = std::max(maxPos.y, pos.y);
maxPos.z = std::max(maxPos.z, pos.z);
}
}
// We assume that world's up axis is Z-coordinate axis.
Vector3df importPivotPos = Vector3df((minPos.x + maxPos.x) / 2, (minPos.y + maxPos.y) / 2, minPos.z);
Vector3df offset = pos - importPivotPos;
foreach(Scene::Entity *e, entities)
{
EC_Placeable *p = e->GetComponent<EC_Placeable>().get();
if (p)
{
Transform t = p->transform.Get();
t.position += offset;
p->transform.Set(t, AttributeChange::Default);
}
}
}
bool SceneStructureModule::IsSupportedFileType(const QString &filename)
{
if (filename.endsWith(cTundraXmlFileExtension, Qt::CaseInsensitive) ||
filename.endsWith(cTundraBinFileExtension, Qt::CaseInsensitive) ||
filename.endsWith(cOgreMeshFileExtension, Qt::CaseInsensitive) ||
filename.endsWith(cOgreSceneFileExtension, Qt::CaseInsensitive))
{
return true;
}
else
{
#ifdef ASSIMP_ENABLED
boost::filesystem::path path(filename.toStdString());
AssImp::OpenAssetImport assimporter;
QString extension = QString(path.extension().c_str()).toLower();
if (assimporter.IsSupportedExtension(extension))
return true;
#endif
return false;
}
}
void SceneStructureModule::ShowSceneStructureWindow()
{
/*UiServiceInterface *ui = framework_->GetService<UiServiceInterface>();
if (!ui)
return;*/
if (sceneWindow)
{
//ui->ShowWidget(sceneWindow);
sceneWindow->show();
return;
}
NaaliUi *ui = GetFramework()->Ui();
if (!ui)
return;
sceneWindow = new SceneStructureWindow(framework_);
//sceneWindow->move(200,200);
sceneWindow->SetScene(framework_->GetDefaultWorldScene());
sceneWindow->setParent(ui->MainWindow());
sceneWindow->setWindowFlags(Qt::Tool);
sceneWindow->show();
//ui->AddWidgetToScene(sceneWindow);
//ui->ShowWidget(sceneWindow);
}
void SceneStructureModule::HandleKeyPressed(KeyEvent *e)
{
if (e->eventType != KeyEvent::KeyPressed || e->keyPressCount > 1)
return;
Input &input = *framework_->GetInput();
const QKeySequence showSceneStruct = input.KeyBinding("ShowSceneStructureWindow", QKeySequence(Qt::ShiftModifier + Qt::Key_S));
if (QKeySequence(e->keyCode | e->modifiers) == showSceneStruct)
ShowSceneStructureWindow();
}
void SceneStructureModule::HandleDragEnterEvent(QDragEnterEvent *e)
{
// If at least one file is supported, accept.
if (e->mimeData()->hasUrls())
foreach(QUrl url, e->mimeData()->urls())
if (IsSupportedFileType(url.path()))
e->accept();
}
void SceneStructureModule::HandleDragMoveEvent(QDragMoveEvent *e)
{
// If at least one file is supported, accept.
if (e->mimeData()->hasUrls())
foreach(QUrl url, e->mimeData()->urls())
if (IsSupportedFileType(url.path()))
e->accept();
}
void SceneStructureModule::HandleDropEvent(QDropEvent *e)
{
if (e->mimeData()->hasUrls())
{
QList<Scene::Entity *> importedEntities;
Foundation::RenderServiceInterface *renderer = framework_->GetService<Foundation::RenderServiceInterface>();
if (!renderer)
return;
Vector3df worldPos;
RaycastResult* res = renderer->Raycast(e->pos().x(), e->pos().y());
if (!res->entity_)
{
// No entity hit, use camera's position with hard-coded offset.
const Scene::ScenePtr &scene = framework_->GetDefaultWorldScene();
if (!scene)
return;
foreach(Scene::EntityPtr cam, scene->GetEntitiesWithComponent(EC_OgreCamera::TypeNameStatic()))
if (cam->GetComponent<EC_OgreCamera>()->IsActive())
{
EC_Placeable *placeable = cam->GetComponent<EC_Placeable>().get();
if (placeable)
{
//Ogre::Ray ray = cam->GetComponent<EC_OgreCamera>()->GetCamera()->getCameraToViewportRay(e->pos().x(), e->pos().y());
Quaternion q = placeable->GetOrientation();
Vector3df v = q * -Vector3df::UNIT_Z;
//Ogre::Vector3 oV = ray.getPoint(20);
worldPos = /*Vector3df(oV.x, oV.y, oV.z);*/ placeable->GetPosition() + v * 20;
break;
}
}
}
else
worldPos = res->pos_;
foreach (QUrl url, e->mimeData()->urls())
{
QString filename = url.path();
#ifdef _WINDOWS
// We have '/' as the first char on windows and the filename
// is not identified as a file properly. But on other platforms the '/' is valid/required.
filename = filename.mid(1);
#endif
importedEntities.append(InstantiateContent(filename, worldPos/*Vector3df()*/, false));
}
// Calculate import pivot and offset for new content
//if (importedEntities.size())
// CentralizeEntitiesTo(worldPos, importedEntities);
e->acceptProposedAction();
}
}
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
POCO_BEGIN_MANIFEST(IModule)
POCO_EXPORT_CLASS(SceneStructureModule)
POCO_END_MANIFEST
|
Use Add Content dialog also for .txml and .tbin files.
|
Use Add Content dialog also for .txml and .tbin files.
|
C++
|
apache-2.0
|
AlphaStaxLLC/tundra,jesterKing/naali,realXtend/tundra,antont/tundra,BogusCurry/tundra,BogusCurry/tundra,realXtend/tundra,jesterKing/naali,pharos3d/tundra,BogusCurry/tundra,jesterKing/naali,realXtend/tundra,antont/tundra,AlphaStaxLLC/tundra,realXtend/tundra,BogusCurry/tundra,antont/tundra,AlphaStaxLLC/tundra,jesterKing/naali,jesterKing/naali,antont/tundra,realXtend/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,jesterKing/naali,pharos3d/tundra,pharos3d/tundra,antont/tundra,pharos3d/tundra,antont/tundra,BogusCurry/tundra,antont/tundra,realXtend/tundra,AlphaStaxLLC/tundra,BogusCurry/tundra,jesterKing/naali
|
80fef67b7c35d14e0ae1aec10f3c46bd75968adb
|
Siv3D/Include/HamFramework/ScalableWindow.hpp
|
Siv3D/Include/HamFramework/ScalableWindow.hpp
|
//-----------------------------------------------
//
// This file is part of the HamFramework for Siv3D.
//
// Copyright (C) 2014-2017 HAMSTRO
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D.hpp>
namespace s3d
{
namespace ScalableWindow
{
enum class ContentScale
{
EnsureFit,
Maximize,
Default = EnsureFit
};
inline void SetBaseSize(const Size& baseSize = Size(640, 480))
{
Window::SetBaseSize(baseSize);
}
inline void SetBaseSize(int32 width, int32 height)
{
return SetBaseSize({ width, height });
}
inline Transformer2D CreateTransformer(const Size& baseSize, ContentScale contentScale = ContentScale::Default)
{
const double sx = static_cast<double>(Window::Width()) / baseSize.x;
const double sy = static_cast<double>(Window::Height()) / baseSize.y;
const double s = (contentScale == ContentScale::EnsureFit) ? Min(sx, sy) : Max(sx, sy);
if (sx <= sy)
{
return Transformer2D(Mat3x2::Scale(s).translate(0, (Window::Height() - baseSize.y * s) * 0.5), true);
}
else
{
return Transformer2D(Mat3x2::Scale(s).translate((Window::Width() - baseSize.x * s) * 0.5, 0), true);
}
}
inline Transformer2D CreateTransformer(int32 width, int32 height, ContentScale contentScale = ContentScale::Default)
{
return CreateTransformer({ width, height }, contentScale);
}
inline Transformer2D CreateTransformer(ContentScale contentScale = ContentScale::Default)
{
return CreateTransformer(Window::BaseSize(), contentScale);
}
inline RectF GetVirtualWindowArea(const Size& baseSize = Window::BaseSize())
{
const double sx = static_cast<double>(Window::Width()) / baseSize.x;
const double sy = static_cast<double>(Window::Height()) / baseSize.y;
const double s = Min(sx, sy);
if (sx <= sy)
{
return RectF(baseSize * s).moveBy(0, (Window::Height() - baseSize.y * s) * 0.5);
}
else
{
return RectF(baseSize * s).moveBy((Window::Width() - baseSize.x * s) * 0.5, 0);
}
}
inline Array<RectF> GetBlackBars(const Size& baseSize = Window::BaseSize())
{
const double sx = static_cast<double>(Window::Width()) / baseSize.x;
const double sy = static_cast<double>(Window::Height()) / baseSize.y;
const double s = Min(sx, sy);
if (sx < sy)
{
const double h = (Window::Height() - baseSize.y * s) * 0.5;
return{ RectF(0, 0, Window::Width(), h), RectF(0, Window::Height() - h,Window::Width(), h) };
}
else if (sx > sy)
{
const double w = (Window::Width() - baseSize.x * s) * 0.5;
return{ RectF(0, 0, w, Window::Height()), RectF(Window::Width() - w, 0, w, Window::Height()) };
}
else
{
return{};
}
}
inline Array<RectF> GetBlackBars(int32 width, int32 height)
{
return GetBlackBars({ width, height });
}
inline void DrawBlackBars(const ColorF& color = Palette::Black, const Size& baseSize = Window::BaseSize())
{
const Transformer2D transformer(Graphics2D::GetTransform().inversed());
for (const auto& bar : GetBlackBars(baseSize))
{
bar.draw(color);
}
}
inline void DrawBlackBars(const ColorF& color, int32 width, int32 height)
{
return DrawBlackBars(color, { width, height });
}
}
}
/* example
# include <Siv3D.hpp>
# include <HamFramework.hpp>
void Main()
{
ScalableWindow::SetBaseSize(640, 480);
Window::Resize(1280, 640);
const int32 dotSize = 40;
Grid<int32> dots(Window::BaseSize() / dotSize);
Graphics::SetBackground(Palette::White);
while (System::Update())
{
const auto transformer = ScalableWindow::CreateTransformer();
for (auto p : step(dots.size()))
{
const Rect rect(p * dotSize, dotSize);
if (rect.leftClicked())
{
++dots[p] %= 4;
}
rect.stretched(-1).draw(ColorF(0.95 - dots[p] * 0.3));
}
ScalableWindow::DrawBlackBars(HSV(40, 0.2, 0.9));
}
}
*/
|
//-----------------------------------------------
//
// This file is part of the HamFramework for Siv3D.
//
// Copyright (C) 2014-2017 HAMSTRO
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D.hpp>
namespace s3d
{
namespace ScalableWindow
{
enum class ContentScale
{
EnsureFit,
Maximize,
Default = EnsureFit
};
inline void SetBaseSize(const Size& baseSize = Size(640, 480))
{
Window::SetBaseSize(baseSize);
}
inline void SetBaseSize(int32 width, int32 height)
{
return SetBaseSize({ width, height });
}
inline Transformer2D CreateTransformer(const Size& baseSize, ContentScale contentScale = ContentScale::Default)
{
const double sx = static_cast<double>(Window::Width()) / baseSize.x;
const double sy = static_cast<double>(Window::Height()) / baseSize.y;
const double s = (contentScale == ContentScale::EnsureFit) ? Min(sx, sy) : Max(sx, sy);
if (sx <= sy)
{
return Transformer2D(Mat3x2::Scale(s).translated(0, (Window::Height() - baseSize.y * s) * 0.5), true);
}
else
{
return Transformer2D(Mat3x2::Scale(s).translated((Window::Width() - baseSize.x * s) * 0.5, 0), true);
}
}
inline Transformer2D CreateTransformer(int32 width, int32 height, ContentScale contentScale = ContentScale::Default)
{
return CreateTransformer({ width, height }, contentScale);
}
inline Transformer2D CreateTransformer(ContentScale contentScale = ContentScale::Default)
{
return CreateTransformer(Window::BaseSize(), contentScale);
}
inline RectF GetVirtualWindowArea(const Size& baseSize = Window::BaseSize())
{
const double sx = static_cast<double>(Window::Width()) / baseSize.x;
const double sy = static_cast<double>(Window::Height()) / baseSize.y;
const double s = Min(sx, sy);
if (sx <= sy)
{
return RectF(baseSize * s).moveBy(0, (Window::Height() - baseSize.y * s) * 0.5);
}
else
{
return RectF(baseSize * s).moveBy((Window::Width() - baseSize.x * s) * 0.5, 0);
}
}
inline Array<RectF> GetBlackBars(const Size& baseSize = Window::BaseSize())
{
const double sx = static_cast<double>(Window::Width()) / baseSize.x;
const double sy = static_cast<double>(Window::Height()) / baseSize.y;
const double s = Min(sx, sy);
if (sx < sy)
{
const double h = (Window::Height() - baseSize.y * s) * 0.5;
return{ RectF(0, 0, Window::Width(), h), RectF(0, Window::Height() - h,Window::Width(), h) };
}
else if (sx > sy)
{
const double w = (Window::Width() - baseSize.x * s) * 0.5;
return{ RectF(0, 0, w, Window::Height()), RectF(Window::Width() - w, 0, w, Window::Height()) };
}
else
{
return{};
}
}
inline Array<RectF> GetBlackBars(int32 width, int32 height)
{
return GetBlackBars({ width, height });
}
inline void DrawBlackBars(const ColorF& color = Palette::Black, const Size& baseSize = Window::BaseSize())
{
const Transformer2D transformer(Graphics2D::GetTransform().inversed());
for (const auto& bar : GetBlackBars(baseSize))
{
bar.draw(color);
}
}
inline void DrawBlackBars(const ColorF& color, int32 width, int32 height)
{
return DrawBlackBars(color, { width, height });
}
}
}
/* example
# include <Siv3D.hpp>
# include <HamFramework.hpp>
void Main()
{
ScalableWindow::SetBaseSize(640, 480);
Window::Resize(1280, 640);
const int32 dotSize = 40;
Grid<int32> dots(Window::BaseSize() / dotSize);
Graphics::SetBackground(Palette::White);
while (System::Update())
{
const auto transformer = ScalableWindow::CreateTransformer();
for (auto p : step(dots.size()))
{
const Rect rect(p * dotSize, dotSize);
if (rect.leftClicked())
{
++dots[p] %= 4;
}
rect.stretched(-1).draw(ColorF(0.95 - dots[p] * 0.3));
}
ScalableWindow::DrawBlackBars(HSV(40, 0.2, 0.9));
}
}
*/
|
Update ScalableWindow.hpp
|
Update ScalableWindow.hpp
|
C++
|
mit
|
azaika/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,wynd2608/OpenSiv3D,azaika/OpenSiv3D,Siv3D/OpenSiv3D,azaika/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D
|
da8cc108d6d431a0ceb0a382e9c2654695327999
|
Qt5Ogre21/somecustomwidget.cpp
|
Qt5Ogre21/somecustomwidget.cpp
|
#include "somecustomwidget.h"
SomeCustomWidget::SomeCustomWidget(QWidget *parent) : QWidget(parent)
{
setWindowTitle("Some Window");
setMinimumSize(100, 100);
resize(1024,768);
mainLayout = new QVBoxLayout();
w = new QOgreViewport;
QtOgre21::instance()->createNewScene();
w2 = new QOgreViewport(1);
mainLayout->addWidget(w);
mainLayout->addWidget(w2);
setLayout(mainLayout);
}
|
#include "somecustomwidget.h"
SomeCustomWidget::SomeCustomWidget(QWidget *parent) : QWidget(parent)
{
setWindowTitle("Some Window");
setMinimumSize(100, 100);
resize(1024,768);
mainLayout = new QVBoxLayout();
w = new QOgreViewport;
QtOgre21::instance()->createNewScene();
w2 = new QOgreViewport(1);
mainLayout->addWidget(w, 0);
mainLayout->addWidget(w2, 0);
mainLayout->setContentsMargins(0, 0, 0, 0);
mainLayout->setMargin(0);
mainLayout->setSpacing(0);
setLayout(mainLayout);
}
|
Remove margins on the "somecustomwidget" just to show
|
Remove margins on the "somecustomwidget" just to show
|
C++
|
mit
|
Ybalrid/Qt5Ogre21
|
c1d96b4ddaae84fd23bc928691b7116d1c554e74
|
common/ttcn3float.hh
|
common/ttcn3float.hh
|
/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Balasko, Jeno
* Baranyi, Botond
* Raduly, Csaba
*
******************************************************************************/
#ifndef TTCN3FLOAT_HH_
#define TTCN3FLOAT_HH_
// TODO: once we can use C++11 as the base platform replace with cmath
// this way the signedbit will become a defined function instead of a macro
#include <math.h>
/* TTCN-3 float values that have absolute value smaller than this
are displayed in exponential notation. */
#define MIN_DECIMAL_FLOAT 1.0E-4
/* TTCN-3 float values that have absolute value larger or equal than this
are displayed in exponential notation. */
#define MAX_DECIMAL_FLOAT 1.0E+10
#ifndef signbit
// Probably Solaris.
// Thankfully, IEEE Std 1003.1, 2004 Edition says that signbit is a macro,
// hence it's safe to use ifdef.
#ifdef __sparc
// Big endian
inline int signbitfunc(double d)
{
return *((unsigned char*)&d) & 0x80;
}
#else
// Probably Intel, assume little endian
inline int signbitfunc(double d)
{
return ((unsigned char*)&d)[sizeof(double)-1] & 0x80;
}
#endif
#define signbit(d) signbitfunc(d)
#endif // def signbit
/** A class which behaves almost, but not quite, entirely unlike
* a floating-point value.
*
* It is used as a member of a union (in Value.hh);
* it MUST NOT have a constructor.
*/
struct ttcn3float {
/// Implicit conversion
operator double() const { return value; }
/// Assignment from a proper double
const ttcn3float& operator=(double d) {
value = d;
return *this;
}
/// Address-of, for scanf
double* operator&() { return &value; }
const ttcn3float& operator+=(double d) {
value += d;
return *this;
}
const ttcn3float& operator-=(double d) {
value -= d;
return *this;
}
const ttcn3float& operator*=(double d) {
value *= d;
return *this;
}
const ttcn3float& operator/=(double d) {
value /= d;
return *this;
}
bool operator<(double d) const {
if (isnan(value)) {
return false; // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (isnan(d)) {
return true; // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (value==0.0 && d==0.0) { // does not distinguish -0.0
return signbit(value) && !signbit(d); // value negative, d positive
}
else { // finally, the sensible behavior
return value < d;
}
}
bool operator>(double d) const {
if (isnan(value)) {
return true; // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (isnan(d)) {
return false; // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (value==0.0 && d==0.0) { // does not distinguish -0.0
return !signbit(value) && signbit(d); // value positive, d negative
}
else { // finally, the sensible behavior
return value > d;
}
}
bool operator==(double d) const {
if (isnan(value)) {
return !!isnan(d); // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (isnan(d)) {
return false;
}
else if (value==0.0 && d==0.0) { // does not distinguish -0.0
return signbit(value) == signbit(d);
}
else { // finally, the sensible behavior
return value == d;
}
}
public:
double value;
};
/** Replacement for a user-defined constructor that ttcn3float can't have */
inline ttcn3float make_ttcn3float(double f) {
ttcn3float retval = { f };
return retval;
}
#endif /* TTCN3FLOAT_HH_ */
|
/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Balasko, Jeno
* Baranyi, Botond
* Raduly, Csaba
*
******************************************************************************/
#ifndef TTCN3FLOAT_HH_
#define TTCN3FLOAT_HH_
#include <cmath>
/* TTCN-3 float values that have absolute value smaller than this
are displayed in exponential notation. */
#define MIN_DECIMAL_FLOAT 1.0E-4
/* TTCN-3 float values that have absolute value larger or equal than this
are displayed in exponential notation. */
#define MAX_DECIMAL_FLOAT 1.0E+10
//#ifndef signbit
// Probably Solaris.
// Thankfully, IEEE Std 1003.1, 2004 Edition says that signbit is a macro,
// hence it's safe to use ifdef.
//#ifdef __sparc
//// Big endian
//inline int signbitfunc(double d)
//{
// return *((unsigned char*)&d) & 0x80;
//}
//#else
// Probably Intel, assume little endian
//inline int signbitfunc(double d)
//{
// return ((unsigned char*)&d)[sizeof(double)-1] & 0x80;
//}
//#endif
//#define signbit(d) signbitfunc(d)
//#endif // def signbit
/** A class which behaves almost, but not quite, entirely unlike
* a floating-point value.
*
* It is used as a member of a union (in Value.hh);
* it MUST NOT have a constructor.
*/
struct ttcn3float {
/// Implicit conversion
operator double() const { return value; }
/// Assignment from a proper double
const ttcn3float& operator=(double d) {
value = d;
return *this;
}
/// Address-of, for scanf
double* operator&() { return &value; }
const ttcn3float& operator+=(double d) {
value += d;
return *this;
}
const ttcn3float& operator-=(double d) {
value -= d;
return *this;
}
const ttcn3float& operator*=(double d) {
value *= d;
return *this;
}
const ttcn3float& operator/=(double d) {
value /= d;
return *this;
}
bool operator<(double d) const {
if (std::isnan(value)) {
return false; // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (std::isnan(d)) {
return true; // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (value==0.0 && d==0.0) { // does not distinguish -0.0
return std::signbit(value) && !std::signbit(d); // value negative, d positive
}
else { // finally, the sensible behavior
return value < d;
}
}
bool operator>(double d) const {
if (std::isnan(value)) {
return true; // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (std::isnan(d)) {
return false; // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (value==0.0 && d==0.0) { // does not distinguish -0.0
return !std::signbit(value) && std::signbit(d); // value positive, d negative
}
else { // finally, the sensible behavior
return value > d;
}
}
bool operator==(double d) const {
if (std::isnan(value)) {
return !!std::isnan(d); // TTCN-3 special: NaN is bigger than anything except NaN
}
else if (std::isnan(d)) {
return false;
}
else if (value==0.0 && d==0.0) { // does not distinguish -0.0
return std::signbit(value) == std::signbit(d);
}
else { // finally, the sensible behavior
return value == d;
}
}
public:
double value;
};
/** Replacement for a user-defined constructor that ttcn3float can't have */
inline ttcn3float make_ttcn3float(double f) {
ttcn3float retval = { f };
return retval;
}
#endif /* TTCN3FLOAT_HH_ */
|
build experiment: lets use the C++11 signbit function instead of platform dependent buggy macros (needs to be tested on all platforms)
|
build experiment: lets use the C++11 signbit function instead of platform dependent buggy macros (needs to be tested on all platforms)
Signed-off-by: Kristof Szabados <[email protected]>
|
C++
|
epl-1.0
|
BotondBaranyi/titan.core,BotondBaranyi/titan.core,BotondBaranyi/titan.core,BotondBaranyi/titan.core,BotondBaranyi/titan.core,BotondBaranyi/titan.core,BotondBaranyi/titan.core,BotondBaranyi/titan.core
|
c2d190a00c3d1fb7c2e186f4daaeef1cc568bfab
|
src/tsmttsm.cpp
|
src/tsmttsm.cpp
|
#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/math.h"
#include "ghost/tsmttsm.h"
#include "ghost/tsmttsm_gen.h"
#include "ghost/tsmttsm_avx2_gen.h"
#include "ghost/tsmttsm_avx_gen.h"
#include "ghost/tsmttsm_sse_gen.h"
#include "ghost/tsmttsm_kahan_gen.h"
#include "ghost/timing.h"
#include "ghost/machine.h"
#include "ghost/constants.h"
#include <map>
typedef ghost_tsmttsm_parameters_t ghost_tsmttsm_kahan_parameters_t;
typedef ghost_tsmttsm_parameters_t ghost_tsmttsm_kahan_parameters_t;
using namespace std;
static bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b)
{
return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,ghost_hash(a.xstor,a.wstor,ghost_hash(a.alignment,a.unroll,0)))) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,ghost_hash(b.xstor,b.wstor,ghost_hash(b.alignment,b.unroll,0))));
}
static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels;
static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kahan_kernels;
ghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv,
ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, ghost_gemm_flags_t flags, int printerror)
{
/*if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("w must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("v must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {
if (printerror) {
ERROR_LOG("x must be stored col-major!");
}
return GHOST_ERR_INVALID_ARG;
}*/
if (x->traits.location != GHOST_LOCATION_HOST || v->traits.location != GHOST_LOCATION_HOST || w->traits.location != GHOST_LOCATION_HOST) {
if (printerror) {
ERROR_LOG("TSMTTSM only implemented for host densemats!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {
if (printerror) {
ERROR_LOG("Different data types!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {
if (printerror) {
ERROR_LOG("Scattered densemats not supported!");
}
return GHOST_ERR_INVALID_ARG;
}
if (!strncasecmp(transv,"N",1)) {
if (printerror) {
ERROR_LOG("v must be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
if (strncasecmp(transw,"N",1)) {
if (printerror) {
ERROR_LOG("w must not be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
UNUSED(alpha);
UNUSED(beta);
UNUSED(reduce);
UNUSED(flags);
return GHOST_SUCCESS;
}
ghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv,ghost_gemm_flags_t flags)
{
ghost_error_t ret;
const char *vtrans;
if (conjv && v->traits.datatype & GHOST_DT_COMPLEX) {
vtrans = "C";
} else {
vtrans = "T";
}
if ((ret = ghost_tsmttsm_valid(x,v,vtrans,w,"N",alpha,beta,reduce,flags,1)) != GHOST_SUCCESS) {
INFO_LOG("TSMTTSM cannot be applied. Checking whether GEMM is fine!");
if ((ret = ghost_gemm_valid(x,v,vtrans,w,"N",alpha,beta,reduce,GHOST_GEMM_DEFAULT,1)) != GHOST_SUCCESS) {
ERROR_LOG("GEMM cannot be applied!");
return ret;
} else {
return ghost_gemm(x,v,vtrans,w,"N",alpha,beta,reduce,GHOST_GEMM_NOT_SPECIAL);
}
}
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> kernels;
if (flags & GHOST_GEMM_KAHAN) {
if (ghost_tsmttsm_kahan_kernels.empty()) {
#include "tsmttsm_kahan.def"
}
kernels = ghost_tsmttsm_kahan_kernels;
} else {
if (ghost_tsmttsm_kernels.empty()) {
#include "tsmttsm.def"
#include "tsmttsm_avx2.def"
#include "tsmttsm_avx.def"
#include "tsmttsm_sse.def"
}
kernels = ghost_tsmttsm_kernels;
}
ghost_tsmttsm_parameters_t p;
ghost_tsmttsm_kernel_t kernel = NULL;
// fix properties
p.dt = x->traits.datatype;
p.xstor = x->traits.storage;
p.wstor = w->traits.storage;
// initial implementation
#ifdef GHOST_HAVE_MIC
p.impl = GHOST_IMPLEMENTATION_MIC;
#elif defined(GHOST_HAVE_AVX2)
p.impl = GHOST_IMPLEMENTATION_AVX2;
#elif defined(GHOST_HAVE_AVX)
p.impl = GHOST_IMPLEMENTATION_AVX;
#elif defined(GHOST_HAVE_SSE)
p.impl = GHOST_IMPLEMENTATION_SSE;
#else
p.impl = GHOST_IMPLEMENTATION_PLAIN;
#endif
// alignment of large input data
// the alignment of the result array does not matter because we can easily re-allocate it accordingly
int al = ghost_machine_alignment();
if (IS_ALIGNED(x->val,al) && IS_ALIGNED(v->val,al) && !((x->stride*x->elSize) % al) && !((v->stride*v->elSize) % al)) {
p.alignment = GHOST_ALIGNED;
} else {
p.alignment = GHOST_UNALIGNED;
}
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
if (x->traits.flags & GHOST_DENSEMAT_VIEW || v->traits.flags & GHOST_DENSEMAT_VIEW) {
p.unroll = 1;
} else {
p.unroll = GHOST_MAX_ROWS_UNROLL;
}
INFO_LOG("Inital search for kernel dt=%d wcols=%d vcols=%d xstor=%d wstor=%d align=%d unroll=%d!",p.dt,p.wcols,p.vcols,p.xstor,p.wstor,p.alignment,p.unroll);
kernel = kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try plain implementation");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
kernel = kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Decrease unroll size");
while (p.unroll > 1 && !kernel) {
p.unroll /= 2;
kernel = kernels[p];
}
}
if (!kernel) {
PERFWARNING_LOG("Try unaligned kernel");
p.alignment = GHOST_UNALIGNED;
kernel = kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary wcols");
p.wcols = -1;
p.vcols = v->traits.ncols;
kernel = kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary vcols");
p.wcols = w->traits.ncols;
p.vcols = -1;
kernel = kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = kernels[p];
}
if (!kernel) {
INFO_LOG("Could not find TSMTTSM kernel with %d %d %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols,p.xstor,p.wstor);
ret = ghost_gemm(x,v,conjv?"C":"T",w,"N",alpha,beta,reduce,GHOST_GEMM_NOT_SPECIAL);
} else {
ret = kernel(x,v,w,alpha,beta,conjv);
if (reduce != GHOST_GEMM_NO_REDUCE && v->context) {
x->reduce(x,v->context->mpicomm,reduce);
}
}
#ifdef GHOST_HAVE_INSTR_TIMING
ghost_gemm_perf_args_t tsmttsm_perfargs;
tsmttsm_perfargs.n = w->traits.ncols;
tsmttsm_perfargs.m = v->traits.ncols;
if (v->context) {
tsmttsm_perfargs.k = v->context->gnrows;
} else {
tsmttsm_perfargs.k = v->traits.nrows;
}
tsmttsm_perfargs.dt = x->traits.datatype;
tsmttsm_perfargs.betaiszero = ghost_iszero(beta,p.dt);
tsmttsm_perfargs.alphaisone = ghost_isone(alpha,p.dt);
ghost_timing_set_perfFunc(NULL,__ghost_functag,ghost_gemm_perf_GBs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GB/s");
ghost_timing_set_perfFunc(NULL,__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s");
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
|
#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/math.h"
#include "ghost/tsmttsm.h"
#include "ghost/tsmttsm_gen.h"
#include "ghost/tsmttsm_avx2_gen.h"
#include "ghost/tsmttsm_avx_gen.h"
#include "ghost/tsmttsm_sse_gen.h"
#include "ghost/tsmttsm_kahan_gen.h"
#include "ghost/timing.h"
#include "ghost/machine.h"
#include "ghost/constants.h"
#include <map>
typedef ghost_tsmttsm_parameters_t ghost_tsmttsm_kahan_parameters_t;
typedef ghost_tsmttsm_parameters_t ghost_tsmttsm_kahan_parameters_t;
using namespace std;
static bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b)
{
return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,ghost_hash(a.xstor,a.wstor,ghost_hash(a.alignment,a.unroll,0)))) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,ghost_hash(b.xstor,b.wstor,ghost_hash(b.alignment,b.unroll,0))));
}
static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels;
static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kahan_kernels;
ghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv,
ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, ghost_gemm_flags_t flags, int printerror)
{
/*if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("w must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("v must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {
if (printerror) {
ERROR_LOG("x must be stored col-major!");
}
return GHOST_ERR_INVALID_ARG;
}*/
if (x->traits.location != GHOST_LOCATION_HOST || v->traits.location != GHOST_LOCATION_HOST || w->traits.location != GHOST_LOCATION_HOST) {
if (printerror) {
ERROR_LOG("TSMTTSM only implemented for host densemats!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {
if (printerror) {
ERROR_LOG("Different data types!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {
if (printerror) {
ERROR_LOG("Scattered densemats not supported!");
}
return GHOST_ERR_INVALID_ARG;
}
if (!strncasecmp(transv,"N",1)) {
if (printerror) {
ERROR_LOG("v must be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
if (strncasecmp(transw,"N",1)) {
if (printerror) {
ERROR_LOG("w must not be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
UNUSED(alpha);
UNUSED(beta);
UNUSED(reduce);
UNUSED(flags);
return GHOST_SUCCESS;
}
ghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv,ghost_gemm_flags_t flags)
{
ghost_error_t ret;
const char *vtrans;
if (conjv && v->traits.datatype & GHOST_DT_COMPLEX) {
vtrans = "C";
} else {
vtrans = "T";
}
if ((ret = ghost_tsmttsm_valid(x,v,vtrans,w,"N",alpha,beta,reduce,flags,1)) != GHOST_SUCCESS) {
INFO_LOG("TSMTTSM cannot be applied. Checking whether GEMM is fine!");
if ((ret = ghost_gemm_valid(x,v,vtrans,w,"N",alpha,beta,reduce,GHOST_GEMM_DEFAULT,1)) != GHOST_SUCCESS) {
ERROR_LOG("GEMM cannot be applied!");
return ret;
} else {
return ghost_gemm(x,v,vtrans,w,"N",alpha,beta,reduce,GHOST_GEMM_NOT_SPECIAL);
}
}
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> kernels;
if (flags & GHOST_GEMM_KAHAN) {
if (ghost_tsmttsm_kahan_kernels.empty()) {
#include "tsmttsm_kahan.def"
}
kernels = ghost_tsmttsm_kahan_kernels;
} else {
if (ghost_tsmttsm_kernels.empty()) {
#include "tsmttsm.def"
#include "tsmttsm_avx2.def"
#include "tsmttsm_avx.def"
#include "tsmttsm_sse.def"
}
kernels = ghost_tsmttsm_kernels;
}
ghost_tsmttsm_parameters_t p;
ghost_tsmttsm_kernel_t kernel = NULL;
// fix properties
p.dt = x->traits.datatype;
p.xstor = x->traits.storage;
p.wstor = w->traits.storage;
// initial implementation
#ifdef GHOST_HAVE_MIC
p.impl = GHOST_IMPLEMENTATION_MIC;
#elif defined(GHOST_HAVE_AVX2)
p.impl = GHOST_IMPLEMENTATION_AVX2;
#elif defined(GHOST_HAVE_AVX)
p.impl = GHOST_IMPLEMENTATION_AVX;
#elif defined(GHOST_HAVE_SSE)
p.impl = GHOST_IMPLEMENTATION_SSE;
#else
p.impl = GHOST_IMPLEMENTATION_PLAIN;
#endif
// alignment of large input data
// the alignment of the result array does not matter because we can easily re-allocate it accordingly
int al = ghost_machine_alignment();
if (IS_ALIGNED(w->val,al) && IS_ALIGNED(v->val,al) && !((w->stride*w->elSize) % al) && !((v->stride*v->elSize) % al)) {
p.alignment = GHOST_ALIGNED;
} else {
p.alignment = GHOST_UNALIGNED;
}
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
if (x->traits.flags & GHOST_DENSEMAT_VIEW || v->traits.flags & GHOST_DENSEMAT_VIEW) {
p.unroll = 1;
} else {
p.unroll = GHOST_MAX_ROWS_UNROLL;
}
INFO_LOG("Inital search for kernel dt=%d wcols=%d vcols=%d xstor=%d wstor=%d align=%d unroll=%d!",p.dt,p.wcols,p.vcols,p.xstor,p.wstor,p.alignment,p.unroll);
kernel = kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try plain implementation");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
kernel = kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Decrease unroll size");
while (p.unroll > 1 && !kernel) {
p.unroll /= 2;
kernel = kernels[p];
}
}
if (!kernel) {
PERFWARNING_LOG("Try unaligned kernel");
p.alignment = GHOST_UNALIGNED;
kernel = kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary wcols");
p.wcols = -1;
p.vcols = v->traits.ncols;
kernel = kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary vcols");
p.wcols = w->traits.ncols;
p.vcols = -1;
kernel = kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = kernels[p];
}
if (!kernel) {
INFO_LOG("Could not find TSMTTSM kernel with %d %d %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols,p.xstor,p.wstor);
ret = ghost_gemm(x,v,conjv?"C":"T",w,"N",alpha,beta,reduce,GHOST_GEMM_NOT_SPECIAL);
} else {
ret = kernel(x,v,w,alpha,beta,conjv);
if (reduce != GHOST_GEMM_NO_REDUCE && v->context) {
x->reduce(x,v->context->mpicomm,reduce);
}
}
#ifdef GHOST_HAVE_INSTR_TIMING
ghost_gemm_perf_args_t tsmttsm_perfargs;
tsmttsm_perfargs.n = w->traits.ncols;
tsmttsm_perfargs.m = v->traits.ncols;
if (v->context) {
tsmttsm_perfargs.k = v->context->gnrows;
} else {
tsmttsm_perfargs.k = v->traits.nrows;
}
tsmttsm_perfargs.dt = x->traits.datatype;
tsmttsm_perfargs.betaiszero = ghost_iszero(beta,p.dt);
tsmttsm_perfargs.alphaisone = ghost_isone(alpha,p.dt);
ghost_timing_set_perfFunc(NULL,__ghost_functag,ghost_gemm_perf_GBs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GB/s");
ghost_timing_set_perfFunc(NULL,__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s");
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
|
check alignment of correct densemats
|
check alignment of correct densemats
|
C++
|
bsd-3-clause
|
RRZE-HPC/GHOST,RRZE-HPC/GHOST,RRZE-HPC/GHOST,RRZE-HPC/GHOST
|
33b73d89ac973377572909850613b9a9d894a969
|
Source/core/platform/text/cf/StringImplCF.cpp
|
Source/core/platform/text/cf/StringImplCF.cpp
|
/*
* Copyright (C) 2006, 2009, 2012 Apple Inc. All rights reserved.
*
* 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 "config.h"
#include <wtf/text/StringImpl.h>
#if USE(CF)
#include <CoreFoundation/CoreFoundation.h>
#include <wtf/MainThread.h>
#include <wtf/PassRefPtr.h>
#include <wtf/RetainPtr.h>
#include <wtf/Threading.h>
static inline bool garbageCollectionEnabled()
{
return false;
}
namespace WTF {
namespace StringWrapperCFAllocator {
static StringImpl* currentString;
static const void* retain(const void* info)
{
return info;
}
NO_RETURN_DUE_TO_ASSERT
static void release(const void*)
{
ASSERT_NOT_REACHED();
}
static CFStringRef copyDescription(const void*)
{
return CFSTR("WTF::String-based allocator");
}
static void* allocate(CFIndex size, CFOptionFlags, void*)
{
StringImpl* underlyingString = 0;
if (isMainThread()) {
underlyingString = currentString;
if (underlyingString) {
currentString = 0;
underlyingString->ref(); // Balanced by call to deref in deallocate below.
}
}
StringImpl** header = static_cast<StringImpl**>(fastMalloc(sizeof(StringImpl*) + size));
*header = underlyingString;
return header + 1;
}
static void* reallocate(void* pointer, CFIndex newSize, CFOptionFlags, void*)
{
size_t newAllocationSize = sizeof(StringImpl*) + newSize;
StringImpl** header = static_cast<StringImpl**>(pointer) - 1;
ASSERT(!*header);
header = static_cast<StringImpl**>(fastRealloc(header, newAllocationSize));
return header + 1;
}
static void deallocateOnMainThread(void* headerPointer)
{
StringImpl** header = static_cast<StringImpl**>(headerPointer);
StringImpl* underlyingString = *header;
ASSERT(underlyingString);
underlyingString->deref(); // Balanced by call to ref in allocate above.
fastFree(header);
}
static void deallocate(void* pointer, void*)
{
StringImpl** header = static_cast<StringImpl**>(pointer) - 1;
StringImpl* underlyingString = *header;
if (!underlyingString)
fastFree(header);
else {
if (!isMainThread())
callOnMainThread(deallocateOnMainThread, header);
else {
underlyingString->deref(); // Balanced by call to ref in allocate above.
fastFree(header);
}
}
}
static CFIndex preferredSize(CFIndex size, CFOptionFlags, void*)
{
// FIXME: If FastMalloc provided a "good size" callback, we'd want to use it here.
// Note that this optimization would help performance for strings created with the
// allocator that are mutable, and those typically are only created by callers who
// make a new string using the old string's allocator, such as some of the call
// sites in CFURL.
return size;
}
static CFAllocatorRef create()
{
ASSERT(!garbageCollectionEnabled());
CFAllocatorContext context = { 0, 0, retain, release, copyDescription, allocate, reallocate, deallocate, preferredSize };
return CFAllocatorCreate(0, &context);
}
static CFAllocatorRef allocator()
{
static CFAllocatorRef allocator = create();
return allocator;
}
}
RetainPtr<CFStringRef> StringImpl::createCFString()
{
// Since garbage collection isn't compatible with custom allocators, we
// can't use the NoCopy variants of CFStringCreate*() when GC is enabled.
if (!m_length || !isMainThread() || garbageCollectionEnabled()) {
if (is8Bit())
return adoptCF(CFStringCreateWithBytes(0, reinterpret_cast<const UInt8*>(characters8()), m_length, kCFStringEncodingISOLatin1, false));
return adoptCF(CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(characters16()), m_length));
}
CFAllocatorRef allocator = StringWrapperCFAllocator::allocator();
// Put pointer to the StringImpl in a global so the allocator can store it with the CFString.
ASSERT(!StringWrapperCFAllocator::currentString);
StringWrapperCFAllocator::currentString = this;
CFStringRef string;
if (is8Bit())
string = CFStringCreateWithBytesNoCopy(allocator, reinterpret_cast<const UInt8*>(characters8()), m_length, kCFStringEncodingISOLatin1, false, kCFAllocatorNull);
else
string = CFStringCreateWithCharactersNoCopy(allocator, reinterpret_cast<const UniChar*>(characters16()), m_length, kCFAllocatorNull);
// CoreFoundation might not have to allocate anything, we clear currentString in case we did not execute allocate().
StringWrapperCFAllocator::currentString = 0;
return adoptCF(string);
}
// On StringImpl creation we could check if the allocator is the StringWrapperCFAllocator.
// If it is, then we could find the original StringImpl and just return that. But to
// do that we'd have to compute the offset from CFStringRef to the allocated block;
// the CFStringRef is *not* at the start of an allocated block. Testing shows 1000x
// more calls to createCFString than calls to the create functions with the appropriate
// allocator, so it's probably not urgent optimize that case.
}
#endif // USE(CF)
|
/*
* Copyright (C) 2006, 2009, 2012 Apple Inc. All rights reserved.
*
* 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 "config.h"
#include <wtf/text/StringImpl.h>
#if USE(CF)
#include <CoreFoundation/CoreFoundation.h>
#include <wtf/MainThread.h>
#include <wtf/PassRefPtr.h>
#include <wtf/RetainPtr.h>
#include <wtf/Threading.h>
namespace WTF {
namespace StringWrapperCFAllocator {
static StringImpl* currentString;
static const void* retain(const void* info)
{
return info;
}
NO_RETURN_DUE_TO_ASSERT
static void release(const void*)
{
ASSERT_NOT_REACHED();
}
static CFStringRef copyDescription(const void*)
{
return CFSTR("WTF::String-based allocator");
}
static void* allocate(CFIndex size, CFOptionFlags, void*)
{
StringImpl* underlyingString = 0;
if (isMainThread()) {
underlyingString = currentString;
if (underlyingString) {
currentString = 0;
underlyingString->ref(); // Balanced by call to deref in deallocate below.
}
}
StringImpl** header = static_cast<StringImpl**>(fastMalloc(sizeof(StringImpl*) + size));
*header = underlyingString;
return header + 1;
}
static void* reallocate(void* pointer, CFIndex newSize, CFOptionFlags, void*)
{
size_t newAllocationSize = sizeof(StringImpl*) + newSize;
StringImpl** header = static_cast<StringImpl**>(pointer) - 1;
ASSERT(!*header);
header = static_cast<StringImpl**>(fastRealloc(header, newAllocationSize));
return header + 1;
}
static void deallocateOnMainThread(void* headerPointer)
{
StringImpl** header = static_cast<StringImpl**>(headerPointer);
StringImpl* underlyingString = *header;
ASSERT(underlyingString);
underlyingString->deref(); // Balanced by call to ref in allocate above.
fastFree(header);
}
static void deallocate(void* pointer, void*)
{
StringImpl** header = static_cast<StringImpl**>(pointer) - 1;
StringImpl* underlyingString = *header;
if (!underlyingString)
fastFree(header);
else {
if (!isMainThread())
callOnMainThread(deallocateOnMainThread, header);
else {
underlyingString->deref(); // Balanced by call to ref in allocate above.
fastFree(header);
}
}
}
static CFIndex preferredSize(CFIndex size, CFOptionFlags, void*)
{
// FIXME: If FastMalloc provided a "good size" callback, we'd want to use it here.
// Note that this optimization would help performance for strings created with the
// allocator that are mutable, and those typically are only created by callers who
// make a new string using the old string's allocator, such as some of the call
// sites in CFURL.
return size;
}
static CFAllocatorRef create()
{
CFAllocatorContext context = { 0, 0, retain, release, copyDescription, allocate, reallocate, deallocate, preferredSize };
return CFAllocatorCreate(0, &context);
}
static CFAllocatorRef allocator()
{
static CFAllocatorRef allocator = create();
return allocator;
}
}
RetainPtr<CFStringRef> StringImpl::createCFString()
{
// Since garbage collection isn't compatible with custom allocators, we
// can't use the NoCopy variants of CFStringCreate*() when GC is enabled.
if (!m_length || !isMainThread()) {
if (is8Bit())
return adoptCF(CFStringCreateWithBytes(0, reinterpret_cast<const UInt8*>(characters8()), m_length, kCFStringEncodingISOLatin1, false));
return adoptCF(CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(characters16()), m_length));
}
CFAllocatorRef allocator = StringWrapperCFAllocator::allocator();
// Put pointer to the StringImpl in a global so the allocator can store it with the CFString.
ASSERT(!StringWrapperCFAllocator::currentString);
StringWrapperCFAllocator::currentString = this;
CFStringRef string;
if (is8Bit())
string = CFStringCreateWithBytesNoCopy(allocator, reinterpret_cast<const UInt8*>(characters8()), m_length, kCFStringEncodingISOLatin1, false, kCFAllocatorNull);
else
string = CFStringCreateWithCharactersNoCopy(allocator, reinterpret_cast<const UniChar*>(characters16()), m_length, kCFAllocatorNull);
// CoreFoundation might not have to allocate anything, we clear currentString in case we did not execute allocate().
StringWrapperCFAllocator::currentString = 0;
return adoptCF(string);
}
// On StringImpl creation we could check if the allocator is the StringWrapperCFAllocator.
// If it is, then we could find the original StringImpl and just return that. But to
// do that we'd have to compute the offset from CFStringRef to the allocated block;
// the CFStringRef is *not* at the start of an allocated block. Testing shows 1000x
// more calls to createCFString than calls to the create functions with the appropriate
// allocator, so it's probably not urgent optimize that case.
}
#endif // USE(CF)
|
Remove garbageCollectionEnabled
|
Remove garbageCollectionEnabled
Chromium never compiles with Cocoa GC turned on and this function was left
from Webkit which had a real check for GC, now this function just returns false
so we can remove it.
Review URL: https://chromiumcodereview.appspot.com/14829002
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@149629 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.