hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8202a2d19ed1893d8b732124980ab260f9c8a3bb
6,251
cpp
C++
tests/unit_tests/boundaries/test_distributed_boundaries.cpp
tehrengruber/gridtools
92bbbf65174d440c28a33babffde41b46ed943de
[ "BSD-3-Clause" ]
null
null
null
tests/unit_tests/boundaries/test_distributed_boundaries.cpp
tehrengruber/gridtools
92bbbf65174d440c28a33babffde41b46ed943de
[ "BSD-3-Clause" ]
null
null
null
tests/unit_tests/boundaries/test_distributed_boundaries.cpp
tehrengruber/gridtools
92bbbf65174d440c28a33babffde41b46ed943de
[ "BSD-3-Clause" ]
null
null
null
/* * GridTools * * Copyright (c) 2014-2019, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause */ #include <gridtools/boundaries/distributed_boundaries.hpp> #include <functional> #include <gtest/gtest.h> #include <mpi.h> #include <gridtools/boundaries/comm_traits.hpp> #include <gridtools/boundaries/copy.hpp> #include <gridtools/boundaries/value.hpp> #include <gridtools/storage/builder.hpp> #include <gcl_select.hpp> #include <multiplet.hpp> #include <storage_select.hpp> #include <timer_select.hpp> using namespace gridtools; using namespace boundaries; using namespace std::placeholders; constexpr int halo_size = 2; constexpr int d1 = 6; constexpr int d2 = 7; constexpr int d3 = 2; const auto builder = storage::builder<storage_traits_t>.type<triplet>().halos(2, 2, 0).dimensions(d1, d2, d3); using storage_t = decltype(builder()); using testee_t = distributed_boundaries<comm_traits<storage_t, gcl_arch_t, timer_impl_t>>; const auto halos = []() { auto storage = builder(); array<halo_descriptor, 3> res; auto lengths = storage->lengths(); auto total_lengths = make_total_lengths(*storage); return array<halo_descriptor, 3>{{{halo_size, halo_size, halo_size, lengths[0] - halo_size - 1, total_lengths[0]}, {halo_size, halo_size, halo_size, lengths[1] - halo_size - 1, total_lengths[1]}, {0, 0, 0, lengths[2] - 1, total_lengths[2]}}}; }(); // Returns the relative coordinates of a neighbor processor given the dimensions of a storage int region(int index, int size) { return index < halo_size ? -1 : index >= size - halo_size ? 1 : 0; } bool from_core(int i, int j) { return region(i, d1) == 0 and region(j, d2) == 0; } struct distributed_boundaries_test : testing::Test { testee_t testee; int pi, pj, pk; int PI, PJ, PK; storage_t a; storage_t b; storage_t c; storage_t d; using expected_t = std::function<triplet(int, int, int)>; expected_t expected_a; expected_t expected_b; expected_t expected_d; distributed_boundaries_test() : testee(halos, {false, false, false}, 3, [] { int dims[3] = {}; MPI_Dims_create(gcl::procs(), 3, dims); int period[3] = {1, 1, 1}; MPI_Comm res; MPI_Cart_create(gcl::world(), 3, dims, period, false, &res); return res; }()) { testee.proc_grid().coords(pi, pj, pk); testee.proc_grid().dims(PI, PJ, PK); a = builder.initializer([=](int i, int j, int k) { return from_core(i, j) ? a_init(i, j, k) : triplet{}; })(); b = builder.initializer([=](int i, int j, int k) { return from_core(i, j) ? b_init(i, j, k) : triplet{}; })(); c = builder.initializer([=](int i, int j, int k) { return c_init(i, j, k); })(); d = builder.initializer([=](int i, int j, int k) { return from_core(i, j) ? d_init(i, j, k) : triplet{}; })(); } void expect_a(expected_t f) { expected_a = f; } void expect_b(expected_t f) { expected_b = f; } void expect_d(expected_t f) { expected_d = f; } ~distributed_boundaries_test() { for (int i = 0; i < d1; ++i) for (int j = 0; j < d2; ++j) for (int k = 0; k < d3; ++k) { if (expected_a) { EXPECT_EQ(a->host_view()(i, j, k), expected_a(i, j, k)) << gcl::pid() << ": " << i << ", " << j << ", " << k; } if (expected_b) { EXPECT_EQ(b->host_view()(i, j, k), expected_b(i, j, k)) << gcl::pid() << ": " << i << ", " << j << ", " << k; } if (expected_d) { EXPECT_EQ(d->host_view()(i, j, k), expected_d(i, j, k)) << gcl::pid() << ": " << i << ", " << j << ", " << k; } } } triplet a_init(int i, int j, int k) { return {i + pi * (d1 - 2 * halo_size) + 100, j + pj * (d2 - 2 * halo_size) + 100, k + pk * (d3 - 2 * halo_size) + 100}; } triplet b_init(int i, int j, int k) const { return {i + pi * (d1 - 2 * halo_size) + 1000, j + pj * (d2 - 2 * halo_size) + 1000, k + pk * (d3 - 2 * halo_size) + 1000}; } triplet c_init(int i, int j, int k) const { return {i + pi * (d1 - 2 * halo_size) + 10000, j + pj * (d2 - 2 * halo_size) + 10000, k + pk * (d3 - 2 * halo_size) + 10000}; } triplet d_init(int i, int j, int k) const { return {i + pi * (d1 - 2 * halo_size) + 100000, j + pj * (d2 - 2 * halo_size) + 100000, k + pk * (d3 - 2 * halo_size) + 100000}; } bool from_abroad(int i, int j) const { return (i + pi * d1 < halo_size or j + pj * d2 < halo_size or i + pi * d1 >= PI * d1 - halo_size or j + pj * d2 >= PJ * d2 - halo_size) and testee.proc_grid().proc(region(i, d1), region(j, d2), 0) == -1; } }; TEST_F(distributed_boundaries_test, boundary_only) { testee.boundary_only( bind_bc(value_boundary<triplet>(triplet{42, 42, 42}), a), bind_bc(copy_boundary(), b, _1).associate(c), d); expect_a([&](int i, int j, int k) { return from_core(i, j) ? a_init(i, j, k) : from_abroad(i, j) ? triplet{42, 42, 42} : triplet{}; }); expect_b([&](int i, int j, int k) { return from_core(i, j) ? b_init(i, j, k) : from_abroad(i, j) ? c_init(i, j, k) : triplet{}; }); expect_d([&](int i, int j, int k) { return from_core(i, j) ? d_init(i, j, k) : triplet{}; }); } TEST_F(distributed_boundaries_test, exchange) { testee.exchange( bind_bc(value_boundary<triplet>(triplet{42, 42, 42}), a), bind_bc(copy_boundary(), b, _1).associate(c), d); expect_a([&](int i, int j, int k) { return from_abroad(i, j) ? triplet{42, 42, 42} : a_init(i, j, k); }); expect_b([&](int i, int j, int k) { return from_abroad(i, j) ? c_init(i, j, k) : b_init(i, j, k); }); expect_d([&](int i, int j, int k) { return from_abroad(i, j) ? triplet{} : d_init(i, j, k); }); }
38.115854
118
0.550952
tehrengruber
8208c06db473a046db0f796a9ac38e76ee938c09
6,519
cpp
C++
src/cvkb/vkbinputlayout.cpp
CELLINKAB/qtcvkb
5b870f8ea4b42480eb678b065778de5dab36b199
[ "MIT" ]
null
null
null
src/cvkb/vkbinputlayout.cpp
CELLINKAB/qtcvkb
5b870f8ea4b42480eb678b065778de5dab36b199
[ "MIT" ]
null
null
null
src/cvkb/vkbinputlayout.cpp
CELLINKAB/qtcvkb
5b870f8ea4b42480eb678b065778de5dab36b199
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (C) 2020 CELLINK AB <info@cellink.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "vkbinputlayout.h" #include <QtCore/qdebug.h> #include <QtCore/qfile.h> #include <QtCore/qjsonarray.h> #include <QtCore/qjsondocument.h> #include <QtCore/qjsonobject.h> #include <QtCore/qmetaobject.h> #include <cmath> static const QString Key = QStringLiteral("key"); static const QString Text = QStringLiteral("text"); static const QString Alt = QStringLiteral("alt"); static const QString Span = QStringLiteral("span"); static const QString AutoRepeat = QStringLiteral("autoRepeat"); static const QString Checkable = QStringLiteral("checkable"); static const QString Checked = QStringLiteral("checked"); class VkbInputLayoutPrivate : public QSharedData { public: int maxColumns = 0; QVector<QVector<VkbInputKey>> layout; }; VkbInputLayout::VkbInputLayout() : d_ptr(new VkbInputLayoutPrivate) { } VkbInputLayout::VkbInputLayout(const QVector<VkbInputKey> &row) : d_ptr(new VkbInputLayoutPrivate) { addRow(row); } VkbInputLayout::VkbInputLayout(const VkbInputLayout &other) : d_ptr(other.d_ptr) { } VkbInputLayout::~VkbInputLayout() { } VkbInputLayout &VkbInputLayout::operator=(const VkbInputLayout &other) { d_ptr = other.d_ptr; return *this; } bool VkbInputLayout::operator==(const VkbInputLayout &other) const { return d_ptr == other.d_ptr; } bool VkbInputLayout::operator!=(const VkbInputLayout &other) const { return !(*this == other); } bool VkbInputLayout::isEmpty() const { Q_D(const VkbInputLayout); return d->layout.isEmpty(); } int VkbInputLayout::rowCount() const { Q_D(const VkbInputLayout); return d->layout.count(); } int VkbInputLayout::columnCount() const { Q_D(const VkbInputLayout); return d->maxColumns; } QVector<VkbInputKey> VkbInputLayout::rowAt(int row) const { Q_D(const VkbInputLayout); return d->layout.value(row); } void VkbInputLayout::addRow(const QVector<VkbInputKey> &row) { Q_D(VkbInputLayout); insertRow(d->layout.count(), row); } void VkbInputLayout::insertRow(int index, const QVector<VkbInputKey> &row) { Q_D(VkbInputLayout); d->layout.insert(index, row); d->maxColumns = std::max(row.count(), d->maxColumns); } VkbInputKey VkbInputLayout::keyAt(int row, int column) const { Q_D(const VkbInputLayout); return d->layout.value(row).value(column); } void VkbInputLayout::setKey(int row, int column, const VkbInputKey &key) { Q_D(VkbInputLayout); d->layout[row][column] = key; } VkbInputKey VkbInputLayout::findKey(Qt::Key key, const QString &text) const { Q_D(const VkbInputLayout); for (const QVector<VkbInputKey> &row : d->layout) { for (const VkbInputKey &inputKey : row) { if (inputKey.key == key || (!text.isEmpty() && inputKey.text == text)) return inputKey; } } return VkbInputKey(); } // ### TODO: add QJsonArray::toStringList() static QStringList toStringList(const QJsonArray &array) { QStringList strings; strings.reserve(array.size()); for (const QJsonValue &value : array) strings += value.toString(); return strings; } static QString capitalize(const QString &text) { Q_ASSERT(!text.isEmpty()); return text.front().toUpper() + text.mid(1); } static QString formatKey(const QString &key) { return QStringLiteral("Key_") + capitalize(key); } static Qt::Key parseKeyCode(const QString &key) { if (key.isEmpty()) return Qt::Key_unknown; const QMetaEnum metaEnum = QMetaEnum::fromType<Qt::Key>(); bool ok = false; int value = metaEnum.keyToValue(formatKey(key).toLatin1(), &ok); if (!ok) return Qt::Key_unknown; return static_cast<Qt::Key>(value); } static VkbInputKey parseKey(const QJsonObject &json) { VkbInputKey key; key.key = parseKeyCode(json.value(Key).toString()); key.text = json.value(Text).toString(); key.alt = toStringList(json.value(Alt).toArray()); key.span = json.value(Span).toDouble(1); key.autoRepeat = json.value(AutoRepeat).toBool(); key.checkable = json.value(Checkable).toBool(); key.checked = json.value(Checked).toBool(); return key; } static QVector<VkbInputKey> parseRow(const QJsonArray &json, int &maxColumns) { QVector<VkbInputKey> keys; for (const QJsonValue &value : json) keys += parseKey(value.toObject()); maxColumns = std::max(keys.count(), maxColumns); return keys; } static QVector<QVector<VkbInputKey>> parseLayout(const QJsonArray &json, int &maxColumns) { QVector<QVector<VkbInputKey>> layout; for (const QJsonValue &value : json) layout += parseRow(value.toArray(), maxColumns); return layout; } bool VkbInputLayout::load(const QString &filePath) { Q_D(VkbInputLayout); QFile file(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning().nospace().noquote() << "VkbInputLayout::load: error opening " << filePath << ": " << file.errorString(); return false; } QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error); if (error.error != QJsonParseError::NoError) { qWarning().nospace().noquote() << "VkbInputLayout::load: error parsing " << filePath << ": " << error.errorString(); return false; } d->maxColumns = 0; d->layout = parseLayout(doc.array(), d->maxColumns); return true; }
28.343478
124
0.700414
CELLINKAB
8209e2ef8491b4ce3bb1b7c65433a0643530ec5b
8,396
cpp
C++
modules/ti.UI/win32/win32_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
3
2016-03-15T23:50:35.000Z
2016-05-09T09:36:10.000Z
modules/ti.UI/win32/win32_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
null
null
null
modules/ti.UI/win32/win32_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
null
null
null
/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include "win32_menu_item_impl.h" #include <windows.h> #include <shellapi.h> #include "../ui_module.h" #define STUB() printf("Method is still a stub, %s:%i\n", __FILE__, __LINE__) namespace ti { int Win32MenuItemImpl::currentUID = TI_MENU_ITEM_ID_BEGIN + 1; HMENU Win32MenuItemImpl::defaultContextMenu = NULL; static int webInspectorMenuItemID = 0; std::vector<Win32MenuItemImpl::NativeMenuItem *> itemsWithCallbacks; Win32MenuItemImpl::Win32MenuItemImpl(Win32MenuItemImpl* _parent) : parent(_parent) { } Win32MenuItemImpl::~Win32MenuItemImpl() { } void Win32MenuItemImpl::SetParent(Win32MenuItemImpl* parent) { this->parent = parent; } Win32MenuItemImpl* Win32MenuItemImpl::GetParent() { return this->parent; } SharedValue Win32MenuItemImpl::AddSeparator() { Win32MenuItemImpl* item = new Win32MenuItemImpl(this); item->MakeSeparator(); this->children.push_back(item); return MenuItem::AddToListModel(item); } SharedValue Win32MenuItemImpl::AddItem(SharedValue label, SharedValue callback, SharedValue icon_url) { Win32MenuItemImpl* item = new Win32MenuItemImpl(this); item->MakeItem(label, callback, icon_url); this->children.push_back(item); return MenuItem::AddToListModel(item); } SharedValue Win32MenuItemImpl::AddSubMenu(SharedValue label, SharedValue icon_url) { Win32MenuItemImpl* item = new Win32MenuItemImpl(this); item->MakeSubMenu(label, icon_url); this->children.push_back(item); return MenuItem::AddToListModel(item); } HMENU Win32MenuItemImpl::GetDefaultContextMenu() { if(Host::GetInstance()->IsDebugMode() && defaultContextMenu == NULL) { defaultContextMenu = CreatePopupMenu(); RealizeWebInspectorMenuItem(defaultContextMenu); } return defaultContextMenu; } HMENU Win32MenuItemImpl::GetMenu() { if (this->parent == NULL) // top-level { NativeMenuItem* menu_item = this->Realize(NULL, false); // add web inspector menu item if needed if(Host::GetInstance()->IsDebugMode()) { this->RealizeWebInspectorMenuItem(menu_item->menu); } return menu_item->menu; } else { // For now we do not support using a submenu as a menu, // as that makes determining parent-child relationships // really hard, so just return NULL and check above. return NULL; } } HMENU Win32MenuItemImpl::GetMenuBar() { if (this->parent == NULL) // top level { NativeMenuItem* menu_item = this->Realize(NULL, true); return menu_item->menu; } else { // For now we do not support using a submenu as a menu, // as that makes determining parent-child relationships // really hard, so just return NULL and check above. return NULL; } } void Win32MenuItemImpl::ClearRealization(HMENU parent_menu) { if(parent_menu == NULL) { // nothing to do return; } std::vector<NativeMenuItem*>::iterator i; // Find the instance which is contained in parent_menu or, // if we are the root, find the instance which uses this // menu to contain it's children. for (i = this->instances.begin(); i != this->instances.end(); i++) { if ((*i)->parent_menu == parent_menu || (this->parent == NULL && (*i)->menu == parent_menu)) break; } // Could not find an instance which uses the menu. if (i == this->instances.end()) return; // Erase all children which use // the sub-menu as their parent. std::vector<Win32MenuItemImpl*>::iterator c; for (c = this->children.begin(); c != this->children.end(); c++) { (*c)->ClearRealization((*i)->menu); } this->instances.erase(i); // Erase the instance } Win32MenuItemImpl::NativeMenuItem* Win32MenuItemImpl::Realize(NativeMenuItem* parent_menu_item, bool is_menu_bar) { NativeMenuItem* menu_item = this->MakeNativeMenuItem(parent_menu_item, is_menu_bar); /* Realize this widget's children */ if (this->IsSubMenu() || this->parent == NULL) { std::vector<Win32MenuItemImpl*>::iterator i = this->children.begin(); while (i != this->children.end()) { NativeMenuItem* child_menu_item = (*i)->Realize(menu_item, false); i++; } } this->instances.push_back(menu_item); return menu_item; } /*static*/ void Win32MenuItemImpl::RealizeWebInspectorMenuItem(HMENU hMenu) { if(webInspectorMenuItemID == 0) { webInspectorMenuItemID = nextMenuUID(); } if(GetMenuItemCount(hMenu) > 0) { AppendMenu(hMenu, MF_SEPARATOR, 1, "Separator"); } std::string label("Show Inspector"); AppendMenu(hMenu, MF_STRING, webInspectorMenuItemID, (LPCTSTR) label.c_str()); } // this method creates the native menu objects for *this* menu item Win32MenuItemImpl::NativeMenuItem* Win32MenuItemImpl::MakeNativeMenuItem(NativeMenuItem* parent_menu_item, bool is_menu_bar) { NativeMenuItem* menu_item = new NativeMenuItem(); if(parent_menu_item) { menu_item->parent_menu = parent_menu_item->menu; } const char* label = this->GetLabel(); const char* iconUrl = this->GetIconURL(); SharedString iconPath = UIModule::GetResourcePath(iconUrl); SharedValue callbackVal = this->RawGet("callback"); if (this->parent == NULL) // top-level { if (is_menu_bar) menu_item->menu = CreateMenu(); else menu_item->menu = CreatePopupMenu(); } else if(this->IsSeparator()) { AppendMenu(menu_item->parent_menu, MF_SEPARATOR, 1, "Separator"); } else if(this->IsItem()) { menu_item->menuItemID = nextMenuUID(); AppendMenu(menu_item->parent_menu, MF_STRING, menu_item->menuItemID, (LPCTSTR) label); if (callbackVal->IsMethod()) { menu_item->callback = callbackVal->ToMethod(); itemsWithCallbacks.push_back(menu_item); } } else if(this->IsSubMenu()) { menu_item->menu = CreatePopupMenu(); AppendMenu(menu_item->parent_menu, MF_STRING | MF_POPUP, (UINT_PTR) menu_item->menu, (LPCTSTR) label); } else { throw ValueException::FromString("Unknown menu item type requested"); } return menu_item; } SharedValue Win32MenuItemImpl::GetIconPath(const char *url) { STUB(); return NULL; } void Win32MenuItemImpl::Enable() { STUB(); } void Win32MenuItemImpl::Disable() { STUB(); } void Win32MenuItemImpl::SetLabel(std::string label) { if(! this->parent || this->IsSeparator()) { // top level menu doesn't have a label return; } std::vector<NativeMenuItem*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { NativeMenuItem* menu_item = (*i); if (menu_item != NULL) { this->SetLabel(label, menu_item); } i++; } } void Win32MenuItemImpl::SetLabel(std::string label, NativeMenuItem* menu_item) { // TODO after modifying the menu, we need to call DrawMenuBar() on the window that contains this menu if(menu_item->menu) { // this is a sub menu ModifyMenu(menu_item->parent_menu, (UINT_PTR) menu_item->menu, MF_POPUP | MF_STRING, (UINT_PTR) menu_item->menu, label.c_str()); } else { // this is a menu item ModifyMenu(menu_item->parent_menu, menu_item->menuItemID, MF_BYCOMMAND | MF_STRING, menu_item->menuItemID, label.c_str()); } } void Win32MenuItemImpl::SetIcon(std::string icon_path) { STUB(); } /*static*/ bool Win32MenuItemImpl::invokeCallback(int menuItemUID) { for(size_t i = 0; i < itemsWithCallbacks.size(); i++) { Win32MenuItemImpl::NativeMenuItem* item = itemsWithCallbacks[i]; if(item->menuItemID == menuItemUID) { BoundMethod* cb = (BoundMethod*) item->callback; // TODO: Handle exceptions in some way try { ValueList args; cb->Call(args); } catch(...) { std::cout << "Menu callback failed" << std::endl; } return true; } } return false; } /*static*/ LRESULT CALLBACK Win32MenuItemImpl::handleMenuClick(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if(message == WM_COMMAND) { int wmId = LOWORD(wParam); if(wmId == webInspectorMenuItemID) { Win32UserWindow *wuw = Win32UserWindow::FromWindow(hWnd); if(wuw) { wuw->ShowWebInspector(); return true; } else { return false; } } else { return invokeCallback(wmId); } } return FALSE; } }
23.452514
131
0.685565
pjunior
820a94cb0e53991069651071f1be3a9c7f31b118
8,309
cpp
C++
src/Molassembler/RankingInformation.cpp
Dom1L/molassembler
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
[ "BSD-3-Clause" ]
null
null
null
src/Molassembler/RankingInformation.cpp
Dom1L/molassembler
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
[ "BSD-3-Clause" ]
null
null
null
src/Molassembler/RankingInformation.cpp
Dom1L/molassembler
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
[ "BSD-3-Clause" ]
null
null
null
/*!@file * @copyright This code is licensed under the 3-clause BSD license. * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group. * See LICENSE.txt for details. */ #include "Molassembler/RankingInformation.h" #include "Molassembler/Temple/Adaptors/Zip.h" #include "Molassembler/Temple/Functional.h" #include "Molassembler/Temple/TinySet.h" #include "Molassembler/Temple/Poset.h" #include "Molassembler/Cycles.h" namespace Scine { namespace Molassembler { RankingInformation::Link::Link() = default; RankingInformation::Link::Link( std::pair<SiteIndex, SiteIndex> siteIndices, std::vector<AtomIndex> sequence, const AtomIndex source ) { /* Fix degrees of freedom of the underlying information so we can * efficiently implement operator <. sites can be an ordered pair: */ sites = std::move(siteIndices); if(sites.first == sites.second) { throw std::runtime_error("Link site indices are identical!"); } if(sites.first > sites.second) { std::swap(sites.first, sites.second); } // The cycle sequence should be centralized on the source vertex cycleSequence = centralizeRingIndexSequence(std::move(sequence), source); /* After centralization, the source vertex is first. We need to fix the * remaining degree of freedom, which is if that the cycle sequence in * between can be reversed. We choose to fix it by making it ascending if * there are at least three vertices in the sequence between the second and * second-to-last vertices */ if( cycleSequence.size() >= 3 && cycleSequence.at(1) > cycleSequence.back() ) { // Reverse is [first, last), and cycleSequence is a vector, so: std::reverse( std::begin(cycleSequence) + 1, std::end(cycleSequence) ); } } void RankingInformation::Link::applyPermutation(const std::vector<AtomIndex>& permutation) { // A link's site indices do not change, but the sequence does for(AtomIndex& atomIndex : cycleSequence) { atomIndex = permutation.at(atomIndex); } // Conditional reverse of the sequence now depends on the new vertex indices if( cycleSequence.size() >= 3 && cycleSequence.at(1) > cycleSequence.back() ) { // Reverse is [first, last), and cycleSequence is a vector, so: std::reverse( std::begin(cycleSequence) + 1, std::end(cycleSequence) ); } } bool RankingInformation::Link::operator == (const Link& other) const { return std::tie(sites, cycleSequence) == std::tie(other.sites, other.cycleSequence); } bool RankingInformation::Link::operator != (const Link& other) const { return !(*this == other); } bool RankingInformation::Link::operator < (const Link& other) const { return std::tie(sites, cycleSequence) < std::tie(other.sites, other.cycleSequence); } std::vector<unsigned> RankingInformation::siteConstitutingAtomsRankedPositions( const std::vector<AtomIndex>& siteAtomList, const RankingInformation::RankedSubstituentsType& substituentRanking ) { auto positionIndices = Temple::map( siteAtomList, [&substituentRanking](AtomIndex constitutingIndex) -> unsigned { return Temple::find_if( substituentRanking, [&constitutingIndex](const auto& equalPrioritySet) -> bool { return Temple::find(equalPrioritySet, constitutingIndex) != std::end(equalPrioritySet); } ) - std::begin(substituentRanking); } ); std::sort( std::begin(positionIndices), std::end(positionIndices), std::greater<> {} ); return positionIndices; } RankingInformation::RankedSitesType RankingInformation::rankSites( const SiteListType& sites, const RankedSubstituentsType& substituentRanking ) { const unsigned sitesSize = sites.size(); Temple::Poset<SiteIndex> siteIndexPoset {Temple::iota<SiteIndex>(sitesSize)}; // Order by site size siteIndexPoset.orderUnordered( [&](const SiteIndex i, const SiteIndex j) -> bool { return sites.at(i).size() < sites.at(j).size(); } ); // Then sub-order by ranked positions of their site constituting atoms siteIndexPoset.orderUnordered( [&](const SiteIndex i, const SiteIndex j) -> bool { return ( siteConstitutingAtomsRankedPositions(sites.at(i), substituentRanking) < siteConstitutingAtomsRankedPositions(sites.at(j), substituentRanking) ); } ); return siteIndexPoset.extract(); } void RankingInformation::applyPermutation(const std::vector<AtomIndex>& permutation) { // .substituentRanking is mapped by applying the vertex permutation for(auto& group : substituentRanking) { for(AtomIndex& atomIndex : group) { atomIndex = permutation.at(atomIndex); } } // .sites too for(auto& group : sites) { for(AtomIndex& atomIndex : group) { atomIndex = permutation.at(atomIndex); } } // .siteRanking is unchanged as it is index based into .sites // .links do have to be mapped, though for(Link& link : links) { link.applyPermutation(permutation); } // Sort links to re-establish ordering std::sort( std::begin(links), std::end(links) ); } SiteIndex RankingInformation::getSiteIndexOf(const AtomIndex i) const { // Find the atom index i within the set of ligand definitions auto findIter = Temple::find_if( sites, [&](const auto& siteAtomList) -> bool { return Temple::any_of( siteAtomList, [&](const AtomIndex siteConstitutingIndex) -> bool { return siteConstitutingIndex == i; } ); } ); if(findIter == std::end(sites)) { throw std::out_of_range("Specified atom index is not part of any ligand"); } const unsigned idx = findIter - std::begin(sites); return SiteIndex(idx); } unsigned RankingInformation::getRankedIndexOfSite(const SiteIndex i) const { auto findIter = Temple::find_if( siteRanking, [&](const auto& equallyRankedSiteIndices) -> bool { return Temple::any_of( equallyRankedSiteIndices, [&](const unsigned siteIndex) -> bool { return siteIndex == i; } ); } ); if(findIter == std::end(siteRanking)) { throw std::out_of_range("Specified ligand index is not ranked."); } return findIter - std::begin(siteRanking); } bool RankingInformation::hasHapticSites() const { return Temple::any_of( sites, [](const auto& siteAtomList) -> bool { return siteAtomList.size() > 1; } ); } bool RankingInformation::operator == (const RankingInformation& other) const { /* This is a nontrivial operator since there is some degree of freedom in how * sites are chosen */ // Check all sizes if( substituentRanking.size() != other.substituentRanking.size() || sites.size() != other.sites.size() || siteRanking.size() != other.siteRanking.size() || links.size() != other.links.size() ) { return false; } // substituentRanking can be compared lexicographically if(substituentRanking != other.substituentRanking) { return false; } // Combined comparison of siteRanking with sites if( !Temple::all_of( Temple::Adaptors::zip( siteRanking, other.siteRanking ), [&]( const auto& thisEqualSiteGroup, const auto& otherEqualSiteGroup ) -> bool { Temple::TinyUnorderedSet<AtomIndex> thisSiteGroupVertices; for(const auto siteIndex : thisEqualSiteGroup) { for(const auto siteConstitutingIndex : sites.at(siteIndex)) { thisSiteGroupVertices.insert(siteConstitutingIndex); } } for(const auto siteIndex : otherEqualSiteGroup) { for(const auto siteConstitutingIndex : other.sites.at(siteIndex)) { if(thisSiteGroupVertices.count(siteConstitutingIndex) == 0) { return false; } } } return true; } ) ) { return false; } // Compare the links (these should be kept sorted throughout execution) assert(std::is_sorted(std::begin(links), std::end(links))); assert(std::is_sorted(std::begin(other.links), std::end(other.links))); return links == other.links; } bool RankingInformation::operator != (const RankingInformation& other) const { return !(*this == other); } } // namespace Molassembler } // namespace Scine
28.95122
97
0.676134
Dom1L
820e23ceb531d3721628e697aaad19e291464065
35,418
tpp
C++
src/hypro/representations/TaylorModel/TaylorModel.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
22
2016-10-05T12:19:01.000Z
2022-01-23T09:14:41.000Z
src/hypro/representations/TaylorModel/TaylorModel.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
23
2017-05-08T15:02:39.000Z
2021-11-03T16:43:39.000Z
src/hypro/representations/TaylorModel/TaylorModel.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
12
2017-06-07T23:51:09.000Z
2022-01-04T13:06:21.000Z
/* * TaylorModel.cpp * * Created on: Sep 8, 2014 * Author: chen */ #include "TaylorModel.h" namespace hypro { template <typename Number> TaylorModel<Number>::TaylorModel() { carl::Interval<Number> intZero( 0 ); remainder = intZero; } template <typename Number> TaylorModel<Number>::~TaylorModel() { } template <typename Number> TaylorModel<Number>::TaylorModel( const MultivariatePolynomial<carl::Interval<Number>> &p, const carl::Interval<Number> &r ) { expansion = p; remainder = r; } template <typename Number> TaylorModel<Number>::TaylorModel( const MultivariatePolynomial<carl::Interval<Number>> &p ) { expansion = p; carl::Interval<Number> intZero( 0 ); remainder = intZero; } template <typename Number> TaylorModel<Number>::TaylorModel( const carl::Interval<Number> &I ) { MultivariatePolynomial<carl::Interval<Number>> p( I ); expansion = p; carl::Interval<Number> intZero( 0 ); remainder = intZero; } template <typename Number> TaylorModel<Number>::TaylorModel( const TaylorModel<Number> &tm ) { expansion = tm.expansion; remainder = tm.remainder; } template <typename Number> TaylorModel<Number>::TaylorModel( const std::initializer_list<Term<carl::Interval<Number>>> &terms ) { MultivariatePolynomial<carl::Interval<Number>> p( terms ); expansion = p; carl::Interval<Number> intZero( 0 ); remainder = intZero; } template <typename Number> TaylorModel<Number>::TaylorModel( const std::initializer_list<Term<carl::Interval<Number>>> &terms, const carl::Interval<Number> &r ) { MultivariatePolynomial<carl::Interval<Number>> p( terms ); expansion = p; remainder = r; } template <typename Number> TaylorModel<Number>::TaylorModel( const Term<carl::Interval<Number>> &term ) { MultivariatePolynomial<carl::Interval<Number>> p( term ); expansion = p; carl::Interval<Number> intZero( 0 ); remainder = intZero; } template <typename Number> TaylorModel<Number>::TaylorModel( carl::Variable::Arg v ) { MultivariatePolynomial<carl::Interval<Number>> p( v ); expansion = p; carl::Interval<Number> intZero( 0 ); remainder = intZero; } /* template<typename Coeff, typename Number> TaylorModel<Coeff, Number>::TaylorModel(const Monomial & m) { MultivariatePolynomial<Coeff> p(m); expansion = p; carl::Interval<Number> intZero(0); remainder = intZero; } template<typename Coeff, typename Number> TaylorModel<Coeff, Number>::TaylorModel(std::shared_ptr<const Monomial> m) { MultivariatePolynomial<Coeff> p(m); expansion = p; } template<typename Number> TaylorModel<Number>::TaylorModel(std::shared_ptr<const Term<carl::Interval<Number>> > t) { MultivariatePolynomial<carl::Interval<Number>> p(t); expansion = p; carl::Interval<Number> intZero(0); remainder = intZero; } template<typename Coeff, typename Number> TaylorModel<Coeff, Number>::TaylorModel(const std::initializer_list<carl::Variable> & terms) { MultivariatePolynomial<Coeff> p(terms); expansion = p; carl::Interval<Number> intZero(0); remainder = intZero; } */ template <typename Number> bool TaylorModel<Number>::isZero() const { carl::Interval<Number> intZero( 0 ); return ( expansion.isZero() && remainder == intZero ); } template <typename Number> bool TaylorModel<Number>::isConstant() const { return expansion.isConstant(); } template <typename Number> bool TaylorModel<Number>::isLinear() const { return expansion.isLinear(); } template <typename Number> carl::Interval<Number> TaylorModel<Number>::rmConstantTerm() { TermsType &vTerms = expansion.getTerms(); auto iter = vTerms.begin(); carl::Interval<Number> constant( 0 ); if ( ( *iter ).tdeg() == 0 ) { constant = ( *iter ).coeff(); vTerms.erase( iter ); } return constant; } template <typename Number> exponent TaylorModel<Number>::tmOrder() const { return expansion.totalDegree(); } template <typename Number> TaylorModel<Number> TaylorModel<Number>::pow( unsigned exp, Domain<Number> &domain, const exponent order ) const { carl::Interval<Number> intZero( 0 ), intOne( 1 ); if ( exp == 0 ) return TaylorModel( intOne ); if ( isZero() ) return TaylorModel( intZero ); TaylorModel<Number> res( intOne ); TaylorModel<Number> mult( *this ); while ( exp > 0 ) { if ( exp & 1 ) { res.multiply_assign( mult, domain, order ); } exp /= 2; if ( exp > 0 ) { mult.multiply_assign( mult, domain, order ); } } return res; } template <typename Number> void TaylorModel<Number>::cutoff( const carl::Interval<Number> &threshold, Domain<Number> &domain ) { TermsType &vTerms = expansion.getTerms(); typename TermsType::iterator term = vTerms.begin(); for ( ; term != vTerms.end(); ) { MultivariatePolynomial<carl::Interval<Number>> p( *term ); std::map<carl::Variable, carl::Interval<Number>> &d = domain.get_assignments(); carl::Interval<Number> intTemp = p.evaluate( d ); if ( threshold.contains( intTemp ) ) { term = vTerms.erase( term ); remainder += intTemp; } else { ++term; } } } template <typename Number> void TaylorModel<Number>::cutoff_nr( const carl::Interval<Number> &threshold, Domain<Number> &domain ) { TermsType &vTerms = expansion.getTerms(); typename TermsType::iterator term = vTerms.begin(); for ( ; term != vTerms.end(); ) { MultivariatePolynomial<carl::Interval<Number>> p( *term ); std::map<carl::Variable, carl::Interval<Number>> &d = domain.get_assignments(); carl::Interval<Number> intTemp = p.evaluate( d ); if ( threshold.contains( intTemp ) ) { term = vTerms.erase( term ); } else { ++term; } } } template <typename Number> void TaylorModel<Number>::truncation( const exponent order, Domain<Number> &domain ) { TermsType truncated_terms; TermsType &vTerms = expansion.getTerms(); expansion.makeOrdered(); for ( ; vTerms.size() > 0; ) { auto iter = vTerms.end(); --iter; if ( ( *iter ).tdeg() > order ) { truncated_terms.insert( truncated_terms.begin(), vTerms.back() ); vTerms.pop_back(); } else { break; } } MultivariatePolynomial<carl::Interval<Number>> p; TermsType &vTerms2 = p.getTerms(); vTerms2 = truncated_terms; carl::Interval<Number> I; std::map<carl::Variable, carl::Interval<Number>> &d = domain.get_assignments(); I = p.evaluate( d ); remainder += I; } template <typename Number> void TaylorModel<Number>::truncation_nr( const exponent order ) { TermsType &vTerms = expansion.getTerms(); expansion.makeOrdered(); for ( ; vTerms.size() > 0; ) { auto iter = vTerms.end(); --iter; if ( ( *iter ).tdeg() > order ) { vTerms.pop_back(); } else { break; } } } template <typename Number> void TaylorModel<Number>::enclosure( carl::Interval<Number> &I, Domain<Number> &domain ) const { std::map<carl::Variable, carl::Interval<Number>> &d = domain.get_assignments(); I = expansion.evaluate( d ); I += remainder; } template <typename Number> void TaylorModel<Number>::poly_enclosure( carl::Interval<Number> &I, Domain<Number> &domain ) const { std::map<carl::Variable, carl::Interval<Number>> &d = domain.get_assignments(); I = expansion.evaluate( d ); } template <typename Number> void TaylorModel<Number>::normalize( Domain<Number> &domain ) { carl::Interval<Number> intZero( 0 ); std::map<carl::Variable, TaylorModel<Number>> substitutions; std::map<carl::Variable, carl::Interval<Number>> &assignments = domain.get_assignments(); for ( auto iter = assignments.begin(); iter != assignments.end(); ++iter ) { Number center = iter->second.center(); carl::Interval<Number> intCenter( center ); TaylorModel tmCenter( intCenter ); carl::Interval<Number> intTemp = iter->second - intCenter; Number magnitude = intTemp.magnitude(); carl::Interval<Number> intMagnitude( magnitude ); TaylorModel<Number> tmReplace( {(Term<carl::Interval<Number>>)intCenter, (carl::Interval<Number>)intMagnitude * ( iter->first )}, intZero ); std::pair<const carl::Variable, TaylorModel<Number>> replacement( iter->first, tmReplace ); substitutions.insert( replacement ); } *this = this->substitute( substitutions, domain, this->tmOrder() ); } template <typename Number> TaylorModel<Number> &TaylorModel<Number>::operator=( const TaylorModel<Number> &tm ) { if ( this == &tm ) return *this; expansion = tm.expansion; remainder = tm.remainder; return *this; } template <typename Number> TaylorModel<Number> &TaylorModel<Number>::operator+=( const TaylorModel<Number> &tm ) { expansion += tm.expansion; remainder += tm.remainder; return *this; } template <typename Number> TaylorModel<Number> &TaylorModel<Number>::operator-=( const TaylorModel<Number> &tm ) { expansion -= tm.expansion; remainder -= tm.remainder; return *this; } template <typename Number> const TaylorModel<Number> TaylorModel<Number>::operator+( const TaylorModel<Number> &tm ) const { TaylorModel<Number> result = *this; result += tm; return result; } template <typename Number> const TaylorModel<Number> TaylorModel<Number>::operator-( const TaylorModel<Number> &tm ) const { TaylorModel<Number> result = *this; result -= tm; return result; } template <typename Number> TaylorModel<Number> TaylorModel<Number>::multiply( const carl::Interval<Number> &I ) const { TaylorModel<Number> result; result.expansion = expansion * I; result.remainder = remainder * I; return result; } template <typename Number> TaylorModel<Number> TaylorModel<Number>::multiply( const TaylorModel<Number> &tm, Domain<Number> &domain, const exponent order ) const { TaylorModel<Number> result; result.expansion = expansion * tm.expansion; carl::Interval<Number> enclosure_tm1, enclosure_tm2; poly_enclosure( enclosure_tm1, domain ); tm.poly_enclosure( enclosure_tm2, domain ); enclosure_tm1 *= tm.remainder; enclosure_tm2 *= remainder; result.remainder = remainder * tm.remainder + enclosure_tm1 + enclosure_tm2; result.truncation( order, domain ); return result; } template <typename Number> TaylorModel<Number> TaylorModel<Number>::multiply( const Term<carl::Interval<Number>> &term, Domain<Number> &domain, const exponent order ) const { TaylorModel<Number> result, tm( term ); result.expansion = expansion * tm.expansion; carl::Interval<Number> enclosure_tm1, enclosure_tm2; poly_enclosure( enclosure_tm1, domain ); tm.poly_enclosure( enclosure_tm2, domain ); enclosure_tm1 *= tm.remainder; enclosure_tm2 *= remainder; result.remainder = remainder * tm.remainder + enclosure_tm1 + enclosure_tm2; result.truncation( order, domain ); return result; } template <typename Number> TaylorModel<Number> TaylorModel<Number>::multiply( carl::Variable::Arg v, Domain<Number> &domain, const exponent order ) const { TaylorModel<Number> result, tm( v ); result.expansion = expansion * tm.expansion; carl::Interval<Number> enclosure_tm1, enclosure_tm2; poly_enclosure( enclosure_tm1, domain ); tm.poly_enclosure( enclosure_tm2, domain ); enclosure_tm1 *= tm.remainder; enclosure_tm2 *= remainder; result.remainder = remainder * tm.remainder + enclosure_tm1 + enclosure_tm2; result.truncation( order, domain ); return result; } template <typename Number> void TaylorModel<Number>::multiply_assign( const carl::Interval<Number> &I ) { expansion *= I; remainder *= I; } template <typename Number> void TaylorModel<Number>::multiply_assign( const TaylorModel<Number> &tm, Domain<Number> &domain, const exponent order ) { TaylorModel<Number> result; result.expansion = expansion * tm.expansion; carl::Interval<Number> enclosure_tm1, enclosure_tm2; poly_enclosure( enclosure_tm1, domain ); tm.poly_enclosure( enclosure_tm2, domain ); enclosure_tm1 *= tm.remainder; enclosure_tm2 *= remainder; result.remainder = remainder * tm.remainder + enclosure_tm1 + enclosure_tm2; result.truncation( order, domain ); *this = result; } template <typename Number> void TaylorModel<Number>::multiply_assign( const Term<carl::Interval<Number>> &term, Domain<Number> &domain, const exponent order ) { TaylorModel<Number> result, tm( term ); result.expansion = expansion * tm.expansion; carl::Interval<Number> enclosure_tm1, enclosure_tm2; poly_enclosure( enclosure_tm1, domain ); tm.poly_enclosure( enclosure_tm2, domain ); enclosure_tm1 *= tm.remainder; enclosure_tm2 *= remainder; result.remainder = remainder * tm.remainder + enclosure_tm1 + enclosure_tm2; result.truncation( order, domain ); *this = result; } template <typename Number> void TaylorModel<Number>::multiply_assign( carl::Variable::Arg v, Domain<Number> &domain, const exponent order ) { TaylorModel<Number> result, tm( v ); result.expansion = expansion * tm.expansion; carl::Interval<Number> enclosure_tm1, enclosure_tm2; poly_enclosure( enclosure_tm1, domain ); tm.poly_enclosure( enclosure_tm2, domain ); enclosure_tm1 *= tm.remainder; enclosure_tm2 *= remainder; result.remainder = remainder * tm.remainder + enclosure_tm1 + enclosure_tm2; result.truncation( order, domain ); *this = result; } template <typename Number> TaylorModel<Number> TaylorModel<Number>::div( const carl::Interval<Number> &I ) const { TaylorModel<Number> result; carl::Interval<Number> intTemp( 1.0 ); intTemp = intTemp / I; result.expansion = expansion * intTemp; result.remainder = remainder * intTemp; return result; } template <typename Number> void TaylorModel<Number>::div_assign( const carl::Interval<Number> &I ) { carl::Interval<Number> intTemp( 1.0 ); intTemp = intTemp / I; expansion *= intTemp; remainder *= intTemp; } template <typename Number> TaylorModel<Number> TaylorModel<Number>::substitute( const std::map<carl::Variable, TaylorModel<Number>> &substitutions, Domain<Number> &domain, const exponent order ) const { TaylorModel<Number> result( *this ); if ( isConstant() || substitutions.empty() ) { return result; } MultivariatePolynomial<carl::Interval<Number>> polyZero; // Substitute the variables, which have to be replaced by 0, beforehand, // as this could significantly simplify this multivariate polynomial. for ( auto sub = substitutions.begin(); sub != substitutions.end(); ++sub ) { if ( sub->second.isZero() ) { result.expansion.substituteIn( sub->first, polyZero ); if ( result.isConstant() ) { return result; } } } TermsType &mTerms = result.expansion.getTerms(); carl::Interval<Number> intOne( 1 ); TaylorModel<Number> tmOne( intOne ); // Find and sort all exponents occurring for all variables to substitute as // basis. std::map<std::pair<carl::Variable, exponent>, TaylorModel<Number>> expResults; for ( auto term : mTerms ) { if ( term.monomial() ) { const Monomial &m = *( term.monomial() ); for ( unsigned i = 0; i < m.nrVariables(); ++i ) { if ( m[i].second > 1 && substitutions.find( m[i].first ) != substitutions.end() ) { expResults[m[i]] = tmOne; } } } } // Calculate the exponentiation of the multivariate polynomial to substitute // the // for variables for, reusing the already calculated exponentiations. if ( !expResults.empty() ) { auto expResultA = expResults.begin(); auto expResultB = expResultA; auto sub = substitutions.begin(); while ( sub->first != expResultB->first.first ) { assert( sub != substitutions.end() ); ++sub; } expResultB->second = sub->second.pow( expResultB->first.second, domain, order ); ++expResultB; while ( expResultB != expResults.end() ) { if ( expResultA->first.first != expResultB->first.first ) { ++sub; assert( sub != substitutions.end() ); // Go to the next variable. while ( sub->second.isZero() ) { assert( sub != substitutions.end() ); ++sub; } expResultB->second = sub->second.pow( expResultB->first.second, domain, order ); } else { TaylorModel<Number> tmTemp = sub->second.pow( expResultB->first.second - expResultA->first.second, domain, order ); expResultB->second = expResultA->second.multiply( tmTemp, domain, order ); } ++expResultA; ++expResultB; } } carl::Interval<Number> intZero( 0 ); TaylorModel<Number> resultB; // Substitute the variable for which all occurring exponentiations are // calculated. for ( auto term : mTerms ) { TaylorModel<Number> termResult( term.coeff() ); if ( term.monomial() ) { const Monomial &m = *( term.monomial() ); for ( unsigned i = 0; i < m.nrVariables(); ++i ) { if ( m[i].second == 1 ) { auto iter = substitutions.find( m[i].first ); if ( iter != substitutions.end() ) { termResult.multiply_assign( iter->second, domain, order ); } else { termResult.multiply_assign( m[i].first, domain, order ); } } else { auto iter = expResults.find( m[i] ); if ( iter != expResults.end() ) { termResult.multiply_assign( iter->second, domain, order ); } else { termResult.multiply_assign( Term<carl::Interval<Number>>( intOne, m[i].first, m[i].second ), domain, order ); } } } } resultB += termResult; } resultB.remainder += remainder; return resultB; } template <typename Number> TaylorModel<Number> TaylorModel<Number>::substitute( const TaylorModelVec<Number> &substitutions, Domain<Number> &domain, const exponent order ) const { return substitute( substitutions.tms, domain, order ); } template <typename Number> TaylorModel<Number> TaylorModel<Number>::derivative( carl::Variable::Arg v, unsigned nth ) const { TaylorModel<Number> result; result.expansion = this->expansion.derivative( v, nth ); carl::Interval<Number> intZero( 0 ); result.remainder = intZero; return result; } template <typename Number> void TaylorModel<Number>::derivative_assign( carl::Variable::Arg v, unsigned nth ) { expansion = expansion.derivative( v, nth ); carl::Interval<Number> intZero( 0 ); remainder = intZero; } template <typename Number> TaylorModel<Number> TaylorModel<Number>::integration( carl::Variable::Arg v, const carl::Interval<Number> &range_of_v ) { TaylorModel<Number> result; if ( !expansion.has( v ) ) { result.expansion = expansion * v; result.remainder = remainder * range_of_v; return result; } else { TermsType &mTerms = expansion.getTerms(); for ( auto term : mTerms ) { Term<carl::Interval<Number>> newTerm( term ); MonomialType monomial = newTerm.monomial(); if ( monomial == NULL ) { newTerm *= v; } else { exponent d = monomial->exponentOfVariable( v ); if ( d > 0 ) { carl::Interval<Number> intTemp( (double)d + 1 ), intOne( 1 ); intTemp = intOne / intTemp; newTerm *= intTemp; } newTerm *= v; } result.expansion += newTerm; } result.remainder = remainder * range_of_v; } return result; // Todo: Inserted by Stefan, Xin - please check if okay! } template <typename Number> void TaylorModel<Number>::integration_assign( carl::Variable::Arg v, const carl::Interval<Number> &range_of_v ) { *this = integration( v, range_of_v ); } template <typename Number> TaylorModel<Number> TaylorModel<Number>::LieDerivative( const PolynomialODE<Number> &ode ) const { std::set<carl::Variable> vars; expansion.gatherVariables( vars ); TaylorModel<Number> result; std::set<carl::Variable>::iterator iter = vars.begin(); for ( ; iter != vars.end(); ++iter ) { MultivariatePolynomial<carl::Interval<Number>> rhs; bool bFound = ode.find_assignment( rhs, *iter ); if ( bFound ) { MultivariatePolynomial<carl::Interval<Number>> polyTemp = expansion.derivative( *iter ); polyTemp *= rhs; result.expansion += polyTemp; } else { assert( !bFound ); } } vars.clear(); return result; } template <typename Number> void TaylorModel<Number>::LieDerivative_assign( const PolynomialODE<Number> &ode ) { *this = LieDerivative( ode ); } template <typename Number> void TaylorModel<Number>::checkConsistency() const { expansion.checkConsistency(); } template <typename Number> bool TaylorModel<Number>::has( carl::Variable::Arg v ) const { return expansion.has( v ); } template <typename N> std::ostream &operator<<( std::ostream &os, const TaylorModel<N> &tm ) { return os << tm.expansion << '+' << tm.remainder; } template <typename Number> Domain<Number>::Domain() { } template <typename Number> Domain<Number>::~Domain() { assignments.clear(); } template <typename Number> Domain<Number>::Domain( const Domain<Number> &domain ) { assignments = domain.assignments; } template <typename Number> void Domain<Number>::assign( const carl::Variable &v, const carl::Interval<Number> &I ) { auto iter = assignments.find( v ); assignment_type assignment( v, I ); if ( iter == assignments.end() ) { assignments.insert( assignment ); } else { assignments.erase( iter ); assignments.insert( assignment ); } } template <typename Number> bool Domain<Number>::find_assignment( carl::Interval<Number> &I, const carl::Variable &v ) const { auto iter = assignments.find( v ); if ( iter == assignments.end() ) { return false; } else { I = iter->second; return true; } } template <typename Number> std::map<carl::Variable, carl::Interval<Number>> &Domain<Number>::get_assignments() { return assignments; } template <typename Number> void Domain<Number>::clear() { assignments.clear(); } template <typename Number> Domain<Number> &Domain<Number>::operator=( const Domain<Number> &domain ) { if ( this == &domain ) return *this; assignments = domain.assignments; return *this; } template <typename N> std::ostream &operator<<( std::ostream &os, const Domain<N> &domain ) { for ( auto iter = domain.assignments.begin(); iter != domain.assignments.end(); ++iter ) { os << iter->first << " in " << iter->second << std::endl; } return os; } template <typename Number> PolynomialODE<Number>::PolynomialODE() { } template <typename Number> PolynomialODE<Number>::PolynomialODE( const PolynomialODE<Number> &ode ) { assignments = ode.assignments; } template <typename Number> PolynomialODE<Number>::~PolynomialODE() { assignments.clear(); } template <typename Number> void PolynomialODE<Number>::assign( const carl::Variable &v, const MultivariatePolynomial<carl::Interval<Number>> &rhs ) { auto iter = assignments.find( v ); assignment_type assignment( v, rhs ); if ( iter == assignments.end() ) { assignments.insert( assignment ); } else { iter->second = rhs; } } template <typename Number> bool PolynomialODE<Number>::find_assignment( MultivariatePolynomial<carl::Interval<Number>> &rhs, const carl::Variable &v ) const { auto iter = assignments.find( v ); if ( iter == assignments.end() ) { return false; } else { rhs = iter->second; return true; } } template <typename Number> std::map<carl::Variable, MultivariatePolynomial<carl::Interval<Number>>> &PolynomialODE<Number>::get_assignments() { return assignments; } template <typename Number> PolynomialODE<Number> &PolynomialODE<Number>::operator=( const PolynomialODE<Number> &ode ) { if ( this == &ode ) return *this; assignments = ode.assignments; return *this; } template <typename N> std::ostream &operator<<( std::ostream &os, const PolynomialODE<N> &ode ) { for ( auto iter = ode.assignments.begin(); iter != ode.assignments.end(); ++iter ) { os << iter->first << '\'' << " = " << iter->second << std::endl; } os << std::endl; return os; } template <typename Number> Range<Number>::Range() { } template <typename Number> Range<Number>::~Range() { assignments.clear(); } template <typename Number> Range<Number>::Range( const Range<Number> &range ) { assignments = range.assignments; } template <typename Number> void Range<Number>::assign( const carl::Variable &v, const carl::Interval<Number> &I ) { auto iter = assignments.find( v ); assignment_type assignment( v, I ); if ( iter == assignments.end() ) { assignments.insert( assignment ); } else { assignments.erase( iter ); assignments.insert( assignment ); } } template <typename Number> bool Range<Number>::find_assignment( carl::Interval<Number> &I, const carl::Variable &v ) const { auto iter = assignments.find( v ); if ( iter == assignments.end() ) { return false; } else { I = iter->second; return true; } } template <typename Number> std::map<carl::Variable, carl::Interval<Number>> &Range<Number>::get_assignments() { return assignments; } template <typename Number> void Range<Number>::clear() { assignments.clear(); } template <typename Number> Range<Number> &Range<Number>::operator=( const Range<Number> &range ) { if ( this == &range ) return *this; assignments = range.assignments; return *this; } template <typename N> std::ostream &operator<<( std::ostream &os, const Range<N> &range ) { for ( auto iter = range.assignments.begin(); iter != range.assignments.end(); ++iter ) { os << iter->first << " in " << iter->second << std::endl; } return os; } template <typename Number> TaylorModelVec<Number>::TaylorModelVec() { } template <typename Number> TaylorModelVec<Number>::TaylorModelVec( const std::map<carl::Variable, TaylorModel<Number>> &assignments ) { tms = assignments; } template <typename Number> TaylorModelVec<Number>::TaylorModelVec( Range<Number> &range ) { std::map<carl::Variable, carl::Interval<Number>> &assignments = range.get_assignments(); for ( auto iter = assignments.begin(); iter != assignments.end(); ++iter ) { TaylorModel<Number> tmTemp( iter->second ); assignment_type assignment( iter->first, tmTemp ); tms.insert( assignment ); } } template <typename Number> TaylorModelVec<Number>::TaylorModelVec( const TaylorModelVec &tmv ) { tms = tmv.tms; } template <typename Number> TaylorModelVec<Number>::~TaylorModelVec() { } template <typename Number> void TaylorModelVec<Number>::assign( const carl::Variable &v, const TaylorModel<Number> &tm ) { auto iter = tms.find( v ); assignment_type assignment( v, tm ); if ( iter == tms.end() ) { tms.insert( assignment ); } else { iter->second = tm; } } template <typename Number> bool TaylorModelVec<Number>::find_assignment( TaylorModel<Number> &tm, const carl::Variable &v ) const { auto iter = tms.find( v ); if ( iter == tms.end() ) { return false; } else { tm = iter->second; return true; } } template <typename Number> bool TaylorModelVec<Number>::isEmpty() const { if ( tms.size() == 0 ) { return true; } else { return false; } } template <typename Number> void TaylorModelVec<Number>::clear() { tms.clear(); } template <typename Number> void TaylorModelVec<Number>::rmConstantTerm( Range<Number> &constant ) { constant.clear(); for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { carl::Interval<Number> intTemp; intTemp = iter->second.rmConstantTerm(); constant.assign( iter->first, intTemp ); } } template <typename Number> void TaylorModelVec<Number>::cutoff( const carl::Interval<Number> &threshold, Domain<Number> &domain ) { for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { iter->second.cutoff( threshold, domain ); } } template <typename Number> void TaylorModelVec<Number>::cutoff_nr( const carl::Interval<Number> &threshold, Domain<Number> &domain ) { for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { iter->second.cutoff_nr( threshold, domain ); } } template <typename Number> void TaylorModelVec<Number>::truncation( const exponent order, Domain<Number> &domain ) { for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { iter->second.truncation( order, domain ); } } template <typename Number> void TaylorModelVec<Number>::truncation_nr( const exponent order ) { for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { iter->second.truncation_nr( order ); } } template <typename Number> void TaylorModelVec<Number>::enclosure( Range<Number> &range, Domain<Number> &domain ) const { range.clear(); for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { carl::Interval<Number> I; iter->second.enclosure( I, domain ); range.assign( iter->first, I ); } } template <typename Number> TaylorModelVec<Number> &TaylorModelVec<Number>::operator=( const TaylorModelVec<Number> &tmv ) { if ( this == &tmv ) return *this; tms = tmv.tms; return *this; } template <typename Number> TaylorModelVec<Number> &TaylorModelVec<Number>::operator+=( const TaylorModelVec<Number> &tmv ) { if ( tms.size() != tmv.tms.size() ) { std::cout << "operator +: Dimensions of the operands are not equivalent." << std::endl; return *this; } TaylorModelVec<Number> tmvTemp = *this; auto iter1 = tmvTemp.tms.begin(); auto iter2 = tmv.tms.begin(); for ( ; iter1 != tmvTemp.tms.end() && iter2 != tmv.tms.end(); ++iter1, ++iter2 ) { if ( iter1->first != iter2->first ) { std::cout << "operator +: Taylor models in different spaces." << std::endl; return *this; } else { iter1->second += iter2->second; } } *this = tmvTemp; return *this; } template <typename Number> TaylorModelVec<Number> &TaylorModelVec<Number>::operator-=( const TaylorModelVec<Number> &tmv ) { if ( tms.size() != tmv.tms.size() ) { std::cout << "operator +: Dimensions of the operands are not equivalent." << std::endl; return *this; } TaylorModelVec<Number> tmvTemp = *this; auto iter1 = tmvTemp.tms.begin(); auto iter2 = tmv.tms.begin(); for ( ; iter1 != tmvTemp.tms.end() && iter2 != tmv.tms.end(); ++iter1, ++iter2 ) { if ( iter1->first != iter2->first ) { std::cout << "operator +: Taylor models in different spaces." << std::endl; return *this; } else { iter1->second -= iter2->second; } } *this = tmvTemp; return *this; } template <typename Number> const TaylorModelVec<Number> TaylorModelVec<Number>::operator+( const TaylorModelVec<Number> &tmv ) const { if ( tms.size() != tmv.tms.size() ) { std::cout << "operator +: Dimensions of the operands are not equivalent." << std::endl; return *this; } TaylorModelVec<Number> result = *this; auto iter1 = result.tms.begin(); auto iter2 = tmv.tms.begin(); for ( ; iter1 != result.tms.end() && iter2 != tmv.tms.end(); ++iter1, ++iter2 ) { if ( iter1->first != iter2->first ) { std::cout << "operator +: Taylor models in different spaces." << std::endl; return *this; } else { iter1->second += iter2->second; } } return result; } template <typename Number> const TaylorModelVec<Number> TaylorModelVec<Number>::operator-( const TaylorModelVec<Number> &tmv ) const { if ( tms.size() != tmv.tms.size() ) { std::cout << "operator +: Dimensions of the operands are not equivalent." << std::endl; return *this; } TaylorModelVec<Number> result = *this; auto iter1 = result.tms.begin(); auto iter2 = tmv.tms.begin(); for ( ; iter1 != result.tms.end() && iter2 != tmv.tms.end(); ++iter1, ++iter2 ) { if ( iter1->first != iter2->first ) { std::cout << "operator +: Taylor models in different spaces." << std::endl; return *this; } else { iter1->second -= iter2->second; } } return result; } template <typename Number> TaylorModelVec<Number> TaylorModelVec<Number>::substitute( const std::map<carl::Variable, TaylorModel<Number>> &substitutions, Domain<Number> &domain, const exponent order ) const { TaylorModelVec<Number> result; for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { TaylorModel<Number> tmTemp; tmTemp = iter->second.substitute( substitutions, domain, order ); result.assign( iter->first, tmTemp ); } return result; } template <typename Number> TaylorModelVec<Number> TaylorModelVec<Number>::substitute( const TaylorModelVec<Number> &substitutions, Domain<Number> &domain, const exponent order ) const { TaylorModelVec<Number> result; for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { TaylorModel<Number> tmTemp; tmTemp = iter->second.substitute( substitutions, domain, order ); result.assign( iter->first, tmTemp ); } return result; } template <typename Number> TaylorModelVec<Number> TaylorModelVec<Number>::derivative( carl::Variable::Arg v, unsigned nth ) const { TaylorModelVec<Number> result; for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { TaylorModel<Number> tmTemp; tmTemp = iter->second.derivative( v, nth ); result.assign( iter->first, tmTemp ); } return result; } template <typename Number> void TaylorModelVec<Number>::derivative_assign( carl::Variable::Arg v, unsigned nth ) { for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { iter->second.derivative_assign( v, nth ); } } template <typename Number> TaylorModelVec<Number> TaylorModelVec<Number>::LieDerivative( const PolynomialODE<Number> &ode ) const { TaylorModelVec<Number> result; for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { TaylorModel<Number> tmTemp; tmTemp = iter->second.LieDerivative( ode ); result.assign( iter->first, tmTemp ); } return result; } template <typename Number> void TaylorModelVec<Number>::LieDerivative_assign( const PolynomialODE<Number> &ode ) { for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { iter->second.LieDerivative_assign( ode ); } } template <typename Number> TaylorModelVec<Number> TaylorModelVec<Number>::integration( carl::Variable::Arg v, const carl::Interval<Number> &range_of_v ) { TaylorModelVec<Number> result; for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { TaylorModel<Number> tmTemp; tmTemp = iter->second.integration( v, range_of_v ); result.assign( iter->first, tmTemp ); } return result; } template <typename Number> void TaylorModelVec<Number>::integration_assign( carl::Variable::Arg v, const carl::Interval<Number> &range_of_v ) { for ( auto iter = tms.begin(); iter != tms.end(); ++iter ) { iter->second.integration_assign( v, range_of_v ); } } template <typename Number> TaylorModelVec<Number> TaylorModelVec<Number>::Picard( const TaylorModelVec<Number> &x0, const PolynomialODE<Number> &ode, Domain<Number> &domain, carl::Variable::Arg t, const carl::Interval<Number> &range_of_t, const exponent order ) const { TaylorModelVec<Number> tmvTemp; for ( auto iter = ode.assignments.begin(); iter != ode.assignments.end(); ++iter ) { TaylorModel<Number> tmODE( iter->second ), tmTemp; tmTemp = tmODE.substitute( tms, domain, order ); tmvTemp.assign( iter->first, tmTemp ); } tmvTemp.integration_assign( t, range_of_t ); tmvTemp.truncation( order, domain ); tmvTemp += x0; return tmvTemp; } template <typename Number> void TaylorModelVec<Number>::Picard_assign( const TaylorModelVec<Number> &x0, const PolynomialODE<Number> &ode, Domain<Number> &domain, carl::Variable::Arg t, const carl::Interval<Number> &range_of_t, const exponent order ) { TaylorModelVec<Number> tmvTemp; for ( auto iter = ode.assignments.begin(); iter != ode.assignments.end(); ++iter ) { TaylorModel<Number> tmODE( iter->second ), tmTemp; tmTemp = tmODE.substitute( tms, domain, order ); tmvTemp.assign( iter->first, tmTemp ); } tmvTemp.integration_assign( t, range_of_t ); tmvTemp.truncation( order, domain ); tmvTemp += x0; *this = tmvTemp; } template <typename N> std::ostream &operator<<( std::ostream &os, const TaylorModelVec<N> &tmv ) { for ( auto iter = tmv.tms.begin(); iter != tmv.tms.end(); ++iter ) { os << iter->first << " = " << iter->second << std::endl; } os << std::endl; return os; } } // namespace hypro
26.372301
131
0.689085
hypro
8213c2610908d184cec52c29641ea2d98cf43bc6
40,322
cpp
C++
fallen/DDLibrary/Source/MFX_Miles.cpp
inco1/MuckyFoot-UrbanChaos
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
[ "MIT" ]
188
2017-05-20T03:26:33.000Z
2022-03-10T16:58:39.000Z
fallen/DDLibrary/Source/MFX_Miles.cpp
dizzy2003/MuckyFoot-UrbanChaos
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
[ "MIT" ]
7
2017-05-28T14:28:13.000Z
2022-01-09T01:47:38.000Z
fallen/DDLibrary/Source/MFX_Miles.cpp
inco1/MuckyFoot-UrbanChaos
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
[ "MIT" ]
43
2017-05-20T07:31:32.000Z
2022-03-09T18:39:35.000Z
#if 0 // MFX_Miles.cpp // // Miles Sound System // Making it asynchronous: // // 1. Keep everything the same. vptr->smp points to sample, sptr->dptr points to data, only "pending" is marked for sample // 2. When IO completes, go through voices and trigger/modify according to data in vptr #define ASYNC_FILE_IO 1 #define TALK_3D 0 #include "snd_type.h" #include "c:\fallen\headers\demo.h" #include "MFX.h" #include "MFX_Miles.h" #include "c:\fallen\headers\fc.h" #include "c:\fallen\headers\env.h" #include "c:\fallen\headers\xlat_str.h" #include "c:\fallen\headers\demo.h" #include "c:\fallen\ddengine\headers\poly.h" #include "resource.h" #ifndef TARGET_DC #include <cmath> #endif #include "drive.h" #if ASYNC_FILE_IO #include "asyncfile2.h" #endif #ifdef DODGYPSXIFY BOOL dodgy_psx_mode=0; #endif #ifdef NO_SOUND // // GET NO_SOUND COMPILING! // SLONG MFX_QUICK_play(char *c, SLONG a, SLONG b, SLONG d) { return 0; } void MilesTerm(void) { return; } #endif #ifdef M_SOUND #define COORDINATE_UNITS float(1.0 / 256.0) // 1 tile ~= 1 meter HDIGDRIVER drv = NULL; static MFX_Voice Voices[MAX_VOICE]; static MFX_QWave QWaves[MAX_QWAVE]; static MFX_QWave* QFree; // first free queue elt. (NEVER NULL - we waste one element) static MFX_QWave* QFreeLast; // last free queue elt. static MFX_Sample Samples[MAX_SAMPLE]; static MFX_Sample TalkSample; // for talk static int NumSamples; static MFX_Sample LRU; // sentinel for LRU dllist static MFX_3D Providers[MAX_PROVIDER]; static MFX_3D FallbackProvider; static int CurProvider; static int IsEAX; static int NumProviders; static HPROVIDER Provider = NULL; static H3DPOBJECT Listener = NULL; static H3DPOBJECT FallbackListener = NULL; static UBYTE DoMilesDialog = 1; static const float MinDist = 512; // min distance for 3D provider static const float MaxDist = (64 << 8); // max distance for 3D provider static float Gain2D = 1.0; // gain for 2D voices static float LX,LY,LZ; // listener coords static float Volumes[3]; // volumes for each SampleType static int Num3DVoices = 0; static int Max3DVoices = 0; static int AllocatedRAM = 0; static char* PathName(char *fname); static void DumpInfo(); static void InitVoices(); static void LoadWaveFile(MFX_Sample* sptr); static void LoadTalkFile(char* filename); #if ASYNC_FILE_IO static void LoadWaveFileAsync(MFX_Sample* sptr); #endif static void LoadWaveFileFinished(MFX_Sample* sptr); static void UnloadWaveFile(MFX_Sample* sptr); static void UnloadTalkFile(); static void MilesDialog(HINSTANCE hInst, HWND hWnd); static void FinishLoading(MFX_Voice* vptr); static void PlayVoice(MFX_Voice* vptr); static void MoveVoice(MFX_Voice* vptr); static void SetVoiceRate(MFX_Voice* vptr, float mult); static void SetVoiceGain(MFX_Voice* vptr, float gain); extern CBYTE* sound_list[]; //---------------------------------------------------------------------------- // DODGY PSXIFIER (sorry eddie :} ) // // Yeah, sorry is right - why does this mess have to be in my lovely file? // Check out File/New on the VC menu <g> // #ifdef DODGYPSXIFY BOOL dodgy_psx_info_loaded=0; BOOL dodgy_psx_info[1024]; void LoadDodgyPSXInfo() { SLONG i=0; dodgy_psx_info_loaded=1; dodgy_psx_mode=ENV_get_value_number("dodgy_psx_sound",0,"Audio"); if (!dodgy_psx_mode) return; ZeroMemory(dodgy_psx_info,sizeof(dodgy_psx_info)); while (strcmp(sound_list[i],"!")) { dodgy_psx_info[i]=GetPrivateProfileInt("PSXSound",sound_list[i],0,"c:\\fallen\\psxsound.ini"); i++; } } inline BOOL AvailableOnPSX(SLONG i) { if (!dodgy_psx_info_loaded) LoadDodgyPSXInfo(); if (!dodgy_psx_mode) return 1; return dodgy_psx_info[i]; } #define PSXCheck(i) { if (!AvailableOnPSX(i)) return; } #define PSXCheck2(i) { if (!AvailableOnPSX(i)) return 0; } #else #define PSXCheck(i) ; #define PSXCheck2(i) ; #endif //---------------------------------------------------------------------------- // MilesInit // // init the Miles crap void MilesInit(HINSTANCE hInst, HWND hWnd) { if (drv) return; AIL_set_preference(DIG_MIXER_CHANNELS, MAX_VOICE); AIL_set_preference(DIG_DEFAULT_VOLUME, 127); if (!AIL_quick_startup(1,0,44100,16,2)) return; AIL_quick_handles(&drv, NULL, NULL); #if ASYNC_FILE_IO InitAsyncFile(); #endif InitVoices(); // initialize Samples[] LRU.prev_lru = LRU.next_lru = &LRU; AllocatedRAM = 0; NumSamples = 0; CBYTE buf[_MAX_PATH]; CBYTE** names = sound_list; MFX_Sample* sptr = Samples; while (strcmp(names[0], "!")) { sptr->prev_lru = NULL; sptr->next_lru = NULL; sptr->fname = NULL; sptr->dptr = NULL; sptr->is3D = true; sptr->rate = 0; sptr->stream = false; sptr->size = 0; sptr->type = SMP_Effect; sptr->linscale = 1.0; sptr->loading = false; if (stricmp("null.wav", names[0])) { FILE* fd = MF_Fopen(PathName(names[0]), "rb"); if (fd) { sptr->fname = names[0]; sptr->dptr = NULL; if (((!strnicmp(names[0], "music",5))||(!strnicmp(names[0], "generalmusic",12)))&&(!strstr(names[0],"Club1"))&&(!strstr(names[0],"Acid"))) { sptr->is3D = false; sptr->type = SMP_Music; } sptr->rate = 0; sptr->stream = false; fseek(fd, 0, SEEK_END); sptr->size = ftell(fd); MF_Fclose(fd); if (sptr->size > MIN_STREAM_SIZE) { sptr->stream = true; sptr->is3D = false; } // TRACE("FOUND: %s (%s)\n", sptr->fname, PathName(sptr->fname)); } else { TRACE("NOT FOUND: %s (%s)\n", names[0], PathName(names[0])); } } NumSamples++; if (sptr->fname) { int gain = GetPrivateProfileInt("PowerLevels", sptr->fname, 0, "data\\sfx\\powerlvl.ini"); if (gain) { gain *= 4; SetPower(sptr-Samples, float(gain)); TRACE("Setting %s gain to %d dB\n",sptr->fname,gain); } } sptr++; names++; } ASSERT(NumSamples <= MAX_SAMPLE); sptr = &TalkSample; sptr->prev_lru = NULL; sptr->next_lru = NULL; sptr->fname = NULL; sptr->dptr = NULL; sptr->is3D = TALK_3D ? true : false; sptr->rate = 0; sptr->stream = false; sptr->size = 0; sptr->type = SMP_Effect; sptr->linscale = 1.0; sptr->loading = false; // get 3D providers list HPROENUM next = HPROENUM_FIRST; MFX_3D* prov = &Providers[0]; int best = -1; int sbest = 0; FallbackProvider.hnd = NULL; while ((NumProviders < MAX_PROVIDER) && AIL_enumerate_3D_providers(&next, &prov->hnd, &prov->name)) { // try and open this M3DRESULT res = AIL_open_3D_provider(prov->hnd); if (res == M3D_NOERR) { TRACE("Found provider: %s\n", prov->name); AIL_close_3D_provider(prov->hnd); int score; if (!strcmp(prov->name, "Aureal A3D Interactive(TM)")) score = 30; else if (!strcmp(prov->name, "Microsoft DirectSound3D with Creative Labs EAX(TM)")) score = 100; else if (!strcmp(prov->name, "Microsoft DirectSound3D hardware support")) score = 50; else if (!strcmp(prov->name, "Microsoft DirectSound3D software emulation")) score = 20; else if (!strcmp(prov->name, "RSX 3D Audio from RAD Game Tools")) score = 10; else score = 5; if (score > sbest) { best = NumProviders; sbest = score; } if (!strcmp(prov->name, "Miles Fast 2D Positional Audio")) { // store fallback 2D provider FallbackProvider = *prov; } prov++; NumProviders++; } else { TRACE("Can't use provider: %s\n", prov->name); } } CurProvider = best; // create fallback 3D provider if (FallbackProvider.hnd) { if (AIL_open_3D_provider(FallbackProvider.hnd) == M3D_NOERR) { TRACE("Opened fallback provider %s\n", FallbackProvider.name); FallbackListener = AIL_open_3D_listener(FallbackProvider.hnd); } else { TRACE("Couldn't open fallback provider\n"); FallbackProvider.hnd = NULL; } } else { TRACE("No fallback provider\n"); } // read config file DoMilesDialog = ENV_get_value_number("run_sound_dialog", 1, "Audio"); char* str = ENV_get_value_string("3D_sound_driver", "Audio"); if (str) { for (int ii = 0; ii < NumProviders; ii++) { if (!stricmp(Providers[ii].name, str)) CurProvider = ii; } } Volumes[SMP_Ambient] = float(ENV_get_value_number("ambient_volume", 127, "Audio")) / 127; Volumes[SMP_Music] = float(ENV_get_value_number("music_volume", 127, "Audio")) / 127; Volumes[SMP_Effect] = float(ENV_get_value_number("fx_volume", 127, "Audio")) / 127; /* // // WAIT FOR THE GRAPHICS DIALOG BOX TO FINISH OFF INITIALISING US! // // It calls init_my_dialog() and my_dialog_over()... // // // do dialog if (DoMilesDialog) { MilesDialog(hInst, hWnd); ENV_set_value_number("run_sound_dialog", DoMilesDialog, "Audio"); } // set 3D provider Set3DProvider(CurProvider); */ } // MilesTerm // // term the Miles crap void MilesTerm() { if (!drv) return; DumpInfo(); MFX_free_wave_list(); // free waves for (int ii = 0; ii < NumSamples; ii++) { UnloadWaveFile(&Samples[ii]); } NumSamples = 0; UnloadTalkFile(); // free providers & listener Set3DProvider(-1); if (FallbackListener) { AIL_close_3D_listener(FallbackListener); FallbackListener = NULL; } if (FallbackProvider.hnd) { AIL_close_3D_provider(FallbackProvider.hnd); FallbackProvider.hnd = NULL; } AIL_quick_shutdown(); drv = NULL; #if ASYNC_FILE_IO TermAsyncFile(); #endif } // GetMilesDriver // // BinkClient calls this to find the Miles driver for BINK HDIGDRIVER GetMilesDriver() { return drv; } // PathName // // get a sample's full pathname static char* PathName(char* fname) { CBYTE buf[MAX_PATH]; static CBYTE pathname[MAX_PATH]; if (strchr(fname,'-')) // usefully, all the taunts etc have a - in them, and none of the other sounds do... bonus! { CHAR *ptr = strrchr(fname,'\\')+1; sprintf(buf,"talk2\\misc\\%s",ptr); strcpy(pathname, GetSFXPath()); strcat(pathname, buf); return pathname; } else { sprintf(buf, "data\\sfx\\1622\\%s", fname); if (!strnicmp(fname, "music", 5)) { if (!MUSIC_WORLD) MUSIC_WORLD = 1; #ifdef VERSION_DEMO MUSIC_WORLD = 1; #endif buf[19] = '0' + (MUSIC_WORLD / 10); buf[20] = '0' + (MUSIC_WORLD % 10); } } strcpy(pathname, GetSFXPath()); strcat(pathname, buf); return pathname; } // SetLinScale // // set a sample's linear scale void SetLinScale(SLONG wave, float linscale) { if ((wave >= 0) && (wave < NumSamples)) { Samples[wave].linscale = linscale; } } // SetPower // // set a sample's power in dB void SetPower(SLONG wave, float dB) { SetLinScale(wave, float(exp(log(10) * dB / 20))); } // DumpInfo // // dump info about loaded sounds static void DumpInfo() { #ifdef _DEBUG FILE* fd = MF_Fopen("c:\\soundinfo.txt", "w"); if (fd) { int loaded = 0; for (int ii = 0; ii < NumSamples; ii++) { fprintf(fd, "%d : %s : %d K : %s\n", ii, Samples[ii].fname, Samples[ii].size >> 10, Samples[ii].dptr ? "LOADED" : "unloaded"); if (Samples[ii].dptr) loaded++; } fprintf(fd, "-------\nTotal %d samples, (%d loaded = %d K)\n\n", NumSamples, loaded, AllocatedRAM >> 10); fprintf(fd, "LRU queue:\n\n"); for (MFX_Sample* sptr = LRU.next_lru; sptr != &LRU; sptr = sptr->next_lru) { fprintf(fd, "%s (%d)\n", sptr->fname, sptr->usecount); } MF_Fclose(fd); } #endif } // Get3DProviderList // // get the list of providers int Get3DProviderList(MFX_3D** prov) { *prov = &Providers[0]; return NumProviders; } // Get3DProvider // // get the 3D provider int Get3DProvider() { return CurProvider; } // Set3DProvider // // set a provider void Set3DProvider(int ix) { if (!drv) return; if (Listener) { AIL_close_3D_listener(Listener); } Listener = NULL; if (Provider) { MFX_stop(MFX_CHANNEL_ALL, MFX_WAVE_ALL); AIL_close_3D_provider(Provider); } Provider = NULL; if ((ix >= 0) && (ix < NumProviders)) { CurProvider = ix; if (Providers[ix].hnd == FallbackProvider.hnd) { // only use fallback provider IsEAX = false; } else if (AIL_open_3D_provider(Providers[ix].hnd) == M3D_NOERR) { Provider = Providers[ix].hnd; TRACE("Selected 3D provider: %s\n", Providers[ix].name); Listener = AIL_open_3D_listener(Provider); IsEAX = !strcmp(Providers[ix].name, "Microsoft DirectSound3D with Creative Labs EAX(TM)"); } if (IsEAX) { float level = 0.0; AIL_set_3D_provider_preference(Provider, "EAX effect volume", &level); Gain2D = 0.7f; } else { Gain2D = 1.0; } // write to config ENV_set_value_string("3D_sound_driver", Providers[ix].name, "Audio"); } } // InitVoices // // initialize the voices and queue static void InitVoices() { int ii; for (ii = 0; ii < MAX_VOICE; ii++) { Voices[ii].id = 0; Voices[ii].wave = 0; Voices[ii].flags = 0; Voices[ii].x = 0; Voices[ii].y = 0; Voices[ii].z = 0; Voices[ii].thing = NULL; Voices[ii].queue = NULL; Voices[ii].queuesz = 0; Voices[ii].smp = NULL; Voices[ii].h2D = NULL; Voices[ii].h3D = NULL; } for (ii = 0; ii < MAX_QWAVE; ii++) { QWaves[ii].next = &QWaves[ii+1]; } QWaves[ii-1].next = NULL; QFree = &QWaves[0]; QFreeLast = &QWaves[ii-1]; LX = LY = LZ = 0; } // Hash // // hash a channel ID to a voice ID static inline int Hash(UWORD channel_id) { return (channel_id * 37) & VOICE_MSK; } // FindVoice // // find an active voice with the given channel ID and wave # static MFX_Voice* FindVoice(UWORD channel_id, ULONG wave) { int offset = Hash(channel_id); for (int ii = 0; ii < MAX_VOICE; ii++) { int vn = (ii + offset) & VOICE_MSK; if ((Voices[vn].id == channel_id) && (Voices[vn].wave == wave)) return &Voices[vn]; } return NULL; } // FindFirst // // find the first active voice with the given channel ID static MFX_Voice* FindFirst(UWORD channel_id) { int offset = Hash(channel_id); for (int ii = 0; ii < MAX_VOICE; ii++) { int vn = (ii + offset) & VOICE_MSK; if (Voices[vn].id == channel_id) return &Voices[vn]; } return NULL; } // FindNext // // find the next active voice with the same channel ID static MFX_Voice* FindNext(MFX_Voice* vptr) { int offset = Hash(vptr->id); int ii = ((vptr - Voices) - offset) & VOICE_MSK; for (ii++; ii < MAX_VOICE; ii++) { int vn = (ii + offset) & VOICE_MSK; if (Voices[vn].id == vptr->id) return &Voices[vn]; } return NULL; } // FindFree // // find a free voice static MFX_Voice* FindFree(UWORD channel_id) { int offset = Hash(channel_id); for (int ii = 0; ii < MAX_VOICE; ii++) { int vn = (ii + offset) & VOICE_MSK; if (!Voices[vn].smp) return &Voices[vn]; } return NULL; } // FreeVoiceSource // // remove a voice's source static void FreeVoiceSource(MFX_Voice* vptr) { if (vptr->h2D) { vptr->smp->usecount--; AIL_release_sample_handle(vptr->h2D); vptr->h2D = NULL; } if (vptr->h3D) { vptr->smp->usecount--; AIL_release_3D_sample_handle(vptr->h3D); vptr->h3D = NULL; Num3DVoices--; } if (vptr->hStream) { AIL_close_stream(vptr->hStream); vptr->hStream = NULL; } } // FreeVoice // // free a voice up static void FreeVoice(MFX_Voice* vptr) { if (!vptr) return; // remove queue QFreeLast->next = vptr->queue; while (QFreeLast->next) QFreeLast = QFreeLast->next; vptr->queue = NULL; vptr->queuesz = 0; // reset data FreeVoiceSource(vptr); if (vptr->thing) { vptr->thing->Flags &= ~FLAGS_HAS_ATTACHED_SOUND; } vptr->thing = NULL; vptr->flags = 0; vptr->id = 0; vptr->wave = 0; vptr->smp = NULL; } // GetVoiceForWave // // find a voice slot for the wave static MFX_Voice* GetVoiceForWave(UWORD channel_id, ULONG wave, ULONG flags) { // just return a new voice if overlapped if (flags & MFX_OVERLAP) return FindFree(channel_id); MFX_Voice* vptr; if (flags & (MFX_QUEUED | MFX_NEVER_OVERLAP)) { // find first voice on this channel, if any vptr = FindFirst(channel_id); } else { // find voice playing this sample, if any vptr = FindVoice(channel_id, wave); } if (!vptr) { vptr = FindFree(channel_id); } else { // found a voice - return NULL if not queued but never overlapped (else queue) if ((flags & (MFX_NEVER_OVERLAP | MFX_QUEUED)) == MFX_NEVER_OVERLAP) return NULL; } return vptr; } // SetupVoiceTalk // // setup a talking voice static SLONG SetupVoiceTalk(MFX_Voice* vptr, char* filename) { vptr->id = 0; vptr->wave = NumSamples; vptr->flags = 0; vptr->thing = NULL; vptr->queue = NULL; vptr->queuesz = 0; vptr->smp = NULL; vptr->queuesz = 0; vptr->smp = NULL; vptr->playing = false; vptr->ratemult = 1.0; vptr->gain = 1.0; if (!Volumes[SMP_Effect]) return FALSE; LoadTalkFile(filename); if (!TalkSample.dptr) return FALSE; vptr->smp = &TalkSample; FinishLoading(vptr); return TRUE; } // SetupVoice // // setup a voice for playback static void SetupVoice(MFX_Voice* vptr, UWORD channel_id, ULONG wave, ULONG flags) { vptr->id = channel_id; vptr->wave = wave; vptr->flags = flags; vptr->thing = NULL; vptr->queue = NULL; vptr->queuesz = 0; vptr->smp = NULL; vptr->playing = false; vptr->ratemult = 1.0; vptr->gain = 1.0; if (wave >= NumSamples) return; MFX_Sample* sptr = &Samples[wave]; if ((sptr->type!=SMP_Music)&&(GAME_STATE & (GS_LEVEL_LOST|GS_LEVEL_WON))) return ; // once the level's won or lost, no more sounds float level = Volumes[sptr->type]; if (!level) return; if (sptr->stream) { if (!sptr->fname) return; vptr->hStream = AIL_open_stream(drv, PathName(sptr->fname), 0); AIL_set_stream_volume(vptr->hStream, S32(Gain2D * level * 127)); TRACE("Opened stream %s\n", sptr->fname); vptr->smp = sptr; } else { // load the sample if (!sptr->dptr) { #if ASYNC_FILE_IO LoadWaveFileAsync(sptr); #else LoadWaveFile(sptr); #endif if (!sptr->dptr) return; } // unlink from LRU queue if (sptr->prev_lru) { sptr->prev_lru->next_lru = sptr->next_lru; sptr->next_lru->prev_lru = sptr->prev_lru; } // free some stuff if we've got too many loaded if (AllocatedRAM > MAX_SAMPLE_MEM) { MFX_Sample* sptr = LRU.next_lru; while (sptr != &LRU) { MFX_Sample* next = sptr->next_lru; if (!sptr->usecount) { UnloadWaveFile(sptr); if (AllocatedRAM <= MAX_SAMPLE_MEM) break; } sptr = next; } } // link in at front sptr->next_lru = &LRU; sptr->prev_lru = LRU.prev_lru; sptr->next_lru->prev_lru = sptr; sptr->prev_lru->next_lru = sptr; vptr->smp = sptr; if (!sptr->loading) { FinishLoading(vptr); } } } // FinishLoading // // set up voice after sample has loaded static void FinishLoading(MFX_Voice* vptr) { MFX_Sample* sptr = vptr->smp; if (sptr->is3D) { if (Provider) { vptr->h3D = AIL_allocate_3D_sample_handle(Provider); } if (!vptr->h3D && FallbackProvider.hnd) { vptr->h3D = AIL_allocate_3D_sample_handle(FallbackProvider.hnd); } if (vptr->h3D) { sptr->usecount++; AIL_set_3D_sample_file(vptr->h3D, sptr->dptr); AIL_set_3D_sample_distances(vptr->h3D, MaxDist * COORDINATE_UNITS * sptr->linscale, MinDist * COORDINATE_UNITS * sptr->linscale, MaxDist * COORDINATE_UNITS * sptr->linscale, MinDist * COORDINATE_UNITS * sptr->linscale); AIL_set_3D_sample_volume(vptr->h3D, S32(Volumes[sptr->type] * 127)); if (IsEAX) { float level = 0.0; AIL_set_3D_sample_preference(vptr->h3D, "EAX sample reverb mix", &level); } Num3DVoices++; if (Num3DVoices > Max3DVoices) Max3DVoices = Num3DVoices; // TRACE("Setup 3D voice %d for %s - %d in use, max %d\n", vptr - Voices, sptr->fname, Num3DVoices, Max3DVoices); } } if (!vptr->h3D) { // get 2D handle vptr->h2D = AIL_allocate_file_sample(drv, sptr->dptr, 0); // TRACE("Setup 2D voice %d for %s\n", vptr - Voices, sptr->fname); if (vptr->h2D) { sptr->usecount++; AIL_set_sample_volume(vptr->h2D, S32(Gain2D * Volumes[sptr->type] * 127)); } } MoveVoice(vptr); if (vptr->ratemult != 1.0) SetVoiceRate(vptr, vptr->ratemult); if (vptr->gain != 1.0) SetVoiceGain(vptr, vptr->gain); if (vptr->playing) PlayVoice(vptr); } // PlayVoice // // play the voice static void PlayVoice(MFX_Voice* vptr) { if (vptr->h2D) { if (vptr->flags & MFX_LOOPED) { AIL_set_sample_loop_count(vptr->h2D, 0); } AIL_start_sample(vptr->h2D); } if (vptr->h3D) { if (vptr->flags & MFX_LOOPED) { AIL_set_3D_sample_loop_count(vptr->h3D, 0); } AIL_start_3D_sample(vptr->h3D); } if (vptr->hStream) { if (vptr->flags & MFX_LOOPED) { AIL_set_stream_loop_count(vptr->hStream, 0); } AIL_start_stream(vptr->hStream); } vptr->playing = true; } // MoveVoice // // set position of voice source from voice x,y,z static void MoveVoice(MFX_Voice* vptr) { if (vptr->h3D) { float x = vptr->x * COORDINATE_UNITS; float y = vptr->y * COORDINATE_UNITS; float z = vptr->z * COORDINATE_UNITS; /* #ifndef FINAL void AENG_draw_rectr(SLONG x,SLONG y,SLONG w,SLONG h,SLONG col,SLONG layer,SLONG page); AENG_draw_rectr(vptr->x>>6,vptr->z>>7,2,2,0xffff,1,POLY_PAGE_COLOUR); #endif */ if ((fabs(x - LX) < 0.5) && (fabs(y - LY) < 0.5) && (fabs(z - LZ) < 0.5)) { // set exactly at the listener if within epsilon AIL_set_3D_position(vptr->h3D, LX, LY, LZ); } else { AIL_set_3D_position(vptr->h3D, x, y, z); } } } // SetVoiceRate // // set rate for voice static void SetVoiceRate(MFX_Voice* vptr, float mult) { if (vptr->h2D) { AIL_set_sample_playback_rate(vptr->h2D, S32(mult * vptr->smp->rate)); } if (vptr->h3D) { AIL_set_3D_sample_playback_rate(vptr->h3D, S32(mult * vptr->smp->rate)); } if (vptr->hStream) { AIL_set_stream_playback_rate(vptr->hStream, S32(mult * vptr->smp->rate)); } vptr->ratemult = mult; } // SetVoiceGain // // set gain for voice static void SetVoiceGain(MFX_Voice* vptr, float gain) { if (vptr->smp == NULL) { return; } gain *= Volumes[vptr->smp->type]; if (vptr->h2D) { AIL_set_sample_volume(vptr->h2D, S32(Gain2D * gain * 127)); } if (vptr->h3D) { AIL_set_3D_sample_volume(vptr->h3D, S32(gain * 127)); } if (vptr->hStream) { AIL_set_stream_volume(vptr->hStream, S32(Gain2D * gain * 127)); } if (vptr->queue) vptr->queue->gain=gain; vptr->gain = gain; } // IsVoiceDone // // check if voice is done static bool IsVoiceDone(MFX_Voice* vptr) { if (vptr->flags & MFX_LOOPED) return false; U32 status; U32 posn; if (vptr->h2D) { status = AIL_sample_status(vptr->h2D); posn = AIL_sample_position(vptr->h2D); } else if (vptr->h3D) { status = AIL_3D_sample_status(vptr->h3D); posn = AIL_3D_sample_offset(vptr->h3D); } else if (vptr->hStream) { status = AIL_stream_status(vptr->hStream); posn = AIL_stream_position(vptr->hStream); } else if (vptr->smp && vptr->smp->loading) { return false; } else { return true; } if (vptr->flags & MFX_EARLY_OUT) { return (vptr->smp->size - (signed)posn < 440*2); } return (status != SMP_PLAYING); } // QueueWave // // queue a wave static void QueueWave(MFX_Voice* vptr, UWORD wave, ULONG flags, SLONG x, SLONG y, SLONG z) { if ((flags & MFX_SHORT_QUEUE) && vptr->queue) { // short queue - just blat it over the queued one vptr->queue->flags = flags; vptr->queue->wave = wave; vptr->queue->x = x; vptr->queue->y = y; vptr->queue->z = z; return; } if (vptr->queuesz > MAX_QVOICE) return; // too many queued voices if (QFree == QFreeLast) return; // no free slots // allocate a queue element MFX_QWave* qptr = vptr->queue; if (qptr) { while (qptr->next) qptr = qptr->next; qptr->next = QFree; QFree = QFree->next; qptr = qptr->next; } else { vptr->queue = QFree; QFree = QFree->next; qptr = vptr->queue; } qptr->next = NULL; qptr->flags = flags; qptr->wave = wave; qptr->x = x; qptr->y = y; qptr->z = z; qptr->gain = 1.0; } // TriggerPairedVoice // // trigger a paired voice static void TriggerPairedVoice(UWORD channel_id) { MFX_Voice* vptr = FindFirst(channel_id); if (!vptr || !vptr->smp) return; vptr->flags &= ~MFX_PAIRED_TRK2; PlayVoice(vptr); } // PlayWave // // play a sound static UBYTE PlayWave(UWORD channel_id, ULONG wave, ULONG flags, SLONG x, SLONG y, SLONG z, Thing* thing) { MFX_Voice* vptr = GetVoiceForWave(channel_id, wave, flags); if (!vptr) return 0; if (thing) { vptr->x = (thing->WorldPos.X >> 8); vptr->y = (thing->WorldPos.Y >> 8); vptr->z = (thing->WorldPos.Z >> 8); } else { vptr->x = x; vptr->y = y; vptr->z = z; } if (vptr->smp) { if ((vptr->smp->type!=SMP_Music)&&(GAME_STATE & (GS_LEVEL_LOST|GS_LEVEL_WON))) return 0; // once the level's won or lost, no more sounds if (flags & MFX_QUEUED) { QueueWave(vptr, wave, flags, vptr->x, vptr->y, vptr->z); return 2; } if ((vptr->wave == wave) && !(flags & MFX_REPLACE)) { MoveVoice(vptr); return 0; } FreeVoice(vptr); } SetupVoice(vptr, channel_id, wave, flags); MoveVoice(vptr); if (!(flags & MFX_PAIRED_TRK2)) { PlayVoice(vptr); } if (thing) { vptr->thing = thing; thing->Flags |= FLAGS_HAS_ATTACHED_SOUND; } if (flags & MFX_PAIRED_TRK1) { TriggerPairedVoice(channel_id + 1); } return 1; } // PlayTalk // // play a speech static UBYTE PlayTalk(char* filename, SLONG x, SLONG y, SLONG z) { MFX_Voice* vptr = GetVoiceForWave(0, NumSamples, 0); if (!vptr) return 0; if (vptr->smp) { FreeVoice(vptr); } if (x | y | z) TalkSample.is3D = TALK_3D ? true : false; else TalkSample.is3D = false; vptr->x = x; vptr->y = y; vptr->z = z; if (!SetupVoiceTalk(vptr, filename)) { return FALSE; } MoveVoice(vptr); PlayVoice(vptr); return 1; } //----- volume functions // MFX_get_volumes // // get the current volumes, all 0 to 127 void MFX_get_volumes(SLONG* fx, SLONG* amb, SLONG* mus) { *fx = SLONG(127 * Volumes[SMP_Effect]); *amb = SLONG(127 * Volumes[SMP_Ambient]); *mus = SLONG(127 * Volumes[SMP_Music]); } // MFX_set_volumes // // set the current volumes, all 0 to 127 void MFX_set_volumes(SLONG fx, SLONG amb, SLONG mus) { if (fx < 0) fx = 0; else if (fx > 127) fx = 127; if (amb < 0) amb = 0; else if (amb > 127) amb = 127; if (mus < 0) mus = 0; else if (mus > 127) mus = 127; Volumes[SMP_Effect] = float(fx) / 127; Volumes[SMP_Ambient] = float(amb) / 127; Volumes[SMP_Music] = float(mus) / 127; ENV_set_value_number("ambient_volume", amb, "Audio"); ENV_set_value_number("music_volume", mus, "Audio"); ENV_set_value_number("fx_volume", fx, "Audio"); } //----- transport functions ----- // MFX_play_xyz // // play a sound at the given location void MFX_play_xyz(UWORD channel_id, ULONG wave, ULONG flags, SLONG x, SLONG y, SLONG z) { if (!drv) return; PSXCheck(wave); PlayWave(channel_id, wave, flags, x >> 8, y >> 8, z >> 8, NULL); } // MFX_play_thing // // play a sound from a thing void MFX_play_thing(UWORD channel_id, ULONG wave, ULONG flags, Thing* p) { if (!drv) return; PSXCheck(wave); PlayWave(channel_id, wave, flags, 0,0,0, p); } // MFX_play_ambient // // play an ambient sound void MFX_play_ambient(UWORD channel_id, ULONG wave, ULONG flags) { if (!drv) return; PSXCheck(wave); if (wave < NumSamples) { Samples[wave].is3D = false; // save 3D channels for non-ambient sounds if (Samples[wave].type == SMP_Effect) { Samples[wave].type = SMP_Ambient; // use this volume setting } } PlayWave(channel_id, wave, flags, FC_cam[0].x, FC_cam[0].y, FC_cam[0].z, NULL); } // MFX_play_stereo // // play a stereo sound UBYTE MFX_play_stereo(UWORD channel_id, ULONG wave, ULONG flags) { if (!drv) return 0; PSXCheck2(wave); return PlayWave(channel_id, wave, flags, 0, 0, 0, NULL); } // MFX_stop // // stop a sound void MFX_stop(SLONG channel_id, ULONG wave) { if (!drv) return; if (channel_id == MFX_CHANNEL_ALL) { for (int ii = 0; ii < MAX_VOICE; ii++) { FreeVoice(&Voices[ii]); } } else { if (wave == MFX_WAVE_ALL) { MFX_Voice* vptr = FindFirst(channel_id); while (vptr) { FreeVoice(vptr); vptr = FindNext(vptr); } } else { FreeVoice(FindVoice(channel_id, wave)); } } } // MFX_stop_attached // // stop all sounds attached to a thing void MFX_stop_attached(Thing *p) { if (!drv) return; for (int ii = 0; ii < MAX_VOICE; ii++) { if (Voices[ii].thing == p) FreeVoice(&Voices[ii]); } } //----- audio processing functions ----- void MFX_set_pitch(UWORD channel_id, ULONG wave, SLONG pitchbend) { if (!drv) return; MFX_Voice* vptr = FindVoice(channel_id, wave); if (!vptr || !vptr->smp) return; float pitch = float(pitchbend + 256) / 256; SetVoiceRate(vptr, pitch); } void MFX_set_gain(UWORD channel_id, ULONG wave, UBYTE gain) { if (!drv) return; MFX_Voice* vptr = FindVoice(channel_id, wave); if (!vptr || !vptr->smp) return; float fgain = float(gain) / 255; SetVoiceGain(vptr, fgain); } /* void MFX_set_loop_count(UWORD channel_id, ULONG wave, UBYTE count) { if (!drv) return; MFX_Voice* vptr = FindVoice(channel_id, wave); if (!vptr || !vptr->smp) return; float fgain = float(gain) / 255; SetVoiceGain(vptr, fgain); AIL_set_sample_loop_count(); } */ void MFX_set_queue_gain(UWORD channel_id, ULONG wave, UBYTE gain) { if (!drv) return; float fgain = float(gain) / 256; MFX_Voice* vptr = FindFirst(channel_id); while (vptr) { if (!vptr->queue && (vptr->wave == wave)) { SetVoiceGain(vptr, fgain); } for (MFX_QWave* qptr = vptr->queue; qptr; qptr = qptr->next) { if (qptr->wave == wave) qptr->gain = fgain; } vptr = FindNext(vptr); } } //----- sound library functions ----- static void LoadWaveFile(MFX_Sample* sptr) { if (!sptr->fname) return; // no file if (sptr->dptr) return; // already loaded sptr->size = AIL_file_size(PathName(sptr->fname)); sptr->dptr = AIL_file_read(PathName(sptr->fname), NULL); if (!sptr->dptr) return; AllocatedRAM += sptr->size; LoadWaveFileFinished(sptr); } static void LoadTalkFile(char* filename) { if (TalkSample.dptr) { AIL_mem_free_lock(TalkSample.dptr); AllocatedRAM -= TalkSample.size; } TalkSample.dptr = AIL_file_read(filename, NULL); if (!TalkSample.dptr) return; TalkSample.size = AIL_file_size(filename); AllocatedRAM += TalkSample.size; LoadWaveFileFinished(&TalkSample); } #if ASYNC_FILE_IO static void LoadWaveFileAsync(MFX_Sample* sptr) { if (!sptr->fname) return; // no file if (sptr->dptr) return; // loaded sptr->size = AIL_file_size(PathName(sptr->fname)); sptr->dptr = AIL_mem_alloc_lock(sptr->size); if (!sptr->dptr) return; AllocatedRAM += sptr->size; if (!LoadAsyncFile(PathName(sptr->fname), sptr->dptr, sptr->size, sptr)) { AIL_mem_free_lock(sptr->dptr); AllocatedRAM -= sptr->size; sptr->dptr = NULL; // fall back to synchronous loading LoadWaveFile(sptr); return; } sptr->loading = true; } #endif static void LoadWaveFileFinished(MFX_Sample* sptr) { AILSOUNDINFO info; sptr->loading = false; if (!AIL_WAV_info(sptr->dptr, &info)) { TRACE("sample = %s - INVALID\n", sptr->fname); AIL_mem_free_lock(sptr->dptr); AllocatedRAM -= sptr->size; sptr->dptr = NULL; return; } else { sptr->rate = info.rate; if (sptr->is3D) { if (info.channels > 1) { sptr->is3D = false; } if (info.format != WAVE_FORMAT_PCM) { if (sptr->is3D) { // decompress void* wav; U32 size; if (!AIL_decompress_ADPCM(&info, &wav, &size)) { sptr->is3D = false; } else { AIL_mem_free_lock(sptr->dptr); AllocatedRAM -= sptr->size; sptr->dptr = wav; sptr->size = size; AllocatedRAM += sptr->size; } } } } } } static void UnloadWaveFile(MFX_Sample* sptr) { if (!sptr->dptr) return; if (sptr->usecount) return; // unlink if (sptr->prev_lru) { sptr->prev_lru->next_lru = sptr->next_lru; sptr->next_lru->prev_lru = sptr->prev_lru; sptr->next_lru = sptr->prev_lru = NULL; } // cancel pending IO #if ASYNC_FILE_IO if (sptr->loading) { CancelAsyncFile(sptr); sptr->loading = false; } #endif // free AIL_mem_free_lock(sptr->dptr); sptr->dptr = NULL; AllocatedRAM -= sptr->size; } static void UnloadTalkFile() { if (!TalkSample.dptr) return; AIL_mem_free_lock(TalkSample.dptr); TalkSample.dptr = NULL; AllocatedRAM -= TalkSample.size; } void MFX_load_wave_list(CBYTE *names[]) { if (!drv) return; MFX_free_wave_list(); // free waves for (int ii = 0; ii < NumSamples; ii++) { if (Samples[ii].type==SMP_Music) UnloadWaveFile(&Samples[ii]); } UnloadWaveFile(&TalkSample); } void MFX_free_wave_list() { // reset the music system extern void MUSIC_reset(); // yeah yeah i know ugly MUSIC_reset(); if (!drv) return; MFX_stop(MFX_CHANNEL_ALL, MFX_WAVE_ALL); InitVoices(); } //----- listener & environment ----- void MFX_set_listener(SLONG x, SLONG y, SLONG z, SLONG heading, SLONG roll, SLONG pitch) { if (!drv) return; if (Listener || FallbackListener) { x >>= 8; y >>= 8; z >>= 8; LX = x * COORDINATE_UNITS; LY = y * COORDINATE_UNITS; LZ = z * COORDINATE_UNITS; heading += 0x200; heading &= 0x7FF; float xorient = float(COS(heading)) / 65536; float zorient = float(SIN(heading)) / 65536; if (Listener) { AIL_set_3D_position(Listener, LX, LY, LZ); AIL_set_3D_orientation(Listener, xorient, 0, zorient, 0, 1, 0); } if (FallbackListener) { AIL_set_3D_position(FallbackListener, LX, LY, LZ); AIL_set_3D_orientation(FallbackListener, xorient, 0, zorient, 0, 1, 0); } // move voices so the epsilon checks // get made for (int ii = 0; ii < MAX_VOICE; ii++) { if (Voices[ii].h3D) MoveVoice(&Voices[ii]); } } } //----- general system stuff ----- // MFX_render // // update the parameters of the sounds void MFX_render() { if (!drv) return; #if ASYNC_FILE_IO // check for async completions MFX_Sample* sptr; while (sptr = (MFX_Sample*)GetNextCompletedAsyncFile()) { // set up sample now it's in RAM LoadWaveFileFinished(sptr); // and trigger any voices that were waiting for it for (int ii = 0; ii < MAX_VOICE; ii++) { if (Voices[ii].smp == sptr) { FinishLoading(&Voices[ii]); } } } #endif for (int ii = 0; ii < MAX_VOICE; ii++) { MFX_Voice* vptr = &Voices[ii]; if (vptr->flags & MFX_PAIRED_TRK2) continue; if (!vptr->smp) continue; if (IsVoiceDone(vptr)) { if (!vptr->queue) { FreeVoice(vptr); } else { // get next wave from queue MFX_QWave* qptr = vptr->queue; vptr->queue = qptr->next; if (qptr->flags & MFX_PAIRED_TRK1) TriggerPairedVoice(Voices[ii].id + 1); // free the old sample and set up the new one Thing* thing = vptr->thing; FreeVoiceSource(vptr); SetupVoice(vptr, vptr->id, qptr->wave, qptr->flags & ~MFX_PAIRED_TRK2); vptr->thing = thing; // set the position if ((vptr->flags & MFX_MOVING) && vptr->thing) { vptr->x = vptr->thing->WorldPos.X >> 8; vptr->y = vptr->thing->WorldPos.Y >> 8; vptr->z = vptr->thing->WorldPos.Z >> 8; } else { vptr->x = qptr->x; vptr->y = qptr->y; vptr->z = qptr->z; } // relocate and play MoveVoice(vptr); PlayVoice(vptr); SetVoiceGain(vptr, qptr->gain); // release queue element qptr->next = QFree; QFree = qptr; } } else { if (vptr->flags & MFX_CAMERA) { vptr->x = FC_cam[0].x >> 8; vptr->z = FC_cam[0].z >> 8; if (!(vptr->flags & MFX_LOCKY)) vptr->y = FC_cam[0].y >> 8; MoveVoice(vptr); } if ((vptr->flags & MFX_MOVING) && vptr->thing) { vptr->x = vptr->thing->WorldPos.X >> 8; vptr->y = vptr->thing->WorldPos.Y >> 8; vptr->z = vptr->thing->WorldPos.Z >> 8; MoveVoice(vptr); } } } } //----- querying information back ----- UWORD MFX_get_wave(UWORD channel_id, UBYTE index) { if (!drv) return 0; MFX_Voice* vptr = FindFirst(channel_id); while (index--) { vptr = FindNext(vptr); } return vptr ? vptr->wave : 0; } // dlgproc // // dialog box procedure static BOOL CALLBACK dlgproc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { HWND ctrl; int ii; ctrl = GetDlgItem(hWnd, IDC_SOUND_DROPDOWN); switch (message) { case WM_INITDIALOG: { RECT winsize; RECT scrsize; GetWindowRect(hWnd, &winsize); GetClientRect(GetDesktopWindow(), &scrsize); // localise this bastard CBYTE *lang=ENV_get_value_string("language"); if (!lang) lang="text\\lang_english.txt"; XLAT_load(lang); XLAT_init(); SetWindowText(hWnd,XLAT_str(X_MILES_SETUP)); SetDlgItemText(hWnd,IDC_STATIC_SELECT,XLAT_str(X_SELECT_SOUND)); SetDlgItemText(hWnd,IDC_NOSHOW,XLAT_str(X_DO_NOT_SHOW)); SetDlgItemText(hWnd,IDOK,XLAT_str(X_OKAY)); int xoff = ((scrsize.right - scrsize.left) - (winsize.right - winsize.left)) / 2; int yoff = ((scrsize.bottom - scrsize.top) - (winsize.bottom - winsize.top)) / 2; // SetWindowPos(hWnd, NULL, xoff, yoff, 0,0, SWP_NOZORDER | SWP_NOSIZE); for (ii = 0; ii < NumProviders; ii++) { SendMessage(ctrl, CB_INSERTSTRING, -1, (LPARAM)Providers[ii].name); } SendMessage(ctrl, CB_SETCURSEL, CurProvider, 0); } return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: CurProvider = SendMessage(ctrl, CB_GETCURSEL, 0, 0); DoMilesDialog = SendMessage(GetDlgItem(hWnd, IDC_NOSHOW), BM_GETCHECK, 0, 0) ? 0 : 1; case IDCANCEL: EndDialog(hWnd, 0); return TRUE; } break; } return FALSE; } // MilesDialog // // do the dialog box static void MilesDialog(HINSTANCE hInst, HWND hWnd) { DialogBox(hInst, MAKEINTRESOURCE(IDD_MILESDLG), hWnd, (DLGPROC)dlgproc); } // MFX_QUICK_play // // play a speech SLONG MFX_QUICK_play(CBYTE* str, SLONG x, SLONG y, SLONG z) { return PlayTalk(str, x,y,z); } SLONG MFX_QUICK_still_playing() { MFX_Voice* vptr = GetVoiceForWave(0, NumSamples, 0); if (!vptr) return 0; return IsVoiceDone(vptr) ? 0 : 1; } void MFX_QUICK_stop() { MFX_stop(0, NumSamples); } void MFX_QUICK_wait() { while (MFX_QUICK_still_playing()); MFX_QUICK_stop(); } #if 0 static HAUDIO quick_wav=NULL; SLONG MFX_QUICK_play(CBYTE *str) { char filename[256]; strcpy(filename, GetSpeechPath()); strcat(filename, str); quick_wav=AIL_quick_load(filename); if(quick_wav) { AIL_quick_play(quick_wav,1); return(1); } else { return(0); } } void MFX_QUICK_wait(void) { if(quick_wav) { while(AIL_quick_status(quick_wav)==QSTAT_PLAYING) { } AIL_quick_unload(quick_wav); quick_wav=0; } } SLONG MFX_QUICK_still_playing(void) { if(quick_wav) { if(AIL_quick_status(quick_wav)==QSTAT_PLAYING) { return(1); } } return(0); } void MFX_QUICK_stop(void) { if(quick_wav) { // // The big white manual says unloading a playing sample will stop it, so there! // AIL_quick_unload(quick_wav); quick_wav=0; } } #endif #endif // M_SOUND #ifndef M_SOUND #ifndef TARGET_DC SLONG MFX_QUICK_play(CBYTE* fname) { return 1; } void MFX_QUICK_wait(void) { } SLONG MFX_QUICK_still_playing(void) { return 0; } void MFX_QUICK_stop() { } #endif #endif #ifndef TARGET_DC void init_my_dialog (HWND hWnd) { HWND ctrl; int ii; #ifdef NO_SOUND return; #else ctrl = GetDlgItem(hWnd, IDC_SOUND_DROPDOWN); { RECT winsize; RECT scrsize; GetWindowRect(hWnd, &winsize); GetClientRect(GetDesktopWindow(), &scrsize); // localise this bastard CBYTE *lang=ENV_get_value_string("language"); if (!lang) lang="text\\lang_english.txt"; XLAT_load(lang); XLAT_init(); SetDlgItemText(hWnd,IDC_SOUND_OPTIONS,XLAT_str(X_MILES_SETUP)); SetDlgItemText(hWnd,IDC_STATIC_SELECT,XLAT_str(X_SELECT_SOUND)); SetDlgItemText(hWnd,IDC_NOSHOW,XLAT_str(X_DO_NOT_SHOW)); SetDlgItemText(hWnd,IDOK,XLAT_str(X_OKAY)); int xoff = ((scrsize.right - scrsize.left) - (winsize.right - winsize.left)) / 2; int yoff = ((scrsize.bottom - scrsize.top) - (winsize.bottom - winsize.top)) / 2; SetWindowPos(hWnd, NULL, xoff, yoff, 0,0, SWP_NOZORDER | SWP_NOSIZE); SendMessage(ctrl, CB_RESETCONTENT, 0,0); for (ii = 0; ii < NumProviders; ii++) { SendMessage(ctrl, CB_INSERTSTRING, -1, (LPARAM)Providers[ii].name); } SendMessage(ctrl, CB_SETCURSEL, CurProvider, 0); } #endif } void my_dialogs_over(HWND hWnd) { HWND ctrl; #ifdef NO_SOUND return; #else ctrl = GetDlgItem(hWnd, IDC_SOUND_DROPDOWN); CurProvider = SendMessage(ctrl, CB_GETCURSEL, 0, 0); Set3DProvider(CurProvider); #endif } #endif //#ifndef TARGET_DC #endif
19.283596
142
0.651307
inco1
8216b2ad8d36f682cea3517ed4e58d711e06e6df
11,620
cpp
C++
modules/registration/src/noise_model_based_cloud_integration.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
17
2015-11-16T14:21:10.000Z
2020-11-09T02:57:33.000Z
modules/registration/src/noise_model_based_cloud_integration.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
35
2015-07-27T15:04:43.000Z
2019-08-22T10:52:35.000Z
modules/registration/src/noise_model_based_cloud_integration.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
18
2015-08-06T09:26:27.000Z
2020-09-03T01:31:00.000Z
/****************************************************************************** * Copyright (c) 2013 Aitor Aldoma, Thomas Faeulhammer * * 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 <pcl/common/angles.h> #include <pcl/common/io.h> #include <pcl/common/transforms.h> #include <pcl/filters/filter.h> #include <v4r/registration/noise_model_based_cloud_integration.h> #include <glog/logging.h> #include <omp.h> namespace v4r { template<typename PointT> void NMBasedCloudIntegration<PointT>::collectInfo () { size_t total_point_count = 0; for(size_t i = 0; i < input_clouds_.size(); i++) total_point_count += (indices_.empty() || indices_[i].empty()) ? input_clouds_[i]->size() : indices_[i].size(); VLOG(1) << "Allocating memory for point information of " << total_point_count << "points. "; big_cloud_info_.resize(total_point_count); std::vector<pcl::PointCloud<PointT> > input_clouds_aligned (input_clouds_.size()); std::vector<pcl::PointCloud<pcl::Normal> > input_normals_aligned (input_clouds_.size()); #pragma omp parallel for schedule(dynamic) for(size_t i=0; i < input_clouds_.size(); i++) { pcl::transformPointCloud(*input_clouds_[i], input_clouds_aligned[i], transformations_to_global_[i]); transformNormals(*input_normals_[i], input_normals_aligned[i], transformations_to_global_[i]); } size_t point_count = 0; for(size_t i=0; i < input_clouds_.size(); i++) { const pcl::PointCloud<PointT> &cloud_aligned = input_clouds_aligned[i]; const pcl::PointCloud<pcl::Normal> &normals_aligned = input_normals_aligned[i]; size_t kept_new_pts = 0; if (indices_.empty() || indices_[i].empty()) { for(size_t jj=0; jj<cloud_aligned.points.size(); jj++) { if ( !pcl::isFinite(cloud_aligned.points[jj]) || !pcl::isFinite(normals_aligned.points[jj]) ) continue; PointInfo &pt = big_cloud_info_[point_count + kept_new_pts]; pt.pt = cloud_aligned.points[jj]; pt.normal = normals_aligned.points[jj]; pt.sigma_lateral = pt_properties_[i][jj][0]; pt.sigma_axial = pt_properties_[i][jj][1]; pt.distance_to_depth_discontinuity = pt_properties_[i][jj][2]; pt.pt_idx = jj; kept_new_pts++; } } else { for(int idx : indices_[i]) { if ( !pcl::isFinite(cloud_aligned.points[idx]) || !pcl::isFinite(normals_aligned.points[idx]) ) continue; PointInfo &pt = big_cloud_info_[point_count + kept_new_pts]; pt.pt = cloud_aligned.points[idx]; pt.normal = normals_aligned.points[ idx ]; pt.sigma_lateral = pt_properties_[i][idx][0]; pt.sigma_axial = pt_properties_[i][idx][1]; pt.distance_to_depth_discontinuity = pt_properties_[i][idx][2]; pt.pt_idx = idx; kept_new_pts++; } } // compute and store remaining information #pragma omp parallel for schedule (dynamic) firstprivate(i, point_count, kept_new_pts) for(size_t jj=0; jj<kept_new_pts; jj++) { PointInfo &pt = big_cloud_info_ [point_count + jj]; pt.origin = i; Eigen::Matrix3f sigma = Eigen::Matrix3f::Zero(), sigma_aligned = Eigen::Matrix3f::Zero(); sigma(0,0) = pt.sigma_lateral; sigma(1,1) = pt.sigma_lateral; sigma(2,2) = pt.sigma_axial; const Eigen::Matrix4f &tf = transformations_to_global_[ i ]; Eigen::Matrix3f rotation = tf.block<3,3>(0,0); // or inverse? sigma_aligned = rotation * sigma * rotation.transpose(); double det = sigma_aligned.determinant(); // if( std::isfinite(det) && det>0) // pt.probability = 1 / sqrt(2 * M_PI * det); // else // pt.probability = std::numeric_limits<float>::min(); if( std::isfinite(det) && det>0) pt.weight = det; else pt.weight = std::numeric_limits<float>::max(); } point_count += kept_new_pts; } big_cloud_info_.resize(point_count); } template<typename PointT> void NMBasedCloudIntegration<PointT>::reasonAboutPts () { const int width = input_clouds_[0]->width; const int height = input_clouds_[0]->height; const float cx = static_cast<float> (width) / 2.f;// - 0.5f; const float cy = static_cast<float> (height) / 2.f;// - 0.5f; for (size_t i=0; i<big_cloud_info_.size(); i++) { PointInfo &pt = big_cloud_info_[i]; const PointT &ptt = pt.pt; for (size_t cloud=0; cloud<input_clouds_.size(); cloud++) { if( pt.origin == cloud) // we don't have to reason about the point with respect to the original cloud continue; // reproject point onto the cloud's image plane and check if its within FOV and if so, if it can be seen or is occluded const Eigen::Matrix4f &tf = transformations_to_global_[cloud].inverse() * transformations_to_global_[pt.origin]; float x = static_cast<float> (tf (0, 0) * ptt.x + tf (0, 1) * ptt.y + tf (0, 2) * ptt.z + tf (0, 3)); float y = static_cast<float> (tf (1, 0) * ptt.x + tf (1, 1) * ptt.y + tf (1, 2) * ptt.z + tf (1, 3)); float z = static_cast<float> (tf (2, 0) * ptt.x + tf (2, 1) * ptt.y + tf (2, 2) * ptt.z + tf (2, 3)); int u = static_cast<int> (param_.focal_length_ * x / z + cx); int v = static_cast<int> (param_.focal_length_ * y / z + cy); PointT ptt_aligned; ptt_aligned.x = x; ptt_aligned.y = y; ptt_aligned.z = z; if( u<0 || v <0 || u>=width || v >= height ) pt.occluded_++; else { float thresh = param_.threshold_explained_; if( z > 1.f ) thresh+= param_.threshold_explained_ * (z-1.f) * (z-1.f); const float z_c = input_clouds_[cloud]->points[ v*width + u ].z; if ( std::abs(z_c - z) < thresh ) pt.explained_++; else if (z_c > z ) { pt.violated_ ++; } else pt.occluded_ ++; } } } } template<typename PointT> void NMBasedCloudIntegration<PointT>::compute (typename pcl::PointCloud<PointT>::Ptr & output) { if(input_clouds_.empty()) { LOG(ERROR) << "No input clouds set for cloud integration!"; return; } big_cloud_info_.clear(); collectInfo(); if(param_.reason_about_points_) reasonAboutPts(); pcl::octree::OctreePointCloudPointVector<PointT> octree( param_.octree_resolution_ ); typename pcl::PointCloud<PointT>::Ptr big_cloud ( new pcl::PointCloud<PointT>()); big_cloud->width = big_cloud_info_.size(); big_cloud->height = 1; big_cloud->points.resize( big_cloud_info_.size() ); for(size_t i=0; i < big_cloud_info_.size(); i++) big_cloud->points[i] = big_cloud_info_[i].pt; octree.setInputCloud( big_cloud ); octree.addPointsFromInputCloud(); typename pcl::octree::OctreePointCloudPointVector<PointT>::LeafNodeIterator leaf_it; const typename pcl::octree::OctreePointCloudPointVector<PointT>::LeafNodeIterator it2_end = octree.leaf_end(); size_t kept = 0; size_t total_used = 0; std::vector<PointInfo> filtered_cloud_info ( big_cloud_info_.size() ); for (leaf_it = octree.leaf_begin(); leaf_it != it2_end; ++leaf_it) { pcl::octree::OctreeContainerPointIndices& container = leaf_it.getLeafContainer(); // add points from leaf node to indexVector std::vector<int> indexVector; container.getPointIndices (indexVector); if(indexVector.empty()) continue; std::vector<PointInfo> voxel_pts ( indexVector.size() ); for(size_t k=0; k < indexVector.size(); k++) voxel_pts[k] = big_cloud_info_ [indexVector[k]]; PointInfo p; size_t num_good_pts = 0; if(param_.average_) { for(const PointInfo &pt_tmp : voxel_pts) { if (pt_tmp.distance_to_depth_discontinuity > param_.min_px_distance_to_depth_discontinuity_) { p.moving_average( pt_tmp ); num_good_pts++; } } if( num_good_pts < param_.min_points_per_voxel_ ) continue; total_used += num_good_pts; } else // take only point with min weight { for(const PointInfo &pt_tmp : voxel_pts) { if ( pt_tmp.distance_to_depth_discontinuity > param_.min_px_distance_to_depth_discontinuity_) { num_good_pts++; if ( pt_tmp.weight < p.weight || num_good_pts == 1) p = pt_tmp; } } if( num_good_pts < param_.min_points_per_voxel_ ) continue; total_used++; } filtered_cloud_info[kept++] = p; } LOG(INFO) << "Number of points in final noise model based integrated cloud: " << kept << " used: " << total_used << std::endl; if(!output) output.reset(new pcl::PointCloud<PointT>); if(!output_normals_) output_normals_.reset( new pcl::PointCloud<pcl::Normal>); filtered_cloud_info.resize(kept); output->points.resize(kept); output_normals_->points.resize(kept); output->width = output_normals_->width = kept; output->height = output_normals_->height = 1; output->is_dense = output_normals_->is_dense = true; PointT na; na.x = na.y = na.z = std::numeric_limits<float>::quiet_NaN(); input_clouds_used_.resize( input_clouds_.size() ); for(size_t i=0; i<input_clouds_used_.size(); i++) { input_clouds_used_[i].reset( new pcl::PointCloud<PointT> ); input_clouds_used_[i]->points.resize( input_clouds_[i]->points.size(), na); input_clouds_used_[i]->width = input_clouds_[i]->width; input_clouds_used_[i]->height = input_clouds_[i]->height; } for(size_t i=0; i<filtered_cloud_info.size(); i++) { output->points[i] = filtered_cloud_info[i].pt; output_normals_->points[i] = filtered_cloud_info[i].normal; int origin = filtered_cloud_info[i].origin; input_clouds_used_[origin]->points[filtered_cloud_info[i].pt_idx] = filtered_cloud_info[i].pt; } cleanUp(); } template class V4R_EXPORTS NMBasedCloudIntegration<pcl::PointXYZRGB>; }
36.199377
131
0.615749
ToMadoRe
82198c49da3946fa600def6400d63c0bed9b5110
3,495
hh
C++
src/c++/librecordio/exception.hh
darhieus/mapreduce
cd81823732f76baefdff58421082c7f16ddab238
[ "Apache-2.0" ]
194
2015-01-07T11:12:52.000Z
2022-03-14T09:19:24.000Z
src/c++/librecordio/exception.hh
darhieus/mapreduce
cd81823732f76baefdff58421082c7f16ddab238
[ "Apache-2.0" ]
10
2019-11-13T06:03:05.000Z
2021-08-02T17:05:22.000Z
src/c++/librecordio/exception.hh
darhieus/mapreduce
cd81823732f76baefdff58421082c7f16ddab238
[ "Apache-2.0" ]
172
2015-01-14T19:25:48.000Z
2022-02-24T02:42:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCEPTION_HH #define EXCEPTION_HH #include <exception> #include <iostream> #include <string> namespace hadoop { /** * Parent-type for all exceptions in hadoop. * Provides an application specified message to the user, a call stack from * where the exception was created, and optionally an exception that caused * this one. */ class Exception: public std::exception { public: /** * Create an exception. * @param message The message to give to the user. * @param reason The exception that caused the new exception. */ explicit Exception(const std::string& message, const std::string& component="", const std::string& location="", const Exception* reason=NULL); /** * Copy the exception. * Clones the reason, if there is one. */ Exception(const Exception&); virtual ~Exception() throw (); /** * Make a new copy of the given exception by dynamically allocating * memory. */ virtual Exception* clone() const; /** * Print all of the information about the exception. */ virtual void print(std::ostream& stream=std::cerr) const; /** * Result of print() as a string. */ virtual std::string toString() const; #ifdef USE_EXECINFO /** * Print the call stack where the exception was created. */ virtual void printCallStack(std::ostream& stream=std::cerr) const; #endif const std::string& getMessage() const { return mMessage; } const std::string& getComponent() const { return mComponent; } const std::string& getLocation() const { return mLocation; } const Exception* getReason() const { return mReason; } /** * Provide a body for the virtual from std::exception. */ virtual const char* what() const throw () { return mMessage.c_str(); } virtual const char* getTypename() const; private: const static int sMaxCallStackDepth = 10; const std::string mMessage; const std::string mComponent; const std::string mLocation; int mCalls; void* mCallStack[sMaxCallStackDepth]; const Exception* mReason; // NOT IMPLEMENTED std::exception& operator=(const std::exception& right) throw (); }; class IOException: public Exception { public: IOException(const std::string& message, const std::string& component="", const std::string& location="", const Exception* reason = NULL); virtual IOException* clone() const; virtual const char* getTypename() const; }; } #endif
26.884615
78
0.650358
darhieus
821a12d3fe1b2174645fd078ae8e84cca86a772c
5,525
cpp
C++
tests/data/TestFluidDataSet.cpp
jamesb93/flucoma-core
3e964dd569f6fff15bd5249a705dc0da8f7b2ad8
[ "BSD-3-Clause" ]
null
null
null
tests/data/TestFluidDataSet.cpp
jamesb93/flucoma-core
3e964dd569f6fff15bd5249a705dc0da8f7b2ad8
[ "BSD-3-Clause" ]
null
null
null
tests/data/TestFluidDataSet.cpp
jamesb93/flucoma-core
3e964dd569f6fff15bd5249a705dc0da8f7b2ad8
[ "BSD-3-Clause" ]
null
null
null
#define APPROVALS_CATCH #define CATCH_CONFIG_MAIN // #include <catch2/catch.hpp> #include <ApprovalTests.hpp> // #include <catch2/catch_test_macros.hpp> #include <data/FluidTensor.hpp> #include <data/FluidMeta.hpp> #include <data/FluidDataSet.hpp> #include <CatchUtils.hpp> #include <array> #include <vector> #include <algorithm> #include <string> using DataSet = fluid::FluidDataSet<std::string, int, 1>; using fluid::FluidTensor; using fluid::FluidTensorView; using fluid::Slice; using fluid::EqualsRange; //use a subdir for approval test results auto directoryDisposer = ApprovalTests::Approvals::useApprovalsSubdirectory("approval_tests"); TEST_CASE("FluidDataSet can be default constructed","[FluidDataSet]") { DataSet d; CHECK(d.initialized() == false); CHECK(d.size() == 0); CHECK(d.dims() == 0); CHECK(d.getIds().size() == 0); CHECK(d.getData().size() == 0); } TEST_CASE("FluidDataSet can be constructed from data","[FluidDataSet]") { FluidTensor<int, 2> points{{0,1,2,3,4},{5,6,7,8,9}}; FluidTensor<std::string,1> labels{"zero","one"}; SECTION("Non-converting") { DataSet d(labels, points); CHECK(d.initialized() == true); CHECK(d.size() == 2); CHECK(d.dims() == 5); CHECK(d.getIds().size() == 2); CHECK(d.getData().size() == 10); } SECTION("Converting") { FluidTensor<double, 2> float_points(points); DataSet d(FluidTensorView<std::string,1>{labels}, FluidTensorView<const double, 2>{float_points}); CHECK(d.initialized() == true); CHECK(d.size() == 2); CHECK(d.dims() == 5); CHECK(d.getIds().size() == 2); CHECK(d.getData().size() == 10); REQUIRE_THAT(d.getData(),EqualsRange(points)); } } TEST_CASE("FluidDataSet can have points added","[FluidDataSet]") { FluidTensor<int, 2> points{{0,1,2,3,4},{5,6,7,8,9}}; FluidTensor<std::string,1> labels{"zero","one"}; DataSet d(5); CHECK(d.add(labels(0),points.row(0)) == true); CHECK(d.size() == 1); CHECK(d.initialized() == true); CHECK(d.dims() == 5); REQUIRE_THAT(d.getData(),EqualsRange(points.row(0))); REQUIRE_THAT(d.getIds(),EqualsRange(labels(Slice(0,1)))); CHECK(d.add(labels.row(1),points.row(1)) == true); CHECK(d.size() == 2); CHECK(d.initialized() == true); CHECK(d.dims() == 5); REQUIRE_THAT(d.getData(),EqualsRange(points)); REQUIRE_THAT(d.getIds(),EqualsRange(labels)); } TEST_CASE("FluidDataSet can have points retreived","[FluidDataSet]") { FluidTensor<int, 2> points{{0,1,2,3,4},{5,6,7,8,9}}; FluidTensor<std::string,1> labels{"zero","one"}; DataSet d(5); d.add(labels(0),points.row(0)); d.add(labels(1),points.row(1)); FluidTensor<int, 1> output{-1,-1,-1,-1,-1}; CHECK(d.get(labels(0),output) == true); REQUIRE_THAT(output,EqualsRange(points.row(0))); CHECK(d.get(labels(1),output) == true); REQUIRE_THAT(output,EqualsRange(points.row(1))); CHECK(d.get("two",output) == false); //output should be unchanged REQUIRE_THAT(output,EqualsRange(points.row(1))); } TEST_CASE("FluidDataSet can have points updated","[FluidDataSet]") { FluidTensor<int, 2> points{{0,1,2,3,4},{5,6,7,8,9}}; FluidTensor<std::string,1> labels{"zero","one"}; DataSet d(5); d.add(labels(0),points.row(0)); CHECK(d.update(labels(0),points.row(1)) == true); CHECK(d.update(labels(1),points.row(1)) == false); FluidTensor<int, 1> output{-1,-1,-1,-1,-1}; d.get(labels(0),output); REQUIRE_THAT(output,EqualsRange(points.row(1))); } TEST_CASE("FluidDataSet can have points removed","[FluidDataSet]") { FluidTensor<int, 2> points{{0,1,2,3,4},{5,6,7,8,9}}; FluidTensor<std::string,1> labels{"zero","one"}; DataSet d(5); FluidTensor<int, 1> output{-1,-1,-1,-1,-1}; d.add(labels(0),points.row(0)); CHECK(d.remove(labels(0)) == true); CHECK(d.remove(labels(0)) == false); CHECK(d.initialized() == false); CHECK(d.size() == 0); CHECK(d.dims() == 5); //harrumph CHECK(d.getIds().size() == 0); CHECK(d.getData().size() == 0); CHECK(d.update(labels(0),points.row(0)) == false); CHECK(d.get(labels(0),output) == false); CHECK(d.add(labels(0),points.row(0)) == true); CHECK(d.add(labels(1),points.row(1)) == true); CHECK(d.remove(labels(0)) == true); CHECK(d.size() == 1); CHECK(d.dims() == 5); //harrumph CHECK(d.getIds().size() == 1); CHECK(d.getData().size() == 5); CHECK(d.update(labels(0),points.row(0)) == false); CHECK(d.get(labels(0),output) == false); } TEST_CASE("FluidDataSet prints consistent summaries for approval","[FluidDataSet]") { using namespace ApprovalTests; SECTION("small") { FluidTensor<int, 2> points{{0,1,2,3,4},{5,6,7,8,9}}; FluidTensor<std::string,1> labels{"zero","one"}; DataSet d(labels, points); Approvals::verify(d.print()); } SECTION("bigger"){ FluidTensor<int, 2> points(100,100); std::iota(points.begin(), points.end(),0); FluidTensor<std::string,1> labels(100); std::transform(labels.begin(),labels.end(),labels.begin(), [n=0](std::string s)mutable { return std::to_string(n); }); DataSet d(labels, points); Approvals::verify(d.print()); } }
29.545455
83
0.595294
jamesb93
821f44999ec58d8df9d789bdcfee8fb49c5c37a0
2,546
hpp
C++
include/Nazara/Core/Stream.hpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
11
2019-11-27T00:40:43.000Z
2020-01-29T14:31:52.000Z
include/Nazara/Core/Stream.hpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
7
2019-11-27T00:29:08.000Z
2020-01-08T18:53:39.000Z
include/Nazara/Core/Stream.hpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
7
2019-11-27T10:27:40.000Z
2020-01-15T17:43:33.000Z
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_CORE_STREAM_HPP #define NAZARA_CORE_STREAM_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Config.hpp> #include <Nazara/Core/Enums.hpp> #include <Nazara/Utils/Endianness.hpp> #include <filesystem> #include <memory> #include <string> namespace Nz { class ByteArray; class NAZARA_CORE_API Stream { public: Stream(const Stream&) = delete; Stream(Stream&&) noexcept = default; virtual ~Stream(); bool EndOfStream() const; inline void EnableBuffering(bool buffering, std::size_t bufferSize = DefaultBufferSize); inline void EnableTextMode(bool textMode); inline void Flush(); virtual std::filesystem::path GetDirectory() const; virtual std::filesystem::path GetPath() const; inline OpenModeFlags GetOpenMode() const; inline StreamOptionFlags GetStreamOptions() const; UInt64 GetCursorPos() const; virtual UInt64 GetSize() const = 0; std::size_t Read(void* buffer, std::size_t size); virtual std::string ReadLine(unsigned int lineSize = 0); inline bool IsBufferingEnabled() const; inline bool IsReadable() const; inline bool IsSequential() const; inline bool IsTextModeEnabled() const; inline bool IsWritable() const; bool SetCursorPos(UInt64 offset); bool Write(const ByteArray& byteArray); bool Write(const std::string_view& string); inline std::size_t Write(const void* buffer, std::size_t size); Stream& operator=(const Stream&) = delete; Stream& operator=(Stream&&) noexcept = default; static constexpr std::size_t DefaultBufferSize = 0xFFFF; protected: inline Stream(StreamOptionFlags streamOptions = StreamOption::None, OpenModeFlags openMode = OpenMode::NotOpen); virtual void FlushStream() = 0; virtual std::size_t ReadBlock(void* buffer, std::size_t size) = 0; virtual bool SeekStreamCursor(UInt64 offset) = 0; virtual UInt64 TellStreamCursor() const = 0; virtual bool TestStreamEnd() const = 0; virtual std::size_t WriteBlock(const void* buffer, std::size_t size) = 0; std::size_t m_bufferCapacity; std::size_t m_bufferOffset; std::size_t m_bufferSize; std::unique_ptr<UInt8[]> m_buffer; OpenModeFlags m_openMode; StreamOptionFlags m_streamOptions; UInt64 m_bufferCursor; }; } #include <Nazara/Core/Stream.inl> #endif // NAZARA_CORE_STREAM_HPP
29.264368
115
0.737235
NazaraEngine
8222ff5954619fc2fb0ca42c5acabd3f5937683e
630
cpp
C++
src_ref/main.cpp
Joilnen/rge
df20a68a9f86239d9801fcd77f2131e8977a594e
[ "MIT" ]
null
null
null
src_ref/main.cpp
Joilnen/rge
df20a68a9f86239d9801fcd77f2131e8977a594e
[ "MIT" ]
null
null
null
src_ref/main.cpp
Joilnen/rge
df20a68a9f86239d9801fcd77f2131e8977a594e
[ "MIT" ]
null
null
null
#include "ECS.h" #include "GameNode.h" #include <string> #include "Actor.h" #include <OGRE/Ogre.h> #include "GameManager.h" #include "SceneManager.h" #include "RootGame.h" using namespace Ogre; int main() { auto world { World::createWorld() }; auto gameSystem { world->registerSystem(new GameManager) }; auto rootEntity { world->create() }; auto rootAssign { rootEntity->assign<RootGame>(new Ogre::Root) }; auto sceneManager { world->create() }; rootEntity->assign<SceneManagerEnt>(rootAssign->root->createSceneManager()); // ent->assign<GameNode>(root->createSceneManager()); return 0; }
21
80
0.684127
Joilnen
8228d12f592107df1ad1433e86cc3713d187a42e
671
cpp
C++
Array/Insertion Sort/Sol.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
19
2021-04-28T13:32:15.000Z
2022-03-08T11:52:59.000Z
Array/Insertion Sort/Sol.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
17
2021-02-28T17:03:50.000Z
2021-10-19T13:02:03.000Z
Array/Insertion Sort/Sol.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
27
2021-01-18T22:35:01.000Z
2022-02-22T19:52:19.000Z
#include<iostream> using namespace std; class sort { private : int a[20],n,pos,i,j,temp; public: void input(); void process(); void output(); }; void sort :: input() { cout<<"Input the number of array elements :"; cin>>n; cout<<"Input "<<n<<" elements for the array:\n"; for(i=0;i<n;i++) cin>>a[i]; } void sort :: process() { for(i=1;i<n;i++) { j = i; while (j >= 1) { if(a[j] < a[j-1]) { temp = a[j]; a[j] = a[j-1]; a[j-1] = temp; } j=j-1; } } } void sort :: output() { cout<<"Array elements after sorting is "<<endl; for(i=0;i<n;i++) cout<<a[i]<<"\t"; } int main() { sort S; S.input(); S.process(); S.output(); return 0; }
13.156863
65
0.532042
shouryagupta21
822987537b56a0d7dcc43e424c62bb3f87ff087b
552
hh
C++
RecoDataProducts/inc/ExtMonFNALRawClusterCollection.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2021-06-25T00:00:12.000Z
2021-06-25T00:00:12.000Z
RecoDataProducts/inc/ExtMonFNALRawClusterCollection.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
RecoDataProducts/inc/ExtMonFNALRawClusterCollection.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
// // $Id: ExtMonFNALRawClusterCollection.hh,v 1.1 2012/09/19 03:29:45 gandr Exp $ // $Author: gandr $ // $Date: 2012/09/19 03:29:45 $ // // Original author Andrei Gaponenko // #ifndef RecoDataProducts_ExtMonFNALRawClusterCollection_hh #define RecoDataProducts_ExtMonFNALRawClusterCollection_hh #include <vector> #include "RecoDataProducts/inc/ExtMonFNALRawCluster.hh" namespace mu2e { typedef std::vector<ExtMonFNALRawCluster> ExtMonFNALRawClusterCollection; } // namespace mu2e #endif /* RecoDataProducts_ExtMonFNALRawClusterCollection_hh */
25.090909
79
0.791667
bonventre
822f6162d32a407af7c9116c9d2a24d8cd8aed1e
5,392
hpp
C++
PlayRho/Dynamics/Joints/TargetJoint.hpp
godinj/PlayRho
f6f19598a8fca67e10a574faa9bc732d1bd20a2e
[ "Zlib" ]
null
null
null
PlayRho/Dynamics/Joints/TargetJoint.hpp
godinj/PlayRho
f6f19598a8fca67e10a574faa9bc732d1bd20a2e
[ "Zlib" ]
null
null
null
PlayRho/Dynamics/Joints/TargetJoint.hpp
godinj/PlayRho
f6f19598a8fca67e10a574faa9bc732d1bd20a2e
[ "Zlib" ]
null
null
null
/* * Original work Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/PlayRho * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef PLAYRHO_DYNAMICS_JOINTS_MOUSEJOINT_HPP #define PLAYRHO_DYNAMICS_JOINTS_MOUSEJOINT_HPP #include <PlayRho/Dynamics/Joints/Joint.hpp> #include <PlayRho/Dynamics/Joints/TargetJointConf.hpp> namespace playrho { namespace d2 { /// @brief Target Joint. /// /// @details A target joint is used to make a point on a body track a /// specified world point. This a soft constraint with a maximum /// force. This allows the constraint to stretch and without /// applying huge forces. /// @note This structure is 120-bytes large (using a 4-byte Real on at least one 64-bit /// architecture/build). /// /// @ingroup JointsGroup /// class TargetJoint : public Joint { public: /// @brief Is the given definition okay. static bool IsOkay(const TargetJointConf& def) noexcept; /// @brief Initializing constructor. /// @attention To create or use the joint within a world instance, call that world /// instance's create joint method instead of calling this constructor directly. /// @see World::CreateJoint TargetJoint(const TargetJointConf& def); void Accept(JointVisitor& visitor) const override; void Accept(JointVisitor& visitor) override; Length2 GetAnchorA() const override; Length2 GetAnchorB() const override; Momentum2 GetLinearReaction() const override; AngularMomentum GetAngularReaction() const override; bool ShiftOrigin(const Length2 newOrigin) override; /// @brief Gets the local anchor B. Length2 GetLocalAnchorB() const noexcept; /// @brief Sets the target point. void SetTarget(const Length2 target) noexcept; /// @brief Gets the target point. Length2 GetTarget() const noexcept; /// @brief Sets the maximum force. void SetMaxForce(NonNegative<Force> force) noexcept; /// @brief Gets the maximum force. NonNegative<Force> GetMaxForce() const noexcept; /// @brief Sets the frequency. void SetFrequency(NonNegative<Frequency> hz) noexcept; /// @brief Gets the frequency. NonNegative<Frequency> GetFrequency() const noexcept; /// @brief Sets the damping ratio. void SetDampingRatio(NonNegative<Real> ratio) noexcept; /// @brief Gets the damping ratio. NonNegative<Real> GetDampingRatio() const noexcept; private: void InitVelocityConstraints(BodyConstraintsMap& bodies, const StepConf& step, const ConstraintSolverConf& conf) override; bool SolveVelocityConstraints(BodyConstraintsMap& bodies, const StepConf& step) override; bool SolvePositionConstraints(BodyConstraintsMap& bodies, const ConstraintSolverConf& conf) const override; /// @brief Gets the effective mass matrix. Mass22 GetEffectiveMassMatrix(const BodyConstraint& body) const noexcept; Length2 m_targetA; ///< Target location (A). Length2 m_localAnchorB; ///< Local anchor B. NonNegative<Frequency> m_frequency = NonNegative<Frequency>{0_Hz}; ///< Frequency. NonNegative<Real> m_dampingRatio = NonNegative<Real>{0}; ///< Damping ratio. NonNegative<Force> m_maxForce = NonNegative<Force>{0_N}; ///< Max force. InvMass m_gamma = InvMass{0}; ///< Gamma. Momentum2 m_impulse = Momentum2{}; ///< Impulse. // Solver variables. These are only valid after InitVelocityConstraints called. Length2 m_rB; ///< Relative B. Mass22 m_mass; ///< 2-by-2 mass matrix in kilograms. LinearVelocity2 m_C; ///< Velocity constant. }; inline Length2 TargetJoint::GetLocalAnchorB() const noexcept { return m_localAnchorB; } inline Length2 TargetJoint::GetTarget() const noexcept { return m_targetA; } inline void TargetJoint::SetMaxForce(NonNegative<Force> force) noexcept { m_maxForce = force; } inline NonNegative<Force> TargetJoint::GetMaxForce() const noexcept { return m_maxForce; } inline void TargetJoint::SetFrequency(NonNegative<Frequency> hz) noexcept { m_frequency = hz; } inline NonNegative<Frequency> TargetJoint::GetFrequency() const noexcept { return m_frequency; } inline void TargetJoint::SetDampingRatio(NonNegative<Real> ratio) noexcept { m_dampingRatio = ratio; } inline NonNegative<Real> TargetJoint::GetDampingRatio() const noexcept { return m_dampingRatio; } } // namespace d2 } // namespace playrho #endif // PLAYRHO_DYNAMICS_JOINTS_MOUSEJOINT_HPP
33.91195
94
0.727745
godinj
4361f1349b01b2aa209a0db6087d5caddd1d54b2
1,551
cpp
C++
2020-11-25/friday.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
2
2020-12-12T00:02:40.000Z
2021-04-21T19:49:59.000Z
2020-11-25/friday.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
null
null
null
2020-11-25/friday.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
null
null
null
/* ID: pufepro1 LANG: C++ TASK: friday */ #include <cstdio> #include <cstdlib> int week[7]; // sat=0, sun=1, mon=2 ... fri=6 int month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int regular_year[7]; int leap_year[7]; bool is_leap(int year) { if (year % 400 == 0) return true; if (year % 100 == 0) return false; if (year % 4 == 0) return true; return false; } void calculate_regular_year() { int dow = 0; for(int i=0; i<12; ++i) { regular_year[(dow+12)%7]++; dow += month[i]; } } void calculate_leap_year() { int dow = 0; for(int i=0; i<12; ++i) { leap_year[(dow+12)%7]++; if (i==1) ++dow; dow += month[i]; } } int main () { FILE *fin = fopen ("friday.in", "r"); FILE *fout = fopen ("friday.out", "w"); int year = 1900; int dow = 2; int n; fscanf(fin, " %d", &n); calculate_regular_year(); calculate_leap_year(); for(int i=0; i<n; ++i) { if (is_leap(year)) { for(int j=0; j<7; ++j) week[(j+dow)%7]+=leap_year[j]; dow += 366; dow %= 7; } else { for(int j=0; j<7; ++j) week[(j+dow)%7]+=regular_year[j]; dow += 365; dow %= 7; } // printf(" dow = %d\n", dow); // for(int i=0; i<7; ++i) { // printf(" %d", week[i]); // } // printf("\n"); ++year; } for(int i=0; i<7; ++i) { if (i>0) fprintf(fout, " "); fprintf(fout, "%d", week[i]); } fprintf(fout, "\n"); return 0; }
18.914634
46
0.462927
pufe
436387615b72e3f1b95618b03ee2605695bdf702
60,498
cpp
C++
Editor/_src/PhysicsStudio.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
2
2022-02-11T11:59:44.000Z
2022-02-16T20:33:25.000Z
Editor/_src/PhysicsStudio.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
Editor/_src/PhysicsStudio.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
#include "all.h" #include <win_res.h> #include <Insanity\PhysTemplate.h> #include <windows.h> #include "winstuff.h" #include "..\..\Source\IEditor\resource.h" #include "common.h" //---------------------------- //we use -0 to mark 'default float value for some params //const float DEFAULT_VALUE = -0.0f; #define DEFAULT_VALUE I3DIntAsFloat(0x80000000) inline bool IsDefaultValue(float f){ return (I3DFloatAsInt(f)==0x80000000); } //---------------------------- //---------------------------- //conversion of joint value id into sheet control ID static const dword val_ids[] = { IDC_LO, IDC_LO1, IDC_LO2, IDC_HI, IDC_HI1, IDC_HI2, IDC_MAXF, IDC_FUDGE, IDC_BOUNCE, IDC_CFM, IDC_S_ERP, IDC_S_CFM, IDC_SU_ERP, IDC_SU_CFM, }; //---------------------------- class C_physics_studio: public C_editor_item{ const char *GetName()const{ return "Physics Studio"; } bool col_test; //---------------------------- public: void ErrReport(const char *cp) const{ //context is pointer to C_editor class PC_editor_item_Log ei_log = (PC_editor_item_Log)ed->FindPlugin("Log"); if(ei_log) ei_log->AddText(cp, 0xffff0000); } private: //---------------------------- void DebugLine(const S_vector &from, const S_vector &to, int type, dword color = 0xffffffff, int time = 500){ PC_editor_item_DebugLine ei = (PC_editor_item_DebugLine)ed->FindPlugin("DebugLine"); if(ei) ei->AddLine(from, to, (E_DEBUGLINE_TYPE)type, color, time); } //---------------------------- void DebugPoint(const S_vector &from, float radius, int type, dword color = 0xffffffff, int time = 500){ PC_editor_item_DebugLine ei = (PC_editor_item_DebugLine)ed->FindPlugin("DebugLine"); if(ei) ei->AddPoint(from, radius, (E_DEBUGLINE_TYPE)type, color, time); } //---------------------------- void InitModel(PIPH_body body, PI3D_scene scn, const char *fn, float scale) const{ PI3D_model model = I3DCAST_MODEL(scn->CreateFrame(FRAME_MODEL)); model->LinkTo(scn->GetPrimarySector()); model->SetScale(scale); model->SetFlags(I3D_FRMF_SHADOW_CAST, I3D_FRMF_SHADOW_CAST); ed->GetModelCache().Open(model, fn, scn, 0, NULL, NULL); ((PC_editor_item_Modify)ed->FindPlugin("Modify"))->AddFrameFlags(model, E_MODIFY_FLG_TEMPORARY, false); body->SetFrame(model, IPH_STEFRAME_HR_VOLUMES); model->Release(); } //---------------------------- void CloseModel(PIPH_body body) const{ if(body){ PI3D_frame frm = body->GetFrame(); if(ed) ((PC_editor_item_Modify)ed->FindPlugin("Modify"))->RemoveFrame(frm); } } //---------------------------- C_vector<C_smart_ptr<IPH_body> > bodies; C_vector<C_smart_ptr<IPH_joint> > joints; C_smart_ptr<IPH_world> world; //C_game_mission &mission; bool active; bool draw_contacts; bool statistics; bool phys_studio_active; HWND hwnd_sheet; C_smart_ptr<IPH_body> pick_body; S_vector pick_pos; //in picked model's local coords float pick_dist; //distance in which we picked C_str auto_command; C_smart_ptr<C_editor_item_Selection> e_slct; C_smart_ptr<C_editor_item_MouseEdit> e_mouseedit; C_smart_ptr<C_editor_item_Undo> e_undo; C_smart_ptr<C_editor_item_Modify> e_modify; C_smart_ptr<C_editor_item_Properties> e_props; struct S_contact{ S_vector pos, normal; float depth; dword color; }; //---------------------------- enum E_ACTION{ E_PHYS_NULL, /* E_PHYS_JOINT_BALL, E_PHYS_JOINT_HINGE, E_PHYS_JOINT_HINGE2, E_PHYS_JOINT_SLIDER, E_PHYS_JOINT_UNIVERSAL, E_PHYS_JOINT_FIXED, E_PHYS_JOINT_AMOTOR, */ E_PHYS_ACTIVE, E_PHYS_DRAW_CONTACTS, E_PHYS_STATS, E_ACTION_PICK_MODE, E_ACTION_DO_PICK, E_ACTION_EDIT_AUTO_CMD, E_ACTION_PHYS_STUDIO_TOGGLE, E_ACTION_PHYS_STUDIO_TEST, E_SEL_NOTIFY, //E_MODIFY_NOTIFY, E_ACTION_GET_CONTACT_REPORT = 1000, }; //---------------------------- static C_str FloatStrip(const C_str &str){ for(dword i=str.Size(); i--; ) if(str[i]=='.') break; if(i==-1) return str; C_str ret = str; for(i=ret.Size(); i--; ) if(ret[i]!='0') break; if(ret[i]=='.') ++i; ret[i+1] = 0; return ret; } //---------------------------- virtual bool Init(){ e_mouseedit = (PC_editor_item_MouseEdit)ed->FindPlugin("MouseEdit"); e_modify = (PC_editor_item_Modify)ed->FindPlugin("Modify"); e_slct = (PC_editor_item_Selection)ed->FindPlugin("Selection"); e_undo = (PC_editor_item_Undo)ed->FindPlugin("Undo"); e_props = (PC_editor_item_Properties)ed->FindPlugin("Properties"); if(!e_modify || !e_mouseedit || !e_slct || !e_undo || !e_props) return false; #define MENU_BASE "%90 &Physics Studio\\" /* ed->AddShortcut(this, E_PHYS_JOINT_BALL, MENU_BASE"Joint B&all", K_NOKEY, 0); ed->AddShortcut(this, E_PHYS_JOINT_HINGE, MENU_BASE"Joint &Hinge", K_NOKEY, 0); ed->AddShortcut(this, E_PHYS_JOINT_HINGE2, MENU_BASE"Joint Hinge &2", K_NOKEY, 0); ed->AddShortcut(this, E_PHYS_JOINT_SLIDER, MENU_BASE"Joint S&lider", K_NOKEY, 0); ed->AddShortcut(this, E_PHYS_JOINT_UNIVERSAL, MENU_BASE"Joint &Universal", K_NOKEY, 0); ed->AddShortcut(this, E_PHYS_JOINT_FIXED, MENU_BASE"%aJoint &Fixed", K_NOKEY, 0); //ed->AddShortcut(this, E_PHYS_JOINT_AMOTOR, MENU_BASE"Joint &Motor", K_NOKEY, 0); */ ed->AddShortcut(this, E_ACTION_PHYS_STUDIO_TOGGLE, MENU_BASE"&Physics Studio", K_NOKEY, 0); ed->AddShortcut(this, E_ACTION_PHYS_STUDIO_TEST, MENU_BASE"%a &Test physics", K_NOKEY, 0); ed->AddShortcut(this, E_ACTION_PICK_MODE, MENU_BASE"P&ick mode", K_NOKEY, 0); ed->AddShortcut(this, E_PHYS_ACTIVE, MENU_BASE"&Debug", K_NOKEY, 0); ed->AddShortcut(this, E_PHYS_DRAW_CONTACTS, MENU_BASE"D&raw contacts", K_NOKEY, 0); ed->AddShortcut(this, E_PHYS_STATS, MENU_BASE"&Stats", K_NOKEY, 0); ed->AddShortcut(this, E_ACTION_EDIT_AUTO_CMD, MENU_BASE"&Edit start-up command", K_NOKEY, 0); return true; } //---------------------------- /* void InstallShortcuts(){ static const S_tmp_shortcut shortcuts[] = { {E_PHYS_ADD_BOX, K_B, 0, "Drop Ball"}, {E_PHYS_ADD_BLOCK, K_K, 0, "Drop Block"}, {E_PHYS_ADD_SPHERE, K_P, 0, "Drop Sphere"}, {E_PHYS_ADD_HYBRID, K_H, 0, "Drop Hybrid"}, //{E_PHYS_ADD_CYLINDER, K_C, 0, "Drop Cylinder"}, {E_PHYS_ADD_CCYLINDER, K_A, 0, "Drop Capped cylinder"}, {E_PHYS_JOINT_BALL, K_J, SKEY_SHIFT, "Drop Ball joint"}, {E_PHYS_JOINT_HINGE, K_H, SKEY_SHIFT, "Drop Hinge joint"}, {E_PHYS_JOINT_HINGE2, K_2, SKEY_SHIFT, "Drop Hinge2 joint"}, {E_PHYS_JOINT_SLIDER, K_S, SKEY_SHIFT, "Drop Slider joint"}, {E_PHYS_JOINT_UNIVERSAL, K_U, SKEY_SHIFT, "Drop Universal joint"}, {E_PHYS_JOINT_FIXED, K_F, SKEY_SHIFT, "Drop Fixed joint"}, {NULL} }; ed->InstallTempShortcuts(this, shortcuts); } */ //---------------------------- void InitPhysicsScene(){ ClosePhysicsScene(); //world = mission.GetPhysicsWorld(); if(!world){ world = IPHCreateWorld(); world->Release(); } { if(auto_command.Size()){ if(auto_command=="c") col_test = true; else Command(auto_command); } if(!col_test) Action(E_ACTION_PICK_MODE, 0); } //InstallShortcuts(); } //---------------------------- void ClosePhysicsScene(){ for(dword i=bodies.size(); i--; ) CloseModel(bodies[i]); bodies.clear(); joints.clear(); //world = NULL; //ed->RemoveTempShortcuts(this); col_test = false; } //---------------------------- //---------------------------- //physics studio database (run-time version): struct S_phys_info{ struct S_body{ C_smart_ptr<I3D_frame> frm; bool is_static; //used for debugging - this body doesn't move float density; bool density_as_weight; S_body(): is_static(false), density(I3DIntAsFloat(0x80000000)), density_as_weight(false) {} }; C_vector<S_body> bodies; struct S_joint{ C_smart_ptr<I3D_frame> frm; IPH_JOINT_TYPE type; float val[S_phys_template::VAL_LAST]; S_joint(): type(IPHJOINTTYPE_BALL) { for(int i=S_phys_template::VAL_LAST; i--; ) val[i] = DEFAULT_VALUE; } }; C_vector<S_joint> joints; int BodyIndex(CPI3D_frame frm) const{ for(int i=bodies.size(); i--; ){ if(bodies[i].frm==frm) break; } return i; } void RemoveBody(dword i){ assert(i<bodies.size()); bodies[i] = bodies.back(); bodies.pop_back(); } //---------------------------- int JointIndex(CPI3D_frame frm) const{ for(int i=joints.size(); i--; ){ if(joints[i].frm==frm) break; } return i; } void RemoveJoint(dword i){ assert(i<joints.size()); joints[i] = joints.back(); joints.pop_back(); } bool IsEmpty() const{ return (!bodies.size() && !joints.size()); } void Clear(){ bodies.clear(); joints.clear(); } //---------------------------- void Export(S_phys_template &pt, PI3D_scene scn) const{ CPI3D_frame prim_sect = scn->GetPrimarySector(); int i; for(i=bodies.size(); i--; ){ const S_body &b = bodies[i]; pt.bodies.push_back(S_phys_template::S_body()); S_phys_template::S_body &tb = pt.bodies.back(); tb.name = (b.frm==prim_sect) ? "*" : b.frm->GetName(); tb.is_static = b.is_static; tb.density = b.density; tb.density_as_weight = b.density_as_weight; } for(i=joints.size(); i--; ){ const S_joint &j = joints[i]; pt.joints.push_back(S_phys_template::S_joint()); S_phys_template::S_joint &tj = pt.joints.back(); tj.name = j.frm->GetName(); tj.type = j.type; tj.pos.Zero(); memcpy(tj.val, j.val, sizeof(tj.val)); //joint's parent is 'body1' PI3D_frame prnt = j.frm->GetParent(); if(prnt){ if(BodyIndex(prnt)!=-1){ tj.body[0] = (prnt==prim_sect) ? "*" : prnt->GetName(); //joint's position is relative to body1 tj.pos = j.frm->GetPos(); } } //joint's body2 is either joint's frame itself, or its 1st child if(BodyIndex(j.frm)!=-1) tj.body[1] = tj.name; else{ PI3D_frame chld = j.frm->NumChildren() ? j.frm->GetChildren()[0] : NULL; if(chld){ if(BodyIndex(chld)!=-1) tj.body[1] = chld->GetName(); } } } } //---------------------------- void Save(C_chunk &ck, PI3D_scene scn) const{ S_phys_template pt; Export(pt, scn); pt.Save(ck); } //---------------------------- void Import(S_phys_template &pt, PI3D_scene scn, C_physics_studio *ps){ Clear(); bodies.reserve(pt.bodies.size()); joints.reserve(pt.joints.size()); PI3D_frame prim_sect = scn->GetPrimarySector(); int i; for(i=pt.bodies.size(); i--; ){ const S_phys_template::S_body &tb = pt.bodies[i]; bodies.push_back(S_body()); S_body &b = bodies.back(); b.is_static = tb.is_static; b.density = tb.density; b.density_as_weight = tb.density_as_weight; b.frm = tb.name=="*" ? prim_sect : scn->FindFrame(tb.name); if(!b.frm){ ps->ErrReport(C_xstr("PhysStudio: frame '%' not in scene, removing body") %tb.name); bodies.pop_back(); } } for(i=pt.joints.size(); i--; ){ const S_phys_template::S_joint &tj = pt.joints[i]; joints.push_back(S_joint()); S_joint &j = joints.back(); j.frm = scn->FindFrame(tj.name); j.type = tj.type; memcpy(j.val, tj.val, sizeof(j.val)); if(!j.frm){ ps->ErrReport(C_xstr("PhysStudio: frame '%' not in scene, removing joint") %tj.name); joints.pop_back(); } } } }; S_phys_info phys_info; //---------------------------- static BOOL CALLBACK dlgSheet_thunk(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ C_physics_studio *ei = (C_physics_studio*)GetWindowLong(hwnd, GWL_USERDATA); if(!ei){ if(uMsg!=WM_INITDIALOG) return 0; SetWindowLong(hwnd, GWL_USERDATA, lParam); ei = (C_physics_studio*)lParam; assert(ei); } return ei->dlgSheet(hwnd, uMsg, wParam, lParam); } //---------------------------- bool dlgSheet(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ switch(uMsg){ case WM_INITDIALOG: { struct{ IPH_JOINT_TYPE type; const char *name; } jt[] = { IPHJOINTTYPE_BALL, "Ball", IPHJOINTTYPE_HINGE, "Hinge", IPHJOINTTYPE_SLIDER, "Slider", IPHJOINTTYPE_UNIVERSAL, "Universal", IPHJOINTTYPE_HINGE2, "Hinge2", IPHJOINTTYPE_FIXED, "Fixed", IPHJOINTTYPE_NULL }; for(dword i=0; jt[i].type; i++){ dword j = SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_ADDSTRING, 0, (LPARAM)jt[i].name); SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_SETITEMDATA, j, jt[i].type); } } break; case WM_COMMAND: switch(LOWORD(wParam)){ case IDCLOSE: Action(E_ACTION_PHYS_STUDIO_TOGGLE); break; case IDC_PH_RESET: if(!phys_info.IsEmpty()){ if(!ed->CanModify()) break; int i = MessageBox((HWND)ed->GetIGraph()->GetHWND(), "Are you sure to reset all physic info?", "Physics studio", MB_YESNO); if(i==IDYES){ phys_info.Clear(); UpdateSheet(e_slct->GetCurSel()); ed->SetModified(); } } break; case IDC_PH_BODY: case IDC_PH_JOINT: { if(!ed->CanModify()) break; dword id = LOWORD(wParam); bool jnt = (id==IDC_PH_JOINT); bool on = IsDlgButtonChecked(hwnd, id); //toggle state on = !on; //add selection among bodies (of not yet) const C_vector<PI3D_frame> &sel_list = e_slct->GetCurSel(); for(int i=sel_list.size(); i--; ){ PI3D_frame frm = sel_list[i]; int l_i = (jnt ? phys_info.JointIndex(frm) : phys_info.BodyIndex(frm)); if(on){ if(l_i==-1){ //remove from opposite list first, then add to current if(jnt){ /* int ii = phys_info.BodyIndex(frm); if(ii!=-1) phys_info.RemoveBody(ii); */ phys_info.joints.push_back(S_phys_info::S_joint()); phys_info.joints.back().frm = frm; }else{ /* int ii = phys_info.JointIndex(frm); if(ii!=-1) phys_info.RemoveJoint(ii); */ phys_info.bodies.push_back(S_phys_info::S_body()); phys_info.bodies.back().frm = frm; } } }else if(l_i!=-1){ if(jnt){ phys_info.RemoveJoint(l_i); }else{ phys_info.RemoveBody(l_i); } } } UpdateSheet(sel_list); ed->SetModified(); } break; case IDC_PH_BODY_STATIC: { if(!ed->CanModify()) break; dword id = LOWORD(wParam); bool on = IsDlgButtonChecked(hwnd, id); //toggle state on = !on; const C_vector<PI3D_frame> &sel_list = e_slct->GetCurSel(); for(int i=sel_list.size(); i--; ){ PI3D_frame frm = sel_list[i]; int ii = phys_info.BodyIndex(frm); assert(ii!=-1); phys_info.bodies[ii].is_static = on; } UpdateSheet(sel_list); ed->SetModified(); } break; case IDC_PH_UNIT_DENSITY: case IDC_PH_UNIT_WEIGHT: { if(!ed->CanModify()) break; dword id = LOWORD(wParam); bool d_a_w = (id==IDC_PH_UNIT_WEIGHT); const C_vector<PI3D_frame> &sel_list = e_slct->GetCurSel(); for(int i=sel_list.size(); i--; ){ PI3D_frame frm = sel_list[i]; int ii = phys_info.BodyIndex(frm); assert(ii!=-1); phys_info.bodies[ii].density_as_weight = d_a_w; } UpdateSheet(sel_list); ed->SetModified(); } break; case IDC_PH_JTYPE: switch(HIWORD(wParam)){ case CBN_SELCHANGE: { if(!ed->CanModify()) break; int sel = SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_GETCURSEL, 0, 0); IPH_JOINT_TYPE type = (IPH_JOINT_TYPE)SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_GETITEMDATA, sel, 0); //set to all selected joints const C_vector<PI3D_frame> &sel_list = e_slct->GetCurSel(); for(int i=sel_list.size(); i--; ){ PI3D_frame frm = sel_list[i]; int ii = phys_info.JointIndex(frm); assert(ii!=-1); phys_info.joints[ii].type = type; } ed->SetModified(); } break; } break; default: switch(HIWORD(wParam)){ case EN_CHANGE: { if(!hwnd_sheet) break; if(!ed->CanModify()) break; dword id = LOWORD(wParam); //check which value is being changes for(int vi=S_phys_template::VAL_LAST; vi--; ){ if(val_ids[vi]==id) break; } //scan value char buf[256]; GetDlgItemText(hwnd, id, buf, sizeof(buf)); float value; //check for clearing the field (set default val if so) if(!*buf) value = DEFAULT_VALUE; else{ int n; if(sscanf(buf, "%f%n", &value, &n)==-1 || !n) break; } //clamp some values bool clamp = false; switch(vi){ case S_phys_template::VAL_BOUNCE: case S_phys_template::VAL_STOP_ERP: case S_phys_template::VAL_SUSP_ERP: if(value<0.0f){ value = 0.0f; clamp = true; } else if(value>1.0f){ value = 1.0f; clamp = true; } break; case S_phys_template::VAL_CFM: case S_phys_template::VAL_STOP_CFM: case S_phys_template::VAL_SUSP_CFM: if(value<0.0f){ value = 0.0f; clamp = true; } break; } if(clamp){ hwnd_sheet = NULL; SetDlgItemText(hwnd, id, FloatStrip(C_xstr("%")%value)); hwnd_sheet = hwnd; } //modify all selected frames const C_vector<PI3D_frame> &sel_list = e_slct->GetCurSel(); for(int i=sel_list.size(); i--; ){ PI3D_frame frm = sel_list[i]; if(vi!=-1){ //it's joint int ii = phys_info.JointIndex(frm); assert(ii!=-1); phys_info.joints[ii].val[vi] = value; }else switch(id){ case IDC_PH_DENSITY: { int ii = phys_info.BodyIndex(frm); assert(ii!=-1); phys_info.bodies[ii].density = value; } break; } } ed->SetModified(); } break; } } break; case WM_HELP: { HELPINFO *hi = (HELPINFO*)lParam; static S_ctrl_help_info help_texts[] = { IDC_PH_BODY, "Make selected objects to act as rigid-body parts of physics.", IDC_PH_BODY_STATIC, "Make body fixed (not moving) - suitable for debugging.", //IDC_PH_BODY_ROOT, "Instead of this frame, use model's root frame for this body.", IDC_PH_JOINT, "Make selected objects to act as constraint joints. Note that joint is connected to one or two bodies - to make the connection, link the joint to body1, and (optionally) link body2 to the joint.", IDC_PH_JTYPE, "Type of joint.", IDC_LO, "Set low rotational/sliding limit. Positional or angle values are applied, depending on joint type (angle values are in degrees).", IDC_HI, "Set high rotational/sliding limit. Positional or angle values are applied, depending on joint type (angle values are in degrees).", IDC_MAXF, "Maximal force applied by joint onto the constraint. By default, this is a 'suspension' parameter, making the joint move hard.", IDC_FUDGE, "...", IDC_BOUNCE, "Bounce value used when joint reaches limits.", IDC_CFM, "Constraint-force-mixing value. This value specifies how hard joint tries to correct the constraint situation.\nIf CFM is set to zero, the constraint will be hard. If CFM is set to a positive value, it will be possible to violate the constraint by ``pushing on it'' (for example, for contact constraints by forcing the two contacting objects together). In other words the constraint will be soft, and the softness will increase as CFM increases. What is actually happeneng here is that the constraint is allowed to be violated by an amount proportional to CFM times the restoring force that is needed to enforce the constraint.", IDC_S_ERP, "Error-reduction-parameter used at the limit stop.\nThere is a mechanism to reduce joint error: during each simulation step each joint applies a special force to bring its bodies back into correct alignment. This force is controlled by the error reduction parameter (ERP), which has a value between 0 and 1.\nThe ERP specifies what proportion of the joint error will be fixed during the next simulation step. If ERP=0 then no correcting force is applied and the bodies will eventually drift apart as the simulation proceeds. If ERP=1 then the simulation will attempt to fix all joint error during the next time step. However, setting ERP=1 is not recommended, as the joint error will not be completely fixed due to various internal approximations. A value of ERP=0.1 to 0.8 is recommended (0.2 is the default).\nA global ERP value can be set that affects most joints in the simulation. However some joints have local ERP values that control various aspects of the joint.", IDC_S_CFM, "Constraint-force-mixing used at the limit stop. See 'CFM' for details on this parameter.", IDC_SU_ERP, "Suspension error-reduction-parameter (currently applcable only to Hinge2 joint). See 'Stop ERP' for more info on ERP parameter.", IDC_SU_CFM, "Suspension constraint-force-mixing (currently applicable only to Hinge2 joint). See 'CFM' for details on CFM parameter.", IDC_PH_DENSITY,"Density of the body. The density is applied onto all body volumes.", 0 //terminator }; DisplayControlHelp(hwnd, (word)hi->iCtrlId, help_texts); } break; } return 0; } //---------------------------- void InitPhysStudio(){ //world = mission.GetPhysicsWorld(); if(!world){ world = IPHCreateWorld(); world->Release(); } //install editor notifications e_slct->AddNotify(this, E_SEL_NOTIFY); //create and init property sheet hwnd_sheet = CreateDialogParam(GetModuleHandle(NULL), "IDD_PHYS_STUDIO", (HWND)ed->GetIGraph()->GetHWND(), dlgSheet_thunk, (LPARAM)this); e_props->AddSheet(hwnd_sheet); UpdateSheet(e_slct->GetCurSel()); //EnableSheetControls(false); } //---------------------------- void ClosePhysStudio(){ if(!hwnd_sheet) return; //remove notifies e_slct->RemoveNotify(this); e_props->RemoveSheet(hwnd_sheet); DestroyWindow(hwnd_sheet); hwnd_sheet = NULL; } //---------------------------- // Enable/disable all controls in the property sheet window. void EnableSheetControls(bool b){ HWND hwnd_close = GetDlgItem(hwnd_sheet, IDCLOSE); for(HWND hwnd = GetWindow(hwnd_sheet, GW_CHILD); hwnd; hwnd = GetWindow(hwnd, GW_HWNDNEXT)){ if(hwnd!=hwnd_close) EnableWindow(hwnd, b); } } //---------------------------- void UpdateSheet(const C_vector<PI3D_frame> &sel_list){ HWND hwnd = hwnd_sheet; if(!sel_list.size()){ EnableSheetControls(false); /* SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_SETCURSEL, -1, 0); CheckDlgButton(hwnd, IDC_PH_BODY_STATIC, false); return; */ }else EnableSheetControls(true); //temporary clear to mark that we're modifying hwnd_sheet = NULL; //count how many joint and bodies are there in selection dword num_b = 0, num_j = 0; for(int i=sel_list.size(); i--; ){ CPI3D_frame frm = sel_list[i]; if(phys_info.BodyIndex(frm)!=-1) ++num_b; if(phys_info.JointIndex(frm)!=-1) ++num_j; } //setup body info if(!num_b || num_b!=sel_list.size()){ //clear CheckDlgButton(hwnd, IDC_PH_BODY, false); static const struct S_off_data{ dword id; bool also_txt; } off_ids[] = { IDC_PH_BODY_STATIC, false, IDC_PH_DENSITY, true, IDC_PH_UNIT_DENSITY, false, IDC_PH_UNIT_WEIGHT, false, 0 }; for(i=0; off_ids[i].id; i++){ HWND h = GetDlgItem(hwnd, off_ids[i].id); EnableWindow(h, false); if(off_ids[i].also_txt) SetWindowText(h, ""); } } //setup joint info if(!num_j || num_j!=sel_list.size()){ //clear/disable irrelevant parts SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_SETCURSEL, (WPARAM)-1, 0); static const dword off_ids[] = { IDC_PH_JTYPE, IDC_LO, IDC_HI, IDC_LO1, IDC_HI1, IDC_LO2, IDC_HI2, IDC_MAXF, IDC_FUDGE, IDC_BOUNCE, IDC_CFM, IDC_S_CFM, IDC_S_ERP, IDC_SU_CFM, IDC_SU_ERP, 0 }; for(i=0; off_ids[i]; i++){ HWND h = GetDlgItem(hwnd, off_ids[i]); EnableWindow(h, false); SetWindowText(h, ""); } CheckDlgButton(hwnd, IDC_PH_JOINT, false); }else{ } if(num_j!=sel_list.size() && num_b!=sel_list.size()){ //mixed mode, set indeterminate state of checkboxes CheckDlgButton(hwnd, IDC_PH_BODY, num_b ? BST_INDETERMINATE : false); CheckDlgButton(hwnd, IDC_PH_JOINT, num_j ? BST_INDETERMINATE : false); }else{ if(num_b && num_b==sel_list.size()){ //init pure body part CheckDlgButton(hwnd, IDC_PH_BODY, true); bool valid[3] = {true, true, true }; bool stat = false; float density = 0; bool d_a_w = false; for(i=0; i<(int)sel_list.size(); i++){ int ii = phys_info.BodyIndex(sel_list[i]); assert(ii!=-1); const S_phys_info::S_body &b = phys_info.bodies[ii]; if(!i){ stat = b.is_static; density = b.density; d_a_w = b.density_as_weight; }else{ if(stat != b.is_static) valid[0] = false; if(density!=b.density) valid[1] = false; if(d_a_w != b.density_as_weight) valid[2] = false; } } CheckDlgButton(hwnd, IDC_PH_BODY_STATIC, !valid[0] ? BST_INDETERMINATE : stat); SetDlgItemText(hwnd, IDC_PH_DENSITY, !valid[1] ? "?" : IsDefaultValue(density) ? "" : (const char*)FloatStrip(C_xstr("%")%density)); CheckDlgButton(hwnd, IDC_PH_UNIT_DENSITY, !valid[2] ? false : !d_a_w); CheckDlgButton(hwnd, IDC_PH_UNIT_WEIGHT, !valid[2] ? false : d_a_w); } if(num_j && num_j==sel_list.size()){ //init pure joint part CheckDlgButton(hwnd, IDC_PH_JOINT, true); IPH_JOINT_TYPE t = IPHJOINTTYPE_NULL; const int NUM_VALS = S_phys_template::VAL_LAST; float val[NUM_VALS]; bool valid[NUM_VALS]; for(i=NUM_VALS; i--; ) valid[i] = true; for(i=0; i<(int)sel_list.size(); i++){ int ii = phys_info.JointIndex(sel_list[i]); S_phys_info::S_joint &ji = phys_info.joints[ii]; assert(ii!=-1); if(!i) t = ji.type; else if(t != ji.type) t = IPHJOINTTYPE_NULL; //check all vals for(int j=NUM_VALS; j--; ){ if(!i) val[j] = ji.val[j]; else if(valid[j]) valid[j] = (I3DFloatAsInt(val[j]) == I3DFloatAsInt(ji.val[j])); } } if(t){ for(i=0; ; i++){ int id = SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_GETITEMDATA, i, 0); if(id==CB_ERR) break; if(id==t){ SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_SETCURSEL, i, 0); break; } } }else SendDlgItemMessage(hwnd, IDC_PH_JTYPE, CB_SETCURSEL, (WPARAM)-1, 0); for(i=NUM_VALS; i--; ){ SetDlgItemText(hwnd, val_ids[i], !valid[i] ? "?" : IsDefaultValue(val[i]) ? "" : (const char*)FloatStrip(C_xstr("%")%val[i])); } } } //restore hwnd_sheet = hwnd; } //---------------------------- void PhysicsStudioTest(){ if(phys_info.IsEmpty()){ ed->Message("Can't test physics studio - no information set!"); return; } if(!world){ world = IPHCreateWorld(); world->Release(); } PI3D_scene scn = ed->GetScene(); //lock further editing ((PC_editor_item_Mission)ed->FindPlugin("Mission"))->EditLock(); for(dword i=bodies.size(); i--; ) CloseModel(bodies[i]); //export into intermediate template S_phys_template pt; phys_info.Export(pt, ed->GetScene()); if(pt.InitSimulation(bodies, joints, world, scn, NULL)){ assert(bodies.size()==pt.bodies.size()); //for all 'static' bodies, make additional fixed joint for(i=0; i<pt.bodies.size(); i++){ if(pt.bodies[i].is_static){ //attach to one fixed joint PIPH_joint_fixed jnt = (PIPH_joint_fixed)world->CreateJoint(IPHJOINTTYPE_FIXED); joints.push_back(jnt); jnt->Attach(bodies[i], NULL); jnt->SetFixed(); jnt->Release(); } } } } //---------------------------- void Command(const char *cmd){ switch(*cmd){ /* case 'b': case 'k': case 's': case 'c': //case 'x': case 'l': case 'h': { S_object &obj = objs[nextobj]; ++nextobj %= MAX_NUM; obj.Clear(); obj.body = world->CreateBody(); obj.body->Release(); float scale = .2f + S_float_random() * 1.0f; S_vector pos; S_quat rot; if(random_pos){ pos.x = S_float_random() * 2.0f - 1.0f; pos.y = S_float_random() + 3.0f; pos.z = S_float_random() * 2.0f - 1.0f; S_vector ax; ax.x = S_float_random()*2.0f-1.0f; ax.y = S_float_random()*2.0f-1.0f; ax.z = S_float_random()*2.0f-1.0f; const float a = S_float_random(PI*2.0f); rot.Make(ax, a); }else{ pos.Zero(); for(int k=0; k<MAX_NUM; k++){ if(objs[k].body){ S_vector _bpos; S_quat r; objs[k].body->GetPosRot(_bpos, r); if(pos.y < _bpos[1]) pos.y = _bpos[1]; } } pos.y += 1.0f; const float a = S_float_random(PI*2.0f); rot.Make(S_vector(0, 1, 0), a); } obj.body->SetPosRot(pos, rot); const char *mod_name = NULL; switch(*cmd){ case 'b': mod_name = "test\\_box"; break; case 'c': scale *= .5f; mod_name = "test\\capcylinder"; break; case 'l': scale *= .5f; mod_name = "test\\_cylinder"; break; case 's': scale *= .5f; mod_name = "test\\sphere"; break; case 'h': scale *= .5f; mod_name = "+test"; break; case 'k': mod_name = "test\\block"; break; } obj.InitModel(ed->GetScene(), mod_name, scale); } break; */ case 'j': //joint { /* S_object &obj0 = objs[nextobj]; ++nextobj %= MAX_NUM; S_object &obj1 = objs[nextobj]; ++nextobj %= MAX_NUM; obj0.Clear(); obj0.body = world->CreateBody(); obj0.body->Release(); obj1.Clear(); obj1.body = world->CreateBody(); obj1.body->Release(); */ PIPH_body b0 = world->CreateBody(); PIPH_body b1 = world->CreateBody(); bodies.push_back(b0); bodies.push_back(b1); b0->Release(); b1->Release(); S_quat rot; rot.Make(S_vector(1, 0, 0), PI*.0f); S_vector pos(.5f, .5f, 0); { InitModel(b0, ed->GetScene(), "test\\_box", 1.0f); b0->SetPosRot(S_vector(0, pos.y, 0), rot); } { InitModel(b1, ed->GetScene(), "test\\_box", .5f); b1->SetPosRot(S_vector(.6f, pos.y, 0), S_quat(1, 0, 0, 0)); } { static const struct{ char cmd; IPH_JOINT_TYPE jt; } j_map[] = { 'b', IPHJOINTTYPE_BALL, 'h', IPHJOINTTYPE_HINGE, '2', IPHJOINTTYPE_HINGE2, 's', IPHJOINTTYPE_SLIDER, 'u', IPHJOINTTYPE_UNIVERSAL, 'f', IPHJOINTTYPE_FIXED, 0, IPHJOINTTYPE_NULL }; for(int i=0; j_map[i].cmd && j_map[i].cmd!=cmd[1]; i++); IPH_JOINT_TYPE jt = j_map[i].jt; if(!jt) jt = IPHJOINTTYPE_BALL; PIPH_joint j = world->CreateJoint(jt); assert(j); j->Attach(b0, b1); j->SetAnchor(pos); joints.push_back(j); switch(jt){ case IPHJOINTTYPE_BALL: { /* PIPH_joint_ball jb = (PIPH_joint_ball)j; jb->SetUserMode(true); jb->SetNumAxes(3); jb->SetAxis(0, S_vector(1, 0, 0), IPH_JOINT_ball::AXIS_BODY1); jb->SetAxis(1, S_vector(0, 1, 0), IPH_JOINT_ball::AXIS_BODY1); jb->SetAxis(2, S_vector(0, 0, 1), IPH_JOINT_ball::AXIS_BODY1); for(dword i=3; i--; ){ j->SetStopCFM(5.0f, i); j->SetDesiredVelocity(0.0f, i); j->SetMaxForce(.01f, i); j->SetLoStop(-PI*.1f, i); j->SetHiStop(PI*.1f, i); } */ } break; case IPHJOINTTYPE_FIXED: ((PIPH_joint_fixed)j)->SetFixed(); break; case IPHJOINTTYPE_HINGE: { PIPH_joint_hinge jh = (PIPH_joint_hinge)j; //jh->SetAxis(S_vector(1, 0, 0)); jh->SetAxis(S_vector(0, 1, 0)); } break; case IPHJOINTTYPE_SLIDER: { PIPH_joint_slider jh = (PIPH_joint_slider)j; jh->SetAxis(S_vector(1, 0, 0)); } break; case IPHJOINTTYPE_UNIVERSAL: { PIPH_joint_universal ju = (PIPH_joint_universal)j; ju->SetAxis(0, S_vector(0, 1, 0)); ju->SetAxis(1, S_vector(0, 0, 1)); } break; case IPHJOINTTYPE_HINGE2: { PIPH_joint_hinge2 j2 = (PIPH_joint_hinge2)j; j2->SetAxis(0, S_vector(0, 1, 0)); j2->SetAxis(1, S_vector(1, 0, 0)); } break; } //setup some parameters //j->SetLoStop(-PI*.2f); //j->SetHiStop(PI*.5f); //j->SetBounce(.1f); //j->SetStopERP(.1f); //j->SetStopCFM(5.2f); //j->SetSuspensionCFM(2.5f); //j->SetSuspensionERP(2.5f); //j->SetDesiredVelocity(0.0f); //j->SetMaxForce(.01f); j->Release(); } } break; case 'i': { PIPH_body body = world->CreateBody(); bodies.push_back(body); body->Release(); /* S_object &obj0 = objs[nextobj]; ++nextobj %= MAX_NUM; obj0.Clear(); obj0.body = world->CreateBody(); obj0.body->Release(); */ const char *mod_name = NULL; { S_vector pos(0, .5f, 0); float scale = 1.0f; S_quat rot; rot.Identity(); switch(cmd[1]){ case 'm': { PI3D_frame frm = ed->GetScene()->FindFrame("phys"); if(frm){ if(body->SetFrame(frm, IPH_STEFRAME_USE_TRANSFORM | IPH_STEFRAME_HR_VOLUMES)) break; ed->Message("can't use model 'phys'"); }else{ ed->Message("can't find model 'phys'"); } } //... flow case 'b': default: { mod_name = "test\\_box"; pos.y = .6f; const float a = 21.0f*PI/180.0f; rot.Make(S_vector(1, 0, 0), a); rot *= S_quat(S_vector(0, 0, 1), PI*.2f); } break; case 'k': mod_name = "test\\block"; break; case 's': scale *= .5f; //scale = .05f; pos.y += 2.0f; pos.x -= 2.0f; mod_name = "test\\sphere"; break; case 'c': { scale *= .25f; scale = .03f; pos.y += 1.0f; mod_name = "test\\capcylinder"; rot.Make(S_vector(1, 0, 0), PI*.45f); //obj0.body->AddForceAtPos(S_vector(2, 0, 0), S_vector(0, 0, 300)); //obj0.body->AddForceAtPos(S_vector(-2, 0, 0), S_vector(0, 0, -300)); } break; case 'l': scale *= .5f; mod_name = "test\\_cylinder"; pos.y = 1.0f; break; case 'h': { scale *= .5f; mod_name = "+test"; } break; } if(mod_name){ body->SetPosRot(pos, rot); InitModel(body, ed->GetScene(), mod_name, scale); } } } break; } } //---------------------------- //static void ContactReport(CPI3D_volume src_vol, PIPH_body src_body, CPI3D_frame dst_frm, PIPH_body dst_body, //const S_vector &pos, const S_vector &normal, float depth, void *context){ static void I3DAPI ContactReport(CPI3D_frame frm, const S_vector &pos, const S_vector &normal, float depth, void *context){ C_physics_studio *ps = (C_physics_studio*)context; ps->DebugLine(pos, pos + normal * .2f, 1, 0x8000ff00); ps->DebugPoint(pos, .1f, 1, 0x80ffff00); } //---------------------------- virtual void AfterLoad(){ if(active) InitPhysicsScene(); } //---------------------------- virtual void BeforeFree(){ if(active) ClosePhysicsScene(); phys_info.Clear(); } //---------------------------- virtual void LoadFromMission(C_chunk &ck){ S_phys_template pt; pt.Load(ck); phys_info.Import(pt, ed->GetScene(), this); } //---------------------------- virtual void MissionSave(C_chunk &ck, dword phase){ if(phase==2){ if(!phys_info.IsEmpty()){ //ck <<= CT_EDITOR_PLUGIN; ck <<= CT_PHYSICS_TEMPLATE; { //ck(CT_NAME, GetName()); phys_info.Save(ck, ed->GetScene()); } --ck; } } } //---------------------------- virtual void SetActive(bool a){ if(!a) if(active) InitPhysicsScene(); } //---------------------------- virtual void OnFrameDelete(PI3D_frame frm){ int i = phys_info.BodyIndex(frm); if(i!=-1) phys_info.RemoveBody(i); i = phys_info.JointIndex(frm); if(i!=-1) phys_info.RemoveJoint(i); } //---------------------------- public: C_physics_studio(): col_test(false), active(false), phys_studio_active(false), hwnd_sheet(NULL), draw_contacts(false), statistics(false) { } //---------------------------- virtual void Close(){ ClosePhysicsScene(); ClosePhysStudio(); } //---------------------------- virtual void Tick(byte skeys, int time, int mouse_rx, int mouse_ry, int mouse_rz, byte mouse_butt){ do{ if(!pick_body) break; if(!(mouse_butt&1)){ pick_body = NULL; break; } //draw line of picking S_vector from = pick_pos * pick_body->GetFrame()->GetMatrix(); S_vector to, ldir; ed->GetScene()->UnmapScreenPoint(ed->GetIGraph()->Mouse_x(), ed->GetIGraph()->Mouse_y(), to, ldir); to += ldir * pick_dist; DebugLine(from, to, 1, 0xff00ff00); S_vector dir = to - from; //ldir; float m = pick_body->GetWeight(); dword skeys = ed->GetIGraph()->GetShiftKeys(); switch(skeys){ case SKEY_SHIFT: m *= 4.0f; break; case SKEY_CTRL: m *= 2.0f; break; case SKEY_ALT: m *= .5f; break; } //dir *= 3.0f; dir *= m; //DEBUG(dir); DebugLine(from, from+dir, 1, 0xffff00ff); pick_body->AddForceAtPos(from, dir); }while(false); if(active && world){ /* if(bodies.size()){ PIPH_body b = bodies[0]; S_vector pos; S_quat rot; b->GetPosRot(pos, rot); DebugLine(pos, pos+b->GetLinearVelocity(), 1); DebugLine(pos, pos+b->GetAngularVelocity(), 1, 0xff00ff00); pos += b->GetFrame()->GetMatrix()(0); DebugLine(pos, pos+b->GetVelAtPos(pos), 1, 0xffff0000); } */ /* //examine joint #0 if(joints.size()){ PIPH_joint jnt = joints.front(); switch(jnt->GetType()){ case IPHJOINTTYPE_HINGE: { PIPH_joint_hinge j = PIPH_joint_hinge(jnt); DEBUG(C_fstr("Hinge: angle: %.2f, rate: %.2f", j->GetAngle(), j->GetAngleRate())); } break; case IPHJOINTTYPE_SLIDER: DEBUG(PIPH_joint_slider(jnt)->GetSlidePos()); DEBUG(PIPH_joint_slider(jnt)->GetSlidePosRate()); break; case IPHJOINTTYPE_HINGE2: DEBUG(C_fstr("Hinge2: angle: %.2f, rate1: %.2f, rate2: %.2f", PIPH_joint_hinge2(jnt)->GetAngle(), PIPH_joint_hinge2(jnt)->GetAngleRate(0), PIPH_joint_hinge2(jnt)->GetAngleRate(1))); break; } } */ } /* if(statistics && world){ DEBUG(C_xstr("Physics statistics:")); DEBUG(C_xstr(" num bodies: %") % (int)world->NumBodies()); DEBUG(C_xstr(" num joints: %") % (int)world->NumJoints()); DEBUG(C_xstr(" num contacts: %") % (int)world->NumContacts()); } */ } //---------------------------- virtual dword Action(int id, void *context = NULL){ switch(id){ /* case E_PHYS_JOINT_BALL: Command("jb"); break; case E_PHYS_JOINT_HINGE: Command("jh"); break; case E_PHYS_JOINT_HINGE2: Command("j2"); break; case E_PHYS_JOINT_SLIDER: Command("js"); break; case E_PHYS_JOINT_UNIVERSAL: Command("ju"); break; case E_PHYS_JOINT_FIXED: Command("jf"); break; case E_PHYS_JOINT_AMOTOR: Command("jm"); break; */ case E_PHYS_ACTIVE: active = !active; ed->CheckMenu(this, id, active); if(active) InitPhysicsScene(); else ClosePhysicsScene(); break; case E_ACTION_PHYS_STUDIO_TOGGLE: phys_studio_active = !phys_studio_active; ed->CheckMenu(this, id, phys_studio_active); if(phys_studio_active){ InitPhysStudio(); }else{ ClosePhysStudio(); } break; case E_ACTION_PHYS_STUDIO_TEST: PhysicsStudioTest(); break; case E_PHYS_DRAW_CONTACTS: draw_contacts = !draw_contacts; ed->CheckMenu(this, id, draw_contacts); break; case E_PHYS_STATS: statistics = !statistics; ed->CheckMenu(this, id, statistics); break; case E_ACTION_EDIT_AUTO_CMD: WinGetName("Auto-start command", auto_command, ed->GetIGraph()->GetHWND()); break; case E_ACTION_PICK_MODE: e_mouseedit->SetUserPick(this, E_ACTION_DO_PICK, LoadCursor(GetModuleHandle(NULL), "IDC_CURSOR_DEBUG_PHYS")); break; case E_ACTION_DO_PICK: { if(!world) break; const S_MouseEdit_picked *mp = (S_MouseEdit_picked*)context; dword skeys = ed->GetIGraph()->GetShiftKeys(); switch(skeys){ case SKEY_CTRL: case SKEY_ALT: case SKEY_SHIFT: { //generate sphere at this position S_vector pos = mp->pick_from + mp->pick_dir * mp->pick_dist; pos.y += 2.0f; /* S_object &obj = objs[nextobj]; ++nextobj %= MAX_NUM; obj.Clear(); obj.body = world->CreateBody(); obj.body->Release(); */ PIPH_body body = world->CreateBody(); bodies.push_back(body); body->Release(); const char *mod_name = NULL; float scale = 1.0f; switch(skeys){ case SKEY_CTRL: mod_name = "test\\sphere"; break; case SKEY_ALT: mod_name = "test\\block"; break; case SKEY_SHIFT: mod_name = "test\\capcylinder"; scale = .4f; break; default: assert(0); } { S_quat rot; rot.Make(S_vector(1, 0, 0), S_float_random(PI*2.0f)); rot *= S_quat(S_vector(0, 0, 1), S_float_random(PI*2.0f)); body->SetPosRot(pos, rot); } InitModel(body, ed->GetScene(), mod_name, scale); } break; default: //pick volume I3D_collision_data cd(mp->pick_from, mp->pick_dir, I3DCOL_VOLUMES | I3DCOL_RAY); if(!ed->GetScene()->TestCollision(cd)) break; PI3D_frame frm = cd.GetHitFrm(); assert(frm->GetType()==FRAME_VOLUME); pick_body = world->GetVolumeBody(I3DCAST_VOLUME(frm)); if(pick_body){ pick_dist = cd.GetHitDistance(); pick_pos = cd.ComputeHitPos(); pick_pos *= pick_body->GetFrame()->GetInvMatrix(); float n, f; ed->GetScene()->GetActiveCamera()->GetRange(n, f); pick_dist += n; ed->Message(C_xstr("Picked body: '%'") % pick_body->GetFrame()->GetName()); } } } return true; //case E_ACTION_GET_CONTACT_REPORT: //return dword(draw_contacts ? ContactReport : NULL); case E_SEL_NOTIFY: UpdateSheet(*(C_vector<PI3D_frame>*)context); break; } return 0; } //---------------------------- void RenderCircleSector(const S_vector &pos, const S_vector &axis1, const S_vector &axis2, float len, float lo_angle, float hi_angle, dword color1, dword color2){ const int MAX_P = 24; float delta = hi_angle - lo_angle; int num_p = Max(2, Min(MAX_P, int(delta * 6.0f))); //generate points and indices S_vector pt[MAX_P+1]; I3D_triface fc[2][MAX_P-1]; word line_indx[MAX_P+1][2]; pt[num_p] = pos; S_quat rot_dir; rot_dir.SetDir(axis2, axis1); float step = delta / float(num_p-1); for(int i=num_p; i--; ){ float angle = lo_angle + float(i)*step; S_quat rot_y(S_vector(0, 1, 0), angle); S_quat r = rot_y * rot_dir; pt[i] = pos + r.GetDir()*len; if(i!=num_p-1){ I3D_triface &fc1 = fc[0][i]; fc1[0] = word(num_p); fc1[1] = word(i); fc1[2] = word(i+1); I3D_triface &fc2 = fc[1][i]; fc2[0] = word(num_p); fc2[1] = word(i+1); fc2[2] = word(i); } line_indx[i][0] = word(i); line_indx[i][1] = word(i+1); } line_indx[num_p][0] = word(num_p); line_indx[num_p][1] = 0; ed->GetDriver()->SetTexture(NULL); PI3D_scene scn = ed->GetScene(); scn->DrawTriangles(pt, num_p+1, I3DVC_XYZ, &fc[0][0][0], 3*(num_p-1), color1); scn->DrawTriangles(pt, num_p+1, I3DVC_XYZ, &fc[1][0][0], 3*(num_p-1), color1); scn->DrawLines(pt, num_p+1, line_indx[0], (num_p+1)*sizeof(word), color2); } //---------------------------- void Render(){ //visualize phys studio stuff if(phys_studio_active){ //PI3D_scene scn = ed->GetScene(); int i; for(i=phys_info.joints.size(); i--; ){ const S_phys_info::S_joint &jnt = phys_info.joints[i]; CPI3D_frame frm = jnt.frm; const S_matrix &jm = frm->GetMatrix(); const S_vector &j_pos = jm(3); const dword color = 0x80ff00ff; DebugPoint(j_pos, .2f, 1, color); //draw connections towards bodies for(int j=2; j--; ){ PI3D_frame fb = !j ? frm->GetParent() : frm->NumChildren() ? frm->GetChildren()[0] : NULL; if(fb){ if(phys_info.BodyIndex(fb)!=-1){ S_vector pos = fb->GetWorldPos(); DebugLine(pos, j_pos, 1, color); } } } //render joint-specific data float lo0 = jnt.val[S_phys_template::VAL_STOP_LO0], hi0 = jnt.val[S_phys_template::VAL_STOP_HI0]; //float lo1 = jnt.val[S_phys_template::VAL_STOP_LO1], hi1 = jnt.val[S_phys_template::VAL_STOP_HI1]; //float lo2 = jnt.val[S_phys_template::VAL_STOP_LO2], hi2 = jnt.val[S_phys_template::VAL_STOP_HI2]; switch(jnt.type){ case IPHJOINTTYPE_HINGE2: DebugLine(j_pos, j_pos+jm(1), 1, 0xffff00ff); DebugLine(j_pos, j_pos+jm(2), 1, 0xff00ffff); if(!IsDefaultValue(lo0) || !IsDefaultValue(hi0)){ RenderCircleSector(jm(3), jm(1), jm(2), .5f, lo0*PI/180.0f, hi0*PI/180.0f, 0x40ffff00, 0xe0ffff00); } break; case IPHJOINTTYPE_HINGE: DebugLine(j_pos, j_pos+jm(2), 1, 0xff00ffff); if(!IsDefaultValue(lo0) || !IsDefaultValue(hi0)){ RenderCircleSector(jm(3), jm(2), jm(1), .5f, lo0*PI/180.0f, hi0*PI/180.0f, 0x40ffff00, 0xe0ffff00); } break; case IPHJOINTTYPE_UNIVERSAL: DebugLine(j_pos-jm(0)*.5f, j_pos+jm(0)*.5f, 1, 0xff00ffff); DebugLine(j_pos-jm(1)*.5f, j_pos+jm(1)*.5f, 1, 0xff00ffff); break; case IPHJOINTTYPE_SLIDER: if(!IsDefaultValue(lo0) || !IsDefaultValue(hi0)){ S_normal n = jm(2); DebugLine(j_pos-n*lo0, j_pos-n*hi0, 1, 0xff00ffff); } break; } } /* DebugLine(pos, pos + normal * .5f, 1, 0x8000ff00); */ } #if 1 if(col_test){ PI3D_scene scn = ed->GetScene(); PI3D_volume frm = I3DCAST_VOLUME(scn->FindFrame("from", ENUMF_VOLUME)); if(frm){ /* struct S_hlp{ //PI3D_material icon; //PI3D_scene scn; static dword I3DAPI cb_q(CPI3D_frame frm, void *context){ return 4; } static void I3DAPI cb_r(CPI3D_frame frm, const S_vector &pos, const S_vector &normal, float depth, void *context){ //S_hlp *hp = (S_hlp*)context; //hp->scn->DrawSprite(pos, hp->icon, 0xffffff00, .1f); //hp->scn->DrawLine(pos, pos + normal * .5f, 0x8000ff00); DebugPoint(pos, .1f, 1, 0xffffff00); DebugLine(pos, pos + normal * .5f, 1, 0x8000ff00); DEBUG(depth); } };// hlp; */ I3D_contact_data cd; cd.vol_src = frm; //cd.cb_query = S_hlp::cb_q; cd.cb_report = ContactReport; cd.context = this; scn->GenerateContacts(cd); } } #endif } //---------------------------- enum{ SS_reserved, SS_ACTIVE, SS_AUTO_CMD, SS_DRAW_CONTACTS, SS_STUDIO_ACTIVE, SS_STATS, }; //---------------------------- virtual bool SaveState(C_chunk &ck) const{ ck (SS_ACTIVE, active) (SS_AUTO_CMD, auto_command) (SS_DRAW_CONTACTS, draw_contacts) (SS_STUDIO_ACTIVE, phys_studio_active) (SS_STATS, statistics) ; return true; } //---------------------------- virtual bool LoadState(C_chunk &ck){ while(ck) switch(++ck){ case SS_ACTIVE: ck >> active; ed->CheckMenu(this, E_PHYS_ACTIVE, active); break; case SS_AUTO_CMD: ck >> auto_command; break; case SS_STUDIO_ACTIVE: ck >> phys_studio_active; ed->CheckMenu(this, E_ACTION_PHYS_STUDIO_TOGGLE, phys_studio_active); break; case SS_DRAW_CONTACTS: ck >> draw_contacts; ed->CheckMenu(this, E_PHYS_DRAW_CONTACTS, draw_contacts); break; case SS_STATS: ck >> statistics; ed->CheckMenu(this, E_PHYS_STATS, statistics); break; default: --ck; } if(active) InitPhysicsScene(); else ClosePhysicsScene(); if(phys_studio_active) InitPhysStudio(); return true; } //---------------------------- }; //---------------------------- //---------------------------- void InitPhysicsStudio(PC_editor editor){ C_physics_studio *em = new C_physics_studio; editor->InstallPlugin(em); em->Release(); } //----------------------------
34.025872
999
0.484066
mice777
4363b83d413603e467f495715fca5c031c7a1b73
40,006
hpp
C++
libs/c3ga/src/c3ga/InnerExplicit.hpp
qcoumes/GA-physics
be72e0959620973ab29cd9e4705e97eda4356fe9
[ "MIT" ]
null
null
null
libs/c3ga/src/c3ga/InnerExplicit.hpp
qcoumes/GA-physics
be72e0959620973ab29cd9e4705e97eda4356fe9
[ "MIT" ]
null
null
null
libs/c3ga/src/c3ga/InnerExplicit.hpp
qcoumes/GA-physics
be72e0959620973ab29cd9e4705e97eda4356fe9
[ "MIT" ]
1
2020-03-23T19:17:06.000Z
2020-03-23T19:17:06.000Z
// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee // InnerExplicit.hpp // This file is part of the Garamon for c3ga. // Authors: Stephane Breuils and Vincent Nozick // Contact: vincent.nozick@u-pem.fr // // Licence MIT // A a copy of the MIT License is given along with this program /// \file InnerExplicit.hpp /// \author Stephane Breuils, Vincent Nozick /// \brief Explicit precomputed per grades inner products of c3ga. #ifndef C3GA_INNER_PRODUCT_EXPLICIT_HPP__ #define C3GA_INNER_PRODUCT_EXPLICIT_HPP__ #pragma once #include <Eigen/Core> #include "c3ga/Mvec.hpp" #include "c3ga/Inner.hpp" #include "c3ga/Constants.hpp" /*! * @namespace c3ga */ namespace c3ga { template<typename T> class Mvec; /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 0). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0 template<typename T> void inner_0_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 1). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_0_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1.coeff(0)*mv2; } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 2). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2 template<typename T> void inner_0_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1.coeff(0)*mv2; } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 3). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3 template<typename T> void inner_0_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1.coeff(0)*mv2; } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 4). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 4 template<typename T> void inner_0_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1.coeff(0)*mv2; } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 5). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 5 template<typename T> void inner_0_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1.coeff(0)*mv2; } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 0). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_1_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 1). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0 template<typename T> void inner_1_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(1)*mv2.coeff(1) + mv1.coeff(2)*mv2.coeff(2) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 2). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_1_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(3) - mv1.coeff(1)*mv2.coeff(0) - mv1.coeff(2)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(2); mv3.coeffRef(1) += mv1.coeff(0)*mv2.coeff(6) - mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(3)*mv2.coeff(5) - mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(2) += mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(3)*mv2.coeff(7) - mv1.coeff(4)*mv2.coeff(1); mv3.coeffRef(3) += mv1.coeff(0)*mv2.coeff(9) + mv1.coeff(1)*mv2.coeff(5) + mv1.coeff(2)*mv2.coeff(7) - mv1.coeff(4)*mv2.coeff(2); mv3.coeffRef(4) += mv1.coeff(1)*mv2.coeff(6) + mv1.coeff(2)*mv2.coeff(8) + mv1.coeff(3)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(3); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 3). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2 template<typename T> void inner_1_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(2) + mv1.coeff(2)*mv2.coeff(0) + mv1.coeff(3)*mv2.coeff(1); mv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(1)*mv2.coeff(0) + mv1.coeff(3)*mv2.coeff(3); mv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(5) - mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(3); mv3.coeffRef(3) += -mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(3)*mv2.coeff(5); mv3.coeffRef(4) += -mv1.coeff(0)*mv2.coeff(7) + mv1.coeff(3)*mv2.coeff(6) - mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(5) += -mv1.coeff(0)*mv2.coeff(8) - mv1.coeff(2)*mv2.coeff(6) - mv1.coeff(4)*mv2.coeff(1); mv3.coeffRef(6) += -mv1.coeff(2)*mv2.coeff(7) - mv1.coeff(3)*mv2.coeff(8) - mv1.coeff(4)*mv2.coeff(2); mv3.coeffRef(7) += -mv1.coeff(0)*mv2.coeff(9) + mv1.coeff(1)*mv2.coeff(6) - mv1.coeff(4)*mv2.coeff(3); mv3.coeffRef(8) += mv1.coeff(1)*mv2.coeff(7) - mv1.coeff(3)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(4); mv3.coeffRef(9) += mv1.coeff(1)*mv2.coeff(8) + mv1.coeff(2)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(5); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 4). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3 template<typename T> void inner_1_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(0); mv3.coeffRef(1) += mv1.coeff(0)*mv2.coeff(2) + mv1.coeff(2)*mv2.coeff(0); mv3.coeffRef(2) += mv1.coeff(2)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(2); mv3.coeffRef(3) += mv1.coeff(0)*mv2.coeff(3) - mv1.coeff(1)*mv2.coeff(0); mv3.coeffRef(4) += -mv1.coeff(1)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(3); mv3.coeffRef(5) += -mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(3); mv3.coeffRef(6) += mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(7) += mv1.coeff(3)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(1); mv3.coeffRef(8) += -mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(2); mv3.coeffRef(9) += mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(3); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 5). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 4 template<typename T> void inner_1_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(0); mv3.coeffRef(1) += -mv1.coeff(3)*mv2.coeff(0); mv3.coeffRef(2) += mv1.coeff(2)*mv2.coeff(0); mv3.coeffRef(3) += -mv1.coeff(1)*mv2.coeff(0); mv3.coeffRef(4) += -mv1.coeff(4)*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 0). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2 template<typename T> void inner_2_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 1). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_2_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(1) + mv1.coeff(1)*mv2.coeff(2) + mv1.coeff(2)*mv2.coeff(3) - mv1.coeff(3)*mv2.coeff(0); mv3.coeffRef(1) += mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(4)*mv2.coeff(2) + mv1.coeff(5)*mv2.coeff(3) - mv1.coeff(6)*mv2.coeff(0); mv3.coeffRef(2) += mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(1) + mv1.coeff(7)*mv2.coeff(3) - mv1.coeff(8)*mv2.coeff(0); mv3.coeffRef(3) += mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(5)*mv2.coeff(1) - mv1.coeff(7)*mv2.coeff(2) - mv1.coeff(9)*mv2.coeff(0); mv3.coeffRef(4) += mv1.coeff(3)*mv2.coeff(4) - mv1.coeff(6)*mv2.coeff(1) - mv1.coeff(8)*mv2.coeff(2) - mv1.coeff(9)*mv2.coeff(3); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 2). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0 template<typename T> void inner_2_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(6) - mv1.coeff(1)*mv2.coeff(8) - mv1.coeff(2)*mv2.coeff(9) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(4) - mv1.coeff(5)*mv2.coeff(5) - mv1.coeff(6)*mv2.coeff(0) - mv1.coeff(7)*mv2.coeff(7) - mv1.coeff(8)*mv2.coeff(1) - mv1.coeff(9)*mv2.coeff(2); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 3). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_2_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(2) - mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(5) - mv1.coeff(4)*mv2.coeff(0) - mv1.coeff(5)*mv2.coeff(1) - mv1.coeff(7)*mv2.coeff(3); mv3.coeffRef(1) += -mv1.coeff(1)*mv2.coeff(7) - mv1.coeff(2)*mv2.coeff(8) - mv1.coeff(3)*mv2.coeff(2) - mv1.coeff(7)*mv2.coeff(6) + mv1.coeff(8)*mv2.coeff(0) + mv1.coeff(9)*mv2.coeff(1); mv3.coeffRef(2) += mv1.coeff(0)*mv2.coeff(7) - mv1.coeff(2)*mv2.coeff(9) - mv1.coeff(3)*mv2.coeff(4) + mv1.coeff(5)*mv2.coeff(6) - mv1.coeff(6)*mv2.coeff(0) + mv1.coeff(9)*mv2.coeff(3); mv3.coeffRef(3) += mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(1)*mv2.coeff(9) - mv1.coeff(3)*mv2.coeff(5) - mv1.coeff(4)*mv2.coeff(6) - mv1.coeff(6)*mv2.coeff(1) - mv1.coeff(8)*mv2.coeff(3); mv3.coeffRef(4) += -mv1.coeff(4)*mv2.coeff(7) - mv1.coeff(5)*mv2.coeff(8) - mv1.coeff(6)*mv2.coeff(2) - mv1.coeff(7)*mv2.coeff(9) - mv1.coeff(8)*mv2.coeff(4) - mv1.coeff(9)*mv2.coeff(5); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 4). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2 template<typename T> void inner_2_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(2) - mv1.coeff(7)*mv2.coeff(0); mv3.coeffRef(1) += mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(3) + mv1.coeff(5)*mv2.coeff(0); mv3.coeffRef(2) += mv1.coeff(0)*mv2.coeff(2) + mv1.coeff(1)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(3) += -mv1.coeff(4)*mv2.coeff(1) - mv1.coeff(5)*mv2.coeff(2) - mv1.coeff(7)*mv2.coeff(3); mv3.coeffRef(4) += -mv1.coeff(2)*mv2.coeff(4) + mv1.coeff(3)*mv2.coeff(1) - mv1.coeff(9)*mv2.coeff(0); mv3.coeffRef(5) += mv1.coeff(1)*mv2.coeff(4) + mv1.coeff(3)*mv2.coeff(2) + mv1.coeff(8)*mv2.coeff(0); mv3.coeffRef(6) += -mv1.coeff(7)*mv2.coeff(4) + mv1.coeff(8)*mv2.coeff(1) + mv1.coeff(9)*mv2.coeff(2); mv3.coeffRef(7) += -mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(6)*mv2.coeff(0); mv3.coeffRef(8) += mv1.coeff(5)*mv2.coeff(4) - mv1.coeff(6)*mv2.coeff(1) + mv1.coeff(9)*mv2.coeff(3); mv3.coeffRef(9) += -mv1.coeff(4)*mv2.coeff(4) - mv1.coeff(6)*mv2.coeff(2) - mv1.coeff(8)*mv2.coeff(3); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 5). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3 template<typename T> void inner_2_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(2)*mv2.coeff(0); mv3.coeffRef(1) += mv1.coeff(1)*mv2.coeff(0); mv3.coeffRef(2) += -mv1.coeff(7)*mv2.coeff(0); mv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(0); mv3.coeffRef(4) += mv1.coeff(5)*mv2.coeff(0); mv3.coeffRef(5) += -mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(6) += -mv1.coeff(3)*mv2.coeff(0); mv3.coeffRef(7) += -mv1.coeff(9)*mv2.coeff(0); mv3.coeffRef(8) += mv1.coeff(8)*mv2.coeff(0); mv3.coeffRef(9) += -mv1.coeff(6)*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 0). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3 template<typename T> void inner_3_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 1). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2 template<typename T> void inner_3_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(2) + mv1.coeff(1)*mv2.coeff(3) - mv1.coeff(2)*mv2.coeff(0); mv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(2) += -mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(2) - mv1.coeff(5)*mv2.coeff(0); mv3.coeffRef(3) += -mv1.coeff(2)*mv2.coeff(1) - mv1.coeff(4)*mv2.coeff(2) - mv1.coeff(5)*mv2.coeff(3); mv3.coeffRef(4) += -mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(6)*mv2.coeff(3) - mv1.coeff(7)*mv2.coeff(0); mv3.coeffRef(5) += -mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(6)*mv2.coeff(2) - mv1.coeff(8)*mv2.coeff(0); mv3.coeffRef(6) += -mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(7)*mv2.coeff(2) - mv1.coeff(8)*mv2.coeff(3); mv3.coeffRef(7) += -mv1.coeff(3)*mv2.coeff(4) + mv1.coeff(6)*mv2.coeff(1) - mv1.coeff(9)*mv2.coeff(0); mv3.coeffRef(8) += -mv1.coeff(4)*mv2.coeff(4) + mv1.coeff(7)*mv2.coeff(1) - mv1.coeff(9)*mv2.coeff(3); mv3.coeffRef(9) += -mv1.coeff(5)*mv2.coeff(4) + mv1.coeff(8)*mv2.coeff(1) + mv1.coeff(9)*mv2.coeff(2); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 2). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_3_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(1)*mv2.coeff(5) - mv1.coeff(2)*mv2.coeff(0) - mv1.coeff(3)*mv2.coeff(7) - mv1.coeff(4)*mv2.coeff(1) - mv1.coeff(5)*mv2.coeff(2); mv3.coeffRef(1) += mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(1)*mv2.coeff(9) - mv1.coeff(2)*mv2.coeff(3) - mv1.coeff(6)*mv2.coeff(7) - mv1.coeff(7)*mv2.coeff(1) - mv1.coeff(8)*mv2.coeff(2); mv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(6) + mv1.coeff(3)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(3) + mv1.coeff(6)*mv2.coeff(5) + mv1.coeff(7)*mv2.coeff(0) - mv1.coeff(9)*mv2.coeff(2); mv3.coeffRef(3) += -mv1.coeff(1)*mv2.coeff(6) - mv1.coeff(3)*mv2.coeff(8) - mv1.coeff(5)*mv2.coeff(3) - mv1.coeff(6)*mv2.coeff(4) + mv1.coeff(8)*mv2.coeff(0) + mv1.coeff(9)*mv2.coeff(1); mv3.coeffRef(4) += -mv1.coeff(2)*mv2.coeff(6) - mv1.coeff(4)*mv2.coeff(8) - mv1.coeff(5)*mv2.coeff(9) - mv1.coeff(7)*mv2.coeff(4) - mv1.coeff(8)*mv2.coeff(5) - mv1.coeff(9)*mv2.coeff(7); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 3). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0 template<typename T> void inner_3_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(7) + mv1.coeff(1)*mv2.coeff(8) + mv1.coeff(2)*mv2.coeff(2) + mv1.coeff(3)*mv2.coeff(9) + mv1.coeff(4)*mv2.coeff(4) + mv1.coeff(5)*mv2.coeff(5) - mv1.coeff(6)*mv2.coeff(6) + mv1.coeff(7)*mv2.coeff(0) + mv1.coeff(8)*mv2.coeff(1) + mv1.coeff(9)*mv2.coeff(3); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 4). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_3_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(3)*mv2.coeff(3) + mv1.coeff(6)*mv2.coeff(0); mv3.coeffRef(1) += -mv1.coeff(3)*mv2.coeff(4) + mv1.coeff(4)*mv2.coeff(1) + mv1.coeff(5)*mv2.coeff(2) + mv1.coeff(9)*mv2.coeff(0); mv3.coeffRef(2) += mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(1) + mv1.coeff(5)*mv2.coeff(3) - mv1.coeff(8)*mv2.coeff(0); mv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(2) - mv1.coeff(4)*mv2.coeff(3) + mv1.coeff(7)*mv2.coeff(0); mv3.coeffRef(4) += -mv1.coeff(6)*mv2.coeff(4) + mv1.coeff(7)*mv2.coeff(1) + mv1.coeff(8)*mv2.coeff(2) + mv1.coeff(9)*mv2.coeff(3); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 5). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2 template<typename T> void inner_3_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(3)*mv2.coeff(0); mv3.coeffRef(1) += -mv1.coeff(1)*mv2.coeff(0); mv3.coeffRef(2) += mv1.coeff(0)*mv2.coeff(0); mv3.coeffRef(3) += mv1.coeff(6)*mv2.coeff(0); mv3.coeffRef(4) += mv1.coeff(5)*mv2.coeff(0); mv3.coeffRef(5) += -mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(6) += mv1.coeff(9)*mv2.coeff(0); mv3.coeffRef(7) += mv1.coeff(2)*mv2.coeff(0); mv3.coeffRef(8) += -mv1.coeff(8)*mv2.coeff(0); mv3.coeffRef(9) += mv1.coeff(7)*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 0). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 4 template<typename T> void inner_4_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 1). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3 template<typename T> void inner_4_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(3) - mv1.coeff(1)*mv2.coeff(0); mv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(0); mv3.coeffRef(2) += -mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(3); mv3.coeffRef(3) += mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(0); mv3.coeffRef(4) += mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(3); mv3.coeffRef(5) += mv1.coeff(2)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(2); mv3.coeffRef(6) += mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(7) += mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(3); mv3.coeffRef(8) += mv1.coeff(2)*mv2.coeff(4) + mv1.coeff(4)*mv2.coeff(2); mv3.coeffRef(9) += mv1.coeff(3)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(1); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 2). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2 template<typename T> void inner_4_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(7) - mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(2); mv3.coeffRef(1) += mv1.coeff(0)*mv2.coeff(5) + mv1.coeff(1)*mv2.coeff(0) - mv1.coeff(3)*mv2.coeff(2); mv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(2)*mv2.coeff(0) + mv1.coeff(3)*mv2.coeff(1); mv3.coeffRef(3) += -mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(5) - mv1.coeff(3)*mv2.coeff(7); mv3.coeffRef(4) += -mv1.coeff(0)*mv2.coeff(9) + mv1.coeff(1)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(2); mv3.coeffRef(5) += mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(2)*mv2.coeff(3) + mv1.coeff(4)*mv2.coeff(1); mv3.coeffRef(6) += mv1.coeff(1)*mv2.coeff(8) + mv1.coeff(2)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(7); mv3.coeffRef(7) += -mv1.coeff(0)*mv2.coeff(6) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(8) += -mv1.coeff(1)*mv2.coeff(6) + mv1.coeff(3)*mv2.coeff(9) + mv1.coeff(4)*mv2.coeff(5); mv3.coeffRef(9) += -mv1.coeff(2)*mv2.coeff(6) - mv1.coeff(3)*mv2.coeff(8) - mv1.coeff(4)*mv2.coeff(4); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 3). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_4_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(6) + mv1.coeff(1)*mv2.coeff(0) + mv1.coeff(2)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(3); mv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(9) - mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(5) + mv1.coeff(4)*mv2.coeff(3); mv3.coeffRef(2) += mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(3)*mv2.coeff(5) - mv1.coeff(4)*mv2.coeff(1); mv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(7) + mv1.coeff(2)*mv2.coeff(2) + mv1.coeff(3)*mv2.coeff(4) + mv1.coeff(4)*mv2.coeff(0); mv3.coeffRef(4) += -mv1.coeff(1)*mv2.coeff(7) - mv1.coeff(2)*mv2.coeff(8) - mv1.coeff(3)*mv2.coeff(9) + mv1.coeff(4)*mv2.coeff(6); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 4). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0 template<typename T> void inner_4_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(2) - mv1.coeff(3)*mv2.coeff(3) + mv1.coeff(4)*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 5). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_4_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(0); mv3.coeffRef(1) += mv1.coeff(3)*mv2.coeff(0); mv3.coeffRef(2) += -mv1.coeff(2)*mv2.coeff(0); mv3.coeffRef(3) += mv1.coeff(1)*mv2.coeff(0); mv3.coeffRef(4) += mv1.coeff(4)*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 0). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 5 template<typename T> void inner_5_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3 += mv1*mv2.coeff(0); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 1). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 4 template<typename T> void inner_5_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(0); mv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(3); mv3.coeffRef(2) += mv1.coeff(0)*mv2.coeff(2); mv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(1); mv3.coeffRef(4) += -mv1.coeff(0)*mv2.coeff(4); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 2). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3 template<typename T> void inner_5_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(2); mv3.coeffRef(1) += mv1.coeff(0)*mv2.coeff(1); mv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(7); mv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(0); mv3.coeffRef(4) += mv1.coeff(0)*mv2.coeff(5); mv3.coeffRef(5) += -mv1.coeff(0)*mv2.coeff(4); mv3.coeffRef(6) += -mv1.coeff(0)*mv2.coeff(3); mv3.coeffRef(7) += -mv1.coeff(0)*mv2.coeff(9); mv3.coeffRef(8) += mv1.coeff(0)*mv2.coeff(8); mv3.coeffRef(9) += -mv1.coeff(0)*mv2.coeff(6); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 3). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2 template<typename T> void inner_5_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(3); mv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(1); mv3.coeffRef(2) += mv1.coeff(0)*mv2.coeff(0); mv3.coeffRef(3) += mv1.coeff(0)*mv2.coeff(6); mv3.coeffRef(4) += mv1.coeff(0)*mv2.coeff(5); mv3.coeffRef(5) += -mv1.coeff(0)*mv2.coeff(4); mv3.coeffRef(6) += mv1.coeff(0)*mv2.coeff(9); mv3.coeffRef(7) += mv1.coeff(0)*mv2.coeff(2); mv3.coeffRef(8) += -mv1.coeff(0)*mv2.coeff(8); mv3.coeffRef(9) += mv1.coeff(0)*mv2.coeff(7); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 4). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1 template<typename T> void inner_5_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += mv1.coeff(0)*mv2.coeff(0); mv3.coeffRef(1) += mv1.coeff(0)*mv2.coeff(3); mv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(2); mv3.coeffRef(3) += mv1.coeff(0)*mv2.coeff(1); mv3.coeffRef(4) += mv1.coeff(0)*mv2.coeff(4); } /// \brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 5). /// \tparam the type of value that we manipulate, either float or double or something. /// \param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd /// \param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd /// \param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0 template<typename T> void inner_5_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){ mv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(0); } template<typename T> std::array<std::array<std::function<void(const Eigen::Matrix<T, Eigen::Dynamic, 1> & , const Eigen::Matrix<T, Eigen::Dynamic, 1> & , Eigen::Matrix<T, Eigen::Dynamic, 1>&)>, 6>, 6> innerFunctionsContainer = {{ {{inner_0_0<T>,inner_0_1<T>,inner_0_2<T>,inner_0_3<T>,inner_0_4<T>,inner_0_5<T>}}, {{inner_1_0<T>,inner_1_1<T>,inner_1_2<T>,inner_1_3<T>,inner_1_4<T>,inner_1_5<T>}}, {{inner_2_0<T>,inner_2_1<T>,inner_2_2<T>,inner_2_3<T>,inner_2_4<T>,inner_2_5<T>}}, {{inner_3_0<T>,inner_3_1<T>,inner_3_2<T>,inner_3_3<T>,inner_3_4<T>,inner_3_5<T>}}, {{inner_4_0<T>,inner_4_1<T>,inner_4_2<T>,inner_4_3<T>,inner_4_4<T>,inner_4_5<T>}}, {{inner_5_0<T>,inner_5_1<T>,inner_5_2<T>,inner_5_3<T>,inner_5_4<T>,inner_5_5<T>}} }}; }/// End of Namespace #endif // C3GA_INNER_PRODUCT_EXPLICIT_HPP__
70.185965
300
0.691996
qcoumes
43645317dac1cc9e6156bd8dba90d8f7ce9f3915
1,214
hpp
C++
.vscode/cquery_cached_index/@Users@erichamilton@Development@Robotics@VEX-2018-2019@CART-2019-PROS-V5/include@motorControlFuncs.hpp
ehami/CART-2019-PROS-V5
d02f302a214a633ceb8abd73fb5fed0348340007
[ "MIT" ]
1
2019-01-22T02:16:34.000Z
2019-01-22T02:16:34.000Z
.vscode/cquery_cached_index/@Users@erichamilton@Development@Robotics@VEX-2018-2019@CART-2019-PROS-V5/include@motorControlFuncs.hpp
ehami/CART-2019-PROS-V5
d02f302a214a633ceb8abd73fb5fed0348340007
[ "MIT" ]
1
2019-03-01T14:47:26.000Z
2019-03-01T14:47:26.000Z
include/motorControlFuncs.hpp
ehami/CART-2019-PROS-V5
d02f302a214a633ceb8abd73fb5fed0348340007
[ "MIT" ]
null
null
null
// resets all motor encoder positions to zero void resetMotorEncoderPositions(); // initializes all motors with correct settings void initMotors(); void setDriveWheelsToPower(int left, int right); // Sets the left motors to a specific velocity. (positive values go forward) void setLeftWheelsToPower(int power); // Sets the right motors to a specific velocity. (positive values go // backward) void setRightWheelsToPower(int power); // sets motor target, but does not wait for motor to reach target. void driveForDistance(double leftInches, double rightInches, int velocity = 100); bool atDistanceDriveGoal(int threshold); // sets both lift motors to the same locations void setLiftToPosition(double percentRaised); // stop drive wheels void brakeDriveWheels(); // allow drive wheels to move void unBrakeDriveWheels(); // sets motors to a specific velocity (not power) in order to be // consistent. positive goes up void selLiftToVelocity(int velocity); // stop lift motors void brakeLift(); // allow lift to move void unBrakeLift(); void turnActuator(int degrees); void moveActuatorVelocity(int velocity); void shootBall(); void delayUntilShooterReady(); void printTemps();
24.28
76
0.762768
ehami
43661fec3da366448856d105a8b4e9fb7127c93d
390
hh
C++
src/timer.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
null
null
null
src/timer.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
null
null
null
src/timer.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
1
2019-01-24T16:14:56.000Z
2019-01-24T16:14:56.000Z
// timer.hh // // A timer class #ifndef TIMER_HEADER #define TIMER_HEADER #include <ctime> class Timer { public: Timer(); //!< construct and start void Start(); //!< start clock double Stop(); //!< reset clock & return time in seconds //! return time in seconds double Dtime() const; private: std::clock_t t0; // start time std::clock_t t1; // end time }; #endif
15.6
59
0.638462
maciejwlodek
4366226fbc670d2c61d95a71fc3f2bccabe5b77b
744
cpp
C++
algorithm-challenges/baekjoon-online-judge/challenges/9000/9942.cpp
nbsp1221/algorithm
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
[ "MIT" ]
null
null
null
algorithm-challenges/baekjoon-online-judge/challenges/9000/9942.cpp
nbsp1221/algorithm
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
[ "MIT" ]
null
null
null
algorithm-challenges/baekjoon-online-judge/challenges/9000/9942.cpp
nbsp1221/algorithm
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); vector<int> inputs; int maxInput = 0; while (true) { int n; cin >> n; if (cin.fail() || cin.eof()) { break; } inputs.push_back(n); maxInput = max(maxInput, n); } vector<uint64_t> dp(maxInput + 1); dp[1] = 1; for (int i = 2; i <= maxInput; i++) { int factor = i - round(sqrt(i * 2 + 1)) + 1; dp[i] = dp[factor] * 2 + (1ull << (i - factor)) - 1; } for (auto i = 0u; i < inputs.size(); i++) { cout << "Case " << (i + 1) << ": " << dp[inputs[i]] << "\n"; } return 0; }
18.146341
68
0.456989
nbsp1221
4367112792a638f77c87350852f965347958b654
437
cpp
C++
OO/[OO] Folha de Pagamento/OrcamentoEstouradoException.cpp
JovemPedr0/LP1
d1e1a6df95812cab1dca3b981273c9557557572e
[ "MIT" ]
null
null
null
OO/[OO] Folha de Pagamento/OrcamentoEstouradoException.cpp
JovemPedr0/LP1
d1e1a6df95812cab1dca3b981273c9557557572e
[ "MIT" ]
null
null
null
OO/[OO] Folha de Pagamento/OrcamentoEstouradoException.cpp
JovemPedr0/LP1
d1e1a6df95812cab1dca3b981273c9557557572e
[ "MIT" ]
null
null
null
#include "OrcamentoEstouradoException.hpp" #include <iostream> OrcamentoEstouradoException::OrcamentoEstouradoException(double total){ //std::cout << "OrcamentoEstouradoException " << total << std::endl; valorCapturado = total; } std::string OrcamentoEstouradoException::getMessage(){ char texto[50]; sprintf(texto, "%.0lf", valorCapturado); return "OrcamentoEstouradoException " + std::string(texto) + "\n"; }
31.214286
72
0.723112
JovemPedr0
43674e03267b79bb9bc44ba8ae72ce92758983b4
375
cpp
C++
chapter-19/19.14.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-19/19.14.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-19/19.14.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
#include "Screen.hpp" int main() { // legal; auto pmf = &Screen::get_cursor; // pmf is a member function pointer points to Screen::get_cursor, which is a member function which accepts no parameter and return type as char; pmf = &Screen::get; // now pmf points to Screen::get, which has same function type as Screen::get_cursor(refer to my Screen class version). }
34.090909
146
0.72
zero4drift
43678c48cca4b1030020002e6f4f84823c1f544e
308
cpp
C++
src/crypt.cpp
Shtille/scythe
795b482921bed9ab36fd9ced38863371c75367ab
[ "MIT" ]
null
null
null
src/crypt.cpp
Shtille/scythe
795b482921bed9ab36fd9ced38863371c75367ab
[ "MIT" ]
8
2018-07-12T14:10:53.000Z
2020-09-17T11:15:52.000Z
src/crypt.cpp
Shtille/scythe
795b482921bed9ab36fd9ced38863371c75367ab
[ "MIT" ]
null
null
null
#include "crypt.h" #include <cstring> namespace scythe { void Encrypt(char* buffer_out, const char* buffer_in, size_t length, const char* key) { size_t key_size = strlen(key); for (size_t i = 0; i < length; ++i) { buffer_out[i] = buffer_in[i] ^ key[i % key_size]; } } } // namespace scythe
19.25
86
0.646104
Shtille
436861f85c4c3c2caa5c4b1cc510c741b110e4da
1,821
cpp
C++
source/playthrough.cpp
Dani88alv/OoT3D_Randomizer
93b0117672acc0775c164026f71e772c5089e1b8
[ "MIT" ]
null
null
null
source/playthrough.cpp
Dani88alv/OoT3D_Randomizer
93b0117672acc0775c164026f71e772c5089e1b8
[ "MIT" ]
null
null
null
source/playthrough.cpp
Dani88alv/OoT3D_Randomizer
93b0117672acc0775c164026f71e772c5089e1b8
[ "MIT" ]
null
null
null
#include "playthrough.hpp" #include "fill.hpp" #include "location_access.hpp" #include "logic.hpp" #include "random.hpp" #include "spoiler_log.hpp" #include "../code/src/item_override.h" #include <3ds.h> #include <unistd.h> namespace Playthrough { int Playthrough_Init(u32 seed) { Random_Init(seed); overrides.clear(); ItemReset(); HintReset(); Exits::AccessReset(); Settings::UpdateSettings(); Logic::UpdateHelpers(); int ret = Fill(); if (ret < 0) { return ret; } GenerateHash(); if (Settings::GenerateSpoilerLog) { //write logs printf("\x1b[11;10HWriting Spoiler Log..."); if (SpoilerLog_Write()) { printf("Done"); } else { printf("Failed"); } #ifdef ENABLE_DEBUG printf("\x1b[11;10HWriting Placement Log..."); if (PlacementLog_Write()) { printf("Done\n"); } else { printf("Failed\n"); } #endif } else { playthroughLocations.clear(); playthroughBeatable = false; } return 1; } //used for generating a lot of seeds at once int Playthrough_Repeat(int count /*= 1*/) { printf("\x1b[0;0HGENERATING %d SEEDS", count); u32 repeatedSeed = 0; for (int i = 0; i < count; i++) { repeatedSeed = rand() % 0xFFFFFFFF; Settings::seed = std::to_string(repeatedSeed); Playthrough_Init(repeatedSeed); PlacementLog_Clear(); printf("\x1b[15;15HSeeds Generated: %d\n", i + 1); } return 1; } //idk where else to put this so it goes here s16 GetRandomPrice() { return 5 * Random(1, 20); } }
23.960526
59
0.531027
Dani88alv
436eb109cf174314f0cbb599e87f49be17501c84
905
cpp
C++
src/mapper/s3/S3MapperNaive.cpp
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
1
2019-04-06T08:43:15.000Z
2019-04-06T08:43:15.000Z
src/mapper/s3/S3MapperNaive.cpp
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
1
2019-04-15T09:49:13.000Z
2019-04-15T09:49:13.000Z
src/mapper/s3/S3MapperNaive.cpp
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** *include files ******************************************************************************/ #include "../../utils/tools/city.h" #include "S3MapperNaive.h" /****************************************************************************** *Interface ******************************************************************************/ std::pair<std::string, VirtualObject> S3MapperNaive::mapObject(std::string objectName, std::size_t objectSize, operation operationType) { #ifdef TIMER_M Timer timer = Timer(); timer.startTime(); #endif std::string filename = "container_" + objectName + ".dat"; VirtualObject object = VirtualObject(); object.name = objectName; object.size = objectSize; object.containerOffset = 0; #ifdef TIMER_M timer.endTime(__FUNCTION__); #endif return std::make_pair(filename,object); }
33.518519
79
0.472928
akougkas
436f67f30b6bd0bad01e21b0a5f1d95257e73447
1,147
cpp
C++
libvast/test/system/sink.cpp
lava/vast
0bc9e3c12eb31ec50dd0270626d55e84b2255899
[ "BSD-3-Clause" ]
249
2019-08-26T01:44:45.000Z
2022-03-26T14:12:32.000Z
libvast/test/system/sink.cpp
5l1v3r1/vast
a2cb4be879a13cef855da2c1d73083204aed4dff
[ "BSD-3-Clause" ]
586
2019-08-06T13:10:36.000Z
2022-03-31T08:31:00.000Z
libvast/test/system/sink.cpp
satta/vast
6c7587effd4265c4a5de23252bc7c7af3ef78bee
[ "BSD-3-Clause" ]
37
2019-08-16T02:01:14.000Z
2022-02-21T16:13:59.000Z
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2016 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/system/sink.hpp" #include "vast/error.hpp" #include "vast/format/zeek.hpp" #define SUITE system #include "vast/test/data.hpp" #include "vast/test/fixtures/actor_system_and_events.hpp" #include "vast/test/test.hpp" using namespace vast; using namespace vast::system; FIXTURE_SCOPE(sink_tests, fixtures::actor_system_and_events) TEST(zeek sink) { MESSAGE("constructing a sink"); caf::settings options; caf::put(options, "vast.export.write", directory.string()); auto writer = std::make_unique<format::zeek::writer>(options); auto snk = self->spawn(sink, std::move(writer), 20u); MESSAGE("sending table slices"); for (auto& slice : zeek_conn_log) self->send(snk, slice); MESSAGE("shutting down"); self->send_exit(snk, caf::exit_reason::user_shutdown); self->wait_for(snk); CHECK(exists(directory / "zeek.conn.log")); } FIXTURE_SCOPE_END()
28.675
64
0.681779
lava
4372dcffd6dbdb3702036e1c592e860f950b5881
545
cpp
C++
source/Engine/GameObject.cpp
rincew1nd/Minesweeper-Switch
6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467
[ "MIT" ]
8
2018-06-27T00:34:11.000Z
2018-09-07T06:56:20.000Z
source/Engine/GameObject.cpp
rincew1nd/Minesweeper-Switch
6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467
[ "MIT" ]
null
null
null
source/Engine/GameObject.cpp
rincew1nd/Minesweeper-Switch
6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467
[ "MIT" ]
2
2018-06-28T03:02:07.000Z
2019-01-26T06:02:17.000Z
#include "GameObject.hpp" GameObject::GameObject(int x, int y, int w, int h) { _rect = new SDL_Rect(); _rect->x = x; _rect->y = y; _rect->w = w; _rect->h = h; } void GameObject::Move(int dx, int dy) { _rect->x += dx; _rect->y += dy; }; void GameObject::SetAction(std::function<void()> func) { _onPress = func; } bool GameObject::Hovered(TouchInfo* ti) { return ti->ValueOne >= _rect->x && ti->ValueOne <= _rect->x + _rect->w && ti->ValueTwo >= _rect->y && ti->ValueTwo <= _rect->y + _rect->h; }
20.185185
77
0.572477
rincew1nd
4377417baf9a1e949e6080bb1ae99dcf9ff202fb
1,753
cpp
C++
Hw3/Hw3.cpp
dumblole/CMSC-140
00e8ad5f273fe7414e2b15eb28b7e39b25ab188a
[ "MIT" ]
1
2022-03-01T00:30:34.000Z
2022-03-01T00:30:34.000Z
Hw3/Hw3.cpp
dumblole/CMSC-140
00e8ad5f273fe7414e2b15eb28b7e39b25ab188a
[ "MIT" ]
null
null
null
Hw3/Hw3.cpp
dumblole/CMSC-140
00e8ad5f273fe7414e2b15eb28b7e39b25ab188a
[ "MIT" ]
null
null
null
/* Hw3.cpp CMSC 140, CRN 24381, Dr. Kuijt Max C. Develop a program that calculates the final score and the average score for a student from his/her (1)class participation, (2) test, (3) assignment, (4) exam, and (5) practice scores. The user should enter the name of the student and scores ranging from 0 to 100 for each grading item. The final score is the sum of all grading items. The average score is the average of all grading items. */ #include <iostream> #include <string> using namespace std; bool checkNum(float grade) { /* Checks if grade is between 0 and 100 */ return (grade >= 0 && grade <= 100); } int main() { bool isProgramRunning = true; float finalScore = 0, avgScore, input; string studentName, questions[5] = {"Enter Class Participation Score ranging from 0 to 100: ", "Enter Test Score ranging from 0 to 100: ", "Enter Assignment Score ranging from 0 to 100: ", "Enter Exam Score ranging from 0 to 100: ", "Enter Practice Score ranging from 0 to 100: "}; while (isProgramRunning) { finalScore = 0; isProgramRunning = false; cout << "Enter the Student's name: "; getline(cin, studentName); for (int i = 0; i < 5; i++) { cout << questions[i]; cin >> input; if (!checkNum(input)) { isProgramRunning = true; cout << "Error: Please enter a number between 0 and 100 next time.\nRestarting...\n"; cin.ignore(); break; } finalScore += input; } avgScore = finalScore / 5; } cout << studentName << ": Final Score: " << finalScore << " Average Score: " << avgScore; return 0; }
29.216667
285
0.600685
dumblole
4377bfd06ea872fe4b8744feef0eef10ca39c8b9
1,420
cpp
C++
test/gc_ptr_test.cpp
eucpp/allocgc
8d134d58515e0e2a7348fdd1fdbe8c2e8423cfef
[ "Apache-2.0" ]
null
null
null
test/gc_ptr_test.cpp
eucpp/allocgc
8d134d58515e0e2a7348fdd1fdbe8c2e8423cfef
[ "Apache-2.0" ]
2
2017-01-17T16:24:59.000Z
2017-06-08T17:39:26.000Z
test/gc_ptr_test.cpp
eucpp/allocgc
8d134d58515e0e2a7348fdd1fdbe8c2e8423cfef
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <liballocgc/liballocgc.hpp> using namespace allocgc; using namespace allocgc::serial; TEST(gc_ptr_test, test_gc_ptr) { static const size_t SIZE = 8; gc_ptr<int[]> ptr1 = gc_new<int[]>(SIZE); gc_ptr<int[]> ptr2 = ptr1; ASSERT_EQ(ptr1, ptr2); ++ptr2; ASSERT_NE(ptr1, ptr2); --ptr2; ASSERT_EQ(ptr1, ptr2); ptr2 = ptr1 + SIZE; gc_pin<int[]> pin1 = ptr1.pin(); gc_pin<int[]> pin2 = ptr2.pin(); ASSERT_EQ(pin2.get(), pin1.get() + SIZE); ptr2 -= SIZE; ASSERT_EQ(ptr1, ptr2); } namespace { struct Base1 { int b1; }; struct Base2 { short b2; }; struct Derived : public Base1, public Base2 { double d; }; } TEST(gc_ptr_test, test_upcast_constructor) { gc_ptr<Derived> derived = gc_new<Derived>(); derived->b1 = 42; derived->b2 = 11; derived->d = 3.14; gc_ptr<Base1> base1 = derived; ASSERT_EQ(42, base1->b1); base1->b1 = 0; gc_ptr<Base2> base2 = derived; ASSERT_EQ(11, base2->b2); base2->b2 = 0; ASSERT_EQ(0, derived->b1); ASSERT_EQ(0, derived->b2); ASSERT_DOUBLE_EQ(3.14, derived->d); } namespace { struct A { size_t d1; size_t d2; }; } //TEST(gc_ptr_test, test_take) //{ // gc_ptr<A> p = gc_new<A>(); // p->d1 = -1; // p->d2 = 42; // // gc_ptr<size_t> pInner = take_interior<A, size_t, &A::d2>(p); // ASSERT_EQ(42, *pInner); //}
16.705882
66
0.592254
eucpp
4378ba0b8f929a843112c7e2c8bd518b6da63414
1,133
hh
C++
inc/grayvalley/common/OrderID.hh
grayvalley/common
fb5547898ae71c6a86bae6630e7193f5e1cff5db
[ "Apache-2.0" ]
null
null
null
inc/grayvalley/common/OrderID.hh
grayvalley/common
fb5547898ae71c6a86bae6630e7193f5e1cff5db
[ "Apache-2.0" ]
null
null
null
inc/grayvalley/common/OrderID.hh
grayvalley/common
fb5547898ae71c6a86bae6630e7193f5e1cff5db
[ "Apache-2.0" ]
null
null
null
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GVT_COMMON_ORDERID_HH #define GVT_COMMON_ORDERID_HH #include <string> #include <stdexcept> namespace GVT { class OrderID { public: std::string value; OrderID(std::string id) : value{id} {} ; bool operator==(const OrderID &other) const { return value == other.value; } }; } namespace std { template <> struct hash<GVT::OrderID> { size_t operator () (const GVT::OrderID &s) const { using std::hash; return hash<std::string>()(s.value); } }; } #endif //GVT_COMMON_ORDERID_HH
29.051282
84
0.671668
grayvalley
437d5bac8c129c549f047fdfe612cb984c49449a
17,434
cpp
C++
tests/validation/CL/DirectConvolutionLayer.cpp
giorgio-arena/ComputeLibraryBinary
b8bb65f0dc2561907e566908e102aabcb7d41d61
[ "MIT" ]
1
2019-05-14T11:36:51.000Z
2019-05-14T11:36:51.000Z
tests/validation/CL/DirectConvolutionLayer.cpp
giorgio-arena/ComputeLibraryBinary
b8bb65f0dc2561907e566908e102aabcb7d41d61
[ "MIT" ]
null
null
null
tests/validation/CL/DirectConvolutionLayer.cpp
giorgio-arena/ComputeLibraryBinary
b8bb65f0dc2561907e566908e102aabcb7d41d61
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017-2019 ARM Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "arm_compute/core/Types.h" #include "arm_compute/runtime/CL/CLTensor.h" #include "arm_compute/runtime/CL/CLTensorAllocator.h" #include "arm_compute/runtime/CL/functions/CLDirectConvolutionLayer.h" #include "tests/CL/CLAccessor.h" #include "tests/PaddingCalculator.h" #include "tests/datasets/DirectConvolutionLayerDataset.h" #include "tests/datasets/ShapeDatasets.h" #include "tests/framework/Asserts.h" #include "tests/framework/Macros.h" #include "tests/framework/datasets/Datasets.h" #include "tests/validation/Validation.h" #include "tests/validation/fixtures/DirectConvolutionLayerFixture.h" namespace arm_compute { namespace test { namespace validation { namespace { // COMPMID-517 Investigate the mismatch to see whether it is a real bug RelativeTolerance<half> tolerance_fp16(half(0.2)); /**< Tolerance for floating point tests */ RelativeTolerance<float> tolerance_fp32(0.02f); /**< Tolerance for floating point tests */ constexpr float tolerance_num = 0.07f; /**< Tolerance number */ constexpr AbsoluteTolerance<uint8_t> tolerance_qasymm8(1); /**< Tolerance for quantized tests */ const auto data_strides = combine(framework::dataset::make("StrideX", 1, 3), framework::dataset::make("StrideY", 1, 3)); const auto data_strides_small = combine(framework::dataset::make("StrideX", 1), framework::dataset::make("StrideY", 1)); const auto data_ksize_one = combine(framework::dataset::make("PadX", 0, 1), combine(framework::dataset::make("PadY", 0, 1), framework::dataset::make("KernelSize", 1))); const auto data_ksize_one_small = combine(framework::dataset::make("PadX", 0), combine(framework::dataset::make("PadY", 0), framework::dataset::make("KernelSize", 1))); const auto data_ksize_three = combine(framework::dataset::make("PadX", 0, 2), combine(framework::dataset::make("PadY", 0, 2), framework::dataset::make("KernelSize", 3))); const auto data_ksize_five = combine(framework::dataset::make("PadX", 0, 3), combine(framework::dataset::make("PadY", 0, 3), framework::dataset::make("KernelSize", 5))); const auto data_all_kernels = concat(concat(data_ksize_one, data_ksize_three), data_ksize_five); const auto data = combine(datasets::SmallDirectConvolutionShapes(), combine(data_strides, data_all_kernels)); const auto data_small = combine(datasets::SmallDirectConvolutionShapes(), combine(data_strides_small, data_ksize_one_small)); /** Direct convolution nightly data set. */ const auto data_nightly = combine(data, framework::dataset::make("NumKernels", { 1, 4 })); /** Direct convolution precommit data set. */ const auto data_precommit = combine(data_small, framework::dataset::make("NumKernels", { 1 })); /** Activation function Dataset*/ const auto ActivationFunctionsDataset = framework::dataset::make("ActivationInfo", { ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU, 0.5f) }); } // namespace TEST_SUITE(CL) TEST_SUITE(DirectConvolutionLayer) //TODO(COMPMID-415): Configuration tests? // *INDENT-OFF* // clang-format off DATA_TEST_CASE(Validate, framework::DatasetMode::ALL, zip(zip(zip(zip(zip(zip( framework::dataset::make("InputInfo", { TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Mismatching data type input/weights TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Mismatching input feature maps TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Unsupported kernel width TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Non-rectangular weights dimensions TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Invalid weights dimensions TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Invalid stride TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Invalid biases size TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Invalid biases dimensions TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Invalid output size TensorInfo(TensorShape(27U, 13U, 2U), 1, DataType::F32), // Window shrink TensorInfo(TensorShape(32U, 16U, 2U), 1, DataType::F32), }), framework::dataset::make("WeightsInfo",{ TensorInfo(TensorShape(3U, 3U, 2U, 4U), 1, DataType::F16), TensorInfo(TensorShape(3U, 3U, 3U, 4U), 1, DataType::F32), TensorInfo(TensorShape(9U, 9U, 2U, 4U), 1, DataType::F32), TensorInfo(TensorShape(5U, 3U, 2U, 4U), 1, DataType::F32), TensorInfo(TensorShape(3U, 3U, 2U, 4U, 3U), 1, DataType::F32), TensorInfo(TensorShape(3U, 3U, 2U, 4U), 1, DataType::F32), TensorInfo(TensorShape(3U, 3U, 2U, 4U), 1, DataType::F32), TensorInfo(TensorShape(3U, 3U, 2U, 4U), 1, DataType::F32), TensorInfo(TensorShape(3U, 3U, 2U, 4U), 1, DataType::F32), TensorInfo(TensorShape(3U, 3U, 2U, 4U), 1, DataType::F32), TensorInfo(TensorShape(1U, 1U, 2U, 4U), 1, DataType::F32), })), framework::dataset::make("BiasesInfo",{ TensorInfo(TensorShape(4U), 1, DataType::F32), TensorInfo(TensorShape(4U), 1, DataType::F32), TensorInfo(TensorShape(4U), 1, DataType::F32), TensorInfo(TensorShape(4U), 1, DataType::F32), TensorInfo(TensorShape(4U), 1, DataType::F32), TensorInfo(TensorShape(4U), 1, DataType::F32), TensorInfo(TensorShape(3U), 1, DataType::F32), TensorInfo(TensorShape(4U, 2U), 1, DataType::F32), TensorInfo(TensorShape(4U), 1, DataType::F32), TensorInfo(TensorShape(4U), 1, DataType::F32), TensorInfo(TensorShape(4U), 1, DataType::F32), })), framework::dataset::make("OutputInfo",{ TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(26U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(25U, 11U, 4U), 1, DataType::F32), TensorInfo(TensorShape(32U, 16U, 4U), 1, DataType::F32), })), framework::dataset::make("ConvInfo", { PadStrideInfo(1, 1, 0, 0), PadStrideInfo(1, 1, 0, 0), PadStrideInfo(1, 1, 0, 0), PadStrideInfo(1, 1, 0, 0), PadStrideInfo(1, 1, 0, 0), PadStrideInfo(3, 3, 0, 0), PadStrideInfo(1, 1, 0, 0), PadStrideInfo(1, 1, 0, 0), PadStrideInfo(1, 1, 0, 0), PadStrideInfo(1, 1, 0, 0), PadStrideInfo(1, 1, 0, 0), })), framework::dataset::make("ActivationInfo", { ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU) })), framework::dataset::make("Expected", { false, false, false, false, false, false, false, false, false, false, true })), input_info, weights_info, biases_info, output_info, conv_info, act_info, expected) { bool is_valid = bool(CLDirectConvolutionLayer::validate(&input_info.clone()->set_is_resizable(false), &weights_info.clone()->set_is_resizable(false), &biases_info.clone()->set_is_resizable(false), &output_info.clone()->set_is_resizable(false), conv_info, act_info)); ARM_COMPUTE_EXPECT(is_valid == expected, framework::LogLevel::ERRORS); } // clang-format on // *INDENT-ON* template <typename T> using CLDirectConvolutionLayerFixture = DirectConvolutionValidationFixture<CLTensor, CLAccessor, CLDirectConvolutionLayer, T>; template <typename T> using CLDirectConvolutionValidationWithTensorShapesFixture = DirectConvolutionValidationWithTensorShapesFixture<CLTensor, CLAccessor, CLDirectConvolutionLayer, T>; TEST_SUITE(Float) TEST_SUITE(FP16) FIXTURE_DATA_TEST_CASE(RunSmall, CLDirectConvolutionLayerFixture<half>, framework::DatasetMode::PRECOMMIT, combine(combine(combine(data_precommit, framework::dataset::make("DataType", DataType::F16)), ActivationFunctionsDataset), framework::dataset::make("DataLayout", DataLayout::NCHW))) { // Validate output validate(CLAccessor(_target), _reference, tolerance_fp16, tolerance_num); } FIXTURE_DATA_TEST_CASE(RunLarge, CLDirectConvolutionLayerFixture<half>, framework::DatasetMode::NIGHTLY, combine(combine(combine(data_nightly, framework::dataset::make("DataType", DataType::F16)), ActivationFunctionsDataset), framework::dataset::make("DataLayout", DataLayout::NCHW))) { // Validate output validate(CLAccessor(_target), _reference, tolerance_fp16, tolerance_num); } TEST_SUITE_END() // FP16 TEST_SUITE(FP32) FIXTURE_DATA_TEST_CASE(RunSmall, CLDirectConvolutionLayerFixture<float>, framework::DatasetMode::PRECOMMIT, combine(combine(combine(data_precommit, framework::dataset::make("DataType", DataType::F32)), ActivationFunctionsDataset), framework::dataset::make("DataLayout", { DataLayout::NCHW, DataLayout::NHWC }))) { validate(CLAccessor(_target), _reference, tolerance_fp32); } FIXTURE_DATA_TEST_CASE(RunLarge, CLDirectConvolutionLayerFixture<float>, framework::DatasetMode::NIGHTLY, combine(combine(combine(data_nightly, framework::dataset::make("DataType", DataType::F32)), ActivationFunctionsDataset), framework::dataset::make("DataLayout", { DataLayout::NCHW, DataLayout::NHWC }))) { validate(CLAccessor(_target), _reference, tolerance_fp32); } TEST_SUITE_END() // FP32 TEST_SUITE(FP32_CustomDataset) FIXTURE_DATA_TEST_CASE(Run, CLDirectConvolutionValidationWithTensorShapesFixture<float>, framework::DatasetMode::NIGHTLY, combine(combine(datasets::DirectConvolutionLayerDataset(), framework::dataset::make("DataType", DataType::F32)), ActivationFunctionsDataset)) { // Validate output validate(CLAccessor(_target), _reference, tolerance_fp32); } TEST_SUITE_END() // FP32_CustomDataset TEST_SUITE_END() // Float template <typename T> using CLDirectConvolutionLayerQuantizedFixture = DirectConvolutionValidationQuantizedFixture<CLTensor, CLAccessor, CLDirectConvolutionLayer, T>; template <typename T> using CLDirectConvolutionValidationWithTensorShapesQuantizedFixture = DirectConvolutionValidationWithTensorShapesQuantizedFixture<CLTensor, CLAccessor, CLDirectConvolutionLayer, T>; const auto QuantizedActivationFunctionsDataset = framework::dataset::make("ActivationInfo", { ActivationLayerInfo(), ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU), ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU, 6.f) }); TEST_SUITE(Quantized) TEST_SUITE(QASYMM8) FIXTURE_DATA_TEST_CASE(RunSmall, CLDirectConvolutionLayerQuantizedFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(combine(combine(data_precommit, framework::dataset::make("DataType", DataType::QASYMM8)), framework::dataset::make("QuantizationInfo", { QuantizationInfo(2.f / 255, 10) })), QuantizedActivationFunctionsDataset)) { // Validate output validate(CLAccessor(_target), _reference, tolerance_qasymm8); } FIXTURE_DATA_TEST_CASE(RunLarge, CLDirectConvolutionLayerQuantizedFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(combine(combine(data_nightly, framework::dataset::make("DataType", DataType::QASYMM8)), framework::dataset::make("QuantizationInfo", { QuantizationInfo(2.f / 255, 10) })), QuantizedActivationFunctionsDataset)) { // Validate output validate(CLAccessor(_target), _reference, tolerance_qasymm8); } TEST_SUITE_END() // QASYMM8 TEST_SUITE(QASYMM8_CustomDataset) FIXTURE_DATA_TEST_CASE(Run, CLDirectConvolutionValidationWithTensorShapesQuantizedFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(combine(combine(datasets::DirectConvolutionLayerDataset(), framework::dataset::make("DataType", DataType::QASYMM8)), framework::dataset::make("QuantizationInfo", { QuantizationInfo(2.f / 255, 127) })), QuantizedActivationFunctionsDataset)) { // Validate output validate(CLAccessor(_target), _reference, tolerance_qasymm8); } TEST_SUITE_END() // QASYMM8_CustomDataset TEST_SUITE_END() // Quantized TEST_SUITE_END() // DirectConvolutionLayer TEST_SUITE_END() // Float } // namespace validation } // namespace test } // namespace arm_compute
69.18254
270
0.568774
giorgio-arena
437ec2a6c333555098af52656b472e9308b860cd
2,963
cpp
C++
Lithium/vendor/assimp/contrib/openddlparser/code/OpenDDLStream.cpp
ayoubbelatrous/LithiumEngine
bc24d277058b12cce3d95c8494fe366acda48462
[ "MIT" ]
1
2021-12-04T18:07:22.000Z
2021-12-04T18:07:22.000Z
Lithium/vendor/assimp/contrib/openddlparser/code/OpenDDLStream.cpp
ayoubbelatrous/LithiumEngine
bc24d277058b12cce3d95c8494fe366acda48462
[ "MIT" ]
null
null
null
Lithium/vendor/assimp/contrib/openddlparser/code/OpenDDLStream.cpp
ayoubbelatrous/LithiumEngine
bc24d277058b12cce3d95c8494fe366acda48462
[ "MIT" ]
null
null
null
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2015 Kim Kulling 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 <openddlparser/OpenDDLStream.h> BEGIN_ODDLPARSER_NS StreamFormatterBase::StreamFormatterBase() { // empty } StreamFormatterBase::~StreamFormatterBase() { // empty } std::string StreamFormatterBase::format(const std::string &statement) { std::string tmp(statement); return tmp; } IOStreamBase::IOStreamBase(StreamFormatterBase *formatter) : m_formatter(formatter) , m_file(ddl_nullptr) { if (ddl_nullptr == m_formatter) { m_formatter = new StreamFormatterBase; } } IOStreamBase::~IOStreamBase() { delete m_formatter; m_formatter = ddl_nullptr; } bool IOStreamBase::open(const std::string &name) { m_file = ::fopen(name.c_str(), "a"); if (m_file == ddl_nullptr) { return false; } return true; } bool IOStreamBase::close() { if (ddl_nullptr == m_file) { return false; } ::fclose(m_file); m_file = ddl_nullptr; return true; } bool IOStreamBase::isOpen() const { return ( ddl_nullptr != m_file ); } size_t IOStreamBase::read( size_t sizeToRead, std::string &statement ) { if (ddl_nullptr == m_file) { return 0; } statement.resize(sizeToRead); const size_t readBytes = ::fread( &statement[0], 1, sizeToRead, m_file ); return readBytes; } size_t IOStreamBase::write(const std::string &statement) { if (ddl_nullptr == m_file) { return 0; } std::string formatStatement = m_formatter->format(statement); return ::fwrite(formatStatement.c_str(), sizeof(char), formatStatement.size(), m_file); } END_ODDLPARSER_NS
30.546392
98
0.649342
ayoubbelatrous
43814f2e2070c02daaf4c8cd41be59bcb25ab2db
79,366
cpp
C++
src/hardware/vga.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
3
2022-02-20T11:06:29.000Z
2022-03-11T08:16:55.000Z
src/hardware/vga.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
null
null
null
src/hardware/vga.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2002-2021 The DOSBox Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* NTS: Hardware notes * * S3 Virge DX (PCI): * * VGA 256-color chained mode appears to work differently than * expected. Groups of 4 pixels are spread across the VGA planes * as expected, but actual memory storage of those 32-bit quantities * are 4 "bytes" apart (probably the inspiration for DOSBox's * chain emulation using addr = ((addr & ~3) << 2) + (addr & 3) when * emulating chained mode). * * The attribute controller has a bug where if you attempt to read * the palette indexes 0x00-0x0F with PAS=1 (see FreeVGA for more * info) the returned value will be correct except for bit 5 which * will be 1 i.e. if palette index 0x2 is read in this way and * contains 0x02 you will get 0x22 instead. The trick is to write * the index with PAS=0 and read the data, then issue the index with * PAS=1. Related: the S3 acts as if there are different flip-flops * associated with reading vs writing i.e. writing to 0x3C0, then * reading port 0x3C1, then writing port 0x3C0, will treat the second * write to 0x3C0 as data still, not as an index. Both flip flops are * reset by reading 3xAh though. * * VGA BIOS does not support INT 10h TTY functions in VESA BIOS modes. * * Raw planar dumps of the VGA memory in alphanumeric modes suggest * that, not only do the cards direct even writes to 0/2 and odd to 1/3, * it does so without shifting down the address. So in a raw planar * dump, you will see on plane 0 something like "C : \ > " where the * spaces are hex 0x00, and in plane 1, something like 0x07 0x00 0x07 0x00 ... * the card however (in even/odd mode) does mask out bit A0 which * explains why the Plane 1 capture is 0x07 0x00 ... not 0x00 0x07. * * ATI Rage 128 (AGP): * * VGA 256-color chained mode appears to work in the same weird way * that S3 Virge DX does (see above). * * VGA BIOS supports TTY INT 10h functions in 16 & 256-color modes * only. There are apparently INT 10h functions for 15/16bpp modes * as well, but they don't appear to render anything except shades * of green. * * The VESA BIOS interface seems to have INT 10h aliases for many * VBE 1.2 modes i.e. mode 0x110 is also mode 0x42. * * The Attribute Controller palette indexes work as expected in all * VGA modes, however in SVGA VESA BIOS modes, the Attribute Controller * palette has no effect on output EXCEPT in 16-color (4bpp) VESA BIOS * modes. * * Raw planar layout of alphanumeric text modes apply the same rules * as mentioned above in the S3 Virge DX description. * * Compaq Elite LTE 4/50CX laptop: * * No SVGA modes. All modes work as expected. * * VGA 256-color chained mode acts the same weird way as described * above, seems to act like addr = ((addr & ~3) << 2) + (addr & 3) * * There seems to be undocumented INT 10h modes: * * 0x22: 640x480x?? INT 10h text is all green and garbled * 0x28: 320x200x?? INT 10h text is all green and garbled * 0x32: 640x480x?? INT 10h text is all yellow and garbled * 0x5E: 640x400x256-color with bank switching * 0x5F: 640x480x256-color with bank switching * 0x62: 640x480x?? INT 10h text is all dark gray * 0x68: 320x200x?? INT 10h text is all dark gray * 0x72: 640x480x?? INT 10h text is all dark gray * 0x78: 320x200x?? INT 10h text is all dark gray * * And yet, the BIOS does not implement VESA BIOS extensions. Hm.. * * Sharp PC-9030 with Cirrus SVGA (1996): * * VGA 256-color chained mode acts the same weird way, as if: * addr = ((addr & ~3) << 2) + (addr & 3) * * All VESA BIOS modes support INT 10h TTY output. * * Tseng ET4000AX: * * The ET4000 cards appear to be the ONLY SVGA chipset out there * that does NOT do the odd VGA 256-color chained mode that * other cards do. * * Chained 256-color on ET4000: * addr = addr (addr >> 2) byte in planar space, plane select by (addr & 3) * * Other VGA cards: * addr = ((addr & ~3) << 2) + (addr & 3) (addr & ~3) byte in planar space, plane select by (addr & 3) * * I suspect that this difference may be the reason several 1992-1993-ish DOS demos have problems clearing * VRAM. It's possible they noticed that zeroing RAM was faster in planar mode, and coded their routines * around ET4000 cards, not knowing that Trident, Cirrus, and every VGA clone thereafter implemented the * chained 256-color modes differently. */ #include <assert.h> #include "dosbox.h" #include "logging.h" #include "setup.h" #include "video.h" #include "pic.h" #include "vga.h" #include "inout.h" #include "programs.h" #include "support.h" #include "setup.h" #include "timer.h" #include "mem.h" #include "util_units.h" #include "control.h" #include "pc98_cg.h" #include "pc98_dac.h" #include "pc98_gdc.h" #include "pc98_gdc_const.h" #include "mixer.h" #include "menu.h" #include "mem.h" #include "render.h" #include "jfont.h" #include "bitop.h" #include "sdlmain.h" #include <string.h> #include <stdlib.h> #include <string> #include <stdio.h> #if defined(_MSC_VER) # pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ #endif #include "zipfile.h" using namespace std; Bitu pc98_read_9a8(Bitu /*port*/,Bitu /*iolen*/); void pc98_write_9a8(Bitu port,Bitu val,Bitu iolen); bool VGA_IsCaptureEnabled(void); void VGA_UpdateCapturePending(void); bool VGA_CaptureHasNextFrame(void); void VGA_CaptureStartNextFrame(void); void VGA_CaptureMarkError(void); bool VGA_CaptureValidateCurrentFrame(void); unsigned int vbe_window_granularity = 0; unsigned int vbe_window_size = 0; /* current dosplay page (controlled by A4h) */ unsigned char* pc98_pgraph_current_display_page; /* current CPU page (controlled by A6h) */ unsigned char* pc98_pgraph_current_cpu_page; bool vga_8bit_dac = false; bool vga_alt_new_mode = false; bool enable_vga_8bit_dac = true; bool pc98_crt_mode = false; // see port 6Ah command 40h/41h. // this boolean is the INVERSE of the bit. extern int vga_memio_delay_ns; extern bool gdc_5mhz_mode; extern bool gdc_5mhz_mode_initial; extern bool enable_pc98_egc; extern bool enable_pc98_grcg; extern bool enable_pc98_16color; extern bool enable_pc98_256color; extern bool enable_pc98_256color_planar; extern bool enable_pc98_188usermod; extern bool GDC_vsync_interrupt; extern uint8_t GDC_display_plane; extern bool pc98_256kb_boundary; extern bool want_fm_towns; extern bool enveten; extern uint8_t pc98_gdc_tile_counter; extern uint8_t pc98_gdc_modereg; extern uint8_t pc98_gdc_vramop; extern egc_quad pc98_gdc_tiles; extern uint8_t pc98_egc_srcmask[2]; /* host given (Neko: egc.srcmask) */ extern uint8_t pc98_egc_maskef[2]; /* effective (Neko: egc.mask2) */ extern uint8_t pc98_egc_mask[2]; /* host given (Neko: egc.mask) */ uint32_t S3_LFB_BASE = S3_LFB_BASE_DEFAULT; bool enable_pci_vga = true; SDL_Rect vga_capture_rect = {0,0,0,0}; SDL_Rect vga_capture_current_rect = {0,0,0,0}; uint32_t vga_capture_current_address = 0; uint32_t vga_capture_write_address = 0; // literally the address written uint32_t vga_capture_address = 0; uint32_t vga_capture_stride = 0; uint32_t vga_capture_state = 0; SDL_Rect &VGA_CaptureRectCurrent(void) { return vga_capture_current_rect; } SDL_Rect &VGA_CaptureRectFromGuest(void) { return vga_capture_rect; } VGA_Type vga; SVGA_Driver svga; int enableCGASnow; int vesa_modelist_cap = 0; int vesa_mode_width_cap = 0; int vesa_mode_height_cap = 0; bool vesa_bios_modelist_in_info = false; bool vga_3da_polled = false; bool vga_page_flip_occurred = false; bool enable_page_flip_debugging_marker = false; bool enable_vretrace_poll_debugging_marker = false; bool vga_enable_hretrace_effects = false; bool vga_enable_hpel_effects = false; bool vga_enable_3C6_ramdac = false; bool egavga_per_scanline_hpel = true; bool vga_sierra_lock_565 = false; bool vga_fill_inactive_ram = false; bool enable_vga_resize_delay = false; bool vga_ignore_hdispend_change_if_smaller = false; bool ignore_vblank_wraparound = false; bool non_cga_ignore_oddeven = false; bool non_cga_ignore_oddeven_engage = false; bool vga_ignore_extended_memory_bit = false; bool vga_palette_update_on_full_load = true; bool vga_double_buffered_line_compare = false; bool pc98_allow_scanline_effect = true; bool pc98_allow_4_display_partitions = false; bool pc98_graphics_hide_odd_raster_200line = false; bool pc98_attr4_graphic = false; bool pc98_40col_text = false; bool gdc_analog = true; bool pc98_31khz_mode = false; bool int10_vesa_map_as_128kb = false; unsigned char VGA_AC_remap = AC_4x4; unsigned int vga_display_start_hretrace = 0; float hretrace_fx_avg_weight = 3; bool allow_vesa_4bpp_packed = true; bool allow_vesa_lowres_modes = true; bool allow_unusual_vesa_modes = true; bool allow_explicit_vesa_24bpp = true; bool allow_hd_vesa_modes = true; bool vesa12_modes_32bpp = true; bool allow_vesa_32bpp = true; bool allow_vesa_24bpp = true; bool allow_vesa_16bpp = true; bool allow_vesa_15bpp = true; bool allow_vesa_8bpp = true; bool allow_vesa_4bpp = true; bool allow_vesa_tty = true; void gdc_5mhz_mode_update_vars(void); void pc98_port6A_command_write(unsigned char b); void pc98_wait_write(Bitu port,Bitu val,Bitu iolen); void pc98_crtc_write(Bitu port,Bitu val,Bitu iolen); void pc98_port68_command_write(unsigned char b); Bitu pc98_read_9a0(Bitu /*port*/,Bitu /*iolen*/); void pc98_write_9a0(Bitu port,Bitu val,Bitu iolen); Bitu pc98_crtc_read(Bitu port,Bitu iolen); Bitu pc98_a1_read(Bitu port,Bitu iolen); void pc98_a1_write(Bitu port,Bitu val,Bitu iolen); void pc98_gdc_write(Bitu port,Bitu val,Bitu iolen); Bitu pc98_gdc_read(Bitu port,Bitu iolen); Bitu pc98_egc4a0_read(Bitu port,Bitu iolen); void pc98_egc4a0_write(Bitu port,Bitu val,Bitu iolen); Bitu pc98_egc4a0_read_warning(Bitu port,Bitu iolen); void pc98_egc4a0_write_warning(Bitu port,Bitu val,Bitu iolen); void page_flip_debug_notify() { if (enable_page_flip_debugging_marker) vga_page_flip_occurred = true; } void vsync_poll_debug_notify() { if (enable_vretrace_poll_debugging_marker) vga_3da_polled = true; } uint32_t CGA_2_Table[16]; uint32_t CGA_4_Table[256]; uint32_t CGA_4_HiRes_Table[256]; uint32_t CGA_16_Table[256]; uint32_t TXT_Font_Table[16]; uint32_t TXT_FG_Table[16]; uint32_t TXT_BG_Table[16]; uint32_t ExpandTable[256]; uint32_t Expand16Table[4][16]; uint32_t FillTable[16]; uint32_t ColorTable[16]; double vga_force_refresh_rate = -1; void VGA_SetModeNow(VGAModes mode) { if (vga.mode == mode) return; vga.mode=mode; VGA_SetupHandlers(); VGA_StartResize(0); } void VGA_SetMode(VGAModes mode) { if (vga.mode == mode) return; vga.mode=mode; VGA_SetupHandlers(); VGA_StartResize(); } void VGA_DetermineMode(void) { if (svga.determine_mode) { svga.determine_mode(); return; } /* Test for VGA output active or direct color modes */ switch (vga.s3.misc_control_2 >> 4) { case 0: if (vga.attr.mode_control & 1) { // graphics mode if (IS_VGA_ARCH && ((vga.gfx.mode & 0x40)||(vga.s3.reg_3a&0x10))) { // access above 256k? if (vga.s3.reg_31 & 0x8) VGA_SetMode(M_LIN8); else VGA_SetMode(M_VGA); } else if (vga.gfx.mode & 0x20) VGA_SetMode(M_CGA4); else if ((vga.gfx.miscellaneous & 0x0c)==0x0c) VGA_SetMode(M_CGA2); else { // access above 256k? if (vga.s3.reg_31 & 0x8) VGA_SetMode(M_LIN4); else VGA_SetMode(M_EGA); } } else { VGA_SetMode(M_TEXT); } break; case 1:VGA_SetMode(M_LIN8);break; case 3:VGA_SetMode(M_LIN15);break; case 5:VGA_SetMode(M_LIN16);break; case 7:VGA_SetMode(M_LIN24);break; case 13:VGA_SetMode(M_LIN32);break; case 15:VGA_SetMode(M_PACKED4);break;// hacked } } void VGA_StartResize(Bitu delay /*=50*/) { if (!vga.draw.resizing) { /* even if the user disables the delay, we can avoid a lot of window resizing by at least having 1ms of delay */ if (!enable_vga_resize_delay && delay > 1) delay = 1; vga.draw.resizing=true; if (vga.mode==M_ERROR) delay = 5; /* Start a resize after delay (default 50 ms) */ if (delay==0) VGA_SetupDrawing(0); else PIC_AddEvent(VGA_SetupDrawing,(float)delay); } } #define IS_RESET ((vga.seq.reset&0x3)!=0x3) #define IS_SCREEN_ON ((vga.seq.clocking_mode&0x20)==0) //static bool hadReset = false; // disabled for later improvement // Idea behind this: If the sequencer was reset and screen off we can // Problem is some programs measure the refresh rate after switching mode, // and get it wrong because of the 50ms guard time. // On the other side, buggers like UniVBE switch the screen mode several // times so the window is flickering. // Also the demos that switch display end on screen (Dowhackado) // would need some attention void VGA_SequReset(bool reset) { (void)reset;//UNUSED //if(!reset && !IS_SCREEN_ON) hadReset=true; } void VGA_Screenstate(bool enabled) { (void)enabled;//UNUSED /*if(enabled && hadReset) { hadReset=false; PIC_RemoveEvents(VGA_SetupDrawing); VGA_SetupDrawing(0); }*/ } void VGA_SetClock(Bitu which,Bitu target) { if (svga.set_clock) { svga.set_clock(which, target); return; } struct{ Bitu n,m; Bits err; } best; best.err=(Bits)target; best.m=1u; best.n=1u; Bitu r; for (r = 0; r <= 3; r++) { Bitu f_vco = target * ((Bitu)1u << (Bitu)r); if (MIN_VCO <= f_vco && f_vco < MAX_VCO) break; } for (Bitu n=1;n<=31;n++) { Bits m=(Bits)((target * (n + 2u) * ((Bitu)1u << (Bitu)r) + (S3_CLOCK_REF / 2u)) / S3_CLOCK_REF) - 2; if (0 <= m && m <= 127) { Bitu temp_target = (Bitu)S3_CLOCK(m,n,r); Bits err = (Bits)(target - temp_target); if (err < 0) err = -err; if (err < best.err) { best.err = err; best.m = (Bitu)m; best.n = (Bitu)n; } } } /* Program the s3 clock chip */ vga.s3.clk[which].m=best.m; vga.s3.clk[which].r=r; vga.s3.clk[which].n=best.n; VGA_StartResize(); } void VGA_SetCGA2Table(uint8_t val0,uint8_t val1) { const uint8_t total[2] = {val0,val1}; for (Bitu i=0;i<16u;i++) { CGA_2_Table[i]= #ifdef WORDS_BIGENDIAN ((Bitu)total[(i >> 0u) & 1u] << 0u ) | ((Bitu)total[(i >> 1u) & 1u] << 8u ) | ((Bitu)total[(i >> 2u) & 1u] << 16u ) | ((Bitu)total[(i >> 3u) & 1u] << 24u ); #else ((Bitu)total[(i >> 3u) & 1u] << 0u ) | ((Bitu)total[(i >> 2u) & 1u] << 8u ) | ((Bitu)total[(i >> 1u) & 1u] << 16u ) | ((Bitu)total[(i >> 0u) & 1u] << 24u ); #endif } if (machine == MCH_MCGA) { VGA_DAC_CombineColor(0x0,val0); VGA_DAC_CombineColor(0x1,val1); } } void VGA_SetCGA4Table(uint8_t val0,uint8_t val1,uint8_t val2,uint8_t val3) { const uint8_t total[4] = {val0,val1,val2,val3}; for (Bitu i=0;i<256u;i++) { CGA_4_Table[i]= #ifdef WORDS_BIGENDIAN ((Bitu)total[(i >> 0u) & 3u] << 0u ) | ((Bitu)total[(i >> 2u) & 3u] << 8u ) | ((Bitu)total[(i >> 4u) & 3u] << 16u ) | ((Bitu)total[(i >> 6u) & 3u] << 24u ); #else ((Bitu)total[(i >> 6u) & 3u] << 0u ) | ((Bitu)total[(i >> 4u) & 3u] << 8u ) | ((Bitu)total[(i >> 2u) & 3u] << 16u ) | ((Bitu)total[(i >> 0u) & 3u] << 24u ); #endif CGA_4_HiRes_Table[i]= #ifdef WORDS_BIGENDIAN ((Bitu)total[((i >> 0u) & 1u) | ((i >> 3u) & 2u)] << 0u ) | (Bitu)(total[((i >> 1u) & 1u) | ((i >> 4u) & 2u)] << 8u ) | ((Bitu)total[((i >> 2u) & 1u) | ((i >> 5u) & 2u)] << 16u ) | (Bitu)(total[((i >> 3u) & 1u) | ((i >> 6u) & 2u)] << 24u ); #else ((Bitu)total[((i >> 3u) & 1u) | ((i >> 6u) & 2u)] << 0u ) | (Bitu)(total[((i >> 2u) & 1u) | ((i >> 5u) & 2u)] << 8u ) | ((Bitu)total[((i >> 1u) & 1u) | ((i >> 4u) & 2u)] << 16u ) | (Bitu)(total[((i >> 0u) & 1u) | ((i >> 3u) & 2u)] << 24u ); #endif } if (machine == MCH_MCGA) { VGA_DAC_CombineColor(0x0,val0); VGA_DAC_CombineColor(0x1,val1); VGA_DAC_CombineColor(0x2,val2); VGA_DAC_CombineColor(0x3,val3); } } void SetRate(char *x) { if (!strncasecmp(x,"off",3)) vga_force_refresh_rate = -1; else if (!strncasecmp(x,"ntsc",4)) vga_force_refresh_rate = 60000.0/1001; else if (!strncasecmp(x,"pal",3)) vga_force_refresh_rate = 50; else if (strchr(x,'.')) vga_force_refresh_rate = atof(x); else { /* fraction */ int major = -1,minor = 0; major = strtol(x,&x,0); if (*x == '/' || *x == ':') { x++; minor = strtol(x,NULL,0); } if (major > 0) { vga_force_refresh_rate = (double)major; if (minor > 1) vga_force_refresh_rate /= minor; } } VGA_SetupHandlers(); VGA_StartResize(); } #if defined(USE_TTF) void resetFontSize(); static void resetSize(Bitu /*val*/) { resetFontSize(); } #endif class VFRCRATE : public Program { public: void Run(void) { if (cmd->FindExist("/?", false)) { WriteOut("Locks or unlocks the video refresh rate.\n\n"); WriteOut("VFRCRATE [SET [OFF|PAL|NTSC|rate]\n"); WriteOut(" SET OFF Unlock the refresh rate\n"); WriteOut(" SET PAL Lock to PAL frame rate\n"); WriteOut(" SET NTSC Lock to NTSC frame rate\n"); WriteOut(" SET rate Lock to integer frame rate, e.g. 15\n"); WriteOut(" SET rate Lock to decimal frame rate, e.g. 29.97\n"); WriteOut(" SET rate Lock to fractional frame rate, e.g. 60000/1001\n\n"); WriteOut("Type VFRCRATE without a parameter to show the current status.\n"); return; } if (cmd->FindString("SET",temp_line,false)) SetRate((char *)temp_line.c_str()); #if defined(USE_TTF) if (TTF_using()) PIC_AddEvent(&resetSize, 1); #endif if (vga_force_refresh_rate > 0) WriteOut("Video refresh rate is locked to %.3f fps.\n",vga_force_refresh_rate); else WriteOut("Video refresh rate is unlocked.\n"); } }; void VFRCRATE_ProgramStart(Program * * make) { *make=new VFRCRATE; } /*! \brief CGASNOW.COM utility to control CGA snow emulation * * \description Utility to enable, disable, or query CGA snow emulation. * This command is only available when machine=cga and * the video mode is 80x25 text mode. */ class CGASNOW : public Program { public: /*! \brief Program entry point, when the command is run */ void Run(void) { if (cmd->FindExist("/?", false)) { WriteOut("Turns CGA snow emulation on or off.\n\n"); WriteOut("CGASNOW [ON|OFF]\n"); WriteOut(" ON Turns on CGA snow emulation.\n"); WriteOut(" OFF Turns off CGA snow emulation.\n\n"); WriteOut("Type CGASNOW without a parameter to show the current status.\n"); return; } if(cmd->FindExist("ON")) { WriteOut("CGA snow enabled.\n"); enableCGASnow = 1; if (vga.mode == M_TEXT || vga.mode == M_TANDY_TEXT) { VGA_SetupHandlers(); VGA_StartResize(); } } else if(cmd->FindExist("OFF")) { WriteOut("CGA snow disabled.\n"); enableCGASnow = 0; if (vga.mode == M_TEXT || vga.mode == M_TANDY_TEXT) { VGA_SetupHandlers(); VGA_StartResize(); } } else { WriteOut("CGA snow is currently %s.\n", enableCGASnow ? "enabled" : "disabled"); } } }; void CGASNOW_ProgramStart(Program * * make) { *make=new CGASNOW; } /* TODO: move to general header */ static inline unsigned int int_log2(unsigned int val) { unsigned int log = 0; while ((val >>= 1u) != 0u) log++; return log; } extern bool pcibus_enable; extern int hack_lfb_yadjust; extern uint8_t GDC_display_plane_wait_for_vsync; void VGA_VsyncUpdateMode(VGA_Vsync vsyncmode); VGA_Vsync VGA_Vsync_Decode(const char *vsyncmodestr) { if (!strcasecmp(vsyncmodestr,"off")) return VS_Off; else if (!strcasecmp(vsyncmodestr,"on")) return VS_On; else if (!strcasecmp(vsyncmodestr,"force")) return VS_Force; else if (!strcasecmp(vsyncmodestr,"host")) return VS_Host; else LOG_MSG("Illegal vsync type %s, falling back to off.",vsyncmodestr); return VS_Off; } bool has_pcibus_enable(void); uint32_t MEM_get_address_bits(); uint32_t GetReportedVideoMemorySize(void); void VGA_Reset(Section*) { // All non-PC98 video-related config settings are now in the [video] section Section_prop * section=static_cast<Section_prop *>(control->GetSection("video")); Section_prop * pc98_section=static_cast<Section_prop *>(control->GetSection("pc98")); bool lfb_default = false; string str; int i; uint32_t cpu_addr_bits = MEM_get_address_bits(); // uint64_t cpu_max_addr = (uint64_t)1 << (uint64_t)cpu_addr_bits; LOG(LOG_MISC,LOG_DEBUG)("VGA_Reset() reinitializing VGA emulation"); GDC_display_plane_wait_for_vsync = pc98_section->Get_bool("pc-98 buffer page flip"); enable_pci_vga = section->Get_bool("pci vga"); S3_LFB_BASE = (uint32_t)section->Get_hex("svga lfb base"); if (S3_LFB_BASE == 0) { if (cpu_addr_bits >= 32) S3_LFB_BASE = S3_LFB_BASE_DEFAULT; else if (cpu_addr_bits >= 26) S3_LFB_BASE = (enable_pci_vga && has_pcibus_enable()) ? 0x02000000 : 0x03400000; else if (cpu_addr_bits >= 24) S3_LFB_BASE = 0x00C00000; else S3_LFB_BASE = S3_LFB_BASE_DEFAULT; lfb_default = true; } /* no farther than 32MB below the top */ if (S3_LFB_BASE > 0xFE000000UL) S3_LFB_BASE = 0xFE000000UL; /* if the user WANTS the base address to be PCI misaligned, then turn off PCI VGA emulation */ if (enable_pci_vga && has_pcibus_enable() && (S3_LFB_BASE & 0x1FFFFFFul)) { if (!lfb_default) LOG(LOG_VGA,LOG_DEBUG)("S3 linear framebuffer was set by user to an address not aligned to 32MB, switching off PCI VGA emulation"); enable_pci_vga = false; } /* if memalias is below 26 bits, PCI VGA emulation is impossible */ if (cpu_addr_bits < 26) { if (IS_VGA_ARCH && enable_pci_vga && has_pcibus_enable()) LOG(LOG_VGA,LOG_DEBUG)("CPU memalias setting is below 26 bits, switching off PCI VGA emulation"); enable_pci_vga = false; } if (enable_pci_vga && has_pcibus_enable()) { /* must be 32MB aligned (PCI) */ S3_LFB_BASE += 0x0FFFFFFUL; S3_LFB_BASE &= ~0x1FFFFFFUL; } else { /* must be 64KB aligned (ISA) */ S3_LFB_BASE += 0x7FFFUL; S3_LFB_BASE &= ~0xFFFFUL; } /* must not overlap system RAM */ if (S3_LFB_BASE < (MEM_TotalPages()*4096)) S3_LFB_BASE = (MEM_TotalPages()*4096); /* if the constraints we imposed make it impossible to maintain the alignment required for PCI, * then just switch off PCI VGA emulation. */ if (IS_VGA_ARCH && enable_pci_vga && has_pcibus_enable()) { if (S3_LFB_BASE & 0x1FFFFFFUL) { /* not 32MB aligned */ LOG(LOG_VGA,LOG_DEBUG)("S3 linear framebuffer is not 32MB aligned, switching off PCI VGA emulation"); enable_pci_vga = false; } } /* announce LFB framebuffer address only if actually emulating the S3 */ if (IS_VGA_ARCH && svgaCard == SVGA_S3Trio) LOG(LOG_VGA,LOG_DEBUG)("S3 linear framebuffer at 0x%lx%s as %s", (unsigned long)S3_LFB_BASE,lfb_default?" by default":"", (enable_pci_vga && has_pcibus_enable()) ? "PCI" : "(E)ISA"); /* other applicable warnings: */ /* Microsoft Windows 3.1 S3 driver: * If the LFB is set to an address below 16MB, the driver will program the base to something * odd like 0x73000000 and access MMIO through 0x74000000. * * Because of this, if memalias < 31 and LFB is below 16MB mark, Windows won't use the * accelerated features of the S3 emulation properly. * * If memalias=24, the driver hangs and nothing appears on screen. * * As far as I can tell, it's mapping for the LFB, not the MMIO. It uses the MMIO in the * A0000-AFFFF range anyway. The failure to blit and draw seems to be caused by mapping the * LFB out of range like that and then trying to draw on the LFB. * * As far as I can tell from http://www.vgamuseum.info and the list of S3 cards, the S3 chipsets * emulated by DOSBox-X and DOSBox SVN here are all EISA and PCI cards, so it's likely the driver * is written around the assumption that memory addresses are the full 32 bits to the card, not * just the low 24 seen on the ISA slot. So it is unlikely the driver could ever support the * card on a 386SX nor could such a card work on a 386SX. It shouldn't even work on a 486SX * (26-bit limit), but it could. */ if (IS_VGA_ARCH && svgaCard == SVGA_S3Trio && cpu_addr_bits <= 24) LOG(LOG_VGA,LOG_WARN)("S3 linear framebuffer warning: memalias setting is known to cause the Windows 3.1 S3 driver to crash"); if (IS_VGA_ARCH && svgaCard == SVGA_S3Trio && cpu_addr_bits < 31 && S3_LFB_BASE < 0x1000000ul) /* below 16MB and memalias == 31 bits */ LOG(LOG_VGA,LOG_WARN)("S3 linear framebuffer warning: A linear framebuffer below the 16MB mark in physical memory when memalias < 31 is known to have problems with the Windows 3.1 S3 driver"); pc98_allow_scanline_effect = pc98_section->Get_bool("pc-98 allow scanline effect"); mainMenu.get_item("pc98_allow_200scanline").check(pc98_allow_scanline_effect).refresh_item(mainMenu); // whether the GDC is running at 2.5MHz or 5.0MHz. // Some games require the GDC to run at 5.0MHz. // To enable these games we default to 5.0MHz. // NTS: There are also games that refuse to run if 5MHz switched on (TH03) gdc_5mhz_mode = pc98_section->Get_bool("pc-98 start gdc at 5mhz"); mainMenu.get_item("pc98_5mhz_gdc").check(gdc_5mhz_mode).refresh_item(mainMenu); // record the initial setting. // the guest can change it later. // however the 8255 used to hold dip switch settings needs to reflect the // initial setting. gdc_5mhz_mode_initial = gdc_5mhz_mode; enable_pc98_egc = pc98_section->Get_bool("pc-98 enable egc"); enable_pc98_grcg = pc98_section->Get_bool("pc-98 enable grcg"); enable_pc98_16color = pc98_section->Get_bool("pc-98 enable 16-color"); enable_pc98_256color = pc98_section->Get_bool("pc-98 enable 256-color"); enable_pc98_188usermod = pc98_section->Get_bool("pc-98 enable 188 user cg"); enable_pc98_256color_planar = pc98_section->Get_bool("pc-98 enable 256-color planar"); #if 0//TODO: Do not enforce until 256-color mode is fully implemented. // Some users out there may expect the EGC, GRCG, 16-color options to disable the emulation. // Having 256-color mode on by default, auto-enable them, will cause surprises and complaints. // 256-color mode implies EGC, 16-color, GRCG if (enable_pc98_256color) enable_pc98_grcg = enable_pc98_16color = true; #endif // EGC implies GRCG if (enable_pc98_egc) enable_pc98_grcg = true; // EGC implies 16-color if (enable_pc98_16color) enable_pc98_16color = true; str = section->Get_string("vga attribute controller mapping"); if (str == "4x4") VGA_AC_remap = AC_4x4; else if (str == "4low") VGA_AC_remap = AC_low4; else { /* auto: * * 4x4 by default. * except for ET4000 which is 4low */ VGA_AC_remap = AC_4x4; if (IS_VGA_ARCH) { if (svgaCard == SVGA_TsengET3K || svgaCard == SVGA_TsengET4K) VGA_AC_remap = AC_low4; } } str = pc98_section->Get_string("pc-98 video mode"); if (str == "31khz") pc98_31khz_mode = true; else if (str == "15khz")/*TODO*/ pc98_31khz_mode = false; else pc98_31khz_mode = false; //TODO: Announce 31-KHz mode in BIOS config area. --yksoft1 i = pc98_section->Get_int("pc-98 allow 4 display partition graphics"); pc98_allow_4_display_partitions = (i < 0/*auto*/ || i == 1/*on*/); mainMenu.get_item("pc98_allow_4partitions").check(pc98_allow_4_display_partitions).refresh_item(mainMenu); // TODO: "auto" will default to true if old PC-9801, false if PC-9821, or // a more refined automatic choice according to actual hardware. mainMenu.get_item("pc98_enable_egc").check(enable_pc98_egc).refresh_item(mainMenu); mainMenu.get_item("pc98_enable_grcg").check(enable_pc98_grcg).refresh_item(mainMenu); mainMenu.get_item("pc98_enable_analog").check(enable_pc98_16color).refresh_item(mainMenu); mainMenu.get_item("pc98_enable_analog256").check(enable_pc98_256color).refresh_item(mainMenu); mainMenu.get_item("pc98_enable_188user").check(enable_pc98_188usermod).refresh_item(mainMenu); vga_force_refresh_rate = -1; str=section->Get_string("forcerate"); if (str == "ntsc") vga_force_refresh_rate = 60000.0 / 1001; else if (str == "pal") vga_force_refresh_rate = 50; else if (str.find_first_of('/') != string::npos) { char *p = (char*)str.c_str(); int num = 1,den = 1; num = strtol(p,&p,0); if (*p == '/') p++; den = strtol(p,&p,0); if (num < 1) num = 1; if (den < 1) den = 1; vga_force_refresh_rate = (double)num / den; } else { vga_force_refresh_rate = atof(str.c_str()); } enableCGASnow = section->Get_bool("cgasnow"); vesa_modelist_cap = section->Get_int("vesa modelist cap"); vesa_mode_width_cap = section->Get_int("vesa modelist width limit"); vesa_mode_height_cap = section->Get_int("vesa modelist height limit"); vga_enable_3C6_ramdac = section->Get_bool("sierra ramdac"); vga_enable_hpel_effects = section->Get_bool("allow hpel effects"); vga_sierra_lock_565 = section->Get_bool("sierra ramdac lock 565"); vga_fill_inactive_ram = section->Get_bool("vga fill active memory"); hretrace_fx_avg_weight = section->Get_double("hretrace effect weight"); egavga_per_scanline_hpel = section->Get_bool("ega per scanline hpel"); ignore_vblank_wraparound = section->Get_bool("ignore vblank wraparound"); int10_vesa_map_as_128kb = section->Get_bool("vesa map non-lfb modes to 128kb region"); vga_enable_hretrace_effects = section->Get_bool("allow hretrace effects"); enable_page_flip_debugging_marker = section->Get_bool("page flip debug line"); vga_palette_update_on_full_load = section->Get_bool("vga palette update on full load"); non_cga_ignore_oddeven = section->Get_bool("ignore odd-even mode in non-cga modes"); vga_ignore_extended_memory_bit = section->Get_bool("ignore extended memory bit"); enable_vretrace_poll_debugging_marker = section->Get_bool("vertical retrace poll debug line"); vga_double_buffered_line_compare = section->Get_bool("double-buffered line compare"); hack_lfb_yadjust = section->Get_int("vesa lfb base scanline adjust"); allow_vesa_lowres_modes = section->Get_bool("allow low resolution vesa modes"); vesa12_modes_32bpp = section->Get_bool("vesa vbe 1.2 modes are 32bpp"); allow_vesa_4bpp_packed = section->Get_bool("allow 4bpp packed vesa modes"); allow_explicit_vesa_24bpp = section->Get_bool("allow explicit 24bpp vesa modes"); allow_hd_vesa_modes = section->Get_bool("allow high definition vesa modes"); allow_unusual_vesa_modes = section->Get_bool("allow unusual vesa modes"); allow_vesa_32bpp = section->Get_bool("allow 32bpp vesa modes"); allow_vesa_24bpp = section->Get_bool("allow 24bpp vesa modes"); allow_vesa_16bpp = section->Get_bool("allow 16bpp vesa modes"); allow_vesa_15bpp = section->Get_bool("allow 15bpp vesa modes"); allow_vesa_8bpp = section->Get_bool("allow 8bpp vesa modes"); allow_vesa_4bpp = section->Get_bool("allow 4bpp vesa modes"); allow_vesa_tty = section->Get_bool("allow tty vesa modes"); enable_vga_resize_delay = section->Get_bool("enable vga resize delay"); vga_ignore_hdispend_change_if_smaller = section->Get_bool("resize only on vga active display width increase"); vesa_bios_modelist_in_info = section->Get_bool("vesa vbe put modelist in vesa information"); /* sanity check: "VBE 1.2 modes 32bpp" doesn't make any sense if neither 24bpp or 32bpp is enabled */ if (!allow_vesa_32bpp && !allow_vesa_24bpp) vesa12_modes_32bpp = 0; /* sanity check: "VBE 1.2 modes 32bpp=true" doesn't make sense if the user disabled 32bpp */ else if (vesa12_modes_32bpp && !allow_vesa_32bpp) vesa12_modes_32bpp = 0; /* sanity check: "VBE 1.2 modes 32bpp=false" doesn't make sense if the user disabled 24bpp */ else if (!vesa12_modes_32bpp && !allow_vesa_24bpp && allow_vesa_32bpp) vesa12_modes_32bpp = 1; if (vga_force_refresh_rate > 0) LOG(LOG_VGA,LOG_NORMAL)("VGA forced refresh rate active = %.3f",vga_force_refresh_rate); vga.draw.resizing=false; vga_8bit_dac = false; enable_vga_8bit_dac = section->Get_bool("enable 8-bit dac"); vga_memio_delay_ns = section->Get_int("vmemdelay"); if (vga_memio_delay_ns < 0) { if (IS_EGAVGA_ARCH) { if (pcibus_enable) { /* some delay based on PCI bus protocol with frame start, turnaround, and burst transfer */ double t = (1000000000.0 * clockdom_PCI_BCLK.freq_div * (1/*turnaround*/+1/*frame start*/+1/*burst*/-0.25/*fudge*/)) / clockdom_PCI_BCLK.freq; vga_memio_delay_ns = (int)floor(t); } else { /* very optimistic setting, ISA bus cycles are longer than 2, but also the 386/486/Pentium pipeline * instruction decoding. so it's not a matter of sucking up enough CPU cycle counts to match the * duration of a memory I/O cycle, because real hardware probably has another instruction decode * going while it does it. * * this is long enough to fix some demo's raster effects to work properly but not enough to * significantly bring DOS games to a crawl. Apparently, this also fixes Future Crew "Panic!" * by making the shadebob take long enough to allow the 3D rotating dot object to finish it's * routine just in time to become the FC logo, instead of sitting there waiting awkwardly * for 3-5 seconds. */ double t = (1000000000.0 * clockdom_ISA_BCLK.freq_div * 3.75) / clockdom_ISA_BCLK.freq; vga_memio_delay_ns = (int)floor(t); } } else if (machine == MCH_CGA || machine == MCH_HERC || machine == MCH_MDA) { /* default IBM PC/XT 4.77MHz timing. this is carefully tuned so that Trixter's CGA test program * times our CGA emulation as having about 305KB/sec reading speed. */ double t = (1000000000.0 * clockdom_ISA_OSC.freq_div * 143) / (clockdom_ISA_OSC.freq * 3); vga_memio_delay_ns = (int)floor(t); } else { /* dunno. pick something */ double t = (1000000000.0 * clockdom_ISA_BCLK.freq_div * 6) / clockdom_ISA_BCLK.freq; vga_memio_delay_ns = (int)floor(t); } } LOG(LOG_VGA,LOG_DEBUG)("VGA memory I/O delay %uns",vga_memio_delay_ns); vbe_window_granularity = (unsigned int)section->Get_int("vbe window granularity") << 10u; /* KB to bytes */ vbe_window_size = (unsigned int)section->Get_int("vbe window size") << 10u; /* KB to bytes */ if (vbe_window_granularity != 0 && !bitop::ispowerof2(vbe_window_granularity)) LOG(LOG_VGA,LOG_WARN)("User specified VBE window granularity is not a power of 2. May break some programs."); if (vbe_window_size != 0 && !bitop::ispowerof2(vbe_window_size)) LOG(LOG_VGA,LOG_WARN)("User specified VBE window size is not a power of 2. May break some programs."); if (vbe_window_size != 0 && vbe_window_granularity != 0 && vbe_window_size < vbe_window_granularity) LOG(LOG_VGA,LOG_WARN)("VBE window size is less than window granularity, which prevents full access to video memory and may break some programs."); /* mainline compatible vmemsize (in MB) * plus vmemsizekb for KB-level control. * then we round up a page. * * FIXME: If PCjr/Tandy uses system memory as video memory, * can we get away with pointing at system memory * directly and not allocate a dedicated char[] * array for VRAM? Likewise for VGA emulation of * various motherboard chipsets known to "steal" * off the top of system RAM, like Intel and * Chips & Tech VGA implementations? */ { int sz_m = section->Get_int("vmemsize"); int sz_k = section->Get_int("vmemsizekb"); if (sz_m >= 0 || sz_k > 0) { vga.mem.memsize = _MB_bytes((unsigned int)sz_m); vga.mem.memsize += _KB_bytes((unsigned int)sz_k); vga.mem.memsize = (vga.mem.memsize + 0xFFFu) & (~0xFFFu); /* mainline compatible: vmemsize == 0 means 512KB */ if (vga.mem.memsize == 0) vga.mem.memsize = _KB_bytes(512); /* round up to the nearest power of 2 (TODO: Any video hardware that uses non-power-of-2 sizes?). * A lot of DOSBox's VGA emulation code assumes power-of-2 VRAM sizes especially when wrapping * memory addresses with (a & (vmemsize - 1)) type code. */ if (!is_power_of_2(vga.mem.memsize)) { vga.mem.memsize = 1u << (int_log2(vga.mem.memsize) + 1u); LOG(LOG_VGA,LOG_WARN)("VGA RAM size requested is not a power of 2, rounding up to %uKB",vga.mem.memsize>>10); } } else { vga.mem.memsize = 0; /* machine-specific code will choose below */ } } /* sanity check according to adapter type. * FIXME: Again it was foolish for DOSBox to standardize on machine= * for selecting machine type AND video card. */ switch (machine) { case MCH_HERC: if (vga.mem.memsize < _KB_bytes(64)) vga.mem.memsize = _KB_bytes(64); break; case MCH_MDA: if (vga.mem.memsize < _KB_bytes(4)) vga.mem.memsize = _KB_bytes(4); break; case MCH_CGA: if (vga.mem.memsize < _KB_bytes(16)) vga.mem.memsize = _KB_bytes(16); break; case MCH_TANDY: case MCH_PCJR: if (vga.mem.memsize < _KB_bytes(128)) vga.mem.memsize = _KB_bytes(128); /* FIXME: Right? */ break; case MCH_EGA: // EGA cards supported either 64KB, 128KB or 256KB. if (vga.mem.memsize == 0) vga.mem.memsize = _KB_bytes(256);//default else if (vga.mem.memsize <= _KB_bytes(64)) vga.mem.memsize = _KB_bytes(64); else if (vga.mem.memsize <= _KB_bytes(128)) vga.mem.memsize = _KB_bytes(128); else vga.mem.memsize = _KB_bytes(256); break; case MCH_VGA: // TODO: There are reports of VGA cards that have less than 256KB in the early days of VGA. // How does that work exactly, especially when 640x480 requires about 37KB per plane? // Did these cards have some means to chain two bitplanes odd/even in the same way // tha EGA did it? if (vga.mem.memsize != 0 || svgaCard == SVGA_None) { if (vga.mem.memsize < _KB_bytes(256)) vga.mem.memsize = _KB_bytes(256); } break; case MCH_AMSTRAD: if (vga.mem.memsize < _KB_bytes(64)) vga.mem.memsize = _KB_bytes(64); /* FIXME: Right? */ break; case MCH_PC98: if (vga.mem.memsize < _KB_bytes(544)) vga.mem.memsize = _KB_bytes(544); /* 544 = 512KB graphics + 32KB text */ break; case MCH_MCGA: if (vga.mem.memsize < _KB_bytes(64)) vga.mem.memsize = _KB_bytes(64); break; default: E_Exit("Unexpected machine"); } /* I'm sorry, emulating 640x350 4-color chained EGA graphics is * harder than I thought and would require revision of quite a * bit of VGA planar emulation to update only bitplane 0 and 2 * in such a manner. --J.C. */ if (IS_EGA_ARCH && vga.mem.memsize < _KB_bytes(128)) LOG_MSG("WARNING: EGA 64KB emulation is very experimental and not well supported"); /* If video memory is limited by bank switching, then reduce video memory */ if (vbe_window_granularity != 0 && !IS_PC98_ARCH) { const uint32_t sz = GetReportedVideoMemorySize(); LOG(LOG_VGA,LOG_NORMAL)("Video RAM size %uKB exceeds maximum possible %uKB given VBE window granularity, reducing", vga.mem.memsize>>10,(unsigned int)(sz>>10ul)); /* reduce by half, until video memory is reported or larger but not more than 2x */ while (vga.mem.memsize > _KB_bytes(512) && (vga.mem.memsize/2ul) >= sz) vga.mem.memsize /= 2u; } // prepare for transition if (want_fm_towns) { if (vga.mem.memsize < _KB_bytes(640)) vga.mem.memsize = _KB_bytes(640); /* "640KB of RAM, 512KB VRAM and 128KB sprite RAM" */ } if (!IS_PC98_ARCH) SVGA_Setup_Driver(); // svga video memory size is set here, possibly over-riding the user's selection // NTS: This is WHY the memory size must be a power of 2 vga.mem.memmask = vga.mem.memsize - 1u; LOG(LOG_VGA,LOG_NORMAL)("Video RAM: %uKB",vga.mem.memsize>>10); // TODO: If S3 emulation, and linear framebuffer bumps up against the CPU memalias limits, // trim Video RAM to fit (within reasonable limits) or else E_Exit() to let the user // know of impossible constraints. mainMenu.get_item("debug_pageflip").check(enable_page_flip_debugging_marker).refresh_item(mainMenu); mainMenu.get_item("debug_retracepoll").check(enable_vretrace_poll_debugging_marker).refresh_item(mainMenu); VGA_SetupMemory(); // memory is allocated here if (!IS_PC98_ARCH) { VGA_SetupMisc(); VGA_SetupDAC(); VGA_SetupGFX(); VGA_SetupSEQ(); VGA_SetupAttr(); VGA_SetupOther(); VGA_SetupXGA(); VGA_SetClock(0,CLK_25); VGA_SetClock(1,CLK_28); /* Generate tables */ VGA_SetCGA2Table(0,1); VGA_SetCGA4Table(0,1,2,3); } Section_prop * section2=static_cast<Section_prop *>(control->GetSection("vsync")); const char * vsyncmodestr; vsyncmodestr=section2->Get_string("vsyncmode"); void change_output(int output); change_output(9); VGA_VsyncUpdateMode(VGA_Vsync_Decode(vsyncmodestr)); const char * vsyncratestr; vsyncratestr=section2->Get_string("vsyncrate"); double vsyncrate=70; if (!strcasecmp(vsyncmodestr,"host")) { #if defined (WIN32) DEVMODE devmode; if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devmode)) vsyncrate=devmode.dmDisplayFrequency; else sscanf(vsyncratestr,"%lf",&vsyncrate); #endif } else { sscanf(vsyncratestr,"%lf",&vsyncrate); } vsync.period = (1000.0F)/vsyncrate; if (IS_PC98_ARCH) { void VGA_OnEnterPC98(Section *sec); void VGA_OnEnterPC98_phase2(Section *sec); void PC98_FM_OnEnterPC98(Section *sec); VGA_OnEnterPC98(NULL); VGA_OnEnterPC98_phase2(NULL); // TODO: Move to separate file PC98_FM_OnEnterPC98(NULL); } } extern void VGA_TweakUserVsyncOffset(float val); void INT10_PC98_CurMode_Relocate(void); void VGA_UnsetupMisc(void); void VGA_UnsetupAttr(void); void VGA_UnsetupDAC(void); void VGA_UnsetupGFX(void); void VGA_UnsetupSEQ(void); #define gfx(blah) vga.gfx.blah #define seq(blah) vga.seq.blah #define crtc(blah) vga.crtc.blah void VGA_OnEnterPC98(Section *sec) { (void)sec;//UNUSED VGA_UnsetupMisc(); VGA_UnsetupAttr(); VGA_UnsetupDAC(); VGA_UnsetupGFX(); VGA_UnsetupSEQ(); LOG_MSG("PC-98: GDC is running at %.1fMHz.",gdc_5mhz_mode ? 5.0 : 2.5); pc98_egc_srcmask[0] = 0xFF; pc98_egc_srcmask[1] = 0xFF; pc98_egc_maskef[0] = 0xFF; pc98_egc_maskef[1] = 0xFF; pc98_egc_mask[0] = 0xFF; pc98_egc_mask[1] = 0xFF; for (unsigned int i=0;i < 8;i++) pc98_pal_digital[i] = i; for (unsigned int i=0;i < 8;i++) { pc98_pal_analog[(i*3) + 0] = (i & 4) ? 0x0F : 0x00; pc98_pal_analog[(i*3) + 1] = (i & 2) ? 0x0F : 0x00; pc98_pal_analog[(i*3) + 2] = (i & 1) ? 0x0F : 0x00; if (i != 0) { pc98_pal_analog[((i+8)*3) + 0] = (i & 4) ? 0x0A : 0x00; pc98_pal_analog[((i+8)*3) + 1] = (i & 2) ? 0x0A : 0x00; pc98_pal_analog[((i+8)*3) + 2] = (i & 1) ? 0x0A : 0x00; } else { pc98_pal_analog[((i+8)*3) + 0] = 0x07; pc98_pal_analog[((i+8)*3) + 1] = 0x07; pc98_pal_analog[((i+8)*3) + 2] = 0x07; } } for (unsigned int i=0;i < 256;i++) { pc98_pal_vga[(i*3)+0] = i; pc98_pal_vga[(i*3)+1] = i; pc98_pal_vga[(i*3)+2] = i; } pc98_update_palette(); { for (unsigned int i=0;i < 8;i++) { unsigned char r = (i & 2) ? 255 : 0; unsigned char g = (i & 4) ? 255 : 0; unsigned char b = (i & 1) ? 255 : 0; if (GFX_bpp >= 24) /* FIXME: Assumes 8:8:8. What happens when desktops start using the 10:10:10 format? */ pc98_text_palette[i] = ((Bitu)(((Bitu)b << GFX_Bshift) + ((Bitu)g << GFX_Gshift) + ((Bitu)r << GFX_Rshift) + (Bitu)GFX_Amask)); else { /* FIXME: PC-98 mode renders as 32bpp regardless (at this time), so we have to fake 32bpp order */ /* Since PC-98 itself has 4-bit RGB precision, it might be best to offer a 16bpp rendering mode, * or even just have PC-98 mode stay in 16bpp entirely. */ if (GFX_Bshift == 0) pc98_text_palette[i] = (Bitu)(((Bitu)b << 0U) + ((Bitu)g << 8U) + ((Bitu)r << 16U)); else pc98_text_palette[i] = (Bitu)(((Bitu)b << 16U) + ((Bitu)g << 8U) + ((Bitu)r << 0U)); } } } pc98_gdc_tile_counter=0; pc98_gdc_modereg=0; for (unsigned int i=0;i < 4;i++) pc98_gdc_tiles[i].w = 0; vga.dac.pel_mask = 0xFF; vga.crtc.maximum_scan_line = 15; /* 200-line tradition on PC-98 seems to be to render only every other scanline */ pc98_graphics_hide_odd_raster_200line = true; pc98_256kb_boundary = false; /* port 6Ah command 68h/69h */ // as a transition to PC-98 GDC emulation, move VGA alphanumeric buffer // down to A0000-AFFFFh. gdc_analog = false; pc98_gdc_vramop &= ~(1 << VOPBIT_ANALOG); gfx(miscellaneous) &= ~0x0C; /* bits[3:2] = 0 to map A0000-BFFFF */ VGA_DetermineMode(); VGA_SetupHandlers(); VGA_DAC_UpdateColorPalette(); INT10_PC98_CurMode_Relocate(); /* make sure INT 10h knows */ if(!pc98_31khz_mode) { /* Set up 24KHz hsync 56.42Hz rate */ vga.crtc.horizontal_total = 106 - 5; vga.crtc.vertical_total = (440 - 2) & 0xFF; vga.crtc.end_vertical_blanking = (440 - 2 - 8) & 0xFF; // FIXME vga.crtc.vertical_retrace_start = (440 - 2 - 30) & 0xFF; // FIXME vga.crtc.vertical_retrace_end = (440 - 2 - 28) & 0xFF; // FIXME vga.crtc.start_vertical_blanking = (400 + 8) & 0xFF; // FIXME vga.crtc.overflow |= 0x01; vga.crtc.overflow &= ~0x20; } else { //Set up 31-KHz mode. Values guessed according to other 640x400 modes in int10_modes.cpp. //TODO: Find the right values by inspecting a real PC-9821 system. vga.crtc.horizontal_total = 100 - 5; vga.crtc.vertical_total = (449 - 2) & 0xFF; vga.crtc.end_vertical_blanking = (449 - 2 - 8) & 0xFF; // FIXME vga.crtc.vertical_retrace_start = (449 - 2 - 30) & 0xFF; // FIXME vga.crtc.vertical_retrace_end = (449 - 2 - 28) & 0xFF; // FIXME vga.crtc.start_vertical_blanking = (400 + 8) & 0xFF; // FIXME vga.crtc.overflow |= 0x01; vga.crtc.overflow &= ~0x20; } /* 8-char wide mode. change to 25MHz clock to match. */ vga.config.addr_shift = 0; seq(clocking_mode) |= 1; /* 8-bit wide char */ vga.misc_output &= ~0x0C; /* bits[3:2] = 0 25MHz clock */ /* PC-98 seems to favor a block cursor */ vga.draw.cursor.enabled = true; crtc(cursor_start) = 0; vga.draw.cursor.sline = 0; crtc(cursor_end) = 15; vga.draw.cursor.eline = 15; /* now, switch to PC-98 video emulation */ for (unsigned int i=0;i < 16;i++) VGA_ATTR_SetPalette(i,i); for (unsigned int i=0;i < 16;i++) vga.dac.combine[i] = i; vga.mode=M_PC98; assert(vga.mem.memsize >= 0x80000); memset(vga.mem.linear,0,0x80000); VGA_StartResize(); } void MEM_ResetPageHandler_Unmapped(Bitu phys_page, Bitu pages); void updateGDCpartitions4(bool enable) { pc98_allow_4_display_partitions = enable; pc98_gdc[GDC_SLAVE].display_partition_mask = pc98_allow_4_display_partitions ? 3 : 1; } /* source: Neko Project II GDC SYNC parameters for each mode */ #if 0 // NOT YET USED static const UINT8 gdc_defsyncm15[8] = {0x10,0x4e,0x07,0x25,0x0d,0x0f,0xc8,0x94}; static const UINT8 gdc_defsyncs15[8] = {0x06,0x26,0x03,0x11,0x86,0x0f,0xc8,0x94}; #endif static const UINT8 gdc_defsyncm24[8] = {0x10,0x4e,0x07,0x25,0x07,0x07,0x90,0x65}; static const UINT8 gdc_defsyncs24[8] = {0x06,0x26,0x03,0x11,0x83,0x07,0x90,0x65}; static const UINT8 gdc_defsyncm31[8] = {0x10,0x4e,0x47,0x0c,0x07,0x0d,0x90,0x89}; static const UINT8 gdc_defsyncs31[8] = {0x06,0x26,0x41,0x0c,0x83,0x0d,0x90,0x89}; static const UINT8 gdc_defsyncm31_480[8] = {0x10,0x4e,0x4b,0x0c,0x03,0x06,0xe0,0x95}; static const UINT8 gdc_defsyncs31_480[8] = {0x06,0x4e,0x4b,0x0c,0x83,0x06,0xe0,0x95}; void PC98_Set24KHz(void) { pc98_gdc[GDC_MASTER].write_fifo_command(0x0F/*sync DE=1*/); for (unsigned int i=0;i < 8;i++) pc98_gdc[GDC_MASTER].write_fifo_param(gdc_defsyncm24[i]); pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_SLAVE].write_fifo_command(0x0F/*sync DE=1*/); for (unsigned int i=0;i < 8;i++) pc98_gdc[GDC_SLAVE].write_fifo_param(gdc_defsyncs24[i]); pc98_gdc[GDC_SLAVE].force_fifo_complete(); } void PC98_Set31KHz(void) { pc98_gdc[GDC_MASTER].write_fifo_command(0x0F/*sync DE=1*/); for (unsigned int i=0;i < 8;i++) pc98_gdc[GDC_MASTER].write_fifo_param(gdc_defsyncm31[i]); pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_SLAVE].write_fifo_command(0x0F/*sync DE=1*/); for (unsigned int i=0;i < 8;i++) pc98_gdc[GDC_SLAVE].write_fifo_param(gdc_defsyncs31[i]); pc98_gdc[GDC_SLAVE].force_fifo_complete(); } void PC98_Set31KHz_480line(void) { pc98_gdc[GDC_MASTER].write_fifo_command(0x0F/*sync DE=1*/); for (unsigned int i=0;i < 8;i++) pc98_gdc[GDC_MASTER].write_fifo_param(gdc_defsyncm31_480[i]); pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_SLAVE].write_fifo_command(0x0F/*sync DE=1*/); for (unsigned int i=0;i < 8;i++) pc98_gdc[GDC_SLAVE].write_fifo_param(gdc_defsyncs31_480[i]); pc98_gdc[GDC_SLAVE].force_fifo_complete(); } void VGA_OnEnterPC98_phase2(Section *sec) { (void)sec;//UNUSED VGA_SetupHandlers(); /* GDC 2.5/5.0MHz setting is also reflected in BIOS data area and DIP switch registers */ gdc_5mhz_mode_update_vars(); /* delay I/O port at 0x5F (0.6us) */ IO_RegisterWriteHandler(0x5F,pc98_wait_write,IO_MB); /* master GDC at 0x60-0x6F (even) * slave GDC at 0xA0-0xAF (even) */ for (unsigned int i=0x60;i <= 0xA0;i += 0x40) { for (unsigned int j=0;j < 0x10;j += 2) { IO_RegisterWriteHandler(i+j,pc98_gdc_write,IO_MB); IO_RegisterReadHandler(i+j,pc98_gdc_read,IO_MB); } } /* initial implementation of I/O ports 9A0h-9AEh even */ IO_RegisterReadHandler(0x9A0,pc98_read_9a0,IO_MB); IO_RegisterWriteHandler(0x9A0,pc98_write_9a0,IO_MB); /* 9A8h which controls 24khz/31khz mode */ IO_RegisterReadHandler(0x9A8,pc98_read_9a8,IO_MB); IO_RegisterWriteHandler(0x9A8,pc98_write_9a8,IO_MB); /* There are some font character RAM controls at 0xA1-0xA5 (odd) * combined with A4000-A4FFF. Found by unknown I/O tracing in DOSBox-X * and by tracing INT 18h AH=1Ah on an actual system using DEBUG.COM. * * If I find documentation on what exactly these ports are, I will * list them as such. * * Some games (Touhou Project) load font RAM directly through these * ports instead of using the BIOS. */ for (unsigned int i=0xA1;i <= 0xA9;i += 2) { IO_RegisterWriteHandler(i,pc98_a1_write,IO_MB); } /* Touhou Project appears to read font RAM as well */ IO_RegisterReadHandler(0xA9,pc98_a1_read,IO_MB); /* CRTC at 0x70-0x7F (even) */ for (unsigned int j=0x70;j < 0x80;j += 2) { IO_RegisterWriteHandler(j,pc98_crtc_write,IO_MB); IO_RegisterReadHandler(j,pc98_crtc_read,IO_MB); } /* EGC at 0x4A0-0x4AF (even). * All I/O ports are 16-bit. * NTS: On real hardware, doing 8-bit I/O on these ports will often hang the system. */ for (unsigned int i=0;i < 0x10;i += 2) { IO_RegisterWriteHandler(i+0x4A0,pc98_egc4a0_write_warning,IO_MB); IO_RegisterWriteHandler(i+0x4A0,pc98_egc4a0_write, IO_MW); IO_RegisterWriteHandler(i+0x4A1,pc98_egc4a0_write_warning,IO_MB); IO_RegisterWriteHandler(i+0x4A1,pc98_egc4a0_write_warning,IO_MW); IO_RegisterReadHandler(i+0x4A0,pc98_egc4a0_read_warning,IO_MB); IO_RegisterReadHandler(i+0x4A0,pc98_egc4a0_read, IO_MW); IO_RegisterReadHandler(i+0x4A1,pc98_egc4a0_read_warning,IO_MB); IO_RegisterReadHandler(i+0x4A1,pc98_egc4a0_read_warning,IO_MW); } pc98_gdc[GDC_MASTER].master_sync = true; pc98_gdc[GDC_MASTER].display_enable = true; pc98_gdc[GDC_MASTER].row_height = 16; pc98_gdc[GDC_MASTER].display_pitch = 80; pc98_gdc[GDC_MASTER].active_display_words_per_line = 80; pc98_gdc[GDC_MASTER].display_partition_mask = 3; pc98_gdc[GDC_SLAVE].master_sync = false; pc98_gdc[GDC_SLAVE].display_enable = false;//FIXME pc98_gdc[GDC_SLAVE].row_height = 1; pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_mode ? 80u : 40u; pc98_gdc[GDC_SLAVE].display_partition_mask = pc98_allow_4_display_partitions ? 3 : 1; const unsigned char *gdcsync_m; const unsigned char *gdcsync_s; if (!pc98_31khz_mode) { gdcsync_m = gdc_defsyncm24; gdcsync_s = gdc_defsyncs24; } else { gdcsync_m = gdc_defsyncm31; gdcsync_s = gdc_defsyncs31; } pc98_gdc[GDC_MASTER].write_fifo_command(0x0F/*sync DE=1*/); for (unsigned int i=0;i < 8;i++) pc98_gdc[GDC_MASTER].write_fifo_param(gdcsync_m[i]); pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_SLAVE].write_fifo_command(0x0F/*sync DE=1*/); for (unsigned int i=0;i < 8;i++) pc98_gdc[GDC_SLAVE].write_fifo_param(gdcsync_s[i]); pc98_gdc[GDC_SLAVE].force_fifo_complete(); VGA_StartResize(); } void VGA_Destroy(Section*) { void PC98_FM_Destroy(Section *sec); PC98_FM_Destroy(NULL); } extern uint8_t pc98_pal_analog[256*3]; /* G R B 0x0..0xF */ extern uint8_t pc98_pal_digital[8]; /* G R B 0x0..0x7 */ void pc98_update_palette(void); void UpdateCGAFromSaveState(void); bool debugpollvga_pf_menu_callback(DOSBoxMenu * const xmenu, DOSBoxMenu::item * const menuitem) { (void)xmenu;//UNUSED (void)menuitem;//UNUSED enable_page_flip_debugging_marker = !enable_page_flip_debugging_marker; mainMenu.get_item("debug_pageflip").check(enable_page_flip_debugging_marker).refresh_item(mainMenu); return true; } bool debugpollvga_rtp_menu_callback(DOSBoxMenu * const xmenu, DOSBoxMenu::item * const menuitem) { (void)xmenu;//UNUSED (void)menuitem;//UNUSED enable_vretrace_poll_debugging_marker = !enable_vretrace_poll_debugging_marker; mainMenu.get_item("debug_retracepoll").check(enable_vretrace_poll_debugging_marker).refresh_item(mainMenu); return true; } void VGA_Init() { Bitu i,j; enveten = false; vga.mode=M_ERROR; //For first init vga.other.mcga_mode_control = 0; vga.config.chained = false; vga.draw.render_step = 0; vga.draw.render_max = 1; vga.tandy.draw_base = NULL; vga.tandy.mem_base = NULL; LOG(LOG_MISC,LOG_DEBUG)("Initializing VGA"); LOG(LOG_MISC,LOG_DEBUG)("Render scaler maximum resolution is %u x %u",SCALER_MAXWIDTH,SCALER_MAXHEIGHT); VGA_TweakUserVsyncOffset(0.0f); for (i=0;i<256;i++) { ExpandTable[i]=(Bitu)(i + (i << 8u) + (i << 16u) + (i << 24u)); } for (i=0;i<16;i++) { TXT_FG_Table[i]=(Bitu)(i + (i << 8u) + (i << 16u) + (i << 24u)); TXT_BG_Table[i]=(Bitu)(i + (i << 8u) + (i << 16u) + (i << 24u)); #ifdef WORDS_BIGENDIAN FillTable[i]= ((i & 1u) ? 0xff000000u : 0u) | ((i & 2u) ? 0x00ff0000u : 0u) | ((i & 4u) ? 0x0000ff00u : 0u) | ((i & 8u) ? 0x000000ffu : 0u) ; TXT_Font_Table[i]= ((i & 1u) ? 0x000000ffu : 0u) | ((i & 2u) ? 0x0000ff00u : 0u) | ((i & 4u) ? 0x00ff0000u : 0u) | ((i & 8u) ? 0xff000000u : 0u) ; #else FillTable[i]= ((i & 1u) ? 0x000000ffu : 0u) | ((i & 2u) ? 0x0000ff00u : 0u) | ((i & 4u) ? 0x00ff0000u : 0u) | ((i & 8u) ? 0xff000000u : 0u) ; TXT_Font_Table[i]= ((i & 1u) ? 0xff000000u : 0u) | ((i & 2u) ? 0x00ff0000u : 0u) | ((i & 4u) ? 0x0000ff00u : 0u) | ((i & 8u) ? 0x000000ffu : 0u) ; #endif } for (j=0;j<4;j++) { for (i=0;i<16;i++) { #ifdef WORDS_BIGENDIAN Expand16Table[j][i] = ((i & 1u) ? 1u << j : 0u) | ((i & 2u) ? 1u << (8u + j) : 0u) | ((i & 4u) ? 1u << (16u + j) : 0u) | ((i & 8u) ? 1u << (24u + j) : 0u); #else Expand16Table[j][i] = ((i & 1u) ? 1u << (24u + j) : 0u) | ((i & 2u) ? 1u << (16u + j) : 0u) | ((i & 4u) ? 1u << (8u + j) : 0u) | ((i & 8u) ? 1u << j : 0u); #endif } } mainMenu.alloc_item(DOSBoxMenu::item_type_id,"debug_pageflip").set_text("Page flip debug line").set_callback_function(debugpollvga_pf_menu_callback); mainMenu.alloc_item(DOSBoxMenu::item_type_id,"debug_retracepoll").set_text("Retrace poll debug line").set_callback_function(debugpollvga_rtp_menu_callback); AddExitFunction(AddExitFunctionFuncPair(VGA_Destroy)); AddVMEventFunction(VM_EVENT_RESET,AddVMEventFunctionFuncPair(VGA_Reset)); } JEGA_DATA jega; // Store font void JEGA_writeFont() { jega.RSTAT &= ~0x02; Bitu chr = jega.RDFFB; Bitu chr_2 = jega.RDFSB; // Check the char code is in Wide charset of Shift-JIS if ((chr >= 0x40 && chr <= 0x7e) || (chr >= 0x80 && chr <= 0xfc)) { if (jega.fontIndex >= 32) jega.fontIndex = 0; chr <<= 8; //fix vertical char position chr |= chr_2; if (jega.fontIndex < 16) // read font from register and store it jfont_dbcs_16[chr * 32 + jega.fontIndex * 2] = jega.RDFAP;// w16xh16 font else jfont_dbcs_16[chr * 32 + (jega.fontIndex - 16) * 2 + 1] = jega.RDFAP;// w16xh16 font } else { if (jega.fontIndex >= 19) jega.fontIndex = 0; jfont_sbcs_19[chr * 19 + jega.fontIndex] = jega.RDFAP;// w16xh16 font } jega.fontIndex++; jega.RSTAT |= 0x02; } // Read font void JEGA_readFont() { jega.RSTAT &= ~0x02; Bitu chr = jega.RDFFB; Bitu chr_2 = jega.RDFSB; // Check the char code is in Wide charset of Shift-JIS if ((chr >= 0x40 && chr <= 0x7e) || (chr >= 0x80 && chr <= 0xfc)) { if (jega.fontIndex >= 32) jega.fontIndex = 0; chr <<= 8; //fix vertical char position chr |= chr_2; if (jega.fontIndex < 16) // get font and set to register jega.RDFAP = jfont_dbcs_16[chr * 32 + jega.fontIndex * 2];// w16xh16 font else jega.RDFAP = jfont_dbcs_16[chr * 32 + (jega.fontIndex - 16) * 2 + 1]; } else { if (jega.fontIndex >= 19) jega.fontIndex = 0; jega.RDFAP = jfont_sbcs_19[chr * 19 + jega.fontIndex];// w16xh16 font } jega.fontIndex++; jega.RSTAT |= 0x02; } void write_p3d5_jega(Bitu reg, Bitu val, Bitu iolen) { (void)iolen;//UNUSED switch (reg) { case 0xb9://Mode register 1 jega.RMOD1 = val; break; case 0xba://Mode register 2 jega.RMOD2 = val; break; case 0xbb://ANK Group sel jega.RDAGS = val; break; case 0xbc:// Font access first byte if (jega.RDFFB != val) { jega.RDFFB = val; jega.fontIndex = 0; } break; case 0xbd:// Font access Second Byte if (jega.RDFSB != val) { jega.RDFSB = val; jega.fontIndex = 0; } break; case 0xbe:// Font Access Pattern jega.RDFAP = val; JEGA_writeFont(); break; //case 0x09:// end scan line // jega.RPESL = val; // break; //case 0x14:// under scan line // jega.RPULP = val; // break; case 0xdb: jega.RPSSC = val; break; case 0xd9: jega.RPSSU = val; break; case 0xda: jega.RPSSL = val; break; case 0xdc://super imposed (only AX-2 system, not implemented) jega.RPPAJ = val; break; case 0xdd: jega.RCMOD = val; break; //case 0x0e://Cursor location Upper bits // jega.RCCLH = val; // break; //case 0x0f://Cursor location Lower bits // jega.RCCLL = val; // break; //case 0x0a://Cursor Start Line // jega.RCCSL = val; // break; //case 0x0b://Cursor End Line // jega.RCCEL = val; // break; case 0xde://Cursor Skew control jega.RCSKW = val; break; case 0xdf://Unused? jega.ROMSL = val; break; case 0xbf://font r/w register jega.RSTAT = val; break; default: LOG(LOG_VGAMISC, LOG_NORMAL)("VGA:GFX:JEGA:Write to illegal index %2X", (unsigned int)reg); break; } } //CRT Control Register can be read from I/O 3D5h, after setting index at I/O 3D4h Bitu read_p3d5_jega(Bitu reg, Bitu iolen) { (void)iolen;//UNUSED switch (reg) { case 0xb9: return jega.RMOD1; case 0xba: return jega.RMOD2; case 0xbb: return jega.RDAGS; case 0xbc:// BCh RDFFB Font access First Byte return jega.RDFFB; case 0xbd:// BDh RDFFB Font access Second Byte return jega.RDFSB; case 0xbe:// BEh RDFAP Font Access Pattern JEGA_readFont(); return jega.RDFAP; //case 0x09: // return jega.RPESL; //case 0x14: // return jega.RPULP; case 0xdb: return jega.RPSSC; case 0xd9: return jega.RPSSU; case 0xda: return jega.RPSSL; case 0xdc: return jega.RPPAJ; case 0xdd: return jega.RCMOD; //case 0x0e: // return jega.RCCLH; //case 0x0f: // return jega.RCCLL; //case 0x0a: // return jega.RCCSL; //case 0x0b: // return jega.RCCEL; case 0xde: return jega.RCSKW; case 0xdf: return jega.ROMSL; case 0xbf: return 0x03;//Font always read/writeable default: LOG(LOG_VGAMISC, LOG_NORMAL)("VGA:GFX:JEGA:Read from illegal index %2X", (unsigned int)reg); break; } return 0x0; } void JEGA_setupAX(void) { memset(&jega, 0, sizeof(JEGA_DATA)); jega.RMOD1 = 0xC8;//b9: Mode register 1 jega.RMOD2 = 0x00;//ba: Mode register 2 jega.RDAGS = 0x00;//bb: ANK Group sel (not implemented) jega.RDFFB = 0x00;//bc: Font access first byte jega.RDFSB = 0x00;//bd: second jega.RDFAP = 0x00;//be: Font Access Pattern jega.RPESL = 0x00;//09: end scan line (superceded by EGA) jega.RPULP = 0x00;//14: under scan line (superceded by EGA) jega.RPSSC = 1;//db: DBCS start scan line jega.RPSSU = 3;//d9: 2x DBCS upper start scan jega.RPSSL = 0;//da: 2x DBCS lower start scan jega.RPPAJ = 0x00;//dc: super imposed (only AX-2 system, not implemented) jega.RCMOD = 0x00;//dd: Cursor Mode (not implemented) jega.RCCLH = 0x00;//0e: Cursor location Upper bits (superceded by EGA) jega.RCCLL = 0x00;//0f: Cursor location Lower bits (superceded by EGA) jega.RCCSL = 0x00;//0a: Cursor Start Line (superceded by EGA) jega.RCCEL = 0x00;//0b: Cursor End Line (superceded by EGA) jega.RCSKW = 0x20;//de: Cursor Skew control (not implemented) jega.ROMSL = 0x00;//df: Unused? jega.RSTAT = 0x03;//bf: Font register accessible status real_writeb(BIOSMEM_AX_SEG, BIOSMEM_AX_JPNSTATUS, 0); real_writeb(BIOSMEM_AX_SEG, BIOSMEM_AX_JEGA_RMOD1, jega.RMOD1); real_writeb(BIOSMEM_AX_SEG, BIOSMEM_AX_JEGA_RMOD2, jega.RMOD2); real_writeb(BIOSMEM_AX_SEG, BIOSMEM_AX_GRAPH_ATTR, 0); real_writeb(BIOSMEM_AX_SEG, BIOSMEM_AX_GRAPH_CHAR, 0); real_writeb(BIOSMEM_AX_SEG, BIOSMEM_AX_VTRAM_SEGADDR, 0); real_writeb(BIOSMEM_AX_SEG, BIOSMEM_AX_KBDSTATUS, 0x00); } void SVGA_Setup_JEGA(void) { JEGA_setupAX(); svga.write_p3d5 = &write_p3d5_jega; svga.read_p3d5 = &read_p3d5_jega; // Adjust memory to 256K if (vga.mem.memsize < 256 * 1024) vga.mem.memsize = 256 * 1024; /* JEGA BIOS ROM signature for AX architecture To run MS-DOS, signature ("JA") must be put at C000h:N*512-18+2 ;N=Number of ROM blocks (rom_base+2) */ PhysPt rom_base = PhysMake(0xc000, 0); phys_writeb(rom_base + 0x40 * 512 - 18 + 2, 'J'); phys_writeb(rom_base + 0x40 * 512 - 18 + 3, 'A'); } void SVGA_Setup_Driver(void) { memset(&svga, 0, sizeof(SVGA_Driver)); switch(svgaCard) { case SVGA_S3Trio: SVGA_Setup_S3Trio(); break; case SVGA_TsengET4K: SVGA_Setup_TsengET4K(); break; case SVGA_TsengET3K: SVGA_Setup_TsengET3K(); break; case SVGA_ParadisePVGA1A: SVGA_Setup_ParadisePVGA1A(); break; default: if (IS_JEGA_ARCH) SVGA_Setup_JEGA(); break; } } void VGA_CaptureStartNextFrame(void) { vga_capture_current_rect = vga_capture_rect; vga_capture_current_address = vga_capture_address; vga_capture_write_address = vga_capture_address; vga_capture_address = 0; VGA_UpdateCapturePending(); } bool VGA_CaptureValidateCurrentFrame(void) { if (VGA_IsCaptureEnabled()) { if (vga_capture_current_rect.x >= 0 && vga_capture_current_rect.y >= 0 && // crop rect is within frame (unsigned int)vga_capture_current_rect.y < vga.draw.height && (unsigned int)vga_capture_current_rect.x < vga.draw.width && vga_capture_current_rect.w > 0 && vga_capture_current_rect.h > 0 && // crop rect size is within frame (unsigned int)vga_capture_current_rect.h <= vga.draw.height && (unsigned int)vga_capture_current_rect.w <= vga.draw.width && ((unsigned int)vga_capture_current_rect.x+vga_capture_current_rect.w) <= vga.draw.width && // crop rect pos+size within frame ((unsigned int)vga_capture_current_rect.y+vga_capture_current_rect.h) <= vga.draw.height) { return true; } } return false; } bool VGA_CaptureHasNextFrame(void) { return !!(vga_capture_address != (uint32_t)0); } void VGA_MarkCaptureAcquired(void) { if (vga_capture_state & ((uint32_t)(1ul << 1ul))) // if already acquired and guest has not cleared the bit vga_capture_state |= (uint32_t)(1ul << 6ul); // mark overrun vga_capture_state |= (uint32_t)(1ul << 1ul); // mark acquired } void VGA_MarkCaptureRetrace(void) { vga_capture_state |= (uint32_t)(1ul << 5ul); // mark retrace } void VGA_MarkCaptureInProgress(bool en) { const uint32_t f = (uint32_t)(1ul << 3ul); if (en) vga_capture_state |= f; else vga_capture_state &= ~f; } bool VGA_IsCapturePending(void) { return !!(vga_capture_state & ((uint32_t)(1ul << 0ul))); } bool VGA_IsCaptureEnabled(void) { return !!(vga_capture_state & ((uint32_t)(1ul << 4ul))); } bool VGA_IsCaptureInProgress(void) { return !!(vga_capture_state & ((uint32_t)(1ul << 3ul))); } void VGA_CaptureMarkError(void) { vga_capture_state |= (uint32_t)(1ul << 2ul); // set error vga_capture_state &= ~((uint32_t)(1ul << 4ul)); // clear enable } void VGA_UpdateCapturePending(void) { bool en = false; if (VGA_IsCaptureEnabled()) { if (vga_capture_address != (uint32_t)0) en = true; } if (en) vga_capture_state |= (uint32_t)(1ul << 0ul); // set bit 0 capture pending else vga_capture_state &= ~((uint32_t)(1ul << 0ul)); // clear bit 0 capture pending } uint32_t VGA_QueryCaptureState(void) { /* bits[0:0] = if set, capture pending * bits[1:1] = if set, capture acquired * bits[2:2] = if set, capture state error (such as crop rectangle out of bounds) * bits[3:3] = if set, capture in progress * bits[4:4] = if set, capture enabled * bits[5:5] = if set, vertical retrace occurred. capture must be enabled for this to occur * bits[6:6] = if set, capture was acquired and acquired bit was already set (overrun) * * both bits 0 and 1 can be set if one capture has finished and the "next" capture address has been loaded. */ return vga_capture_state; } void VGA_SetCaptureState(uint32_t v) { /* bits[1:1] = if set, clear capture acquired bit * bits[2:2] = if set, clear capture state error bits[4:4] = if set, enable capture bits[5:5] = if set, clear vertical retrace occurrence flag bits[6:6] = if set, clear overrun (acquired) bit */ vga_capture_state ^= (vga_capture_state & v & 0x66/*x110 0110*/); vga_capture_state &= ~0x10u; vga_capture_state |= v & 0x10u; if (!VGA_IsCaptureEnabled()) vga_capture_state = 0; VGA_UpdateCapturePending(); } uint32_t VGA_QueryCaptureAddress(void) { return vga_capture_current_address; } void VGA_SetCaptureAddress(uint32_t v) { vga_capture_address = v; VGA_UpdateCapturePending(); } void VGA_SetCaptureStride(uint32_t v) { vga_capture_stride = v; VGA_UpdateCapturePending(); } extern void POD_Save_VGA_Draw( std::ostream & ); extern void POD_Save_VGA_Seq( std::ostream & ); extern void POD_Save_VGA_Attr( std::ostream & ); extern void POD_Save_VGA_Crtc( std::ostream & ); extern void POD_Save_VGA_Gfx( std::ostream & ); extern void POD_Save_VGA_Dac( std::ostream & ); extern void POD_Save_VGA_S3( std::ostream & ); extern void POD_Save_VGA_Other( std::ostream & ); extern void POD_Save_VGA_Memory( std::ostream & ); extern void POD_Save_VGA_Paradise( std::ostream & ); extern void POD_Save_VGA_Tseng( std::ostream & ); extern void POD_Save_VGA_XGA( std::ostream & ); extern void POD_Load_VGA_Draw( std::istream & ); extern void POD_Load_VGA_Seq( std::istream & ); extern void POD_Load_VGA_Attr( std::istream & ); extern void POD_Load_VGA_Crtc( std::istream & ); extern void POD_Load_VGA_Gfx( std::istream & ); extern void POD_Load_VGA_Dac( std::istream & ); extern void POD_Load_VGA_S3( std::istream & ); extern void POD_Load_VGA_Other( std::istream & ); extern void POD_Load_VGA_Memory( std::istream & ); extern void POD_Load_VGA_Paradise( std::istream & ); extern void POD_Load_VGA_Tseng( std::istream & ); extern void POD_Load_VGA_XGA( std::istream & ); //save state support void *VGA_SetupDrawing_PIC_Event = (void*)((uintptr_t)VGA_SetupDrawing); namespace { class SerializeVga : public SerializeGlobalPOD { public: SerializeVga() : SerializeGlobalPOD("Vga") {} private: virtual void getBytes(std::ostream& stream) { uint32_t tandy_drawbase_idx, tandy_membase_idx; if( vga.tandy.draw_base == vga.mem.linear ) tandy_drawbase_idx=0xffffffff; else tandy_drawbase_idx = vga.tandy.draw_base - MemBase; if( vga.tandy.mem_base == vga.mem.linear ) tandy_membase_idx=0xffffffff; else tandy_membase_idx = vga.tandy.mem_base - MemBase; //******************************** //******************************** SerializeGlobalPOD::getBytes(stream); // - pure data WRITE_POD( &vga.mode, vga.mode ); WRITE_POD( &vga.misc_output, vga.misc_output ); // VGA_Draw.cpp POD_Save_VGA_Draw(stream); // - pure struct data WRITE_POD( &vga.config, vga.config ); WRITE_POD( &vga.internal, vga.internal ); // VGA_Seq.cpp / VGA_Attr.cpp / (..) POD_Save_VGA_Seq(stream); POD_Save_VGA_Attr(stream); POD_Save_VGA_Crtc(stream); POD_Save_VGA_Gfx(stream); POD_Save_VGA_Dac(stream); // - pure data WRITE_POD( &vga.latch, vga.latch ); // VGA_S3.cpp POD_Save_VGA_S3(stream); // - pure struct data WRITE_POD( &vga.svga, vga.svga ); WRITE_POD( &vga.herc, vga.herc ); // - near-pure struct data WRITE_POD( &vga.tandy, vga.tandy ); // - reloc data WRITE_POD( &tandy_drawbase_idx, tandy_drawbase_idx ); WRITE_POD( &tandy_membase_idx, tandy_membase_idx ); // vga_other.cpp / vga_memory.cpp POD_Save_VGA_Other(stream); POD_Save_VGA_Memory(stream); // - pure data //WRITE_POD( &vga.vmemwrap, vga.vmemwrap ); // - static ptrs + 'new' data //uint8_t* fastmem; //uint8_t* fastmem_orgptr; // - 'new' data //WRITE_POD_SIZE( vga.fastmem_orgptr, sizeof(uint8_t) * ((vga.vmemsize << 1) + 4096 + 16) ); // - pure data (variable on S3 card) WRITE_POD( &vga.mem.memsize, vga.mem.memsize ); #ifdef VGA_KEEP_CHANGES // - static ptr //uint8_t* map; // - 'new' data WRITE_POD_SIZE( vga.changes.map, sizeof(uint8_t) * (VGA_MEMORY >> VGA_CHANGE_SHIFT) + 32 ); // - pure data WRITE_POD( &vga.changes.checkMask, vga.changes.checkMask ); WRITE_POD( &vga.changes.frame, vga.changes.frame ); WRITE_POD( &vga.changes.writeMask, vga.changes.writeMask ); WRITE_POD( &vga.changes.active, vga.changes.active ); WRITE_POD( &vga.changes.clearMask, vga.changes.clearMask ); WRITE_POD( &vga.changes.start, vga.changes.start ); WRITE_POD( &vga.changes.last, vga.changes.last ); WRITE_POD( &vga.changes.lastAddress, vga.changes.lastAddress ); #endif // - pure data WRITE_POD( &vga.lfb.page, vga.lfb.page ); WRITE_POD( &vga.lfb.addr, vga.lfb.addr ); WRITE_POD( &vga.lfb.mask, vga.lfb.mask ); // - static ptr //PageHandler *handler; // VGA_paradise.cpp / VGA_tseng.cpp / VGA_xga.cpp POD_Save_VGA_Paradise(stream); POD_Save_VGA_Tseng(stream); POD_Save_VGA_XGA(stream); } virtual void setBytes(std::istream& stream) { uint32_t tandy_drawbase_idx, tandy_membase_idx; //******************************** //******************************** SerializeGlobalPOD::setBytes(stream); // - pure data READ_POD( &vga.mode, vga.mode ); READ_POD( &vga.misc_output, vga.misc_output ); // VGA_Draw.cpp POD_Load_VGA_Draw(stream); // - pure struct data READ_POD( &vga.config, vga.config ); READ_POD( &vga.internal, vga.internal ); // VGA_Seq.cpp / VGA_Attr.cpp / (..) POD_Load_VGA_Seq(stream); POD_Load_VGA_Attr(stream); POD_Load_VGA_Crtc(stream); POD_Load_VGA_Gfx(stream); POD_Load_VGA_Dac(stream); // - pure data READ_POD( &vga.latch, vga.latch ); // VGA_S3.cpp POD_Load_VGA_S3(stream); // - pure struct data READ_POD( &vga.svga, vga.svga ); READ_POD( &vga.herc, vga.herc ); // - near-pure struct data READ_POD( &vga.tandy, vga.tandy ); // - reloc data READ_POD( &tandy_drawbase_idx, tandy_drawbase_idx ); READ_POD( &tandy_membase_idx, tandy_membase_idx ); // vga_other.cpp / vga_memory.cpp POD_Load_VGA_Other(stream); POD_Load_VGA_Memory(stream); // - pure data //READ_POD( &vga.vmemwrap, vga.vmemwrap ); // - static ptrs + 'new' data //uint8_t* fastmem; //uint8_t* fastmem_orgptr; // - 'new' data //READ_POD_SIZE( vga.fastmem_orgptr, sizeof(uint8_t) * ((vga.vmemsize << 1) + 4096 + 16) ); // - pure data (variable on S3 card) READ_POD( &vga.mem.memsize, vga.mem.memsize ); #ifdef VGA_KEEP_CHANGES // - static ptr //uint8_t* map; // - 'new' data READ_POD_SIZE( vga.changes.map, sizeof(uint8_t) * (VGA_MEMORY >> VGA_CHANGE_SHIFT) + 32 ); // - pure data READ_POD( &vga.changes.checkMask, vga.changes.checkMask ); READ_POD( &vga.changes.frame, vga.changes.frame ); READ_POD( &vga.changes.writeMask, vga.changes.writeMask ); READ_POD( &vga.changes.active, vga.changes.active ); READ_POD( &vga.changes.clearMask, vga.changes.clearMask ); READ_POD( &vga.changes.start, vga.changes.start ); READ_POD( &vga.changes.last, vga.changes.last ); READ_POD( &vga.changes.lastAddress, vga.changes.lastAddress ); #endif // - pure data READ_POD( &vga.lfb.page, vga.lfb.page ); READ_POD( &vga.lfb.addr, vga.lfb.addr ); READ_POD( &vga.lfb.mask, vga.lfb.mask ); // - static ptr //PageHandler *handler; // VGA_paradise.cpp / VGA_tseng.cpp / VGA_xga.cpp POD_Load_VGA_Paradise(stream); POD_Load_VGA_Tseng(stream); POD_Load_VGA_XGA(stream); //******************************** //******************************** if( tandy_drawbase_idx == 0xffffffff ) vga.tandy.draw_base = vga.mem.linear; else vga.tandy.draw_base = MemBase + tandy_drawbase_idx; if( tandy_membase_idx == 0xffffffff ) vga.tandy.mem_base = vga.mem.linear; else vga.tandy.mem_base = MemBase + tandy_membase_idx; } } dummy; }
36.490115
200
0.646876
mediaexplorer74
438b794f6cb9e99fad368b51b68d6fe50c5867cd
4,498
cpp
C++
src/plugins/map/plugin.cpp
osen/openradiant
47f0b65006e3e3325003f65cddbc7f1c78b5f138
[ "BSD-3-Clause" ]
11
2021-01-04T16:27:48.000Z
2022-01-22T00:37:31.000Z
src/plugins/map/plugin.cpp
osen/openradiant
47f0b65006e3e3325003f65cddbc7f1c78b5f138
[ "BSD-3-Clause" ]
6
2021-01-05T04:47:45.000Z
2021-11-30T09:25:11.000Z
src/plugins/map/plugin.cpp
osen/openradiant
47f0b65006e3e3325003f65cddbc7f1c78b5f138
[ "BSD-3-Clause" ]
1
2021-04-01T20:57:22.000Z
2021-04-01T20:57:22.000Z
/* Copyright (C) 1999-2007 id Software, Inc. and contributors. For a list of contributors, see the accompanying CONTRIBUTORS file. This file is part of GtkRadiant. GtkRadiant is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GtkRadiant 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 GtkRadiant; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "plugin.h" // ============================================================================= // Globals namespace map { // function tables _QERFuncTable_1 g_FuncTable; _QERScripLibTable g_ScripLibTable; _QERShadersTable g_ShadersTable; _QEREntityTable __ENTITYTABLENAME; _QERBrushTable g_BrushTable; _QERPatchTable g_PatchTable; _QERFileSystemTable g_FileSystemTable; /*! the map version we have been initialized with: Q1/Q2/Q3 we provide all three formats in the same module */ int g_MapVersion; // ============================================================================= // SYNAPSE CSynapseServer* g_pSynapseServer = NULL; CSynapseClientMap g_SynapseClient; static const XMLConfigEntry_t entries[] = { { SHADERS_MAJOR, SYN_REQUIRE, sizeof( g_ShadersTable ), &g_ShadersTable }, { NULL, SYN_UNKNOWN, 0, NULL } }; #if __GNUC__ >= 4 #pragma GCC visibility push(default) #endif CSynapseClient * EnumerateInterfaces( const char *version, CSynapseServer *pServer ) { #if __GNUC__ >= 4 #pragma GCC visibility pop #endif if ( strcmp( version, SYNAPSE_VERSION ) ) { Syn_Printf( "ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version ); return NULL; } g_pSynapseServer = pServer; g_pSynapseServer->IncRef(); Set_Syn_Printf( g_pSynapseServer->Get_Syn_Printf() ); g_SynapseClient.AddAPI( MAP_MAJOR, "mapq3", sizeof( _QERPlugMapTable ) ); g_SynapseClient.AddAPI( MAP_MAJOR, "maphl", sizeof( _QERPlugMapTable ) ); g_SynapseClient.AddAPI( MAP_MAJOR, "mapq2", sizeof( _QERPlugMapTable ) ); g_SynapseClient.AddAPI( RADIANT_MAJOR, NULL, sizeof( g_FuncTable ), SYN_REQUIRE, &g_FuncTable ); g_SynapseClient.AddAPI( SCRIPLIB_MAJOR, NULL, sizeof( g_ScripLibTable ), SYN_REQUIRE, &g_ScripLibTable ); // same trick as bobtoolz, see bug #828 g_SynapseClient.AddAPI( VFS_MAJOR, "*", sizeof( g_FileSystemTable ), SYN_REQUIRE, &g_FileSystemTable ); if ( !g_SynapseClient.ConfigXML( pServer, NULL, entries ) ) { return NULL; } g_SynapseClient.AddAPI( ENTITY_MAJOR, NULL, sizeof( __ENTITYTABLENAME ), SYN_REQUIRE, &__ENTITYTABLENAME ); g_SynapseClient.AddAPI( BRUSH_MAJOR, NULL, sizeof( g_BrushTable ), SYN_REQUIRE, &g_BrushTable ); g_SynapseClient.AddAPI( PATCH_MAJOR, NULL, sizeof( g_PatchTable ), SYN_REQUIRE, &g_PatchTable ); return &g_SynapseClient; } bool CSynapseClientMap::RequestAPI( APIDescriptor_t *pAPI ){ if ( !strcmp( pAPI->major_name, MAP_MAJOR ) ) { _QERPlugMapTable* pTable = static_cast<_QERPlugMapTable*>( pAPI->mpTable ); if ( !strcmp( pAPI->minor_name, "mapq3" ) ) { pTable->m_pfnMap_Read = &Map_ReadQ3; pTable->m_pfnMap_Write = &Map_WriteQ3; return true; } if ( !strcmp( pAPI->minor_name, "maphl" ) ) { pTable->m_pfnMap_Read = &Map_ReadHL; pTable->m_pfnMap_Write = &Map_WriteHL; mbMapHL = true; return true; } if ( !strcmp( pAPI->minor_name, "mapq2" ) ) { pTable->m_pfnMap_Read = &Map_ReadQ2; pTable->m_pfnMap_Write = &Map_WriteQ2; return true; } Syn_Printf( "ERROR: RequestAPI( Major: '%s' Minor: '%s' ) not found in '%s'\n", pAPI->major_name, pAPI->minor_name, GetInfo() ); return false; } Syn_Printf( "ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo() ); return false; } bool CSynapseClientMap::OnActivate() { return true; } const char* CSynapseClientMap::GetInfo(){ return "MAP format module built " __DATE__; } const char* CSynapseClientMap::GetName(){ return "map"; } } CSynapseClient* SYNAPSE_DLL_EXPORT map_EnumerateInterfaces(const char* version, CSynapseServer* pServer) { return map::EnumerateInterfaces(version, pServer); }
33.073529
130
0.714095
osen
438e1d3d425b8b6c961db3db7a1a633c067c5780
107
cpp
C++
docs/mfc/codesnippet/CPP/coledispatchdriver-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
14
2018-01-28T18:10:55.000Z
2021-11-16T13:21:18.000Z
docs/mfc/codesnippet/CPP/coledispatchdriver-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
null
null
null
docs/mfc/codesnippet/CPP/coledispatchdriver-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
2
2018-11-01T12:33:08.000Z
2021-11-16T13:21:19.000Z
void IMyComObject::SetString(DISPID dispid, LPCTSTR propVal) { SetProperty(dispid, VT_BSTR, propVal); }
26.75
60
0.766355
jmittert
438fc1a650a8ae6c233503a005fea5fdead5bdca
838
hh
C++
RecoDataProducts/inc/ExtMonFNALRawCluster.hh
michaelmackenzie/Offline
57bcd11d499af77ed0619deeddace51ed2b0b097
[ "Apache-2.0" ]
null
null
null
RecoDataProducts/inc/ExtMonFNALRawCluster.hh
michaelmackenzie/Offline
57bcd11d499af77ed0619deeddace51ed2b0b097
[ "Apache-2.0" ]
26
2019-11-08T09:56:55.000Z
2020-09-09T17:25:33.000Z
RecoDataProducts/inc/ExtMonFNALRawCluster.hh
ryuwd/Offline
92957f111425910274df61dbcbd2bad76885f993
[ "Apache-2.0" ]
null
null
null
// "Raw" pixel clusters are groups of adjacent hits. // // // Original author Andrei Gaponenko // #ifndef RecoDataProducts_ExtMonFNALRawCluster_hh #define RecoDataProducts_ExtMonFNALRawCluster_hh #include <ostream> #include "canvas/Persistency/Common/PtrVector.h" #include "Offline/RecoDataProducts/inc/ExtMonFNALRawHit.hh" namespace mu2e { class ExtMonFNALRawCluster { public: typedef art::PtrVector<ExtMonFNALRawHit> Hits; const Hits& hits() const { return hits_; } explicit ExtMonFNALRawCluster(const Hits& hits) : hits_(hits) {} // Default constructor for ROOT persistency ExtMonFNALRawCluster() : hits_() {} private: Hits hits_; }; std::ostream& operator<<(std::ostream& os, const ExtMonFNALRawCluster& c); } // namespace mu2e #endif /* RecoDataProducts_ExtMonFNALRawCluster_hh */
21.487179
76
0.73747
michaelmackenzie
439155803f776aff9ed957924626335410bba550
6,644
cc
C++
bpnn/bpnn.cc
ruoshuiwyl/Machine-Learning
22d835ae63a84855472f0f0de8b31a9ce637ba21
[ "Apache-2.0" ]
null
null
null
bpnn/bpnn.cc
ruoshuiwyl/Machine-Learning
22d835ae63a84855472f0f0de8b31a9ce637ba21
[ "Apache-2.0" ]
null
null
null
bpnn/bpnn.cc
ruoshuiwyl/Machine-Learning
22d835ae63a84855472f0f0de8b31a9ce637ba21
[ "Apache-2.0" ]
null
null
null
// // Created by ruoshui on 9/22/16. // #include <algorithm> #include <iostream> #include "bpnn.h" BackPropNNetwork::BackPropNNetwork(std::vector<int> &sizes, double eta, int max_iters, int batch_num) : sizes_(sizes), eta_(eta), max_iters_(max_iters), batch_num_(batch_num) { for (int i = 1; i < sizes.size(); ++i) { Matrix temp_matrix{sizes_[i], sizes_[i-1], 1.0}; global_weights_.push_back(temp_matrix); std::vector<double> biase; biase.resize(sizes_[i], 1.0); global_biases_.push_back(biase); delta_.push_back(biase); input_z_.push_back(biase); } for (int i = 0; i < sizes_.size(); ++i){ std::vector<double> t; t.resize(sizes_[i]); output_a_.push_back(t); } } void BackPropNNetwork::SingleTraining(const std::vector<double> &tarining_data, const std::vector<double> &training_result) { output_a_[0] = tarining_data; for ( int iter = 0; iter < max_iters_; ++iter) { FeedForward(); for ( int j = 0; j < training_result.size(); ++j){ double t = fabs(training_result[j] - output_a_[output_a_.size() - 1][j]); if ( t > 0.2){ std::cout << "error" << std::endl; } } std::vector<double> &activation = output_a_[sizes_.size() - 1]; ComputeCostDerivative(activation, training_result); for (int i = sizes_.size() - 3; i >= 0; i--) { ComputeDelta(i); } } } void BackPropNNetwork::ComputeCostDerivative(const std::vector<double> &activation, const std::vector<double> &taining_result) { int j = sizes_.size() - 2; for ( int i = 0; i < activation.size(); ++i) { delta_[j][i] = (activation[i] - taining_result[i] ) * sigmoid_prime(output_a_[j+1][i]); delta_biases_[j][i] += delta_[j][i]; } Matrix delta_weight{output_a_[j], delta_[j] }; delta_weight_[j].Add(delta_weight); } void BackPropNNetwork::ComputeDelta(const int &layer_num) { std::vector<double> &delta = delta_[layer_num]; std::vector<double> &delta_biases = delta_biases_[layer_num]; Matrix &weight = global_weights_[layer_num+1]; std::vector<double> &back_delta = delta_[layer_num+1]; weight.Dot(back_delta, delta); for (int i = 0; i < delta.size(); ++i){ delta[i] = delta[i] * sigmoid_prime(output_a_[layer_num][i]); delta_biases[i] += delta[i]; } Matrix delta_weight(output_a_[layer_num], delta); delta_weight_[layer_num].Add(delta_weight); } void BackPropNNetwork::ComputeSigmoid(const std::vector<double> &input, std::vector<double> &output) { for (int i = 0; i < input.size(); ++i ) { output[i] = sigmoid(input[i]); } } void BackPropNNetwork::FeedForward() { for (int i = 0; i < sizes_.size() - 1; ++i) { Matrix &weight = global_weights_[i]; std::vector<double> &biase = global_biases_[i]; std::vector<double> &z = input_z_[i]; std::vector<double> &output = output_a_[i+1]; std::vector<double> &a = output_a_[i]; ComputeOutput(weight, biase, z, a, output); } } void BackPropNNetwork::ComputeOutput(const Matrix &weight, const std::vector<double> biases, std::vector<double> &z, std::vector<double> &a, std::vector<double> &output) { weight.Dot(a, z); for ( int i = 0 ; i < biases.size(); ++i){ z[i] += biases[i]; } ComputeSigmoid(z, output); } void BackPropNNetwork::SetGobalWeightAndBiases() { for ( int i = 1; i < sizes_.size(); ++i) { Matrix temp_matrix{sizes_[i], sizes_[i - 1], 0.0}; delta_weight_.push_back(temp_matrix); std::vector<double> biase; biase.resize(sizes_[i], 0.0); delta_biases_.push_back(biase); } } void BackPropNNetwork::UpdetaGobalWeightAndBiases() { const double eta = eta_/batch_num_; for ( int i = 0; i < sizes_.size() - 1; ++i) { Matrix &weight = global_weights_[i]; Matrix &delta_weight = delta_weight_[i]; std::vector<double> &biases = global_biases_[i]; std::vector<double> &delta_biases = delta_biases_[i]; weight.Sub(eta, delta_weight); for ( int j = 0; j < biases.size(); ++j){ biases[j] -= eta * delta_biases[i]; } } } void BackPropNNetwork::BatchTraining(const std::vector<std::vector<double>> &batch_training_data, const std::vector<std::vector<double>> &batch_tarining_result) { SetGobalWeightAndBiases(); for ( int i = 0; i < batch_tarining_result.size(); ++i) { SingleTraining(batch_training_data[i], batch_tarining_result[i]); } UpdetaGobalWeightAndBiases(); } void BackPropNNetwork::Training(const std::vector<std::vector<double>> &training_data, const std::vector<std::vector<double>> &training_result) { std::vector<int> shuffle; for (int i = 0; i < training_data.size(); ++i) { shuffle.push_back(i); } std::random_shuffle(shuffle.begin(), shuffle.end()); std::vector<std::vector<double>> batch_data, batch_result; for (int i = 0; i < training_data.size(); i += batch_num_) { for (int j = 0; j < batch_num_; ++j) { batch_data.push_back(training_data[i + j]); batch_result.push_back(training_result[i + j]); } BatchTraining(batch_data, batch_result); } } double BackPropNNetwork::Test(const std::vector<std::vector<double>> &training_data, const std::vector<std::vector<double>> &training_result) { double total = training_data.size(); double error = 0.0; for ( int i = 0; i < training_data.size(); ++i) { output_a_[0] = training_data[i]; FeedForward(); bool error_flag = false; for ( int j = 0; j < training_result[i].size(); ++j){ double t = fabs(training_result[i][j] - output_a_[output_a_.size() - 1][j]); if (t > 0.1 ) { error_flag = true; } } error += error_flag ? 1.0 : 0.0; } return 1.0 - error / total; } int main() { std::vector<std::vector<double>> tarining_data{ {1.0, 1.0}, {1.0, 0.0}, {0.0, 1.0}, {0.0, 0.0}}; std::vector<std::vector<double>> tarining_result{{1.0}, {0.0}, {0.0}, {0.0}}; std::vector<int> sizes{2, 2, 1}; BackPropNNetwork bpp(sizes, 0.1, 40, 2); bpp.Training(tarining_data, tarining_result); std::cout << bpp.Test(tarining_data, tarining_result) << std::endl; return 0; }
36.505495
116
0.587748
ruoshuiwyl
439978ea5aab64eece3b54072e90ff01c90d04e0
27,564
cpp
C++
main.cpp
MrBlinky/ard-drivin
eef17d856f8b7bb982802b038333b7738691f647
[ "MIT" ]
null
null
null
main.cpp
MrBlinky/ard-drivin
eef17d856f8b7bb982802b038333b7738691f647
[ "MIT" ]
null
null
null
main.cpp
MrBlinky/ard-drivin
eef17d856f8b7bb982802b038333b7738691f647
[ "MIT" ]
null
null
null
/* Buttons example June 11, 2015 Copyright (C) 2015 David Martinez All rights reserved. This code is the most basic barebones code for showing how to use buttons in Arduboy. 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. */ #include "ArduboyRem.h" #include <ArduboyTones.h> #include "pics/playercar.h" #include "pics/playercar_bottom.h" #include "pics/skybox.h" #include "pics/enemycar_z1.h" #include "pics/enemycar_z2.h" #include "pics/enemycar_z3.h" #include "pics/enemycar_z4.h" #include "pics/playercar_tire2.h" #include "pics/puff_1.h" #include "pics/puff_2.h" #include "pics/puff_3.h" #include "pics/palm_1.h" #include "pics/palm_2.h" #include "pics/palm_3.h" #include "pics/title.h" #include "pics/instructions.h" #include "pics/big_1.h" #include "pics/big_2.h" #include "pics/big_3.h" #include "pics/big_go.h" // Make an instance of arduboy used for many functions ArduboyRem arduboy; ArduboyTones sound(arduboy.audio.enabled); void drawOutrunTrack(); // Variables for your game go here. byte fps = 0; byte fpscount = 0; uint16_t lastMilli = 0; byte hflip; byte gear; byte gameTimer; byte speed; byte score; uint16_t speedAcc; int16_t playerX; int16_t playerY; int16_t currentRoadCurve; int16_t desiredRoadCurve; int16_t nextRoadCurveChange; int16_t backgroundXOffset; int8_t trackCenteredX; int8_t puffX; int8_t puffY; int8_t puffFrame; int16_t enemyX; uint16_t enemyYAcc; byte enemySpeed; // Maximum number of simultaneously tree/road-side object #define MAX_TREE 8 // Y position of palm trees uint16_t palmYAcc[MAX_TREE]; // State of the object: 0=none, 1=left palm tree, 2=right palm tree, etc. byte palmState[MAX_TREE]; // Counter to determine when the next palm tree should appear uint16_t nextPalm; byte trackPixWidth[44]; int16_t trackStartX[44]; // Perpective lookup table: for any y value (0..255), remap it to a perpective y value for our road (20..63) const byte PROGMEM yLookup[256] = { 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 37, 37, 37, 37, 38, 38, 38, 38, 39, 39, 39, 40, 40, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44, 45, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 55, 55, 56, 57, 58, 58, 59, 60, 61, 62, 62, 63, }; const PROGMEM byte* const PROGMEM puffBitmaps[] = { puff_1, puff_2, puff_3 }; enum class EState : byte { Title, Instructions, Game, GameOver, } currentState = EState::Title; uint16_t stateFrame; // This function runs once in your game. // use it for anything that needs to be set only once in your game. void setup() { //initiate arduboy instance //arduboy.begin(); // Exanded 'begin()' in order to skip logo arduboy.boot(); // raw hardware arduboy.blank(); // blank the display arduboy.flashlight(); // light the RGB LED and screen if UP button is being held. arduboy.systemButtons(); // check for and handle buttons held during start up for system control arduboy.audio.begin(); arduboy.audio.on(); arduboy.setFrameRate(1000000 / 67); // At 67 fps, each frame takes 14925 microseconds // At 16 Mhz, we have about 238805 clock cycles per frame, i.e.: 16 clock cycle per microsecond // We draw 44 lines of road: // drawFastHline can be called up to 220 times per frame to draw to road, so any clock cycle in that function cost 14 us (!!) // During the paint, the loop could have up to 128 times per line, so cost 352 us per clock cycle in the draw loop (!!) // For example: it takes 8 clock/pixel, so about 2816 us for the draw part // First, optimise drawChar (because extremely slow!) // First optim: removing size: prints take 3438 micros // Second optim: removing transparent: prints take 3290 micros // 3rd optim: removing color support: prints take 3110 micros // 4th optim: force full byte alignment: prints take 670 micros // Removed clear screen, should not be needed if we repaint the screen anyway. It is very fast at 188 us. // Copy to oled buffer takes 1816us.. slow! We have a lot of 'free cycles' during this operation because it needs to wait for the // SPI display acknowledgement after each byte // drawBitmap is very slow when not aligned on a full byte // Currently: 7532 idle, 1816 drawscreen, 4746 render stuff, 678 print debug // Currently, before drawHLine optimization: 6330 render stuff // Nov 13 2016, current state, with full optimize O3 in ArduboyCoreRem.h: // free time = 1100 us // copy oled = 1360 us // render game = 11700 us // print text = 844 us // total: 15004 us // Sketch uses 9,880 bytes (34%) of program storage space. Maximum is 28,672 bytes. // Global variables use 1, 360 bytes(53 % ) of dynamic memory, leaving 1, 200 bytes for local variables.Maximum is 2, 560 bytes. // With optimize Os, we save 222 bytes of rom, 8 bytes of ram, but lose almost 2000 us in rendering speed! // DONE: drawFastHLine: use uint8 internally (after clipping) for faster loop, free time = 1330 us, saved about 230 us // DONE: drawFastHLine optimized more:free time = 1440 us // DONE: after yMask[] in MaskBitmap, render: 10160, free time = 2544 us (!!) Suspicious, gain is way too high.. Maybe because a register was freed? // current render game = 10160 us // with sourceMask = ~(pgm_read_byte(sourceAddress++) * yOffset); 9980 us // with pgm_read_byte_and_increment: 9064 us! Mega performance boost using lpm Z+ // DONE: After intense optimization to DrawMaskBitmap: New speed: 9060 us for render, currently 32 clocks per byte // TODO: idea: align screen buffer on a 256 bytes-address, so we can use only high-byte for quicker compare // TODO: support hflip for drawMaskedBitmap // TODO: integrate maskedbitmap size in the data itself // TODO: add support for sprite hotspot // TODO: ask LouisP to always trim bitmap perfectly flush (i.e.: no waste around) // TODO: ..which implies support non-multiple of 8 in Processing and auto-pad with transparent // TODO: optimize DrawOpaque (and drawMask?) when perfectly y-aligned on 8 pixels // TODO: draw scrolling city background // TODO: print score info at top of screen // TODO: sound and music, is it possible to integrate them into the screen copy feature? // TODO: Use Optimize O3 only in specific section: see performance vs rom space compromise // TODO: Road curve support // TODO: Road hill support? // TODO: Support inverted text (black, on white background)? } inline void AddWithClamp(int16_t& ioBaseNumber, int16_t inAddValue) { if (inAddValue > 0 && ioBaseNumber > 32767 - inAddValue) { ioBaseNumber = 32767; return; } if (inAddValue < 0 && ioBaseNumber < -32768 - inAddValue) { ioBaseNumber = -32768; return; } ioBaseNumber += inAddValue; } void UpdatePalm() { if (gameTimer > 99) return; if (nextPalm < speed) { // Spawn a new tree by checking the first available slot for (byte i = 0; i < MAX_TREE; i++) { if (palmState[i] == 0) { palmState[i] = random(2) + 1; palmYAcc[i] = 0; nextPalm = 100 + random(1400); break; } } } else { nextPalm -= speed; } for (byte i = 0; i < MAX_TREE; i++) { if (palmState[i] == 0) continue; // Make tree move according to player current speed palmYAcc[i] += speed; // Check if tree would go off the bottom of the screen: if so, free its slot uint16_t tempy = (palmYAcc[i] >> 3); if (tempy > 255) { palmState[i] = 0; continue; } // Calculate perspective y using lookup table byte palmy = pgm_read_byte(yLookup + byte(tempy)); // Determine which sprite scale, depending on hard-coded y values: const byte* whichSprite2 = palmy > 43 ? palm_1 : palmy > 32 ? palm_2 : palm_3; // Draw test palm tree on side of the road, left or right: int16_t palmx = trackStartX[palmy - 20]; if (palmState[i] == 1) { palmx -= 8; if (palmx >= 0) { arduboy.drawMaskBitmap(palmx, palmy, whichSprite2, false); } } else { palmx += 8 + (trackPixWidth[palmy - 20] << 1); if (palmx <= 136) { arduboy.drawMaskBitmap(palmx, palmy, whichSprite2, true); } } } } // 'x' position is based on a referencial of track line 41 (41+20 = 61, which is player 'y' position) int8_t GetScreenXPos(int8_t inX, int8_t inY) { return (inX * trackPixWidth[inY - 20] / trackPixWidth[41]) + trackPixWidth[inY - 20] + trackStartX[inY - 20]; } void UpdateEnemy() { // Make enemy move according to player current speed and its own speed // divide by a factor to make enemy slightly 'glue' to player speed, or else it is too frantic enemyYAcc += (speed - enemySpeed) >> 2; // Check if enemy would go off the bottom of the screen: if so, spawn a new one uint16_t tempy = (enemyYAcc >> 3); if (tempy > 255) { // Don't spawn enemies during the start countdown if (gameTimer > 99) { return; } enemySpeed = random(40) + 130; // If player is faster than enemy, spawn a new enemy ahead if (speed > enemySpeed) { enemyYAcc = 0; enemyX = random(65535) - 32768; score++; } else { // If player is slower, then spawn enemy behind enemyYAcc = 255 << 3; // Enemy spawning behind should never crash into the player: they avoid left or right enemyX = playerX + 10240 + random(50175); } return; } byte ey = pgm_read_byte(yLookup + byte(tempy)); int8_t ex = GetScreenXPos(enemyX >> 8, ey); // Draw enemy car const byte* whichSprite = ey > 48 ? enemycar_z1 : ey > 37 ? enemycar_z2 : ey > 29 ? enemycar_z3 : enemycar_z4; byte hflip = 0; if (currentRoadCurve < -2000 || ex > 64) { hflip = 1; } arduboy.drawMaskBitmap(ex, ey, whichSprite, hflip); // Detect collision with player: int8_t dx = (playerX - enemyX) >> 8; int8_t dy = (playerY >> 8) - ey; // Collision! Bring player speed equal to the enemy if (dx > -40 && dx < 40 && dy > -8 && dy < 8) { speed = enemySpeed - 20; playerX += dx << 6; enemyX -= dx << 6; } } void SetState(EState inState) { currentState = inState; stateFrame = 0; // Initialization when going to 'Game' state: if (currentState == EState::Game) { gameTimer = 104; // 102 = 3!, 101 = 2!, 100 = 1!, 99 = GO! ... gear = 0; hflip = 0; speed = 0; score = 0; speedAcc = 0; playerX = 0 << 8; playerY = 61 << 8; currentRoadCurve = 0 << 8; desiredRoadCurve = 0 << 8; nextRoadCurveChange = 0; backgroundXOffset = 0 << 8; trackCenteredX = 0; puffX = 0; puffY = 0; puffFrame = -1; enemyX = 0; enemyYAcc = 9999; } } void TitleState() { arduboy.drawMaskBitmap(0, 0, title); if (stateFrame > 120) { arduboy.setCursor(104, 0); arduboy.print("Sfx"); arduboy.drawChar(122, 0, arduboy.audio.enabled() ? '@' : ' '); } if (stateFrame > 300) { if (stateFrame < 500 || (stateFrame & 64) == 0) { arduboy.setCursor(4, 56); arduboy.print(" > Push A to start < "); } // Auto-switch to game after a delay, but instantly gameover by setting timer to 0 if (stateFrame > 900) { SetState(EState::Game); speed = 220; gear = 1; gameTimer = 0; } } if (arduboy.justPressed(A_BUTTON)) { SetState(EState::Instructions); } if (arduboy.justPressed(B_BUTTON)) { if (arduboy.audio.enabled()) { arduboy.audio.off(); } else { arduboy.audio.on(); } } } void InstructionsState() { arduboy.drawMaskBitmap(0, 0, instructions); if (arduboy.justPressed(A_BUTTON) || stateFrame > 900) { SetState(EState::Game); } } void DrawCountdown() { const byte* whichSprite = nullptr; switch (gameTimer) { case 102: whichSprite = big_3; break; case 101: whichSprite = big_2; break; case 100: whichSprite = big_1; break; case 99: case 98: whichSprite = big_go; break; } if (whichSprite) { arduboy.drawMaskBitmap(64, 23, whichSprite); } } void DrawHud() { arduboy.drawByte(0, 0, 0xFF); arduboy.drawByte(1, 0, 0x81); // Convert speed (0..220) to a speedmeter range of 0..33 byte speedometer = (speed * 39) >> 8; if (speedometer > 0 && arduboy.flicker & 2) { speedometer--; } for (byte i = 0; i < speedometer; i++) { arduboy.drawByte(i + 2, 0, 0xBD); } for (byte i = speedometer; i < 33; i++) { arduboy.drawByte(i + 2, 0, 0x81); } arduboy.drawByte(35, 0, 0x81); for (byte i = 36; i <= 56; i++) { arduboy.drawByte(i, 0, 0xFF); } for (byte i = 69; i <= 115; i++) { arduboy.drawByte(i, 0, 0xFF); } //for (byte i = 0; i < 128; i++) { // arduboy.drawByte(i, 0, 0xFF); //} if (gameTimer <= 99) { arduboy.printBytePadded(57, 0, gameTimer); } byte flickerGear = arduboy.flicker & 4; // arduboy.flicker the currently selected gear if ((gear == 1) || flickerGear) { arduboy.drawChar(81, 0, 'L'); } if ((gear == 0) || flickerGear) { arduboy.drawChar(93, 0, 'H'); } if (gear == 0) { // Blink the arrow when running fast in low gear (indicating it is time to switch in high gear) if (speed > 120 && flickerGear) { arduboy.drawChar(87, 0, '>'); } } else { // Blink the arrow when running too slow in high gear (accelerate would be better in low gear) if (speed < 120 && flickerGear) { arduboy.drawChar(87, 0, '<'); } } arduboy.printBytePadded(116, 0, score); if (gameTimer == 0) { arduboy.setCursor(31, 32); arduboy.print(" Game over "); // If going into the 'game over' part of this game state: if (currentState == EState::Game) { currentState = EState::GameOver; stateFrame = 0; } else if (stateFrame > 300) { SetState(EState::Title); } } } void GameState() { // the next couple of lines will deal with checking if the D-pad buttons // are pressed and move our text accordingly. // We check to make sure that x and y stay within a range that keeps the // text on the screen. // if the right button is pressed move 1 pixel to the right every frame constexpr uint16_t baseSpeed = 400; constexpr uint16_t topSpeed = 900; constexpr byte speedMultiplier = 5; uint16_t moveSpeed = speed >= byte((topSpeed - baseSpeed) / speedMultiplier) ? topSpeed : (speed * speedMultiplier) + baseSpeed; int16_t playerXMovement = 0; bool isMovingSide = false; byte buttons = arduboy.buttonsState(); // Prevent any button pressed when game over if (gameTimer == 0) { buttons = 0; } if ((buttons & RIGHT_BUTTON) && playerX <= int16_t(32767 - moveSpeed)) { hflip = 0; isMovingSide = true; //x++; playerXMovement = moveSpeed; } // if the left button is pressed move 1 pixel to the left every frame if ((buttons & LEFT_BUTTON) && playerX >= (-32768 + moveSpeed)) { hflip = 1; isMovingSide = true; playerXMovement = -moveSpeed; } // Moving up/down is enabled only when race starts if (gameTimer <= 99) { // if the up button is pressed, move up if (((buttons & UP_BUTTON)) && playerY > 13568) { playerY -= 128; } // if the down button is pressed, move down if (((buttons & DOWN_BUTTON)) && playerY < 16128) { playerY += 128; } } if ((buttons & B_BUTTON) && arduboy.justPressed(B_BUTTON)) { gear = !gear; } // Hold A to accelerate, release to auto-brake if ((buttons & A_BUTTON)) { if (gear == 0) { if (speed < 140) { // Top speed in low gear: speed++; } } else { if (speed < 120) { // If running a low speed but in high gear, make it ineffective if ((arduboy.flicker & 3) == 0) { speed++; } } else if (speed < 220) { // Top speed in high gear: speed++; } } } else if (speed > 0) { if (speed >= 2) { speed -= 2; } else { speed = 0; } } int8_t roadCurve8 = currentRoadCurve >> 8; // During initial countdown, don't really move the track: We consider the car to be in neutral and just revving if (gameTimer <= 99) { // Engine compression brake if running high speed in low gear: if (gear == 0 && speed > 140) { speed -= 2; } int8_t x = playerX >> 8; int8_t y = playerY >> 8; // Brake if running off-road (i.e.: left-side or right-side of the road if (speed > 50 && (x <= -127 || x >= 126)) { speed = 50; } // Make road curve 'push' player to outside of the track, according to its speed: // with >> 3, it is a bit easy, with >> 2 too hard playerXMovement -= (roadCurve8 * speed) >> 3; //playerXMovement -= (currentRoadCurve * (int16_t)speed) >> 10; AddWithClamp(playerX, playerXMovement); // And also make it move the skybox background backgroundXOffset -= (roadCurve8 * speed) >> 3; // Determine next road curve nextRoadCurveChange -= speed; if (nextRoadCurveChange <= 0) { nextRoadCurveChange = random(32767); desiredRoadCurve = random(25600) - 12800; } byte speedMult = 3; int16_t curveSpeedChange = (speed * speedMult) >> 1; // Comment this block to disable curves: if (currentRoadCurve + curveSpeedChange < desiredRoadCurve) { currentRoadCurve += curveSpeedChange; } else if (currentRoadCurve - curveSpeedChange > desiredRoadCurve) { currentRoadCurve -= curveSpeedChange; } } // With nothing, idle 11888 // with clear: 11700 cost 188 us // with drawBitmap: 7128 cost 4760 us // drawtrack: 8356 cost 3532 us // clear+draw = 6950 cost 4938 us // clear+drawtrack = 8188 cost 3700 us // clear+bitmap+track = 3068 cost 8820 us // we clear our screen to black: useless if we repaint everything! // No need to clear, since 'paintScreen' does it for free. // arduboy.clear(); drawOutrunTrack(); //arduboy.drawTurboBitmap(x - 24, y - 24, pgm_read_ptr(mypics + (arduboy.flicker & 1)), 85, 64); //arduboy.drawGrayBitmap(x - 24, y - 24, outrun, 82, 40); //for (byte i = 0; i < 6; ++i) { // arduboy.drawMaskBitmap(i, i + 8, outrun); //} //arduboy.drawMaskBitmap(-127, -127, outrun, hflip); arduboy.drawMaskBitmap((backgroundXOffset >> 8), 8, skybox, false); arduboy.drawMaskBitmap((backgroundXOffset >> 8) + 128, 8, skybox, false); UpdatePalm(); UpdateEnemy(); // Draw player car int8_t py = playerY >> 8; int8_t px = GetScreenXPos(playerX >> 8, py); arduboy.drawMaskBitmap(px, py, playercar_bottom, hflip); // Make tire animate according to current accumulator if (gameTimer <= 99) { int8_t tireOverlay = (speedAcc & 256) ? -17 : 13; arduboy.drawMaskBitmap(px + tireOverlay, py, playercar_tire2); } int8_t carBobOffset = (speedAcc & 512) ? -6 : -5; arduboy.drawMaskBitmap(px, py + carBobOffset, playercar, hflip); // If puff is off and player is moving left/right and speed is high enough and we are in a steep curve, then emit a puff if (puffFrame == -1 && isMovingSide && speed > 100 && (roadCurve8 > 15 || roadCurve8 < -15)) { puffFrame = 0; puffX = px - 16; puffY = py - 1; } // If puff is currently active: make it animate then die if (puffFrame != -1) { arduboy.drawMaskBitmap(puffX, puffY, (const byte*)pgm_read_ptr(puffBitmaps + (puffFrame >> 4)), 0); arduboy.drawMaskBitmap(puffX + 34, puffY, (const byte*)pgm_read_ptr(puffBitmaps + (puffFrame >> 4)), 1); puffFrame += 8; if (puffFrame >= (3 << 4)) { puffFrame = -1; } } //arduboy.drawFastHLine(10, 5, 100, arduboy.flicker & 1); //arduboy.drawFastHLine(10, 6, 100, 1); // we set our cursor x pixels to the right and y down from the top // arduboy.setCursor(x, y); //// pixel 0 is always full black //for (byte i = 1; i < 32; ++i) { // if (arduboy.flicker % (63 / i) == 0) { // arduboy.drawFastHLine(80, i, 38, 1); // } // else { // arduboy.drawFastHLine(80, 63 - i, 38, 1); // } //} //// pixel 63 is always full white //arduboy.drawFastHLine(127, 63, 38, 1); // then we print to screen what is stored in our title variable we declared earlier //arduboy.print((__FlashStringHelper*)title); DrawHud(); DrawCountdown(); //arduboy.setCursor(0, 0); //arduboy.print(x); //arduboy.setCursor(30, 0); //arduboy.print(y); //arduboy.setCursor(60, 0); //arduboy.print(speed); //arduboy.setCursor(90, 0); //arduboy.print(fps); //uint16_t endMicros = micros(); //arduboy.setCursor(90, 8); //arduboy.print(afterWaitMicros - startMicros); //arduboy.setCursor(90, 16); //arduboy.print(afterDisplay - afterWaitMicros); //arduboy.setCursor(90, 24); //arduboy.print(endMicros - afterDisplay); //arduboy.setCursor(90, 32); //// Special case for this profile: use a 'static' to print the time of the previous frame because we want to also include this print itself //static uint16_t previousFrameAfterPrintDelta = 0; //arduboy.print(previousFrameAfterPrintDelta); //previousFrameAfterPrintDelta = micros() - endMicros; // Only play sound during actual play, not while gameover: if (currentState == EState::Game) { if ((arduboy.flicker & 1) == 0) { uint16_t freq = 16 + (speed >> 1); if (puffFrame != -1 && (arduboy.flicker & 2) == 0) { freq = 800; } sound.tone(freq, 50); //else { // sound.tone(16 + (enemySpeed >> 1), 30); //} } } } void drawOutrunTrack() { uint16_t trackWidth = 1 << 7; //uint16_t trackIncrement = 128 + (y << 4); uint16_t trackIncrement = 128 + (47 << 4); int16_t trackCenter = 64 << 4; uint16_t roadLineAcc = 0; if (gameTimer <= 99) { speedAcc += speed; } roadLineAcc = 8192 - (speedAcc << 6); int16_t roadCurve = (currentRoadCurve >> 1); trackCenter += roadCurve >> 2; //byte yMult = 139; //int8_t roadCurveInc = ((currentRoadCurve >> 8) * yMult) >> 8; int8_t roadCurveInc = currentRoadCurve / 118; int8_t newCenteredX = (playerX >> 10); if (trackCenteredX < newCenteredX && trackCenteredX < 45) { trackCenteredX++; } else if (trackCenteredX > newCenteredX && trackCenteredX > -45) { trackCenteredX--; } //byte xMult = 120; //int8_t xViewShift = (trackCenteredX * xMult + 128) >> 8; for (byte i = 20; i < 64; ++i) { //arduboy.drawFastHLine(0, i, 127, 1); byte pixWidth = trackWidth >> 8; trackPixWidth[i - 20] = pixWidth; int16_t startx = (trackCenter - (int16_t)(trackWidth >> 4)) >> 4; trackStartX[i - 20] = startx; byte sideline = (pixWidth >> 4) + 1; byte road = pixWidth - ((sideline * 3 + 1) >> 1); // using this if, we skip drawing completely if the HLine would be color 2 (gray), since the screen is pre-filled with gray if (roadLineAcc & 16384) { arduboy.drawFastHLine(0, i, startx, 1); } arduboy.drawFastHLine(startx, i, sideline, roadLineAcc & 8192 ? 1 : 0); startx += sideline; //arduboy.drawFastHLine(startx, i, road, 2); startx += road; if (roadLineAcc & 16384) { arduboy.drawFastHLine(startx, i, sideline, 1); } startx += sideline; //arduboy.drawFastHLine(startx, i, road, 2); startx += road; arduboy.drawFastHLine(startx, i, sideline, roadLineAcc & 8192 ? 1 : 0); startx += sideline; if (roadLineAcc & 16384) { arduboy.drawFastHLine(startx, i, 256, 1); } //roadLineAcc += (45184 - trackWidth) >> 3; roadLineAcc += uint16_t(60000) / byte(6 + (trackWidth >> 9)); trackWidth += trackIncrement; trackCenter -= trackCenteredX + ((-roadCurveInc + (roadCurve >> 4)) >> 2); roadCurve -= roadCurveInc; } // perspective: // at horizon (20), track width should be 4 // at bottom (63), track width should be 220 //uint16_t trackWidth = 4 << 7; //uint16_t trackIncrement = 128; //int16_t trackCenter = 64 << 4; //static uint16_t stripOffset = 6912; //uint16_t stripSize = (stripOffset + (24000 / y) * (y - 32)) & 8191; //byte alternateStrip = 0; //arduboy.setCursor(90, 40); //arduboy.print(stripOffset); //static uint16_t speed = 0; ///* //a y=26, strip 1280 (938 par y) //a y=30, strip 5120 (896 par y) //a y=32, strip 6912 reference //a y=34, strip 256 (768 par y) //a y=36, strip 1280 (640 par y) //a y=40, strip 3584 (608 par y) //*/ //if (arduboy.pressed(A_BUTTON)) { // speed--; //} //if (arduboy.pressed(B_BUTTON)) { // speed++; //} //stripOffset += speed; //stripOffset = stripOffset & 8191; //for (byte i = 20; i < 64; ++i) { // uint16_t pixWidth = trackWidth >> 7; // //arduboy.drawFastHLine((trackCenter >> 4) - (pixWidth >> 1), i, pixWidth, 1); // uint16_t startx = (trackCenter >> 4) - (pixWidth >> 1); // uint16_t sideline = (pixWidth >> 4) + 1; // uint16_t road = (pixWidth - sideline * 3) >> 1; // arduboy.drawFastHLine(startx, i, sideline, 1); // startx += sideline; // arduboy.drawFastHLine(startx, i, road, 0); // startx += road; // if (alternateStrip) { // arduboy.drawFastHLine(startx, i, sideline, 1); // } // startx += sideline; // arduboy.drawFastHLine(startx, i, road, 0); // startx += road; // arduboy.drawFastHLine(startx, i, sideline, 1); // trackWidth += trackIncrement; // trackIncrement += (y); // trackCenter += (x - 64); // stripSize += 2048; // if (stripSize > trackWidth) { // alternateStrip ^= 1; // stripSize -= trackWidth; // } //} } // our main game loop, this runs once every cycle/frame. // this is where our game logic goes. void loop() { // uint16_t startMicros = micros(); // pause render until it's time for the next frame arduboy.nextFrame(); // uint16_t afterWaitMicros = micros(); //arduboy.LCDCommandMode(); //SPI.transfer(0xAE); //SPI.transfer(0xAF); //arduboy.LCDDataMode(); // then we finaly we tell the arduboy to display what we just wrote to the display. // Note: the display() function now also clears the ram buffer with a gray-flickering pattern while copying it to the display arduboy.display(); // fill display buffer with pattern, added because not using ArduboyRem uint16_t pattern = 0xAA55; if (arduboy.flicker & 1) pattern = ~pattern; for (uint16_t i=0; i < (WIDTH * HEIGHT / 8);) { arduboy.sBuffer[i++] = pattern & 0xFF; arduboy.sBuffer[i++] = pattern >> 8; } arduboy.pollButtons(); // uint16_t afterDisplay = micros(); fpscount++; uint16_t currentMilli = millis(); if (currentMilli - lastMilli >= 1000) { lastMilli += 1000; fps = fpscount; fpscount = 0; if (gameTimer > 0) { gameTimer--; } } stateFrame++; switch (currentState) { case EState::Title: TitleState(); break; case EState::Instructions: InstructionsState(); break; case EState::Game: case EState::GameOver: GameState(); break; } }
31.429875
1,064
0.638333
MrBlinky
439ae0eb804f8d50081015165e6f2eca28df520f
7,925
cpp
C++
src/slave/containerizer/mesos/provisioner/appc/store.cpp
yisun99/yisun
0bef3cdd0de61d4c5e10e1f995caffbaff0c6856
[ "Apache-2.0" ]
null
null
null
src/slave/containerizer/mesos/provisioner/appc/store.cpp
yisun99/yisun
0bef3cdd0de61d4c5e10e1f995caffbaff0c6856
[ "Apache-2.0" ]
null
null
null
src/slave/containerizer/mesos/provisioner/appc/store.cpp
yisun99/yisun
0bef3cdd0de61d4c5e10e1f995caffbaff0c6856
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <list> #include <glog/logging.h> #include <process/defer.hpp> #include <process/dispatch.hpp> #include <stout/check.hpp> #include <stout/hashmap.hpp> #include <stout/os.hpp> #include <stout/path.hpp> #include "slave/containerizer/mesos/provisioner/appc/paths.hpp" #include "slave/containerizer/mesos/provisioner/appc/spec.hpp" #include "slave/containerizer/mesos/provisioner/appc/store.hpp" using namespace process; using std::list; using std::string; using std::vector; namespace mesos { namespace internal { namespace slave { namespace appc { // Defines a locally cached image (which has passed validation). struct CachedImage { static Try<CachedImage> create(const string& imagePath); CachedImage( const AppcImageManifest& _manifest, const string& _id, const string& _path) : manifest(_manifest), id(_id), path(_path) {} string rootfs() const { return path::join(path, "rootfs"); } const AppcImageManifest manifest; // Image ID of the format "sha512-value" where "value" is the hex // encoded string of the sha512 digest of the uncompressed tar file // of the image. const string id; // Absolute path to the extracted image. const string path; }; Try<CachedImage> CachedImage::create(const string& imagePath) { Option<Error> error = spec::validateLayout(imagePath); if (error.isSome()) { return Error("Invalid image layout: " + error.get().message); } string imageId = Path(imagePath).basename(); error = spec::validateImageID(imageId); if (error.isSome()) { return Error("Invalid image ID: " + error.get().message); } Try<string> read = os::read(paths::getImageManifestPath(imagePath)); if (read.isError()) { return Error("Failed to read manifest: " + read.error()); } Try<AppcImageManifest> manifest = spec::parse(read.get()); if (manifest.isError()) { return Error("Failed to parse manifest: " + manifest.error()); } return CachedImage(manifest.get(), imageId, imagePath); } // Helper that implements this: // https://github.com/appc/spec/blob/master/spec/aci.md#dependency-matching static bool matches(Image::Appc requirements, const CachedImage& candidate) { // The name must match. if (candidate.manifest.name() != requirements.name()) { return false; } // If an id is specified the candidate must match. if (requirements.has_id() && (candidate.id != requirements.id())) { return false; } // Extract labels for easier comparison, this also weeds out duplicates. // TODO(xujyan): Detect duplicate labels in image manifest validation // and Image::Appc validation. hashmap<string, string> requiredLabels; foreach (const Label& label, requirements.labels().labels()) { requiredLabels[label.key()] = label.value(); } hashmap<string, string> candidateLabels; foreach (const AppcImageManifest::Label& label, candidate.manifest.labels()) { candidateLabels[label.name()] = label.value(); } // Any label specified must be present and match in the candidate. foreachpair (const string& name, const string& value, requiredLabels) { if (!candidateLabels.contains(name) || candidateLabels.get(name).get() != value) { return false; } } return true; } class StoreProcess : public Process<StoreProcess> { public: StoreProcess(const string& rootDir); ~StoreProcess() {} Future<Nothing> recover(); Future<vector<string>> get(const Image& image); private: // Absolute path to the root directory of the store as defined by // --appc_store_dir. const string rootDir; // Mappings: name -> id -> image. hashmap<string, hashmap<string, CachedImage>> images; }; Try<Owned<slave::Store>> Store::create(const Flags& flags) { Try<Nothing> mkdir = os::mkdir(paths::getImagesDir(flags.appc_store_dir)); if (mkdir.isError()) { return Error("Failed to create the images directory: " + mkdir.error()); } // Make sure the root path is canonical so all image paths derived // from it are canonical too. Result<string> rootDir = os::realpath(flags.appc_store_dir); if (!rootDir.isSome()) { // The above mkdir call recursively creates the store directory // if necessary so it cannot be None here. CHECK_ERROR(rootDir); return Error( "Failed to get the realpath of the store root directory: " + rootDir.error()); } return Owned<slave::Store>(new Store( Owned<StoreProcess>(new StoreProcess(rootDir.get())))); } Store::Store(Owned<StoreProcess> _process) : process(_process) { spawn(CHECK_NOTNULL(process.get())); } Store::~Store() { terminate(process.get()); wait(process.get()); } Future<Nothing> Store::recover() { return dispatch(process.get(), &StoreProcess::recover); } Future<vector<string>> Store::get(const Image& image) { return dispatch(process.get(), &StoreProcess::get, image); } StoreProcess::StoreProcess(const string& _rootDir) : rootDir(_rootDir) {} Future<Nothing> StoreProcess::recover() { // Recover everything in the store. Try<list<string>> imageIds = os::ls(paths::getImagesDir(rootDir)); if (imageIds.isError()) { return Failure( "Failed to list images under '" + paths::getImagesDir(rootDir) + "': " + imageIds.error()); } foreach (const string& imageId, imageIds.get()) { string path = paths::getImagePath(rootDir, imageId); if (!os::stat::isdir(path)) { LOG(WARNING) << "Unexpected entry in storage: " << imageId; continue; } Try<CachedImage> image = CachedImage::create(path); if (image.isError()) { LOG(WARNING) << "Unexpected entry in storage: " << image.error(); continue; } LOG(INFO) << "Restored image '" << image.get().manifest.name() << "'"; images[image.get().manifest.name()].put(image.get().id, image.get()); } return Nothing(); } Future<vector<string>> StoreProcess::get(const Image& image) { if (image.type() != Image::APPC) { return Failure("Not an Appc image: " + stringify(image.type())); } const Image::Appc& appc = image.appc(); if (!images.contains(appc.name())) { return Failure("No Appc image named '" + appc.name() + "' can be found"); } // Get local candidates. vector<CachedImage> candidates; foreach (const CachedImage& candidate, images[appc.name()].values()) { // The first match is returned. // TODO(xujyan): Some tie-breaking rules are necessary. if (matches(appc, candidate)) { LOG(INFO) << "Found match for Appc image '" << appc.name() << "' in the store"; // The Appc store current doesn't support dependencies and this // is enforced by manifest validation: if the image's manifest // contains dependencies it would fail the validation and // wouldn't be stored in the store. return vector<string>({candidate.rootfs()}); } } return Failure("No Appc image named '" + appc.name() + "' can match the requirements"); } } // namespace appc { } // namespace slave { } // namespace internal { } // namespace mesos {
27.61324
77
0.678738
yisun99
439da1bc1b5bf79319b4896c69518f39bba2a09f
744
cxx
C++
Software/CPU/myscrypt/build/cmake-3.12.3/Source/cmDocumentationSection.cxx
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
107
2021-08-28T20:08:42.000Z
2022-03-22T08:02:16.000Z
Software/CPU/myscrypt/build/cmake-3.12.3/Source/cmDocumentationSection.cxx
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
2
2022-01-13T04:03:55.000Z
2022-03-12T01:02:31.000Z
Software/CPU/myscrypt/build/cmake-3.12.3/Source/cmDocumentationSection.cxx
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
16
2021-08-30T06:57:36.000Z
2022-03-22T08:05:52.000Z
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmDocumentationSection.h" void cmDocumentationSection::Append(const char* data[][2]) { int i = 0; while (data[i][1]) { this->Entries.emplace_back(data[i][0], data[i][1]); data += 1; } } void cmDocumentationSection::Prepend(const char* data[][2]) { std::vector<cmDocumentationEntry> tmp; int i = 0; while (data[i][1]) { tmp.emplace_back(data[i][0], data[i][1]); data += 1; } this->Entries.insert(this->Entries.begin(), tmp.begin(), tmp.end()); } void cmDocumentationSection::Append(const char* n, const char* b) { this->Entries.emplace_back(n, b); }
25.655172
77
0.665323
duonglvtnaist
439f18a3d19efd2e1b3df1bd6bfea4ec20459971
8,239
cpp
C++
sp/src/game/client/hl2/c_rotorwash.cpp
joshmartel/source-sdk-2013
524e87f708d6c30360613b1f65ee174deafa20f4
[ "Unlicense" ]
2,268
2015-01-01T19:31:56.000Z
2022-03-31T20:15:31.000Z
sp/src/game/client/hl2/c_rotorwash.cpp
joshmartel/source-sdk-2013
524e87f708d6c30360613b1f65ee174deafa20f4
[ "Unlicense" ]
241
2015-01-01T15:26:14.000Z
2022-03-31T22:09:59.000Z
sp/src/game/client/hl2/c_rotorwash.cpp
DimasDSF/SMI
76cc2df8d1f51eb06743d66169524c3493b6d407
[ "Unlicense" ]
2,174
2015-01-01T08:18:05.000Z
2022-03-31T10:43:59.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "particlemgr.h" #include "particle_prototype.h" #include "particle_util.h" #include "c_te_particlesystem.h" #include "fx.h" #include "fx_quad.h" #include "clienteffectprecachesystem.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // ============================================== // Rotorwash particle emitter // ============================================== #ifndef _XBOX class WashEmitter : public CSimpleEmitter { public: WashEmitter( const char *pDebugName ) : CSimpleEmitter( pDebugName ) {} static WashEmitter *Create( const char *pDebugName ) { return new WashEmitter( pDebugName ); } void UpdateVelocity( SimpleParticle *pParticle, float timeDelta ) { // Float up when lifetime is half gone. pParticle->m_vecVelocity[ 2 ] += 64 * timeDelta; // FIXME: optimize this.... pParticle->m_vecVelocity *= ExponentialDecay( 0.8, 0.05, timeDelta ); } virtual float UpdateRoll( SimpleParticle *pParticle, float timeDelta ) { pParticle->m_flRoll += pParticle->m_flRollDelta * timeDelta; pParticle->m_flRollDelta += pParticle->m_flRollDelta * ( timeDelta * -2.0f ); //Cap the minimum roll if ( fabs( pParticle->m_flRollDelta ) < 0.5f ) { pParticle->m_flRollDelta = ( pParticle->m_flRollDelta > 0.0f ) ? 0.5f : -0.5f; } return pParticle->m_flRoll; } virtual float UpdateAlpha( const SimpleParticle *pParticle ) { return ( ((float)pParticle->m_uchStartAlpha/255.0f) * sin( M_PI * (pParticle->m_flLifetime / pParticle->m_flDieTime) ) ); } private: WashEmitter( const WashEmitter & ); }; #endif // !_XBOX // ============================================== // Rotorwash entity // ============================================== #define ROTORWASH_THINK_INTERVAL 0.1f class C_RotorWashEmitter : public C_BaseEntity { public: DECLARE_CLASS( C_RotorWashEmitter, C_BaseEntity ); DECLARE_CLIENTCLASS(); C_RotorWashEmitter( void ); virtual void OnDataChanged( DataUpdateType_t updateType ); virtual void ClientThink( void ); protected: float m_flAltitude; PMaterialHandle m_hWaterMaterial[2]; #ifndef _XBOX void InitSpawner( void ); CSmartPtr<WashEmitter> m_pSimple; #endif // !XBOX }; IMPLEMENT_CLIENTCLASS_DT( C_RotorWashEmitter, DT_RotorWashEmitter, CRotorWashEmitter) RecvPropFloat(RECVINFO(m_flAltitude)), END_RECV_TABLE() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_RotorWashEmitter::C_RotorWashEmitter( void ) { #ifndef _XBOX m_pSimple = NULL; m_hWaterMaterial[0] = NULL; m_hWaterMaterial[1] = NULL; #endif // !_XBOX } #ifndef _XBOX //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_RotorWashEmitter::InitSpawner( void ) { if ( m_pSimple.IsValid() ) return; m_pSimple = WashEmitter::Create( "wash" ); m_pSimple->SetNearClip( 128, 256 ); } #endif // !XBOX //----------------------------------------------------------------------------- // Purpose: // Input : updateType - //----------------------------------------------------------------------------- void C_RotorWashEmitter::OnDataChanged( DataUpdateType_t updateType ) { BaseClass::OnDataChanged( updateType ); if ( updateType == DATA_UPDATE_CREATED ) { SetNextClientThink( gpGlobals->curtime + ROTORWASH_THINK_INTERVAL ); #ifndef _XBOX InitSpawner(); #endif // !XBOX } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_RotorWashEmitter::ClientThink( void ) { SetNextClientThink( gpGlobals->curtime + ROTORWASH_THINK_INTERVAL ); trace_t tr; UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin()+(Vector(0, 0, -1024)), (MASK_SOLID_BRUSHONLY|CONTENTS_WATER|CONTENTS_SLIME), NULL, COLLISION_GROUP_NONE, &tr ); if ( /*!m_bIgnoreSolid && */(tr.fraction == 1.0f || tr.startsolid || tr.allsolid) ) return; // If we hit the skybox, don't do it either if ( tr.surface.flags & SURF_SKY ) return; float heightScale = RemapValClamped( tr.fraction * 1024, 512, 1024, 1.0f, 0.0f ); Vector vecDustColor; if ( tr.contents & CONTENTS_WATER ) { vecDustColor.x = 0.8f; vecDustColor.y = 0.8f; vecDustColor.z = 0.75f; } else if ( tr.contents & CONTENTS_SLIME ) { vecDustColor.x = 0.6f; vecDustColor.y = 0.5f; vecDustColor.z = 0.15f; } else { vecDustColor.x = 0.35f; vecDustColor.y = 0.3f; vecDustColor.z = 0.25f; } #ifndef _XBOX InitSpawner(); if ( m_pSimple.IsValid() == false ) return; m_pSimple->SetSortOrigin( GetAbsOrigin() ); PMaterialHandle *hMaterial; // Cache and set our material based on the surface we're over (ie. water) if ( tr.contents & (CONTENTS_WATER|CONTENTS_SLIME) ) { if ( m_hWaterMaterial[0] == NULL ) { m_hWaterMaterial[0] = m_pSimple->GetPMaterial("effects/splash1"); m_hWaterMaterial[1] = m_pSimple->GetPMaterial("effects/splash2"); } hMaterial = m_hWaterMaterial; } else { hMaterial = g_Mat_DustPuff; } #endif // !XBOX // If we're above water, make ripples if ( tr.contents & (CONTENTS_WATER|CONTENTS_SLIME) ) { float flScale = random->RandomFloat( 7.5f, 8.5f ); Vector color = Vector( 0.8f, 0.8f, 0.75f ); Vector startPos = tr.endpos + Vector(0,0,8); Vector endPos = tr.endpos + Vector(0,0,-64); if ( tr.fraction < 1.0f ) { //Add a ripple quad to the surface FX_AddQuad( tr.endpos + ( tr.plane.normal * 0.5f ), tr.plane.normal, 64.0f * flScale, 128.0f * flScale, 0.8f, 0.75f * heightScale, 0.0f, 0.75f, random->RandomFloat( 0, 360 ), random->RandomFloat( -2.0f, 2.0f ), vecDustColor, 0.2f, "effects/splashwake3", (FXQUAD_BIAS_SCALE|FXQUAD_BIAS_ALPHA) ); } } #ifndef _XBOX int numRingSprites = 32; float yaw = random->RandomFloat( 0, 2*M_PI ); // Randomly placed on the unit circle float yawIncr = (2*M_PI) / numRingSprites; Vector vecForward; Vector offset; SimpleParticle *pParticle; // Draw the rings for ( int i = 0; i < numRingSprites; i++ ) { // Get our x,y on the unit circle SinCos( yaw, &vecForward.y, &vecForward.x ); // Increment ahead yaw += yawIncr; // @NOTE toml (3-28-07): broke out following expression because vc2005 optimizer was screwing up in presence of SinCos inline assembly. Would also // go away if offset were referenced below as in the AddLineOverlay() //offset = ( RandomVector( -4.0f, 4.0f ) + tr.endpos ) + ( vecForward * 128.0f ); offset = vecForward * 128.0f; offset += tr.endpos + RandomVector( -4.0f, 4.0f ); pParticle = (SimpleParticle *) m_pSimple->AddParticle( sizeof(SimpleParticle), hMaterial[random->RandomInt(0,1)], offset ); if ( pParticle != NULL ) { pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = random->RandomFloat( 0.25f, 1.0f ); pParticle->m_vecVelocity = vecForward * random->RandomFloat( 1000, 1500 ); #if __EXPLOSION_DEBUG debugoverlay->AddLineOverlay( m_vecOrigin, m_vecOrigin + pParticle->m_vecVelocity, 255, 0, 0, false, 3 ); #endif if ( tr.contents & CONTENTS_SLIME ) { vecDustColor.x = random->RandomFloat( 0.4f, 0.6f ); vecDustColor.y = random->RandomFloat( 0.3f, 0.5f ); vecDustColor.z = random->RandomFloat( 0.1f, 0.2f ); } pParticle->m_uchColor[0] = vecDustColor.x * 255.0f; pParticle->m_uchColor[1] = vecDustColor.y * 255.0f; pParticle->m_uchColor[2] = vecDustColor.z * 255.0f; pParticle->m_uchStartSize = random->RandomInt( 16, 64 ); pParticle->m_uchEndSize = pParticle->m_uchStartSize * 4; pParticle->m_uchStartAlpha = random->RandomFloat( 16, 32 ) * heightScale; pParticle->m_uchEndAlpha = 0; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = random->RandomFloat( -16.0f, 16.0f ); } } #endif // !XBOX }
26.837134
159
0.609419
joshmartel
439f2ba39bab3a52dfdcb9144b7f700ce9578e8a
782
hh
C++
src/pindefs.hh
klaus-liebler/smopla-dps
ab92c73d16769a09d70b5519792c29a4276543c5
[ "MIT" ]
null
null
null
src/pindefs.hh
klaus-liebler/smopla-dps
ab92c73d16769a09d70b5519792c29a4276543c5
[ "MIT" ]
null
null
null
src/pindefs.hh
klaus-liebler/smopla-dps
ab92c73d16769a09d70b5519792c29a4276543c5
[ "MIT" ]
null
null
null
#pragma once #include "gpio.hh" constexpr Pin DBGPIN = Pin::PA06; constexpr Pin SW_ONOFF = Pin::PB04; constexpr Pin SW_DOWN = Pin::PA01; constexpr Pin SW_SET = Pin::PA02; constexpr Pin SW_UP = Pin::PA03; constexpr Pin ROTENC_SW = Pin::PB05; constexpr Pin ROTENC_A = Pin::PB08; constexpr Pin ROTENC_B = Pin::PB09; constexpr Pin LCD_SCK = Pin::PB13; constexpr Pin LCD_MOSI = Pin::PB15; constexpr Pin LCD_CS = Pin::NO_PIN; constexpr Pin LCD_DC = Pin::PB14; constexpr Pin LCD_BL = Pin::PB07; constexpr Pin LCD_RST = Pin::PB12; constexpr Pin ADC_VIN = Pin::PB00; //ADC1_IN8 constexpr Pin ADC_VOUT = Pin::PB01; //ADC1_IN9 constexpr Pin ADC_IOUT = Pin::PA07; //ADC1_IN7 constexpr Pin PWR_PWR = Pin::PB11; constexpr Pin PWR_DAC_U = Pin::PA04; constexpr Pin PWR_DAC_I = Pin::PA05;
23.69697
46
0.734015
klaus-liebler
439f8f5ac427167ccaf20dc36390c8d1073e5763
1,379
cpp
C++
ros/src/computing/perception/detection/vision_detector/libs/dpm_ttic/common/common.cpp
filiperinaldi/Autoware
9fae6cc7cb8253586578dbb62a2f075b52849e6e
[ "Apache-2.0" ]
20
2019-05-21T06:14:17.000Z
2021-11-03T04:36:09.000Z
ros/src/computing/perception/detection/vision_detector/libs/dpm_ttic/common/common.cpp
anhnv3991/autoware
d5b2ed9dc309193c8a2a7c77a2b6c88104c28328
[ "Apache-2.0" ]
18
2019-04-08T16:09:37.000Z
2019-06-05T15:24:40.000Z
ros/src/computing/perception/detection/vision_detector/libs/dpm_ttic/common/common.cpp
anhnv3991/autoware
d5b2ed9dc309193c8a2a7c77a2b6c88104c28328
[ "Apache-2.0" ]
8
2019-04-28T13:15:18.000Z
2021-06-03T07:05:16.000Z
/* * Copyright 2015-2019 Autoware Foundation. 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 "common.hpp" void dpm_ttic_add_part_calculation(FLOAT *score, FLOAT*M,int *rootsize,int *partsize,int ax,int ay) { FLOAT *S = score; int jj_L = ax+2*(rootsize[1]-1)-1; int ii_L = ay+2*(rootsize[0]-1); int axm = ax-1; //add part score(resolution of part is 2x of root) for(int jj=axm;jj<=jj_L;jj+=2) { int L = jj*partsize[0]; for(int ii=ay;ii<=ii_L;ii+=2) { *S -= M[ii+L-1]; S++; } } } //initialize accumulated score FLOAT *dpm_ttic_init_accumulated_score(IplImage *image, size_t& accumulated_size) { size_t num = image->height * image->width; accumulated_size = num * sizeof(FLOAT); FLOAT *scores = (FLOAT *)calloc(num, sizeof(FLOAT)); for(size_t i = 0; i < num; i++) scores[i] = -100.0; return scores; }
27.58
99
0.693981
filiperinaldi
43a02f4e18a8c0e3c5e1296f7692bce70bb11a1e
411
cpp
C++
pi/pi.cpp
anydream/PerfTest
b22d0e4463036cda5c20b55681f28dfc36caf356
[ "MIT" ]
2
2018-12-31T13:13:43.000Z
2019-01-04T02:58:36.000Z
pi/pi.cpp
anydream/PerfTest
b22d0e4463036cda5c20b55681f28dfc36caf356
[ "MIT" ]
null
null
null
pi/pi.cpp
anydream/PerfTest
b22d0e4463036cda5c20b55681f28dfc36caf356
[ "MIT" ]
1
2018-12-28T05:30:09.000Z
2018-12-28T05:30:09.000Z
#include <stdio.h> #include <time.h> int main() { time_t start = clock(); double s = 1; double pi = 0; double i = 1.0; double n = 1.0; for (int x = 0; x < 500000000; ++x) { pi += i; n = n + 2; s = -s; i = s / n; } volatile double result = 4 * pi; time_t elapsed = clock() - start; printf("c++ pi(500000000)=%.10lf, elapsed=%lldms\n", result, elapsed); return 0; }
16.44
72
0.520681
anydream
43a23e25b179e4aca7994855a71772c5d5cbbbdc
37
cpp
C++
ProceduralGeneration/VertexBufferLayout.cpp
cristi191096/ProceduralGeneration
912b738ced73d676f9d0885d917a94c710857396
[ "Apache-2.0" ]
null
null
null
ProceduralGeneration/VertexBufferLayout.cpp
cristi191096/ProceduralGeneration
912b738ced73d676f9d0885d917a94c710857396
[ "Apache-2.0" ]
null
null
null
ProceduralGeneration/VertexBufferLayout.cpp
cristi191096/ProceduralGeneration
912b738ced73d676f9d0885d917a94c710857396
[ "Apache-2.0" ]
null
null
null
#include "VertexBufferLayout.h"
5.285714
31
0.702703
cristi191096
43a31b0cfaa145640d1d7deadecfbecb6b119a3b
6,134
cpp
C++
SDK/Extras/Textify3DMF/Source/TypeHandlers/Geometries/TriMesh.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
24
2019-10-28T07:01:48.000Z
2022-03-04T16:10:39.000Z
SDK/Extras/Textify3DMF/Source/TypeHandlers/Geometries/TriMesh.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
8
2020-04-22T19:42:45.000Z
2021-04-30T16:28:32.000Z
SDK/Extras/Textify3DMF/Source/TypeHandlers/Geometries/TriMesh.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
6
2019-09-22T14:44:15.000Z
2021-04-01T20:04:29.000Z
/* * TriMesh.cpp * Textify3DMF * * Created by James Walker on 4/7/12. * Copyright (c) 2012 James W. Walker. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from the * use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in a * product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * */ #include "TriMesh.h" TriMesh::TriMesh() : TypeHandler( 'tmsh', "TriMesh" ) , mFaces( 0 ) , mEdges( 0 ) , mPoints( 0 ) { } void TriMesh::GetCounts( uint32_t& outFaces, uint32_t& outEdges, uint32_t& outPoints ) const { outFaces = mFaces; outEdges = mEdges; outPoints = mPoints; } void TriMesh::Process( size_t inStartOffset, size_t inEndOffset ) { size_t dataLen = inEndOffset - inStartOffset; if (dataLen < 52) { throw DataLengthException( Name(), inStartOffset, inEndOffset, 52 ); } mFaces = FetchUInt32( inStartOffset ); uint32_t numFaceAtts = FetchUInt32( inStartOffset+4 ); mEdges = FetchUInt32( inStartOffset+8 ); uint32_t numEdgeAtts = FetchUInt32( inStartOffset+12 ); mPoints = FetchUInt32( inStartOffset+16 ); uint32_t numPointAtts = FetchUInt32( inStartOffset+20 ); int bytesPointIndex, bytesPerFaceIndex; if (mPoints - 1 <= 0xFE) { bytesPointIndex = 1; } else if (mPoints - 1 <= 0xFFFE) { bytesPointIndex = 2; } else { bytesPointIndex = 4; } if (mFaces - 1 <= 0xFE) { bytesPerFaceIndex = 1; } else if (mFaces - 1 <= 0xFFFE) { bytesPerFaceIndex = 2; } else { bytesPerFaceIndex = 4; } uint32_t trianglesSize = mFaces * 3 * bytesPointIndex; uint32_t edgesSize = mEdges * 2 * (bytesPointIndex + bytesPerFaceIndex); uint32_t pointsSize = mPoints * 12; uint32_t expectedLength = 52 + trianglesSize + edgesSize + pointsSize; if (dataLen != expectedLength) { throw DataLengthException( Name(), inStartOffset, inEndOffset, expectedLength ); } Out() << Indent() << Name() << " (\n" << Indent(1) << mFaces << " " << numFaceAtts << " " << mEdges << " " << numEdgeAtts << " " << mPoints << " " << numPointAtts << "\t" << "# faces faceAtts edges edgeAtts pts ptAtts\n"; WriteTriangles( inStartOffset+24, mFaces, bytesPointIndex ); WriteEdges( inStartOffset+24+trianglesSize, mEdges, bytesPointIndex, bytesPerFaceIndex ); WritePoints( inStartOffset+24+trianglesSize+edgesSize, mPoints ); WriteBoundingBox( inStartOffset+24+trianglesSize+edgesSize+pointsSize ); Out() << Indent() << ")\n"; } uint32_t TriMesh::FetchIndex( size_t inStartOffset, int inBytes ) { uint32_t result = 0; if (inBytes == 1) { result = Boss()->FetchUInt8( inStartOffset ); if (result == 0xFF) { result = 0xFFFFFFFFUL; } } else if (inBytes == 2) { if (result == 0xFFFF) { result = 0xFFFFFFFFUL; } result = Boss()->FetchUInt16( inStartOffset ); } else { result = FetchUInt32( inStartOffset ); } return result; } void TriMesh::WriteTriangles( size_t inStartOffset, uint32_t inNumFaces, int inBytesPerPointIndex ) { for (uint32_t i = 0; i < inNumFaces; ++i) { uint32_t ind1 = FetchIndex( inStartOffset + i*3*inBytesPerPointIndex, inBytesPerPointIndex ); uint32_t ind2 = FetchIndex( inStartOffset + i*3*inBytesPerPointIndex + inBytesPerPointIndex, inBytesPerPointIndex ); uint32_t ind3 = FetchIndex( inStartOffset + i*3*inBytesPerPointIndex + 2 * inBytesPerPointIndex, inBytesPerPointIndex ); Out() << Indent(1) << ind1 << ' ' << ind2 << ' ' << ind3; if (i == 0) { Out() << "\t# triangles\n"; } else { Out() << '\n'; } } } void TriMesh::WriteEdges( size_t inStartOffset, uint32_t inNumEdges, int inBytesPerPointIndex, int inBytesPerFaceIndex ) { uint32_t edgeDataLen = 2 * (inBytesPerPointIndex + inBytesPerFaceIndex); for (uint32_t i = 0; i < inNumEdges; ++i) { uint32_t ptInd1 = FetchIndex( inStartOffset + i*edgeDataLen, inBytesPerPointIndex ); uint32_t ptInd2 = FetchIndex( inStartOffset + i*edgeDataLen + inBytesPerPointIndex, inBytesPerPointIndex ); uint32_t faceInd1 = FetchIndex( inStartOffset + i*edgeDataLen + 2*inBytesPerPointIndex, inBytesPerFaceIndex ); uint32_t faceInd2 = FetchIndex( inStartOffset + i*edgeDataLen + 2*inBytesPerPointIndex + inBytesPerFaceIndex, inBytesPerFaceIndex ); Out() << Indent(1) << ptInd1 << ' ' << ptInd2 << ' ' << faceInd1 << ' ' << faceInd2; if (i == 0) { Out() << "\t# edges\n"; } else { Out() << '\n'; } } } void TriMesh::WritePoints( size_t inStartOffset, uint32_t inNumPoints ) { for (uint32_t i = 0; i < inNumPoints; ++i) { float x = FetchFloat32( inStartOffset + i*12 ); float y = FetchFloat32( inStartOffset + i*12 + 4 ); float z = FetchFloat32( inStartOffset + i*12 + 8 ); Out() << Indent(1) << x << ' ' << y << ' ' << z; if (i == 0) { Out() << "\t# points\n"; } else { Out() << '\n'; } } } void TriMesh::WriteBoundingBox( size_t inStartOffset ) { float xMin = FetchFloat32( inStartOffset ); float yMin = FetchFloat32( inStartOffset+4 ); float zMin = FetchFloat32( inStartOffset+8 ); float xMax = FetchFloat32( inStartOffset+12 ); float yMax = FetchFloat32( inStartOffset+16 ); float zMax = FetchFloat32( inStartOffset+20 ); uint32_t emptyFlag = FetchUInt32( inStartOffset+24 ); Out() << Indent(1) << xMin << ' ' << yMin << ' ' << zMin << ' ' << xMax << ' ' << yMax << ' ' << zMax << ' ' << ((emptyFlag == 0)? "False" : "True") << "\t# bounding box\n"; }
25.991525
80
0.659439
h-haris
43a78b6a53f338ce7efe3f42ece9b9178f2cba87
7,408
cpp
C++
Firmware/OTPManagerFirmware/gui_ssd1306_i2c.cpp
DarkCaster/ArduinoOTP
ce6ff3b041abe3b38647c0ded9caa64b750891fa
[ "MIT" ]
1
2018-12-10T18:03:45.000Z
2018-12-10T18:03:45.000Z
Firmware/OTPManagerFirmware/gui_ssd1306_i2c.cpp
DarkCaster/ArduinoOTP
ce6ff3b041abe3b38647c0ded9caa64b750891fa
[ "MIT" ]
null
null
null
Firmware/OTPManagerFirmware/gui_ssd1306_i2c.cpp
DarkCaster/ArduinoOTP
ce6ff3b041abe3b38647c0ded9caa64b750891fa
[ "MIT" ]
null
null
null
#include <U8g2lib.h> #include "configuration.h" #include "gui_ssd1306_i2c.h" #include "debug.h" static U8G2_SSD1306_128X64_NONAME_2_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE); GuiSSD1306_I2C::GuiSSD1306_I2C(uint8_t displayPowerPin, uint8_t displayAddr, ClockHelper &clockHelper, ProfileManager &profileManager, CodeGenAggregator& codeGenAggregator) : displayPowerPin(displayPowerPin), displayAddr(displayAddr), clockHelper(clockHelper), profileManager(profileManager), codeGenAggregator(codeGenAggregator), rnd(0), curItem(MenuItemType::MainScreen), menuPos(0) { } void GuiSSD1306_I2C::InitPre() { //power-on pinMode(displayPowerPin, OUTPUT); digitalWrite(displayPowerPin, HIGH); curItem=MenuItemType::MainScreen; } void GuiSSD1306_I2C::InitPost() { u8g2.setI2CAddress(displayAddr); u8g2.begin(); } void GuiSSD1306_I2C::DescendPre() { u8g2.clearDisplay(); } void GuiSSD1306_I2C::DescendPost() { digitalWrite(displayPowerPin,LOW); } void GuiSSD1306_I2C::WakeupPre() { digitalWrite(displayPowerPin,HIGH); } void GuiSSD1306_I2C::WakeupPost() { u8g2.begin(); } MenuItemType GuiSSD1306_I2C::GetCurItem() { return curItem; } void GuiSSD1306_I2C::DrawCaption(const char * caption) { auto xPos=static_cast<uint8_t>(rnd.Next(CAPTION_MIN_POS_X, CAPTION_MAX_POS_X)); auto yPos=static_cast<uint8_t>(rnd.Next(CAPTION_MIN_POS_Y, CAPTION_MAX_POS_Y)); u8g2.firstPage(); u8g2.setFont(MENU_MAIN_FONT); do { u8g2.drawStr(xPos,yPos,caption); } while ( u8g2.nextPage()!=0 ); } void GuiSSD1306_I2C::DrawCaption(const __FlashStringHelper* fCaption) { //instead of using fat strlen_P+strcpy_P or strncpy_P use this simplified code //saves 72 bytes of progmem if not using strlen_P and strcpy_P methods anywhere else char caption[CAPTION_MAX_LEN+1]; caption[CAPTION_MAX_LEN]='\0'; for(uint16_t pos=0; pos<CAPTION_MAX_LEN; ++pos) { char testChar=pgm_read_byte(reinterpret_cast<const char*>(fCaption)+pos); *(caption+pos)=testChar; if(testChar=='\0') break; } DrawCaption(caption); } void GuiSSD1306_I2C::ShowCDScr() { DrawCaption(F("<Resync>")); } void GuiSSD1306_I2C::ShowCEScr() { DrawCaption(F("<Connected>")); } void GuiSSD1306_I2C::ShowCodeScr(const char * const code) { DrawCaption(code); } void GuiSSD1306_I2C::DrawProfileMenu() { u8g2.firstPage(); u8g2.setFont(MENU_MAIN_FONT); do { auto item=prBuffer.GetHead(); for(uint8_t curPos=0; curPos<PROFILES_MENU_ITEMS_COUNT; ++curPos) { if(item->profile.type==ProfileType::Empty) break; if(curPos==menuPos) u8g2.drawStr(0,MENU_CAPTION_HEIGHT*curPos,">"); u8g2.drawStr(16,MENU_CAPTION_HEIGHT*curPos,item->profile.name); item=item->Next(); } } while ( u8g2.nextPage()!=0 ); } void GuiSSD1306_I2C::MenuReset() { prBuffer.Clear(); menuPos=0; auto prLimit=profileManager.GetProfilesCount(); auto prIdx=prLimit; auto head=prBuffer.GetHead(); for(prIdx=0; prIdx<prLimit; ++prIdx) { //try to read profile header auto profile=profileManager.ReadProfileHeader(prIdx); //add it to prBuffer, switch head if(profile.type!=ProfileType::Empty && profile.type!=ProfileType::Invalid) { head->Set(profile,prIdx); head=head->Next(); } if(head==prBuffer.GetTail()) break; } //set cutItem for external queries curItem=MenuItemType::ProfileMenu; STATUS(); LOG(F("MenuReset")); } void GuiSSD1306_I2C::Reseed() { rnd=LCGRandom(clockHelper.GetSeed()); } void GuiSSD1306_I2C::MenuNext() { if(curItem==MenuItemType::MainScreen) { DrawCaption(F("<Loading>")); STATUS(); LOG(F("Menu init from MainScreen")); MenuReset(); //if prBuffer is empty, goto main menu if(prBuffer.GetHead()->profile.type==ProfileType::Empty) { ResetToMainScr(); return; } DrawProfileMenu(); return; } if(curItem==MenuItemType::ProfileMenu) { STATUS(); LOG(F("Select next profile menu item")); //increase menuPos ++menuPos; if(menuPos==PROFILES_MENU_ITEMS_COUNT) { MenuReset(); return; } //check, whether we at the empty item now, set menu-pos to zero if so auto bItem=prBuffer.GetHead(); for(uint8_t testPos=0; testPos<menuPos; ++testPos) bItem=bItem->Next(); if(bItem->profile.type==ProfileType::Empty) { menuPos=0; bItem=prBuffer.GetHead(); } //if we switched to the last position, try to read more profiles if(menuPos==PROFILES_MENU_ITEMS_COUNT-1) { //try to read one extra profile from eeprom auto prLimit=profileManager.GetProfilesCount(); auto prIdx=prLimit; auto profile=Profile::Empty(); for(prIdx=bItem->index+1; prIdx<prLimit; ++prIdx) { profile=profileManager.ReadProfileHeader(prIdx); if(profile.type!=ProfileType::Empty && profile.type!=ProfileType::Invalid) break; } //if succeed if(prIdx<prLimit) { //shift profiles' ring buffer prBuffer.Shift(); //and add new profile to the new tail of the buffer auto tail=prBuffer.GetTail(); tail->Set(profile,prIdx); //decrease menuPos --menuPos; //and select new buffer's item bItem=prBuffer.GetHead(); for(uint8_t testPos=0; testPos<menuPos; ++testPos) bItem=bItem->Next(); } } //set curItem curItem=MenuItemType::ProfileMenu; DrawProfileMenu(); return; } if(curItem==MenuItemType::ProfileItem) { STATUS(); LOG(F("Go back to profile menu")); //go back to ProfileMenu curItem=MenuItemType::ProfileMenu; DrawProfileMenu(); return; } } void GuiSSD1306_I2C::MenuSelect() { if(curItem==MenuItemType::MainScreen) return; //do nothing if(curItem==MenuItemType::ProfileMenu || curItem==MenuItemType::ProfileItem) { STATUS(); LOG(F("Selecting profile item")); //get profile from prBuffer, using menuPos auto bItem=prBuffer.GetHead(); for(uint8_t testPos=0; testPos<menuPos; ++testPos) bItem=bItem->Next(); //load profile data uint8_t profilePayload[PROFILE_PAYLOAD_LEN]; profileManager.ReadProfileData(bItem->index,profilePayload); //get codegen manager from aggregator auto codeGenManager=codeGenAggregator.GetManager(bItem->profile.type); if(codeGenManager==nullptr) { DrawCaption(F("PROFILE\nUNSUPPORTED")); return; } //generate and display code using codegen manager and profilePayload char caption[CAPTION_MAX_LEN+1]; caption[CAPTION_MAX_LEN]='\0'; bool updateNeeded=codeGenManager->GenerateCode(caption, profilePayload); DrawCaption(caption); //update profilePayload data and save it if(updateNeeded) profileManager.WriteProfileData(bItem->index,profilePayload); return; } } void GuiSSD1306_I2C::ResetToMainScr() { char timeString[6]; char dateString[48]; clockHelper.Update(); clockHelper.WriteTimeString(timeString,6); clockHelper.WriteDateString(dateString,48); auto timeXPos=static_cast<uint8_t>(rnd.Next(MAIN_SCREEN_TIME_MIN_POS_X, MAIN_SCREEN_TIME_MAX_POS_X)); auto timeYPos=static_cast<uint8_t>(rnd.Next(MAIN_SCREEN_TIME_MIN_POS_Y, MAIN_SCREEN_TIME_MAX_POS_Y)); auto dateXPos=static_cast<uint8_t>(rnd.Next(MAIN_SCREEN_DATE_MIN_POS_X, MAIN_SCREEN_DATE_MAX_POS_X)); auto dateYPos=static_cast<uint8_t>(rnd.Next(MAIN_SCREEN_DATE_MIN_POS_Y, MAIN_SCREEN_DATE_MAX_POS_Y)); u8g2.firstPage(); do { u8g2.setFont(MAIN_SCREEN_DATE_FONT); u8g2.drawStr(dateXPos,dateYPos,dateString); u8g2.setFont(MAIN_SCREEN_TIME_FONT); u8g2.drawStr(timeXPos,timeYPos,timeString); } while ( u8g2.nextPage()!=0 ); curItem=MenuItemType::MainScreen; STATUS(); LOG(F("ResetToMainScr")); }
25.111864
174
0.734746
DarkCaster
43a9f1107ff31eab3ebfd60f9b0fd5dc33f2a02d
2,544
cc
C++
public/util/thread/rate_limited_shared_queue_test.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
3
2015-05-18T14:52:47.000Z
2018-11-12T07:51:00.000Z
public/util/thread/rate_limited_shared_queue_test.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
null
null
null
public/util/thread/rate_limited_shared_queue_test.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
3
2015-08-04T05:58:18.000Z
2018-11-12T07:51:01.000Z
// Copyright 2013 Room77, Inc. // Author: Nicholas Edelman (edelman) #include <thread> #include "test/cc/test_main.h" #include "util/thread/rate_limited_shared_queue.h" namespace util { namespace threading { namespace test { uint64_t TimestampMs() { return chrono::duration_cast<chrono::milliseconds>( chrono::high_resolution_clock::now().time_since_epoch()).count(); } template <typename T> void AddValues(RateLimitedSharedQueue<T>& rls_queue, T default_val, int nvals) { for (int i = 0; i < nvals; ++i) { rls_queue.push(default_val); } } template <typename T> void ConsumeVals(RateLimitedSharedQueue<T>& rls_queue, int nvals) { for (int i = 0; i < nvals; ++i) { rls_queue.consume_batch(); } } TEST(RateLimitedSharedQueue, CanRetrieveImmediately) { const double num_vals = 100; const double ms_per_query = 1000; RateLimitedSharedQueue<int> rls_queue(1000.0 / ms_per_query, 1); AddValues(rls_queue, 0, num_vals); uint64_t start_ms = TimestampMs(); rls_queue.consume_batch(); double measured_ms_query = TimestampMs() - start_ms; // verify the read happens in much less than the 1000 ms per query EXPECT_TRUE(measured_ms_query < 10); } TEST(RateLimitedSharedQueue, AddValuesVerifyRate) { const double num_vals = 100; const double ms_per_query = 10; RateLimitedSharedQueue<int> rls_queue(1000.0 / ms_per_query, 1); AddValues(rls_queue, 0, num_vals); uint64_t start_ms = TimestampMs(); for (int i = 0; i < num_vals; ++i) { rls_queue.consume_batch(); } double measured_ms_per_query = (TimestampMs() - start_ms) / num_vals; EXPECT_GT(measured_ms_per_query, 9.8); EXPECT_LT(measured_ms_per_query, 10.0); } TEST(RateLimitedSharedQueue, MultipleConsumersAddValuesVerifyRate) { const uint64_t num_vals = 1e2; const double ms_per_query = 10; const double num_threads = 4; RateLimitedSharedQueue<int> rls_queue(1000.0/ms_per_query, 1); vector<thread> ths; for (int i = 0; i < num_threads; ++i) { ths.push_back(thread(std::bind(AddValues<int>, ref(rls_queue), 0, num_vals))); } for (auto& th : ths) th.join(); uint64_t start_ms = TimestampMs(); ths.clear(); for (int i = 0; i < num_threads; ++i) { ths.push_back(thread(std::bind(ConsumeVals<int>, ref(rls_queue), num_vals))); } for (auto& th : ths) th.join(); double measured_ms_per_query = (TimestampMs() - start_ms) / (num_threads*num_vals); EXPECT_GT(measured_ms_per_query, 9.9); EXPECT_LT(measured_ms_per_query, 10.1); } } // namespace test } // namespace threading } // namespace util
29.929412
85
0.717767
room77
43bbc69c75c395bbdfb99dc3cdae7134657af51a
2,699
cpp
C++
Tools/ShaderCompiler/src/DEMShaderCompilerDLL.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
15
2019-05-07T11:26:13.000Z
2022-01-12T18:26:45.000Z
Tools/ShaderCompiler/src/DEMShaderCompilerDLL.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
16
2021-10-04T17:15:31.000Z
2022-03-20T09:34:29.000Z
Tools/ShaderCompiler/src/DEMShaderCompilerDLL.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
2
2019-04-28T23:27:48.000Z
2019-05-07T11:26:18.000Z
#include "DEMShaderCompilerDLL.h" /* #define WIN32_LEAN_AND_MEAN #include <windows.h> static HMODULE hDLL = nullptr; static FDEMShaderCompiler_InitCompiler pInitCompiler = nullptr; static FDEMShaderCompiler_GetLastOperationMessages pGetLastOperationMessages = nullptr; static FDEMShaderCompiler_CompileShader pCompileShader = nullptr; static FDEMShaderCompiler_CreateShaderMetadata pCreateShaderMetadata = nullptr; static FDEMShaderCompiler_LoadShaderMetadataByObjectFileID pLoadShaderMetadataByObjectFileID = nullptr; static FDEMShaderCompiler_FreeShaderMetadata pFreeShaderMetadata = nullptr; //static FDEMShaderCompiler_SaveShaderMetadata pSaveShaderMetadata = nullptr; static FDEMShaderCompiler_PackShaders pPackShaders = nullptr; bool InitDEMShaderCompilerDLL(const char* pDLLPath, const char* pDBFilePath, const char* pOutputDirectory) { if (!hDLL) { hDLL = ::LoadLibrary(pDLLPath); if (!hDLL) return false; } pInitCompiler = (FDEMShaderCompiler_InitCompiler)GetProcAddress(hDLL, "InitCompiler"); if (!pInitCompiler) return false; return pInitCompiler(pDBFilePath, pOutputDirectory); } //--------------------------------------------------------------------- // DB is closed inside a DLL bool TermDEMShaderCompilerDLL() { bool Result = true; if (hDLL) { if (::FreeLibrary(hDLL) != TRUE) Result = false; hDLL = 0; } pInitCompiler = nullptr; pGetLastOperationMessages = nullptr; pCompileShader = nullptr; pLoadShaderMetadataByObjectFileID = nullptr; pFreeShaderMetadata = nullptr; pPackShaders = nullptr; return Result; } //--------------------------------------------------------------------- int DLLCompileShader(const char* pSrcPath, EShaderType ShaderType, uint32_t Target, const char* pEntryPoint, const char* pDefines, bool Debug, bool OnlyMetadata, uint32_t& ObjectFileID, uint32_t& InputSignatureFileID) { if (!pCompileShader) { if (!hDLL) return DEM_SHADER_COMPILER_ERROR; pCompileShader = (FDEMShaderCompiler_CompileShader)GetProcAddress(hDLL, "CompileShader"); if (!pCompileShader) return DEM_SHADER_COMPILER_ERROR; } return pCompileShader(pSrcPath, ShaderType, Target, pEntryPoint, pDefines, Debug, OnlyMetadata, ObjectFileID, InputSignatureFileID); } //--------------------------------------------------------------------- unsigned int DLLPackShaders(const char* pCommaSeparatedShaderIDs, const char* pLibraryFilePath) { if (!pPackShaders) { if (!hDLL) return 0; pPackShaders = (FDEMShaderCompiler_PackShaders)GetProcAddress(hDLL, "PackShaders"); if (!pPackShaders) return 0; } return pPackShaders(pCommaSeparatedShaderIDs, pLibraryFilePath); } //--------------------------------------------------------------------- */
34.164557
133
0.718414
niello
43c1086c9cce804f080e1726bf128619abd2ce42
18,031
cpp
C++
src/generate_dynamic_scene/generate_obstacle.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
1
2021-07-31T12:34:11.000Z
2021-07-31T12:34:11.000Z
src/generate_dynamic_scene/generate_obstacle.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
null
null
null
src/generate_dynamic_scene/generate_obstacle.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
2
2021-05-08T13:27:31.000Z
2021-09-24T07:59:04.000Z
#include "generate_dynamic_scene/generate_obstacle.hpp" namespace hdi_plan { GenerateObstacle::GenerateObstacle(const ros::NodeHandle &nh, const ros::NodeHandle &pnh) : nh_(nh), pnh_(pnh) { // load parameters if (!this->load_params()) { ROS_WARN("[%s] Could not load all parameters in motion planner.", this->pnh_.getNamespace().c_str()); } else { ROS_INFO("[%s] Loaded all parameters in motion planner.", this->pnh_.getNamespace().c_str()); } this->human_movement_pub_ = nh_.advertise<hdi_plan::obstacle_info>("hdi_plan/human_movement", 1); this->update_human_obstacle_pub_ = nh_.advertise<hdi_plan::obstacle_info>("hdi_plan/obstacle_info_topic", 1); this->path_spot_pub_ = nh_.advertise<hdi_plan::obstacle_info>("hdi_plan/path_spot_topic", 100); //this->trajectory_sub_ = nh_.subscribe("hdi_plan/full_trajectory", 1, &GenerateObstacle::trajectory_callback, this); ros::Duration(20.0).sleep(); this->publish_goal_position(); // wait until human movement start ros::Duration(24.0 + 20.0).sleep(); this->publish_obstacle(); //ros::Duration(5.0).sleep(); //this->remove_obstacle(); //ros::Duration(24.0 + 20.0).sleep(); //this->publish_human_movement_1(); } GenerateObstacle::~GenerateObstacle() = default; bool GenerateObstacle::load_params() { this->pnh_.getParam("goal_position", this->goal_position_param_); return true; } hdi_plan::obstacle_info GenerateObstacle::get_obstacle_message(bool operation, int human_id, double position_x, double position_y) { hdi_plan::obstacle_info obstacle_msg; obstacle_msg.name = "human_" + std::to_string(human_id); obstacle_msg.type = hdi_plan::Obstacle_type::human; obstacle_msg.operation = operation; obstacle_msg.size = 1; obstacle_msg.position.x = position_x; obstacle_msg.position.y = position_y; obstacle_msg.position.z = 0; return obstacle_msg; } void GenerateObstacle::publish_goal_position() { ROS_INFO("Publish goal position"); hdi_plan::obstacle_info obstacle_msg; obstacle_msg.name = "goal_position"; obstacle_msg.type = hdi_plan::Obstacle_type::cube; obstacle_msg.operation = true; obstacle_msg.size = 0.5; obstacle_msg.position.x = this->goal_position_param_[0]; obstacle_msg.position.y = this->goal_position_param_[1]; obstacle_msg.position.z = this->goal_position_param_[2]; this->path_spot_pub_.publish(obstacle_msg); } void GenerateObstacle::publish_obstacle() { hdi_plan::obstacle_info obstacle_msg; obstacle_msg.name = "sphere1"; obstacle_msg.type = hdi_plan::Obstacle_type::sphere; obstacle_msg.operation = true; obstacle_msg.size = 3; obstacle_msg.position.x = 10.0; obstacle_msg.position.y = 10.0; obstacle_msg.position.z = 2.0; update_human_obstacle_pub_.publish(obstacle_msg); } void GenerateObstacle::remove_obstacle() { hdi_plan::obstacle_info obstacle_msg; obstacle_msg.name = "sphere1"; obstacle_msg.type = hdi_plan::Obstacle_type::sphere; obstacle_msg.operation = false; obstacle_msg.size = 3; obstacle_msg.position.x = 10.0; obstacle_msg.position.y = 10.0; obstacle_msg.position.z = 2.0; update_human_obstacle_pub_.publish(obstacle_msg); } void GenerateObstacle::publish_obstacle2() { hdi_plan::obstacle_info obstacle_msg; obstacle_msg.name = "sphere2"; obstacle_msg.type = hdi_plan::Obstacle_type::sphere; obstacle_msg.operation = true; obstacle_msg.size = 5; obstacle_msg.position.x = 10.0; obstacle_msg.position.y = 5.0; obstacle_msg.position.z = 2.0; update_human_obstacle_pub_.publish(obstacle_msg); } void GenerateObstacle::publish_human_movement_1() { Eigen::Vector2d start_point(10.0, 23.0); Eigen::Vector2d goal_point(10.0, 0.0); Eigen::Vector2d current_point(start_point(0), start_point(1)); double distance = hdi_plan_utils::get_distance_2d(start_point, goal_point); double velocity = 1; double period = 1; int human_id = 1; int count = 0; ROS_INFO("###Generate Obstacle: Start to spawn a moving obstacle 1."); while (hdi_plan_utils::get_distance_2d(current_point, goal_point) > 0.5 * period * velocity) { if (count > 0) update_human_obstacle_pub_.publish(get_obstacle_message(false, human_id)); current_point(0) = (goal_point(0) - start_point(0)) * (velocity * count * period) / distance + start_point(0); current_point(1) = (goal_point(1) - start_point(1)) * (velocity * count * period) / distance + start_point(1); std::cout << "Sending pos: " << current_point(0) << " " << current_point(1) << std::endl; update_human_obstacle_pub_.publish(get_obstacle_message(true, human_id, current_point(0), current_point(1))); if (count > 0) human_movement_pub_.publish(get_obstacle_message(true, human_id, current_point(0), current_point(1))); ros::Duration(period).sleep(); count += 1; } //ROS_INFO("###Finish Generate Obstacle: Start to spawn a moving obstacle 1."); } void GenerateObstacle::publish_human_movement_2() { Eigen::Vector2d start_point(15.0, 1.0); Eigen::Vector2d goal_point(15.0, 30.0); Eigen::Vector2d current_point(start_point(0), start_point(1)); double distance = hdi_plan_utils::get_distance_2d(start_point, goal_point); double velocity = 1; double period = 1; int human_id = 2; int count = 0; ROS_INFO("###Generate Obstacle: Start to spawn a moving obstacle 2."); while (hdi_plan_utils::get_distance_2d(current_point, goal_point) > 0.5 * period * velocity) { if (count > 0) update_human_obstacle_pub_.publish(get_obstacle_message(false, human_id)); current_point(0) = (goal_point(0) - start_point(0)) * (velocity * count * period) / distance + start_point(0); current_point(1) = (goal_point(1) - start_point(1)) * (velocity * count * period) / distance + start_point(1); update_human_obstacle_pub_.publish(get_obstacle_message(true, human_id, current_point(0), current_point(1))); if (count > 0) human_movement_pub_.publish(get_obstacle_message(true, human_id, current_point(0), current_point(1))); ros::Duration(period).sleep(); count += 1; } } /* void GenerateObstacle::trajectory_callback(const hdi_plan::point_array::ConstPtr &msg) { int trajectory_size = msg->points.size(); int path_spot_list_size = this->path_spot_list_.size(); std::cout << "Size: " << trajectory_size << " spot: " << path_spot_list_size << std::endl; int index = 0; int stop_index = -1; for (auto &obstacle_msg : this->path_spot_list_) { if (index < trajectory_size) { obstacle_msg.position.x = msg->points[index].x; obstacle_msg.position.y = msg->points[index].y; obstacle_msg.position.z = msg->points[index].z; index += 1; continue; } if (obstacle_msg.position.x == 100.0 && obstacle_msg.position.y == 100.0 && obstacle_msg.position.z == 100.0) { stop_index = index; break; } obstacle_msg.position.x = 100.0; obstacle_msg.position.y = 100.0; obstacle_msg.position.z = 100.0; index += 1; } if (trajectory_size > path_spot_list_size) { for (int i = path_spot_list_size; i < trajectory_size; i++) { hdi_plan::obstacle_info obstacle_msg; obstacle_msg.name = "spot_" + std::to_string(i); obstacle_msg.type = hdi_plan::Obstacle_type::spot; obstacle_msg.operation = true; obstacle_msg.size = 0.1; obstacle_msg.position.x = msg->points[i].x; obstacle_msg.position.y = msg->points[i].y; obstacle_msg.position.z = msg->points[i].z; this->path_spot_list_.push_back(obstacle_msg); } } this->publish_path_spot(stop_index); } void GenerateObstacle::publish_path_spot(int stop_index) { int index = 0; for (auto obstacle_msg : this->path_spot_list_) { if (index == stop_index) break; //std::cout << "spot pos: " << obstacle_msg.position.x << " " << obstacle_msg.position.y << " " << obstacle_msg.position.z << std::endl; this->path_spot_pub_.publish(obstacle_msg); index += 1; } } */ } /* int main(int argc, char **argv) { ros::init(argc, argv, "generate_obstacle"); ros::NodeHandle nh; //ros::Publisher pub_get_new_path_ = nh.advertise<std_msgs::Bool>("hdi_plan/get_new_path", 1); ros::Publisher pub_optimized_path_ = nh.advertise<hdi_plan::point_array>("hdi_plan/full_trajectory", 1); ros::Rate loop_rate(10); ROS_INFO("test1"); std::vector<Eigen::Vector3d> solution_path; solution_path.resize(5); Eigen::Vector3d point_1(0.0, 1.0, 1.0); solution_path[0] = point_1; Eigen::Vector3d point_2(1.0, 2.0, 1.0); solution_path[1] = point_2; Eigen::Vector3d point_3(2.0, 0.0, 1.0); solution_path[2] = point_3; Eigen::Vector3d point_4(3.0, 2.0, 1.0); solution_path[3] = point_4; Eigen::Vector3d point_5(4.0, 1.0, 1.0); solution_path[4] = point_5; for (int i=0;i<10;i++) { Eigen::Vector3d s_point(1.0, i+1, 1.0); solution_path[i] = s_point; } std::map<std::string, std::shared_ptr<hdi_plan::Obstacle>> obstacle_map; std::string obstacle_name = "cube1"; bool obstacle_operation = true; double obstacle_size = 1; Eigen::Vector3d obstacle_position(100, 100, 100); auto obstacle = std::make_shared<hdi_plan::Obstacle>(obstacle_name, hdi_plan::Obstacle_type::cube, obstacle_operation, obstacle_size, obstacle_position); obstacle_map[obstacle_name] = obstacle; ros::WallTime chomp_start_time = ros::WallTime::now(); auto chomp_trajectory = std::make_shared<hdi_plan::ChompTrajectory>(solution_path); auto chomp = std::make_shared<hdi_plan::Chomp>(chomp_trajectory, obstacle_map); std::vector<Eigen::Vector3d> optimized_trajectory = chomp->get_optimized_trajectory(); double chomp_process_time = (ros::WallTime::now() - chomp_start_time).toSec(); std::cout << "The optimization time is: " << chomp_process_time << std::endl; int trajectory_size = optimized_trajectory.size(); std::ofstream data_file ("data.txt"); for (int i = 0; i < trajectory_size; i++) { Eigen::Vector3d point = optimized_trajectory.at(i); //ROS_INFO("the optimized trajectory is: x=%.2f, y=%.2f, z=%.2f", point(0), point(1), point(2)); //std::cout << point(0) << " " << point(1) << std::endl; data_file << point(0) << " " << point(1) << "\n"; } if (data_file.is_open()) { data_file.close(); } int trajectory_size = solution_path.size(); hdi_plan::point_array trajectory_msg; geometry_msgs::Point trajectory_point; for (int i = 0; i < trajectory_size; i++) { Eigen::Vector3d point = solution_path.at(i); trajectory_point.x = point(0); trajectory_point.y = point(1); trajectory_point.z = point(2); trajectory_msg.points.push_back(trajectory_point); //ROS_INFO("the optimized trajectory is: x=%.2f, y=%.2f, z=%.2f", point(0), point(1), point(2)); } //std_msgs::Bool get_new_path_msg; //get_new_path_msg.data = true; //pub_get_new_path_.publish(get_new_path_msg); ROS_INFO("Publish the path now1"); while (ros::ok()) { ROS_INFO("Start publish 1"); ros::Duration(1.0).sleep(); ROS_INFO("Start publish 2"); pub_optimized_path_.publish(trajectory_msg); ROS_INFO("Start publish 3"); ros::spinOnce(); loop_rate.sleep(); } return 0; } */ /* #include "generate_dynamic_scene/generate_obstacle.hpp" namespace hdi_plan { GenerateObstacle::GenerateObstacle(const ros::NodeHandle &nh, const ros::NodeHandle &pnh) : nh_(nh), pnh_(pnh) { // load parameters if (!this->load_params()) { ROS_WARN("[%s] Could not load all parameters in motion planner.", this->pnh_.getNamespace().c_str()); } else { ROS_INFO("[%s] Loaded all parameters in motion planner.", this->pnh_.getNamespace().c_str()); } ros::Duration(1.0).sleep(); publish_trajectory(); ROS_INFO("FInished"); } GenerateObstacle::~GenerateObstacle() = default; bool GenerateObstacle::load_params() { this->pnh_.getParam("total_planning_time", this->total_plan_time_); this->pnh_.getParam("quadrotor_radius", this->quadrotor_radius_); this->pnh_.getParam("quadrotor_speed", this->quadrotor_speed_); this->pnh_.getParam("collision_threshold", this->collision_threshold_); this->pnh_.getParam("planning_time_limit", this->planning_time_limit_); this->pnh_.getParam("max_iterations", this->max_iterations_); this->pnh_.getParam("max_iterations_after_collision_free", this->max_iterations_after_collision_free_); this->pnh_.getParam("learning_rate", this->learning_rate_); this->pnh_.getParam("obstacle_cost_weight", this->obstacle_cost_weight_); this->pnh_.getParam("dynamic_obstacle_cost_weight", this->dynamic_obstacle_cost_weight_); this->pnh_.getParam("dynamic_collision_factor", this->dynamic_collision_factor_); this->pnh_.getParam("smoothness_cost_weight", this->smoothness_cost_weight_); this->pnh_.getParam("smoothness_cost_velocity", this->smoothness_cost_velocity_); this->pnh_.getParam("smoothness_cost_acceleration", this->smoothness_cost_acceleration_); this->pnh_.getParam("smoothness_cost_jerk", this->smoothness_cost_jerk_); this->pnh_.getParam("ridge_factor", this->ridge_factor_); this->pnh_.getParam("min_clearence", this->min_clearence_); this->pnh_.getParam("joint_update_limit", this->joint_update_limit_); this->pnh_.getParam("discretization", this->discretization_); return true; } void GenerateObstacle::publish_trajectory() { std::vector<Eigen::Vector3d> solution_path; solution_path.resize(11); Eigen::Vector3d point_1(2.45292, 3.51743, 1.15095); solution_path[0] = point_1; Eigen::Vector3d point_2(3.67979, 5.12402, 1.01063); solution_path[1] = point_2; Eigen::Vector3d point_3(5.96799, 7.49909, 1.99399); solution_path[2] = point_3; Eigen::Vector3d point_4(6.16125, 9.16252, 2.19597); solution_path[3] = point_4; Eigen::Vector3d point_5(6.45006, 12.4731, 1.64777); solution_path[4] = point_5; Eigen::Vector3d point_6(9.49938, 13.6013, 1.80064); solution_path[5] = point_6; Eigen::Vector3d point_7(12.3138, 14.9923, 2.36284); solution_path[6] = point_7; Eigen::Vector3d point_8(14.7372, 17.1306, 1.78767); solution_path[7] = point_8; Eigen::Vector3d point_9(15.3523, 17.9035, 1.94358); solution_path[8] = point_9; Eigen::Vector3d point_10(17.815, 18.8867, 2.0752); solution_path[9] = point_10; Eigen::Vector3d point_11(20, 20, 2); solution_path[10] = point_11; std::vector<Eigen::Vector3d> solution_path; solution_path.resize(11); Eigen::Vector3d point_1(2.84782, 3.53338, 1.25199); solution_path[0] = point_1; Eigen::Vector3d point_2(3.548, 4.2471, 1.23326); solution_path[1] = point_2; Eigen::Vector3d point_3(5.7596, 6.63072, 1.24123); solution_path[2] = point_3; Eigen::Vector3d point_4(9.17822, 6.41438, 0.634579); solution_path[3] = point_4; Eigen::Vector3d point_5(10.4976, 6.69923, 0.639617); solution_path[4] = point_5; Eigen::Vector3d point_6(13.3017, 8.46523, 1.43444); solution_path[5] = point_6; Eigen::Vector3d point_7(14.3369, 10.4171, 0.835684); solution_path[6] = point_7; Eigen::Vector3d point_8(15.4546, 13.5029, 0.638429); solution_path[7] = point_8; Eigen::Vector3d point_9(17.4934, 15.2709, 1.26955); solution_path[8] = point_9; Eigen::Vector3d point_10(19.1406, 17.4181, 1.61743); solution_path[9] = point_10; Eigen::Vector3d point_11(20, 20, 2); solution_path[10] = point_11; std::vector<Eigen::Vector3d> solution_path; solution_path.resize(9); Eigen::Vector3d point_1(4.55281, 4.11356, 1.49805); solution_path[0] = point_1; Eigen::Vector3d point_2(3.78132, 6.6611, 1.01547); solution_path[1] = point_2; Eigen::Vector3d point_3(5.02077, 8.07318, 2.01937); solution_path[2] = point_3; Eigen::Vector3d point_4(5.65907, 9.77609, 1.20362); solution_path[3] = point_4; Eigen::Vector3d point_5(6.77827, 11.9087, 1.74742); solution_path[4] = point_5; Eigen::Vector3d point_6(7.67982, 15.0323, 1.52923); solution_path[5] = point_6; Eigen::Vector3d point_7(10.43, 17.0713, 1.81861); solution_path[6] = point_7; Eigen::Vector3d point_8(13.3463, 17.6473, 1.11981); solution_path[7] = point_8; Eigen::Vector3d point_9(16.4863, 18.2276, 1.60694); solution_path[7] = point_9; Eigen::Vector3d point_10(17.9467, 18.4052, 1.66529); solution_path[8] = point_10; Eigen::Vector3d point_11(20, 20, 2); solution_path[9] = point_11; std::ofstream data_file2("original_trajectory.txt"); for (int i = 0; i < static_cast<int>(solution_path.size()); i++) { Eigen::Vector3d point = solution_path.at(i); data_file2 << point(0) << " " << point(1) << " " << point(2) << "\n"; } if (data_file2.is_open()) { data_file2.close(); } std::map<std::string, std::shared_ptr<hdi_plan::Obstacle>> obstacle_map; std::map<int, std::shared_ptr<Human>> human_map; std::string obstacle_name = "cube1"; bool obstacle_operation = true; double obstacle_size = 3; Eigen::Vector3d obstacle_position(10.0, 10.0, 2.0); auto obstacle = std::make_shared<hdi_plan::Obstacle>(obstacle_name, hdi_plan::Obstacle_type::sphere, obstacle_operation, obstacle_size, obstacle_position); obstacle_map[obstacle_name] = obstacle; ros::WallTime chomp_start_time = ros::WallTime::now(); auto chomp_trajectory = std::make_shared<ChompTrajectory>(solution_path, 1.0 , this->total_plan_time_, this->discretization_, this->quadrotor_speed_); auto chomp = std::make_shared<Chomp>(this->collision_threshold_, this->planning_time_limit_, this->max_iterations_, this->max_iterations_after_collision_free_, this->learning_rate_, this->obstacle_cost_weight_, this->dynamic_obstacle_cost_weight_, this->dynamic_collision_factor_, this->smoothness_cost_weight_, this->smoothness_cost_velocity_, this->smoothness_cost_acceleration_, this->smoothness_cost_jerk_, this->ridge_factor_, this->min_clearence_, this->joint_update_limit_, this->quadrotor_radius_, chomp_trajectory, obstacle_map, human_map, 1); std::vector<Eigen::Vector3d> optimized_trajectory = chomp->get_optimized_trajectory(); double chomp_process_time = (ros::WallTime::now() - chomp_start_time).toSec(); std::cout << "The optimization time is: " << chomp_process_time << std::endl; std::ofstream data_file1("optimized_trajectory.txt"); for (int i = 0; i < static_cast<int>(optimized_trajectory.size()); i++) { Eigen::Vector3d point = optimized_trajectory.at(i); std::cout << point(0) << " " << point(1) << " " << point(2) << std::endl; data_file1 << point(0) << " " << point(1) << " " << point(2) << "\n"; } if (data_file1.is_open()) { data_file1.close(); } } }*/
38.201271
156
0.72941
test-bai-cpu
43c88c3fea02760d482c72abaff5c32fd5dacf78
7,110
cpp
C++
Eunoia-Engine/Src/Eunoia/Core/Input.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
Eunoia-Engine/Src/Eunoia/Core/Input.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
Eunoia-Engine/Src/Eunoia/Core/Input.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
#include "Input.h" #include <cstring> #ifdef EU_PLATFORM_WINDOWS #include "../Platform/Win32/DisplayWin32.h" #include <Xinput.h> #endif namespace Eunoia { u8 EUInput::s_Keys[]; u8 EUInput::s_LastKeys[]; u8 EUInput::s_Buttons[]; u8 EUInput::s_LastButtons[]; u16 EUInput::s_GamepadButtons[]; u16 EUInput::s_LastGamepadButtons[]; b32 EUInput::s_ActiveGamepads[]; r32 EUInput::s_GamepadTriggerValues[EU_MAX_GAMEPADS][EU_NUM_GAMEPAD_TRIGGERS]; b32 EUInput::s_LastGamepadTriggers[EU_MAX_GAMEPADS][EU_NUM_GAMEPAD_TRIGGERS]; v2 EUInput::s_GamepadThumbsticks[EU_MAX_GAMEPADS][EU_NUM_GAMEPAD_THUMBSTICKS]; char EUInput::s_CharMap[]; void EUInput::InitInput() { memset(s_Keys, false, EU_MAX_KEYS); memset(s_LastKeys, false, EU_MAX_KEYS); memset(s_Buttons, false, EU_MAX_MOUSE_BUTTONS); memset(s_LastButtons, false, EU_MAX_MOUSE_BUTTONS); memset(s_CharMap, 0, EU_MAX_KEYS); s_CharMap[EU_KEY_Q] = 'q'; s_CharMap[EU_KEY_W] = 'w'; s_CharMap[EU_KEY_E] = 'e'; s_CharMap[EU_KEY_R] = 'r'; s_CharMap[EU_KEY_T] = 't'; s_CharMap[EU_KEY_Y] = 'y'; s_CharMap[EU_KEY_U] = 'u'; s_CharMap[EU_KEY_I] = 'i'; s_CharMap[EU_KEY_O] = 'o'; s_CharMap[EU_KEY_P] = 'p'; s_CharMap[EU_KEY_A] = 'a'; s_CharMap[EU_KEY_S] = 's'; s_CharMap[EU_KEY_D] = 'd'; s_CharMap[EU_KEY_F] = 'f'; s_CharMap[EU_KEY_G] = 'g'; s_CharMap[EU_KEY_H] = 'h'; s_CharMap[EU_KEY_J] = 'j'; s_CharMap[EU_KEY_K] = 'k'; s_CharMap[EU_KEY_L] = 'l'; s_CharMap[EU_KEY_Z] = 'z'; s_CharMap[EU_KEY_X] = 'x'; s_CharMap[EU_KEY_C] = 'c'; s_CharMap[EU_KEY_V] = 'v'; s_CharMap[EU_KEY_B] = 'b'; s_CharMap[EU_KEY_N] = 'n'; s_CharMap[EU_KEY_M] = 'm'; s_CharMap[EU_KEY_SPACE] = ' '; s_CharMap[EU_KEY_1] = '1'; s_CharMap[EU_KEY_2] = '2'; s_CharMap[EU_KEY_3] = '3'; s_CharMap[EU_KEY_4] = '4'; s_CharMap[EU_KEY_5] = '5'; s_CharMap[EU_KEY_6] = '6'; s_CharMap[EU_KEY_7] = '7'; s_CharMap[EU_KEY_8] = '8'; s_CharMap[EU_KEY_9] = '9'; s_CharMap[EU_KEY_0] = '0'; s_CharMap[EU_KEY_PERIOD] = '.'; s_CharMap[EU_KEY_COMMA] = ','; s_CharMap[EU_KEY_SLASH] = ','; s_CharMap[EU_KEY_SEMI_COLON] = ':'; s_CharMap[EU_KEY_QUOTE] = '\''; s_CharMap[EU_KEY_LEFT_BRACKET] = '['; s_CharMap[EU_KEY_RIGHT_BRACKET] = ']'; s_CharMap[EU_KEY_BACK_SLASH] = '\\'; s_CharMap[EU_KEY_DASH] = '-'; s_CharMap[EU_KEY_EQUALS] = '='; s_CharMap[EU_KEY_TILDE] = '`'; } void EUInput::BeginInput() { #ifdef EU_PLATFORM_WINDOWS XINPUT_STATE state{}; for (u32 i = 0; i < XUSER_MAX_COUNT; i++) { if (XInputGetState(i, &state) != ERROR_SUCCESS) { s_ActiveGamepads[i] = false; continue; } s_ActiveGamepads[i] = true; s_GamepadButtons[i] = state.Gamepad.wButtons; s_GamepadTriggerValues[i][EU_GAMEPAD_XBOX360_TRIGGER_LT] = (r32)state.Gamepad.bLeftTrigger / 255.0f; s_GamepadTriggerValues[i][EU_GAMEPAD_XBOX360_TRIGGER_RT] = (r32)state.Gamepad.bRightTrigger / 255.0f; s_GamepadThumbsticks[i][EU_GAMEPAD_XBOX360_THUMBSTICK_LEFT] = v2(EU_MAX(-1.0f, (r32)state.Gamepad.sThumbLX / 32767.0f), EU_MAX(-1.0f, (r32)state.Gamepad.sThumbLY / 32767.0f)); s_GamepadThumbsticks[i][EU_GAMEPAD_XBOX360_THUMBSTICK_RIGHT] = v2(EU_MAX(-1.0f, (r32)state.Gamepad.sThumbRX / 32767.0f), EU_MAX(-1.0f, (r32)state.Gamepad.sThumbRY / 32767.0f)); } #endif } void EUInput::UpdateInput() { memcpy(s_LastKeys, s_Keys, EU_MAX_KEYS); memcpy(s_LastButtons, s_Buttons,EU_MAX_MOUSE_BUTTONS); for (u32 i = 0; i < EU_MAX_GAMEPADS; i++) { s_LastGamepadButtons[i] = s_GamepadButtons[i]; s_LastGamepadTriggers[i][EU_GAMEPAD_XBOX360_TRIGGER_LT] = s_GamepadTriggerValues[i][EU_GAMEPAD_XBOX360_TRIGGER_LT] >= 0.0f; s_LastGamepadTriggers[i][EU_GAMEPAD_XBOX360_TRIGGER_RT] = s_GamepadTriggerValues[i][EU_GAMEPAD_XBOX360_TRIGGER_RT] >= 0.0f; } } void EUInput::DestroyInput() { } b32 EUInput::IsKeyDown(Key key) { return s_Keys[key]; } b32 EUInput::IsKeyPressed(Key key) { return s_Keys[key] && !s_LastKeys[key]; } b32 EUInput::IsKeyRelease(Key key) { return !s_Keys[key] && s_LastKeys[key]; } b32 EUInput::IsButtonDown(MouseButton button) { return s_Buttons[button]; } b32 EUInput::IsButtonPressed(MouseButton button) { return s_Buttons[button] && !s_LastButtons[button]; } b32 EUInput::IsButtonRelease(MouseButton button) { return !s_Buttons[button] && s_LastButtons[button]; } b32 EUInput::IsGamepadActive(Gamepad gamepad) { return s_ActiveGamepads[gamepad]; } b32 EUInput::IsGamepadButtonDown(Gamepad gamepad, GamepadButton button) { if (button == EU_GAMEPAD_XBOX360_BUTTON_LT) return s_GamepadTriggerValues[gamepad][EU_GAMEPAD_XBOX360_TRIGGER_LT] > 0.0f; else if (button == EU_GAMEPAD_XBOX360_BUTTON_RT) return s_GamepadTriggerValues[gamepad][EU_GAMEPAD_XBOX360_TRIGGER_RT] > 0.0f; return (s_GamepadButtons[gamepad] & button); } b32 EUInput::IsGamepadButtonPressed(Gamepad gamepad, GamepadButton button) { if (button == EU_GAMEPAD_XBOX360_BUTTON_LT) return s_GamepadTriggerValues[gamepad][EU_GAMEPAD_XBOX360_TRIGGER_LT] > 0.0f && !s_LastGamepadTriggers[EU_GAMEPAD_XBOX360_TRIGGER_LT]; else if (button == EU_GAMEPAD_XBOX360_BUTTON_RT) return s_GamepadTriggerValues[gamepad][EU_GAMEPAD_XBOX360_TRIGGER_RT] > 0.0f && !s_LastGamepadTriggers[EU_GAMEPAD_XBOX360_TRIGGER_RT]; return (s_GamepadButtons[gamepad] & button) && !(s_LastGamepadButtons[gamepad] & button); } b32 EUInput::IsGamepadButtonReleased(Gamepad gamepad, GamepadButton button) { if (button == EU_GAMEPAD_XBOX360_BUTTON_LT) return !(s_GamepadTriggerValues[gamepad][EU_GAMEPAD_XBOX360_TRIGGER_LT] > 0.0f) && s_LastGamepadTriggers[EU_GAMEPAD_XBOX360_TRIGGER_LT]; else if (button == EU_GAMEPAD_XBOX360_BUTTON_RT) return !(s_GamepadTriggerValues[gamepad][EU_GAMEPAD_XBOX360_TRIGGER_RT] > 0.0f) && s_LastGamepadTriggers[EU_GAMEPAD_XBOX360_TRIGGER_RT]; return !(s_GamepadButtons[gamepad] & button) && (s_LastGamepadButtons[gamepad] & button); } r32 EUInput::GetGamepadTriggerAmount(Gamepad gamepad, GamepadTrigger trigger) { return s_GamepadTriggerValues[gamepad][trigger]; } v2 EUInput::GetGamepadThumbstick(Gamepad gamepad, GamepadThumbstick thumbstick) { return s_GamepadThumbsticks[gamepad][thumbstick]; } char EUInput::GetChar(Key key) { char c = s_CharMap[key]; if (s_Keys[EU_KEY_LEFT_SHIFT] || s_Keys[EU_KEY_RIGHT_SHIFT]) { if (c >= 'a' && c <= 'z') return toupper(c); else if (c == '1') return '!'; else if (c == '2') return '@'; else if (c == '3') return '#'; else if (c == '4') return '$'; else if (c == '5') return '%'; else if (c == '6') return '^'; else if (c == '7') return '&'; else if (c == '8') return '*'; else if (c == '9') return '('; else if (c == '0') return ')'; else if (c == '`') return '~'; else if (c == '-') return '_'; else if (c == '=') return '+'; else if (c == '[') return '{'; else if (c == ']') return '}'; else if (c == '\\') return '|'; else if (c == ';') return ':'; else if (c == '\'') return '"'; else if (c == ',') return '<'; else if (c == '.') return '>'; else if (c == '/') return '?'; else return c; } else { return c; } } }
34.019139
179
0.696624
EunoiaGames
43cadcd456e0e1111e6607e5d3880b571da0f6fb
46,798
cpp
C++
Src/C_BaseLib/FabArray.cpp
dappelha/BoxLib-omp4-Hackathon2016
d35c11aaa85eed03baa04317c346921a349fdfcf
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/C_BaseLib/FabArray.cpp
dappelha/BoxLib-omp4-Hackathon2016
d35c11aaa85eed03baa04317c346921a349fdfcf
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/C_BaseLib/FabArray.cpp
dappelha/BoxLib-omp4-Hackathon2016
d35c11aaa85eed03baa04317c346921a349fdfcf
[ "BSD-3-Clause-LBNL" ]
1
2019-08-06T13:09:09.000Z
2019-08-06T13:09:09.000Z
#include <winstd.H> #include <iterator> #include <numeric> #ifdef BL_LAZY #include <Lazy.H> #endif #include <Utility.H> #include <FabArray.H> #include <ParmParse.H> #include <Geometry.H> #ifdef BL_MEM_PROFILING #include <MemProfiler.H> #endif // // Set default values in Initialize()!!! // bool FabArrayBase::do_async_sends; int FabArrayBase::MaxComp; #if BL_SPACEDIM == 1 IntVect FabArrayBase::mfiter_tile_size(1024000); #elif BL_SPACEDIM == 2 IntVect FabArrayBase::mfiter_tile_size(1024000,1024000); #else IntVect FabArrayBase::mfiter_tile_size(1024000,8,8); #endif IntVect FabArrayBase::comm_tile_size(D_DECL(1024000, 8, 8)); IntVect FabArrayBase::mfghostiter_tile_size(D_DECL(1024000, 8, 8)); int FabArrayBase::nFabArrays(0); FabArrayBase::TACache FabArrayBase::m_TheTileArrayCache; FabArrayBase::FBCache FabArrayBase::m_TheFBCache; FabArrayBase::CPCache FabArrayBase::m_TheCPCache; FabArrayBase::FPinfoCache FabArrayBase::m_TheFillPatchCache; FabArrayBase::CacheStats FabArrayBase::m_TAC_stats("TileArrayCache"); FabArrayBase::CacheStats FabArrayBase::m_FBC_stats("FBCache"); FabArrayBase::CacheStats FabArrayBase::m_CPC_stats("CopyCache"); FabArrayBase::CacheStats FabArrayBase::m_FPinfo_stats("FillPatchCache"); std::map<FabArrayBase::BDKey, int> FabArrayBase::m_BD_count; FabArrayBase::FabArrayStats FabArrayBase::m_FA_stats; namespace { bool initialized = false; } bool FabArrayBase::IsInitialized () const { return initialized; } void FabArrayBase::SetInitialized (bool binit) { initialized = binit; } void FabArrayBase::Initialize () { if (initialized) return; // // Set default values here!!! // FabArrayBase::do_async_sends = true; FabArrayBase::MaxComp = 25; ParmParse pp("fabarray"); Array<int> tilesize(BL_SPACEDIM); if (pp.queryarr("mfiter_tile_size", tilesize, 0, BL_SPACEDIM)) { for (int i=0; i<BL_SPACEDIM; i++) FabArrayBase::mfiter_tile_size[i] = tilesize[i]; } if (pp.queryarr("mfghostiter_tile_size", tilesize, 0, BL_SPACEDIM)) { for (int i=0; i<BL_SPACEDIM; i++) FabArrayBase::mfghostiter_tile_size[i] = tilesize[i]; } if (pp.queryarr("comm_tile_size", tilesize, 0, BL_SPACEDIM)) { for (int i=0; i<BL_SPACEDIM; i++) FabArrayBase::comm_tile_size[i] = tilesize[i]; } pp.query("maxcomp", FabArrayBase::MaxComp); pp.query("do_async_sends", FabArrayBase::do_async_sends); if (MaxComp < 1) MaxComp = 1; FabArrayBase::nFabArrays = 0; BoxLib::ExecOnFinalize(FabArrayBase::Finalize); #ifdef BL_MEM_PROFILING MemProfiler::add(m_TAC_stats.name, std::function<MemProfiler::MemInfo()> ([] () -> MemProfiler::MemInfo { return {m_TAC_stats.bytes, m_TAC_stats.bytes_hwm}; })); MemProfiler::add(m_FBC_stats.name, std::function<MemProfiler::MemInfo()> ([] () -> MemProfiler::MemInfo { return {m_FBC_stats.bytes, m_FBC_stats.bytes_hwm}; })); MemProfiler::add(m_CPC_stats.name, std::function<MemProfiler::MemInfo()> ([] () -> MemProfiler::MemInfo { return {m_CPC_stats.bytes, m_CPC_stats.bytes_hwm}; })); MemProfiler::add(m_FPinfo_stats.name, std::function<MemProfiler::MemInfo()> ([] () -> MemProfiler::MemInfo { return {m_FPinfo_stats.bytes, m_FPinfo_stats.bytes_hwm}; })); #endif initialized = true; } FabArrayBase::FabArrayBase () { Initialize(); aFAPId = nFabArrays++; aFAPIdLock = 0; // ---- not locked } FabArrayBase::~FabArrayBase () {} Box FabArrayBase::fabbox (int K) const { return BoxLib::grow(boxarray[K], n_grow); } long FabArrayBase::bytesOfMapOfCopyComTagContainers (const FabArrayBase::MapOfCopyComTagContainers& m) { long r = sizeof(MapOfCopyComTagContainers); for (MapOfCopyComTagContainers::const_iterator it = m.begin(); it != m.end(); ++it) { r += sizeof(it->first) + BoxLib::bytesOf(it->second) + BoxLib::gcc_map_node_extra_bytes; } return r; } long FabArrayBase::CPC::bytes () const { long cnt = sizeof(FabArrayBase::CPC); if (m_LocTags) cnt += BoxLib::bytesOf(*m_LocTags); if (m_SndTags) cnt += FabArrayBase::bytesOfMapOfCopyComTagContainers(*m_SndTags); if (m_RcvTags) cnt += FabArrayBase::bytesOfMapOfCopyComTagContainers(*m_RcvTags); if (m_SndVols) cnt += BoxLib::bytesOf(*m_SndVols); if (m_RcvVols) cnt += BoxLib::bytesOf(*m_RcvVols); return cnt; } long FabArrayBase::FB::bytes () const { int cnt = sizeof(FabArrayBase::FB); if (m_LocTags) cnt += BoxLib::bytesOf(*m_LocTags); if (m_SndTags) cnt += FabArrayBase::bytesOfMapOfCopyComTagContainers(*m_SndTags); if (m_RcvTags) cnt += FabArrayBase::bytesOfMapOfCopyComTagContainers(*m_RcvTags); if (m_SndVols) cnt += BoxLib::bytesOf(*m_SndVols); if (m_RcvVols) cnt += BoxLib::bytesOf(*m_RcvVols); return cnt; } long FabArrayBase::TileArray::bytes () const { return sizeof(*this) + (BoxLib::bytesOf(this->indexMap) - sizeof(this->indexMap)) + (BoxLib::bytesOf(this->localIndexMap) - sizeof(this->localIndexMap)) + (BoxLib::bytesOf(this->tileArray) - sizeof(this->tileArray)); } // // Stuff used for copy() caching. // FabArrayBase::CPC::CPC (const FabArrayBase& dstfa, int dstng, const FabArrayBase& srcfa, int srcng, const Periodicity& period) : m_srcbdk(srcfa.getBDKey()), m_dstbdk(dstfa.getBDKey()), m_srcng(srcng), m_dstng(dstng), m_period(period), m_srcba(srcfa.boxArray()), m_dstba(dstfa.boxArray()), m_threadsafe_loc(false), m_threadsafe_rcv(false), m_LocTags(0), m_SndTags(0), m_RcvTags(0), m_SndVols(0), m_RcvVols(0), m_nuse(0) { this->define(m_dstba, dstfa.DistributionMap(), dstfa.IndexArray(), m_srcba, srcfa.DistributionMap(), srcfa.IndexArray()); } FabArrayBase::CPC::CPC (const BoxArray& dstba, const DistributionMapping& dstdm, const Array<int>& dstidx, int dstng, const BoxArray& srcba, const DistributionMapping& srcdm, const Array<int>& srcidx, int srcng, const Periodicity& period, int myproc) : m_srcbdk(0,0), m_dstbdk(0,0), m_srcng(srcng), m_dstng(dstng), m_period(period), m_srcba(srcba), m_dstba(dstba), m_threadsafe_loc(false), m_threadsafe_rcv(false), m_LocTags(0), m_SndTags(0), m_RcvTags(0), m_SndVols(0), m_RcvVols(0), m_nuse(0) { this->define(dstba, dstdm, dstidx, srcba, srcdm, srcidx, myproc); } FabArrayBase::CPC::~CPC () { delete m_LocTags; delete m_SndTags; delete m_RcvTags; delete m_SndVols; delete m_RcvVols; } void FabArrayBase::CPC::define (const BoxArray& ba_dst, const DistributionMapping& dm_dst, const Array<int>& imap_dst, const BoxArray& ba_src, const DistributionMapping& dm_src, const Array<int>& imap_src, int MyProc) { BL_PROFILE("FabArrayBase::CPC::define()"); BL_ASSERT(ba_dst.size() > 0 && ba_src.size() > 0); BL_ASSERT(ba_dst.ixType() == ba_src.ixType()); m_LocTags = new CopyComTag::CopyComTagsContainer; m_SndTags = new CopyComTag::MapOfCopyComTagContainers; m_RcvTags = new CopyComTag::MapOfCopyComTagContainers; m_SndVols = new std::map<int,int>; m_RcvVols = new std::map<int,int>; if (!(imap_dst.empty() && imap_src.empty())) { const int nlocal_src = imap_src.size(); const int ng_src = m_srcng; const int nlocal_dst = imap_dst.size(); const int ng_dst = m_dstng; std::vector< std::pair<int,Box> > isects; const std::vector<IntVect>& pshifts = m_period.shiftIntVect(); CopyComTag::MapOfCopyComTagContainers send_tags; // temp copy for (int i = 0; i < nlocal_src; ++i) { const int k_src = imap_src[i]; const Box& bx_src = BoxLib::grow(ba_src[k_src], ng_src); for (std::vector<IntVect>::const_iterator pit=pshifts.begin(); pit!=pshifts.end(); ++pit) { ba_dst.intersections(bx_src+(*pit), isects, false, ng_dst); for (int j = 0, M = isects.size(); j < M; ++j) { const int k_dst = isects[j].first; const Box& bx = isects[j].second; const int dst_owner = dm_dst[k_dst]; if (ParallelDescriptor::sameTeam(dst_owner)) { continue; // local copy will be dealt with later } else if (MyProc == dm_src[k_src]) { send_tags[dst_owner].push_back(CopyComTag(bx, bx-(*pit), k_dst, k_src)); } } } } CopyComTag::MapOfCopyComTagContainers recv_tags; // temp copy BaseFab<int> localtouch, remotetouch; bool check_local = false, check_remote = false; #ifdef _OPENMP if (omp_get_max_threads() > 1) { check_local = true; check_remote = true; } #endif if (ParallelDescriptor::TeamSize() > 1) { check_local = true; } for (int i = 0; i < nlocal_dst; ++i) { const int k_dst = imap_dst[i]; const Box& bx_dst = BoxLib::grow(ba_dst[k_dst], ng_dst); if (check_local) { localtouch.resize(bx_dst); localtouch.setVal(0); } if (check_remote) { remotetouch.resize(bx_dst); remotetouch.setVal(0); } for (std::vector<IntVect>::const_iterator pit=pshifts.begin(); pit!=pshifts.end(); ++pit) { ba_src.intersections(bx_dst+(*pit), isects, false, ng_src); for (int j = 0, M = isects.size(); j < M; ++j) { const int k_src = isects[j].first; const Box& bx = isects[j].second - *pit; const int src_owner = dm_src[k_src]; if (ParallelDescriptor::sameTeam(src_owner, MyProc)) { // local copy const BoxList tilelist(bx, FabArrayBase::comm_tile_size); for (BoxList::const_iterator it_tile = tilelist.begin(), End_tile = tilelist.end(); it_tile != End_tile; ++it_tile) { m_LocTags->push_back(CopyComTag(*it_tile, (*it_tile)+(*pit), k_dst, k_src)); } if (check_local) { localtouch.plus(1, bx); } } else if (MyProc == dm_dst[k_dst]) { recv_tags[src_owner].push_back(CopyComTag(bx, bx+(*pit), k_dst, k_src)); if (check_remote) { remotetouch.plus(1, bx); } } } } if (check_local) { // safe if a cell is touched no more than once // keep checking thread safety if it is safe so far check_local = m_threadsafe_loc = localtouch.max() <= 1; } if (check_remote) { check_remote = m_threadsafe_rcv = remotetouch.max() <= 1; } } for (int ipass = 0; ipass < 2; ++ipass) // pass 0: send; pass 1: recv { CopyComTag::MapOfCopyComTagContainers & Tags = (ipass == 0) ? *m_SndTags : *m_RcvTags; CopyComTag::MapOfCopyComTagContainers & tmpTags = (ipass == 0) ? send_tags : recv_tags; std::map<int,int> & Vols = (ipass == 0) ? *m_SndVols : *m_RcvVols; for (CopyComTag::MapOfCopyComTagContainers::iterator it = tmpTags.begin(), End = tmpTags.end(); it != End; ++it) { const int key = it->first; std::vector<CopyComTag>& cctv = it->second; // We need to fix the order so that the send and recv processes match. std::sort(cctv.begin(), cctv.end()); std::vector<CopyComTag> new_cctv; new_cctv.reserve(cctv.size()); for (std::vector<CopyComTag>::const_iterator it2 = cctv.begin(), End2 = cctv.end(); it2 != End2; ++it2) { const Box& bx = it2->dbox; const IntVect& d2s = it2->sbox.smallEnd() - it2->dbox.smallEnd(); Vols[key] += bx.numPts(); const BoxList tilelist(bx, FabArrayBase::comm_tile_size); for (BoxList::const_iterator it_tile = tilelist.begin(), End_tile = tilelist.end(); it_tile != End_tile; ++it_tile) { new_cctv.push_back(CopyComTag(*it_tile, (*it_tile)+d2s, it2->dstIndex, it2->srcIndex)); } } Tags[key].swap(new_cctv); } } } } void FabArrayBase::flushCPC (bool no_assertion) const { BL_ASSERT(no_assertion || getBDKey() == m_bdkey); std::vector<CPCacheIter> others; std::pair<CPCacheIter,CPCacheIter> er_it = m_TheCPCache.equal_range(m_bdkey); for (CPCacheIter it = er_it.first; it != er_it.second; ++it) { const BDKey& srckey = it->second->m_srcbdk; const BDKey& dstkey = it->second->m_dstbdk; BL_ASSERT((srckey==dstkey && srckey==m_bdkey) || (m_bdkey==srckey) || (m_bdkey==dstkey)); if (srckey != dstkey) { const BDKey& otherkey = (m_bdkey == srckey) ? dstkey : srckey; std::pair<CPCacheIter,CPCacheIter> o_er_it = m_TheCPCache.equal_range(otherkey); for (CPCacheIter oit = o_er_it.first; oit != o_er_it.second; ++oit) { if (it->second == oit->second) others.push_back(oit); } } #ifdef BL_MEM_PROFILING m_CPC_stats.bytes -= it->second->bytes(); #endif m_CPC_stats.recordErase(it->second->m_nuse); delete it->second; } m_TheCPCache.erase(er_it.first, er_it.second); for (std::vector<CPCacheIter>::iterator it = others.begin(), End = others.end(); it != End; ++it) { m_TheCPCache.erase(*it); } } void FabArrayBase::flushCPCache () { for (CPCacheIter it = m_TheCPCache.begin(); it != m_TheCPCache.end(); ++it) { if (it->first == it->second->m_srcbdk) { m_CPC_stats.recordErase(it->second->m_nuse); delete it->second; } } m_TheCPCache.clear(); #ifdef BL_MEM_PROFILING m_CPC_stats.bytes = 0L; #endif } const FabArrayBase::CPC& FabArrayBase::getCPC (int dstng, const FabArrayBase& src, int srcng, const Periodicity& period) const { BL_PROFILE("FabArrayBase::getCPC()"); BL_ASSERT(getBDKey() == m_bdkey); BL_ASSERT(src.getBDKey() == src.m_bdkey); BL_ASSERT(boxArray().ixType() == src.boxArray().ixType()); const BDKey& srckey = src.getBDKey(); const BDKey& dstkey = getBDKey(); std::pair<CPCacheIter,CPCacheIter> er_it = m_TheCPCache.equal_range(dstkey); for (CPCacheIter it = er_it.first; it != er_it.second; ++it) { if (it->second->m_srcng == srcng && it->second->m_dstng == dstng && it->second->m_srcbdk == srckey && it->second->m_dstbdk == dstkey && it->second->m_period == period && it->second->m_srcba == src.boxArray() && it->second->m_dstba == boxArray()) { ++(it->second->m_nuse); m_CPC_stats.recordUse(); return *(it->second); } } // Have to build a new one CPC* new_cpc = new CPC(*this, dstng, src, srcng, period); #ifdef BL_MEM_PROFILING m_CPC_stats.bytes += new_cpc->bytes(); m_CPC_stats.bytes_hwm = std::max(m_CPC_stats.bytes_hwm, m_CPC_stats.bytes); #endif new_cpc->m_nuse = 1; m_CPC_stats.recordBuild(); m_CPC_stats.recordUse(); m_TheCPCache.insert(er_it.second, CPCache::value_type(dstkey,new_cpc)); if (srckey != dstkey) m_TheCPCache.insert( CPCache::value_type(srckey,new_cpc)); return *new_cpc; } // // Some stuff for fill boundary // FabArrayBase::FB::FB (const FabArrayBase& fa, bool cross, const Periodicity& period, bool enforce_periodicity_only) : m_typ(fa.boxArray().ixType()), m_ngrow(fa.nGrow()), m_cross(cross), m_epo(enforce_periodicity_only), m_period(period), m_threadsafe_loc(false), m_threadsafe_rcv(false), m_LocTags(new CopyComTag::CopyComTagsContainer), m_SndTags(new CopyComTag::MapOfCopyComTagContainers), m_RcvTags(new CopyComTag::MapOfCopyComTagContainers), m_SndVols(new std::map<int,int>), m_RcvVols(new std::map<int,int>), m_nuse(0) { BL_PROFILE("FabArrayBase::FB::FB()"); if (!fa.IndexArray().empty()) { if (enforce_periodicity_only) { BL_ASSERT(m_cross==false); define_epo(fa); } else { define_fb(fa); } } } void FabArrayBase::FB::define_fb(const FabArrayBase& fa) { const int MyProc = ParallelDescriptor::MyProc(); const BoxArray& ba = fa.boxArray(); const DistributionMapping& dm = fa.DistributionMap(); const Array<int>& imap = fa.IndexArray(); BL_ASSERT(BoxLib::convert(ba,IndexType::TheCellType()).isDisjoint()); // For local copy, all workers in the same team will have the identical copy of tags // so that they can share work. But for remote communication, they are all different. const int nlocal = imap.size(); const int ng = m_ngrow; const IndexType& typ = ba.ixType(); std::vector< std::pair<int,Box> > isects; const std::vector<IntVect>& pshifts = m_period.shiftIntVect(); CopyComTag::MapOfCopyComTagContainers send_tags; // temp copy for (int i = 0; i < nlocal; ++i) { const int ksnd = imap[i]; const Box& vbx = ba[ksnd]; for (std::vector<IntVect>::const_iterator pit=pshifts.begin(); pit!=pshifts.end(); ++pit) { ba.intersections(vbx+(*pit), isects, false, ng); for (int j = 0, M = isects.size(); j < M; ++j) { const int krcv = isects[j].first; const Box& bx = isects[j].second; const int dst_owner = dm[krcv]; if (ParallelDescriptor::sameTeam(dst_owner)) { continue; // local copy will be dealt with later } else if (MyProc == dm[ksnd]) { const BoxList& bl = BoxLib::boxDiff(bx, ba[krcv]); for (BoxList::const_iterator lit = bl.begin(); lit != bl.end(); ++lit) send_tags[dst_owner].push_back(CopyComTag(*lit, (*lit)-(*pit), krcv, ksnd)); } } } } CopyComTag::MapOfCopyComTagContainers recv_tags; // temp copy BaseFab<int> localtouch, remotetouch; bool check_local = false, check_remote = false; #ifdef _OPENMP if (omp_get_max_threads() > 1) { check_local = true; check_remote = true; } #endif if (ParallelDescriptor::TeamSize() > 1) { check_local = true; } if (typ.cellCentered()) { m_threadsafe_loc = true; m_threadsafe_rcv = true; check_local = false; check_remote = false; } for (int i = 0; i < nlocal; ++i) { const int krcv = imap[i]; const Box& vbx = ba[krcv]; const Box& bxrcv = BoxLib::grow(vbx, ng); if (check_local) { localtouch.resize(bxrcv); localtouch.setVal(0); } if (check_remote) { remotetouch.resize(bxrcv); remotetouch.setVal(0); } for (std::vector<IntVect>::const_iterator pit=pshifts.begin(); pit!=pshifts.end(); ++pit) { ba.intersections(bxrcv+(*pit), isects); for (int j = 0, M = isects.size(); j < M; ++j) { const int ksnd = isects[j].first; const Box& dst_bx = isects[j].second - *pit; const int src_owner = dm[ksnd]; const BoxList& bl = BoxLib::boxDiff(dst_bx, vbx); for (BoxList::const_iterator lit = bl.begin(); lit != bl.end(); ++lit) { const Box& blbx = *lit; if (ParallelDescriptor::sameTeam(src_owner)) { // local copy const BoxList tilelist(blbx, FabArrayBase::comm_tile_size); for (BoxList::const_iterator it_tile = tilelist.begin(), End_tile = tilelist.end(); it_tile != End_tile; ++it_tile) { m_LocTags->push_back(CopyComTag(*it_tile, (*it_tile)+(*pit), krcv, ksnd)); } if (check_local) { localtouch.plus(1, blbx); } } else if (MyProc == dm[krcv]) { recv_tags[src_owner].push_back(CopyComTag(blbx, blbx+(*pit), krcv, ksnd)); if (check_remote) { remotetouch.plus(1, blbx); } } } } } if (check_local) { // safe if a cell is touched no more than once // keep checking thread safety if it is safe so far check_local = m_threadsafe_loc = localtouch.max() <= 1; } if (check_remote) { check_remote = m_threadsafe_rcv = remotetouch.max() <= 1; } } for (int ipass = 0; ipass < 2; ++ipass) // pass 0: send; pass 1: recv { CopyComTag::MapOfCopyComTagContainers & Tags = (ipass == 0) ? *m_SndTags : *m_RcvTags; CopyComTag::MapOfCopyComTagContainers & tmpTags = (ipass == 0) ? send_tags : recv_tags; std::map<int,int> & Vols = (ipass == 0) ? *m_SndVols : *m_RcvVols; for (CopyComTag::MapOfCopyComTagContainers::iterator it = tmpTags.begin(), End = tmpTags.end(); it != End; ++it) { const int key = it->first; std::vector<CopyComTag>& cctv = it->second; // We need to fix the order so that the send and recv processes match. std::sort(cctv.begin(), cctv.end()); std::vector<CopyComTag> new_cctv; new_cctv.reserve(cctv.size()); for (std::vector<CopyComTag>::const_iterator it2 = cctv.begin(), End2 = cctv.end(); it2 != End2; ++it2) { const Box& bx = it2->dbox; const IntVect& d2s = it2->sbox.smallEnd() - it2->dbox.smallEnd(); std::vector<Box> boxes; int vol = 0; if (m_cross) { const Box& dstvbx = ba[it2->dstIndex]; for (int dir = 0; dir < BL_SPACEDIM; dir++) { Box lo = dstvbx; lo.setSmall(dir, dstvbx.smallEnd(dir) - ng); lo.setBig (dir, dstvbx.smallEnd(dir) - 1); lo &= bx; if (lo.ok()) { boxes.push_back(lo); vol += lo.numPts(); } Box hi = dstvbx; hi.setSmall(dir, dstvbx.bigEnd(dir) + 1); hi.setBig (dir, dstvbx.bigEnd(dir) + ng); hi &= bx; if (hi.ok()) { boxes.push_back(hi); vol += hi.numPts(); } } } else { boxes.push_back(bx); vol += bx.numPts(); } if (vol > 0) { Vols[key] += vol; for (std::vector<Box>::const_iterator it_bx = boxes.begin(), End_bx = boxes.end(); it_bx != End_bx; ++it_bx) { const BoxList tilelist(*it_bx, FabArrayBase::comm_tile_size); for (BoxList::const_iterator it_tile = tilelist.begin(), End_tile = tilelist.end(); it_tile != End_tile; ++it_tile) { new_cctv.push_back(CopyComTag(*it_tile, (*it_tile)+d2s, it2->dstIndex, it2->srcIndex)); } } } } if (!new_cctv.empty()) { Tags[key].swap(new_cctv); } } } } void FabArrayBase::FB::define_epo (const FabArrayBase& fa) { const int MyProc = ParallelDescriptor::MyProc(); const BoxArray& ba = fa.boxArray(); const DistributionMapping& dm = fa.DistributionMap(); const Array<int>& imap = fa.IndexArray(); // For local copy, all workers in the same team will have the identical copy of tags // so that they can share work. But for remote communication, they are all different. const int nlocal = imap.size(); const int ng = m_ngrow; const IndexType& typ = ba.ixType(); std::vector< std::pair<int,Box> > isects; const std::vector<IntVect>& pshifts = m_period.shiftIntVect(); CopyComTag::MapOfCopyComTagContainers send_tags; // temp copy Box pdomain = m_period.Domain(); pdomain.convert(typ); for (int i = 0; i < nlocal; ++i) { const int ksnd = imap[i]; Box bxsnd = BoxLib::grow(ba[ksnd],ng); bxsnd &= pdomain; // source must be inside the periodic domain. if (!bxsnd.ok()) continue; for (std::vector<IntVect>::const_iterator pit=pshifts.begin(); pit!=pshifts.end(); ++pit) { if (*pit != IntVect::TheZeroVector()) { ba.intersections(bxsnd+(*pit), isects, false, ng); for (int j = 0, M = isects.size(); j < M; ++j) { const int krcv = isects[j].first; const Box& bx = isects[j].second; const int dst_owner = dm[krcv]; if (ParallelDescriptor::sameTeam(dst_owner)) { continue; // local copy will be dealt with later } else if (MyProc == dm[ksnd]) { const BoxList& bl = BoxLib::boxDiff(bx, pdomain); for (BoxList::const_iterator lit = bl.begin(); lit != bl.end(); ++lit) { send_tags[dst_owner].push_back(CopyComTag(*lit, (*lit)-(*pit), krcv, ksnd)); } } } } } } CopyComTag::MapOfCopyComTagContainers recv_tags; // temp copy BaseFab<int> localtouch, remotetouch; bool check_local = false, check_remote = false; #ifdef _OPENMP if (omp_get_max_threads() > 1) { check_local = true; check_remote = true; } #endif if (ParallelDescriptor::TeamSize() > 1) { check_local = true; } for (int i = 0; i < nlocal; ++i) { const int krcv = imap[i]; const Box& vbx = ba[krcv]; const Box& bxrcv = BoxLib::grow(vbx, ng); if (pdomain.contains(bxrcv)) continue; if (check_local) { localtouch.resize(bxrcv); localtouch.setVal(0); } if (check_remote) { remotetouch.resize(bxrcv); remotetouch.setVal(0); } for (std::vector<IntVect>::const_iterator pit=pshifts.begin(); pit!=pshifts.end(); ++pit) { if (*pit != IntVect::TheZeroVector()) { ba.intersections(bxrcv+(*pit), isects, false, ng); for (int j = 0, M = isects.size(); j < M; ++j) { const int ksnd = isects[j].first; const Box& dst_bx = isects[j].second - *pit; const int src_owner = dm[ksnd]; const BoxList& bl = BoxLib::boxDiff(dst_bx, pdomain); for (BoxList::const_iterator lit = bl.begin(); lit != bl.end(); ++lit) { Box sbx = (*lit) + (*pit); sbx &= pdomain; // source must be inside the periodic domain. if (sbx.ok()) { Box dbx = sbx - (*pit); if (ParallelDescriptor::sameTeam(src_owner)) { // local copy const BoxList tilelist(dbx, FabArrayBase::comm_tile_size); for (BoxList::const_iterator it_tile = tilelist.begin(), End_tile = tilelist.end(); it_tile != End_tile; ++it_tile) { m_LocTags->push_back(CopyComTag(*it_tile, (*it_tile)+(*pit), krcv, ksnd)); } if (check_local) { localtouch.plus(1, dbx); } } else if (MyProc == dm[krcv]) { recv_tags[src_owner].push_back(CopyComTag(dbx, sbx, krcv, ksnd)); if (check_remote) { remotetouch.plus(1, dbx); } } } } } } } if (check_local) { // safe if a cell is touched no more than once // keep checking thread safety if it is safe so far check_local = m_threadsafe_loc = localtouch.max() <= 1; } if (check_remote) { check_remote = m_threadsafe_rcv = remotetouch.max() <= 1; } } for (int ipass = 0; ipass < 2; ++ipass) // pass 0: send; pass 1: recv { CopyComTag::MapOfCopyComTagContainers & Tags = (ipass == 0) ? *m_SndTags : *m_RcvTags; CopyComTag::MapOfCopyComTagContainers & tmpTags = (ipass == 0) ? send_tags : recv_tags; std::map<int,int> & Vols = (ipass == 0) ? *m_SndVols : *m_RcvVols; for (CopyComTag::MapOfCopyComTagContainers::iterator it = tmpTags.begin(), End = tmpTags.end(); it != End; ++it) { const int key = it->first; std::vector<CopyComTag>& cctv = it->second; // We need to fix the order so that the send and recv processes match. std::sort(cctv.begin(), cctv.end()); std::vector<CopyComTag> new_cctv; new_cctv.reserve(cctv.size()); for (std::vector<CopyComTag>::const_iterator it2 = cctv.begin(), End2 = cctv.end(); it2 != End2; ++it2) { const Box& bx = it2->dbox; const IntVect& d2s = it2->sbox.smallEnd() - it2->dbox.smallEnd(); Vols[key] += bx.numPts(); const BoxList tilelist(bx, FabArrayBase::comm_tile_size); for (BoxList::const_iterator it_tile = tilelist.begin(), End_tile = tilelist.end(); it_tile != End_tile; ++it_tile) { new_cctv.push_back(CopyComTag(*it_tile, (*it_tile)+d2s, it2->dstIndex, it2->srcIndex)); } } if (!new_cctv.empty()) { Tags[key].swap(new_cctv); } } } } FabArrayBase::FB::~FB () { delete m_LocTags; delete m_SndTags; delete m_RcvTags; delete m_SndVols; delete m_RcvVols; } void FabArrayBase::flushFB (bool no_assertion) const { BL_ASSERT(no_assertion || getBDKey() == m_bdkey); std::pair<FBCacheIter,FBCacheIter> er_it = m_TheFBCache.equal_range(m_bdkey); for (FBCacheIter it = er_it.first; it != er_it.second; ++it) { #ifdef BL_MEM_PROFILING m_FBC_stats.bytes -= it->second->bytes(); #endif m_FBC_stats.recordErase(it->second->m_nuse); delete it->second; } m_TheFBCache.erase(er_it.first, er_it.second); } void FabArrayBase::flushFBCache () { for (FBCacheIter it = m_TheFBCache.begin(); it != m_TheFBCache.end(); ++it) { m_FBC_stats.recordErase(it->second->m_nuse); delete it->second; } m_TheFBCache.clear(); #ifdef BL_MEM_PROFILING m_FBC_stats.bytes = 0L; #endif } const FabArrayBase::FB& FabArrayBase::getFB (const Periodicity& period, bool cross, bool enforce_periodicity_only) const { BL_PROFILE("FabArrayBase::getFB()"); BL_ASSERT(getBDKey() == m_bdkey); std::pair<FBCacheIter,FBCacheIter> er_it = m_TheFBCache.equal_range(m_bdkey); for (FBCacheIter it = er_it.first; it != er_it.second; ++it) { if (it->second->m_typ == boxArray().ixType() && it->second->m_ngrow == nGrow() && it->second->m_cross == cross && it->second->m_epo == enforce_periodicity_only && it->second->m_period == period ) { ++(it->second->m_nuse); m_FBC_stats.recordUse(); return *(it->second); } } // Have to build a new one FB* new_fb = new FB(*this, cross, period, enforce_periodicity_only); #ifdef BL_PROFILE m_FBC_stats.bytes += new_fb->bytes(); m_FBC_stats.bytes_hwm = std::max(m_FBC_stats.bytes_hwm, m_FBC_stats.bytes); #endif new_fb->m_nuse = 1; m_FBC_stats.recordBuild(); m_FBC_stats.recordUse(); m_TheFBCache.insert(er_it.second, FBCache::value_type(m_bdkey,new_fb)); return *new_fb; } FabArrayBase::FPinfo::FPinfo (const FabArrayBase& srcfa, const FabArrayBase& dstfa, Box dstdomain, int dstng, const BoxConverter& coarsener) : m_srcbdk (srcfa.getBDKey()), m_dstbdk (dstfa.getBDKey()), m_dstdomain(dstdomain), m_dstng (dstng), m_coarsener(coarsener.clone()), m_nuse (0) { BL_PROFILE("FPinfo::FPinfo()"); const BoxArray& srcba = srcfa.boxArray(); const BoxArray& dstba = dstfa.boxArray(); BL_ASSERT(srcba.ixType() == dstba.ixType()); const IndexType& boxtype = dstba.ixType(); BL_ASSERT(boxtype == dstdomain.ixType()); BL_ASSERT(dstng <= dstfa.nGrow()); const DistributionMapping& dstdm = dstfa.DistributionMap(); const int myproc = ParallelDescriptor::MyProc(); BoxList bl(boxtype); Array<int> iprocs; for (int i = 0, N = dstba.size(); i < N; ++i) { Box bx = dstba[i]; bx.grow(m_dstng); bx &= m_dstdomain; BoxList leftover = srcba.complement(bx); bool ismybox = (dstdm[i] == myproc); for (BoxList::const_iterator bli = leftover.begin(); bli != leftover.end(); ++bli) { bl.push_back(m_coarsener->doit(*bli)); if (ismybox) { dst_boxes.push_back(*bli); dst_idxs.push_back(i); } iprocs.push_back(dstdm[i]); } } if (!iprocs.empty()) { ba_crse_patch.define(bl); iprocs.push_back(myproc); dm_crse_patch.define(iprocs); } } FabArrayBase::FPinfo::~FPinfo () { delete m_coarsener; } long FabArrayBase::FPinfo::bytes () const { long cnt = sizeof(FabArrayBase::FPinfo); cnt += sizeof(Box) * (ba_crse_patch.capacity() + dst_boxes.capacity()); cnt += sizeof(int) * (dm_crse_patch.capacity() + dst_idxs.capacity()); return cnt; } const FabArrayBase::FPinfo& FabArrayBase::TheFPinfo (const FabArrayBase& srcfa, const FabArrayBase& dstfa, Box dstdomain, int dstng, const BoxConverter& coarsener) { BL_PROFILE("FabArrayBase::TheFPinfo()"); const BDKey& srckey = srcfa.getBDKey(); const BDKey& dstkey = dstfa.getBDKey(); std::pair<FPinfoCacheIter,FPinfoCacheIter> er_it = m_TheFillPatchCache.equal_range(dstkey); for (FPinfoCacheIter it = er_it.first; it != er_it.second; ++it) { if (it->second->m_srcbdk == srckey && it->second->m_dstbdk == dstkey && it->second->m_dstdomain == dstdomain && it->second->m_dstng == dstng && it->second->m_dstdomain.ixType() == dstdomain.ixType() && it->second->m_coarsener->doit(it->second->m_dstdomain) == coarsener.doit(dstdomain)) { ++(it->second->m_nuse); m_FPinfo_stats.recordUse(); return *(it->second); } } // Have to build a new one FPinfo* new_fpc = new FPinfo(srcfa, dstfa, dstdomain, dstng, coarsener); #ifdef BL_MEM_PROFILING m_FPinfo_stats.bytes += new_fpc->bytes(); m_FPinfo_stats.bytes_hwm = std::max(m_FPinfo_stats.bytes_hwm, m_FPinfo_stats.bytes); #endif new_fpc->m_nuse = 1; m_FPinfo_stats.recordBuild(); m_FPinfo_stats.recordUse(); m_TheFillPatchCache.insert(er_it.second, FPinfoCache::value_type(dstkey,new_fpc)); if (srckey != dstkey) m_TheFillPatchCache.insert( FPinfoCache::value_type(srckey,new_fpc)); return *new_fpc; } void FabArrayBase::flushFPinfo (bool no_assertion) { BL_ASSERT(no_assertion || getBDKey() == m_bdkey); std::vector<FPinfoCacheIter> others; std::pair<FPinfoCacheIter,FPinfoCacheIter> er_it = m_TheFillPatchCache.equal_range(m_bdkey); for (FPinfoCacheIter it = er_it.first; it != er_it.second; ++it) { const BDKey& srckey = it->second->m_srcbdk; const BDKey& dstkey = it->second->m_dstbdk; BL_ASSERT((srckey==dstkey && srckey==m_bdkey) || (m_bdkey==srckey) || (m_bdkey==dstkey)); if (srckey != dstkey) { const BDKey& otherkey = (m_bdkey == srckey) ? dstkey : srckey; std::pair<FPinfoCacheIter,FPinfoCacheIter> o_er_it = m_TheFillPatchCache.equal_range(otherkey); for (FPinfoCacheIter oit = o_er_it.first; oit != o_er_it.second; ++oit) { if (it->second == oit->second) others.push_back(oit); } } #ifdef BL_MEM_PROFILING m_FPinfo_stats.bytes -= it->second->bytes(); #endif m_FPinfo_stats.recordErase(it->second->m_nuse); delete it->second; } m_TheFillPatchCache.erase(er_it.first, er_it.second); for (std::vector<FPinfoCacheIter>::iterator it = others.begin(), End = others.end(); it != End; ++it) { m_TheFillPatchCache.erase(*it); } } void FabArrayBase::Finalize () { FabArrayBase::flushFBCache(); FabArrayBase::flushCPCache(); FabArrayBase::flushTileArrayCache(); if (ParallelDescriptor::IOProcessor() && BoxLib::verbose) { m_FA_stats.print(); m_TAC_stats.print(); m_FBC_stats.print(); m_CPC_stats.print(); m_FPinfo_stats.print(); } initialized = false; } const FabArrayBase::TileArray* FabArrayBase::getTileArray (const IntVect& tilesize) const { TileArray* p; #ifdef _OPENMP #pragma omp critical(gettilearray) #endif { BL_ASSERT(getBDKey() == m_bdkey); p = &FabArrayBase::m_TheTileArrayCache[m_bdkey][tilesize]; if (p->nuse == -1) { buildTileArray(tilesize, *p); p->nuse = 0; m_TAC_stats.recordBuild(); #ifdef BL_MEM_PROFILING m_TAC_stats.bytes += p->bytes(); m_TAC_stats.bytes_hwm = std::max(m_TAC_stats.bytes_hwm, m_TAC_stats.bytes); #endif } #ifdef _OPENMP #pragma omp master #endif { ++(p->nuse); m_TAC_stats.recordUse(); } } return p; } void FabArrayBase::buildTileArray (const IntVect& tileSize, TileArray& ta) const { // Note that we store Tiles always as cell-centered boxes, even if the boxarray is nodal. const int N = indexArray.size(); if (tileSize == IntVect::TheZeroVector()) { for (int i = 0; i < N; ++i) { if (isOwner(i)) { const int K = indexArray[i]; const Box& bx = boxarray.getCellCenteredBox(K); ta.indexMap.push_back(K); ta.localIndexMap.push_back(i); ta.tileArray.push_back(bx); } } } else { #if defined(BL_USE_TEAM) && !defined(__INTEL_COMPILER) std::vector<int> local_idxs(N); std::iota(std::begin(local_idxs), std::end(local_idxs), 0); #else std::vector<int> local_idxs; for (int i = 0; i < N; ++i) local_idxs.push_back(i); #endif #if defined(BL_USE_TEAM) const int nworkers = ParallelDescriptor::TeamSize(); if (nworkers > 1) { // reorder it so that each worker will be more likely to work on their own fabs std::stable_sort(local_idxs.begin(), local_idxs.end(), [this](int i, int j) { return this->distributionMap[this->indexArray[i]] < this->distributionMap[this->indexArray[j]]; }); } #endif for (std::vector<int>::const_iterator it = local_idxs.begin(); it != local_idxs.end(); ++it) { const int i = *it; // local index const int K = indexArray[i]; // global index const Box& bx = boxarray.getCellCenteredBox(K); IntVect nt_in_fab, tsize, nleft; int ntiles = 1; for (int d=0; d<BL_SPACEDIM; d++) { int ncells = bx.length(d); nt_in_fab[d] = std::max(ncells/tileSize[d], 1); tsize [d] = ncells/nt_in_fab[d]; nleft [d] = ncells - nt_in_fab[d]*tsize[d]; ntiles *= nt_in_fab[d]; } IntVect small, big, ijk; // note that the initial values are all zero. ijk[0] = -1; for (int t = 0; t < ntiles; ++t) { ta.indexMap.push_back(K); ta.localIndexMap.push_back(i); for (int d=0; d<BL_SPACEDIM; d++) { if (ijk[d]<nt_in_fab[d]-1) { ijk[d]++; break; } else { ijk[d] = 0; } } for (int d=0; d<BL_SPACEDIM; d++) { if (ijk[d] < nleft[d]) { small[d] = ijk[d]*(tsize[d]+1); big[d] = small[d] + tsize[d]; } else { small[d] = ijk[d]*tsize[d] + nleft[d]; big[d] = small[d] + tsize[d] - 1; } } Box tbx(small, big, IndexType::TheCellType()); tbx.shift(bx.smallEnd()); ta.tileArray.push_back(tbx); } } } } void FabArrayBase::flushTileArray (const IntVect& tileSize, bool no_assertion) const { BL_ASSERT(no_assertion || getBDKey() == m_bdkey); TACache& tao = m_TheTileArrayCache; TACache::iterator tao_it = tao.find(m_bdkey); if(tao_it != tao.end()) { if (tileSize == IntVect::TheZeroVector()) { for (TAMap::const_iterator tai_it = tao_it->second.begin(); tai_it != tao_it->second.end(); ++tai_it) { #ifdef BL_MEM_PROFILING m_TAC_stats.bytes -= tai_it->second.bytes(); #endif m_TAC_stats.recordErase(tai_it->second.nuse); } tao.erase(tao_it); } else { TAMap& tai = tao_it->second; TAMap::iterator tai_it = tai.find(tileSize); if (tai_it != tai.end()) { #ifdef BL_MEM_PROFILING m_TAC_stats.bytes -= tai_it->second.bytes(); #endif m_TAC_stats.recordErase(tai_it->second.nuse); tai.erase(tai_it); } } } } void FabArrayBase::flushTileArrayCache () { for (TACache::const_iterator tao_it = m_TheTileArrayCache.begin(); tao_it != m_TheTileArrayCache.end(); ++tao_it) { for (TAMap::const_iterator tai_it = tao_it->second.begin(); tai_it != tao_it->second.end(); ++tai_it) { m_TAC_stats.recordErase(tai_it->second.nuse); } } m_TheTileArrayCache.clear(); #ifdef BL_MEM_PROFILING m_TAC_stats.bytes = 0L; #endif } void FabArrayBase::clearThisBD (bool no_assertion) { if ( ! boxarray.empty() ) { BL_ASSERT(no_assertion || getBDKey() == m_bdkey); std::map<BDKey, int>::iterator cnt_it = m_BD_count.find(m_bdkey); if (cnt_it != m_BD_count.end()) { --(cnt_it->second); if (cnt_it->second == 0) { m_BD_count.erase(cnt_it); // Since this is the last one built with these BoxArray // and DistributionMapping, erase it from caches. flushTileArray(IntVect::TheZeroVector(), no_assertion); flushFPinfo(no_assertion); flushFB(no_assertion); flushCPC(no_assertion); Geometry::flushFPB(m_bdkey); } } } } void FabArrayBase::addThisBD () { m_bdkey = getBDKey(); int cnt = ++(m_BD_count[m_bdkey]); if (cnt == 1) { // new one m_FA_stats.recordMaxNumBoxArrays(m_BD_count.size()); } else { m_FA_stats.recordMaxNumBAUse(cnt); } } void FabArrayBase::updateBDKey () { if (getBDKey() != m_bdkey) { clearThisBD(true); addThisBD(); } } MFIter::MFIter (const FabArrayBase& fabarray_, unsigned char flags_) : fabArray(fabarray_), tile_size((flags_ & Tiling) ? FabArrayBase::mfiter_tile_size : IntVect::TheZeroVector()), flags(flags_), index_map(0), local_index_map(0), tile_array(0) { Initialize(); } MFIter::MFIter (const FabArrayBase& fabarray_, bool do_tiling_) : fabArray(fabarray_), tile_size((do_tiling_) ? FabArrayBase::mfiter_tile_size : IntVect::TheZeroVector()), flags(do_tiling_ ? Tiling : 0), index_map(0), local_index_map(0), tile_array(0) { Initialize(); } MFIter::MFIter (const FabArrayBase& fabarray_, const IntVect& tilesize_, unsigned char flags_) : fabArray(fabarray_), tile_size(tilesize_), flags(flags_ | Tiling), index_map(0), local_index_map(0), tile_array(0) { Initialize(); } MFIter::~MFIter () { #if BL_USE_TEAM if ( ! (flags & NoTeamBarrier) ) ParallelDescriptor::MyTeam().MemoryBarrier(); #endif } void MFIter::Initialize () { if (flags & SkipInit) { return; } else if (flags & AllBoxes) // a very special case { index_map = &(fabArray.IndexArray()); currentIndex = 0; beginIndex = 0; endIndex = index_map->size(); } else { const FabArrayBase::TileArray* pta = fabArray.getTileArray(tile_size); index_map = &(pta->indexMap); local_index_map = &(pta->localIndexMap); tile_array = &(pta->tileArray); { int rit = 0; int nworkers = 1; #ifdef BL_USE_TEAM if (ParallelDescriptor::TeamSize() > 1) { if ( tile_size == IntVect::TheZeroVector() ) { // In this case the TileArray contains only boxes owned by this worker. // So there is no sharing going on. rit = 0; nworkers = 1; } else { rit = ParallelDescriptor::MyRankInTeam(); nworkers = ParallelDescriptor::TeamSize(); } } #endif int ntot = index_map->size(); if (nworkers == 1) { beginIndex = 0; endIndex = ntot; } else { int nr = ntot / nworkers; int nlft = ntot - nr * nworkers; if (rit < nlft) { // get nr+1 items beginIndex = rit * (nr + 1); endIndex = beginIndex + nr + 1; } else { // get nr items beginIndex = rit * nr + nlft; endIndex = beginIndex + nr; } } } #ifdef _OPENMP int nthreads = omp_get_num_threads(); if (nthreads > 1) { int tid = omp_get_thread_num(); int ntot = endIndex - beginIndex; int nr = ntot / nthreads; int nlft = ntot - nr * nthreads; if (tid < nlft) { // get nr+1 items beginIndex += tid * (nr + 1); endIndex = beginIndex + nr + 1; } else { // get nr items beginIndex += tid * nr + nlft; endIndex = beginIndex + nr; } } #endif currentIndex = beginIndex; typ = fabArray.boxArray().ixType(); } } Box MFIter::tilebox () const { BL_ASSERT(tile_array != 0); Box bx((*tile_array)[currentIndex]); if (! typ.cellCentered()) { bx.convert(typ); const IntVect& Big = validbox().bigEnd(); for (int d=0; d<BL_SPACEDIM; ++d) { if (typ.nodeCentered(d)) { // validbox should also be nodal in d-direction. if (bx.bigEnd(d) < Big[d]) { bx.growHi(d,-1); } } } } return bx; } Box MFIter::nodaltilebox (int dir) const { BL_ASSERT(tile_array != 0); Box bx((*tile_array)[currentIndex]); bx.convert(typ); const IntVect& Big = validbox().bigEnd(); int d0, d1; if (dir < 0) { d0 = 0; d1 = BL_SPACEDIM-1; } else { d0 = d1 = dir; } for (int d=d0; d<=d1; ++d) { if (typ.cellCentered(d)) { // validbox should also be cell-centered in d-direction. bx.surroundingNodes(d); if (bx.bigEnd(d) <= Big[d]) { bx.growHi(d,-1); } } } return bx; } Box MFIter::growntilebox (int ng) const { Box bx = tilebox(); if (ng < -100) ng = fabArray.nGrow(); const Box& vbx = validbox(); for (int d=0; d<BL_SPACEDIM; ++d) { if (bx.smallEnd(d) == vbx.smallEnd(d)) { bx.growLo(d, ng); } if (bx.bigEnd(d) == vbx.bigEnd(d)) { bx.growHi(d, ng); } } return bx; } Box MFIter::grownnodaltilebox (int dir, int ng) const { Box bx = nodaltilebox(dir); if (ng < -100) ng = fabArray.nGrow(); const Box& vbx = validbox(); for (int d=0; d<BL_SPACEDIM; ++d) { if (bx.smallEnd(d) == vbx.smallEnd(d)) { bx.growLo(d, ng); } if (bx.bigEnd(d) >= vbx.bigEnd(d)) { bx.growHi(d, ng); } } return bx; } // For whatever reason, gcc sometimes doesn't like these two functions in FabArray.H, // unless '-fno-inline' is used. Moving it here seems to solve the problem. Box #ifdef __GNUG__ __attribute__ ((noinline)) #endif MFIter::validbox () const { return fabArray.box((*index_map)[currentIndex]); } Box MFIter::fabbox () const { return fabArray.fabbox((*index_map)[currentIndex]); } MFGhostIter::MFGhostIter (const FabArrayBase& fabarray) : MFIter(fabarray, (unsigned char)(SkipInit|Tiling)) { Initialize(); } void MFGhostIter::Initialize () { int rit = 0; int nworkers = 1; #ifdef BL_USE_TEAM if (ParallelDescriptor::TeamSize() > 1) { rit = ParallelDescriptor::MyRankInTeam(); nworkers = ParallelDescriptor::TeamSize(); } #endif int tid = 0; int nthreads = 1; #ifdef _OPENMP nthreads = omp_get_num_threads(); if (nthreads > 1) tid = omp_get_thread_num(); #endif int npes = nworkers*nthreads; int pid = rit*nthreads+tid; BoxList alltiles; Array<int> allindex; Array<int> alllocalindex; for (int i=0; i < fabArray.IndexArray().size(); ++i) { int K = fabArray.IndexArray()[i]; const Box& vbx = fabArray.box(K); const Box& fbx = fabArray.fabbox(K); const BoxList& diff = BoxLib::boxDiff(fbx, vbx); for (BoxList::const_iterator bli = diff.begin(); bli != diff.end(); ++bli) { BoxList tiles(*bli, FabArrayBase::mfghostiter_tile_size); int nt = tiles.size(); for (int it=0; it<nt; ++it) { allindex.push_back(K); alllocalindex.push_back(i); } alltiles.catenate(tiles); } } int n_tot_tiles = alltiles.size(); int navg = n_tot_tiles / npes; int nleft = n_tot_tiles - navg*npes; int ntiles = navg; if (pid < nleft) ntiles++; // how many tiles should we skip? int nskip = pid*navg + std::min(pid,nleft); BoxList::const_iterator bli = alltiles.begin(); for (int i=0; i<nskip; ++i) ++bli; lta.indexMap.reserve(ntiles); lta.localIndexMap.reserve(ntiles); lta.tileArray.reserve(ntiles); for (int i=0; i<ntiles; ++i) { lta.indexMap.push_back(allindex[i+nskip]); lta.localIndexMap.push_back(alllocalindex[i+nskip]); lta.tileArray.push_back(*bli++); } currentIndex = beginIndex = 0; endIndex = lta.indexMap.size(); lta.nuse = 0; index_map = &(lta.indexMap); local_index_map = &(lta.localIndexMap); tile_array = &(lta.tileArray); }
26.559591
101
0.627698
dappelha
43cbe292b91de2b6acce12950bda6388ad7b3cb1
3,937
cpp
C++
FlowchartEditor/FlowchartLabel.cpp
pmachapman/Tulip
54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a
[ "Unlicense" ]
null
null
null
FlowchartEditor/FlowchartLabel.cpp
pmachapman/Tulip
54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a
[ "Unlicense" ]
33
2018-09-14T21:58:20.000Z
2022-01-12T21:39:22.000Z
FlowchartEditor/FlowchartLabel.cpp
pmachapman/Tulip
54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a
[ "Unlicense" ]
null
null
null
/* ========================================================================== CFlowchartLabel Author : Johan Rosengren, Abstrakt Mekanik AB Date : 2004-04-29 Purpose : CFlowchartLabel is a CDiagramEntity-derived class. It is a non-linkable transparent box with no border and the title attribute displayed as text. Description : The class implements a minimum amount of functionality - drawing, cloning and creating from string. Usage : Create with CFlowchartControlFactory::CreateFromString ========================================================================*/ #include "stdafx.h" #include "FlowchartLabel.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CFlowchartLabel::CFlowchartLabel() /* ============================================================ Function : CFlowchartLabel::CFlowchartLabel Description : constructor Return : void Parameters : none Usage : ============================================================*/ { SetConstraints(CSize(40, 12), CSize(-1, -1)); SetType(_T("flowchart_label")); SetPropertyDialog(&m_dlg, CLabelPropertyDialog::IDD); CString title; if (title.LoadString(IDS_FLOWCHART_LABEL) > 0) { SetTitle(title); } } CFlowchartLabel::~CFlowchartLabel() /* ============================================================ Function : CFlowchartLabel::~CFlowchartLabel Description : destructor Return : void Parameters : none Usage : ============================================================*/ { if (m_dlg.m_hWnd) m_dlg.DestroyWindow(); } void CFlowchartLabel::Draw(CDC* dc, CRect rect) /* ============================================================ Function : CFlowchartLabel::Draw Description : Draws the object. Return : void Parameters : CDC* dc - The CDC to draw to. CRect rect - The real rectangle of the object. Usage : The function should clean up all selected objects. Note that the CDC is a memory CDC, so creating a memory CDC in this function will probably not speed up the function. ============================================================*/ { dc->SelectStockObject(BLACK_PEN); dc->SelectStockObject(WHITE_BRUSH); CFont font; font.CreateFont(-round(12.0 * GetZoom()), 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0, 0, 0, 0, _T("Courier New")); dc->SelectObject(&font); int mode = dc->SetBkMode(TRANSPARENT); dc->DrawText(GetTitle(), rect, DT_NOPREFIX | DT_WORDBREAK); dc->SelectStockObject(DEFAULT_GUI_FONT); dc->SetBkMode(mode); } CDiagramEntity* CFlowchartLabel::Clone() /* ============================================================ Function : CFlowchartLabel::Clone Description : Clone this object to a new object. Return : CDiagramEntity* - The new object. Parameters : none Usage : Call to create a clone of the object. The caller will have to delete the object. ============================================================*/ { CFlowchartLabel* obj = new CFlowchartLabel; obj->Copy(this); return obj; } CDiagramEntity* CFlowchartLabel::CreateFromString(const CString& str) /* ============================================================ Function : CFlowchartLabel::CreateFromString Description : Static factory function that creates and returns an instance of this class if str is a valid representation. Return : CDiagramEntity* - The object, or NULL if str is not a representation of this type. Parameters : const CString& str - The string to create from. Usage : Can be used as a factory for text file loads. Each object type should have its own version - the default one is a model implementation. ============================================================*/ { CFlowchartLabel* obj = new CFlowchartLabel; if (!obj->FromString(str)) { delete obj; obj = NULL; } return obj; }
25.732026
106
0.566675
pmachapman
43cc4cc39a455fe655a2a1c148055992d5f959af
3,618
hpp
C++
include/bitflag/bitflag.hpp
EmilyMansfield/cpp-bitflag
158cc25f8d94ee93fb93e86b76a7d078c1b48ba1
[ "CC0-1.0" ]
null
null
null
include/bitflag/bitflag.hpp
EmilyMansfield/cpp-bitflag
158cc25f8d94ee93fb93e86b76a7d078c1b48ba1
[ "CC0-1.0" ]
null
null
null
include/bitflag/bitflag.hpp
EmilyMansfield/cpp-bitflag
158cc25f8d94ee93fb93e86b76a7d078c1b48ba1
[ "CC0-1.0" ]
null
null
null
#ifndef EM_CPPBITFLAG_BITFLAG_HPP #define EM_CPPBITFLAG_BITFLAG_HPP #include <bitset> #include <type_traits> namespace em { struct BitflagMarker {}; // Alternative to scoped enums for implementing bit flags, without using macros. // Usage is // // struct MyFlags : Bitflag<32, MyFlags> { // static constexpr enum_t None{0u}; // static constexpr enum_t DoFoo{1u}; // static constexpr enum_t DoBar{1u << 1u}; // }; // // MyFlags flags{MyFlags::make(MyFlags::DoFoo)}; // if (flags & MyFlags::DoFoo) doFoo(); // if (flags & MyFlags::DoBar) doBar(); // template<std::size_t N, class Self> class Bitflag : public BitflagMarker { protected: using bitset_t = std::bitset<N>; private: bitset_t mBits{}; static auto constexpr underlying_type_helper() noexcept { if constexpr (N <= 8) return uint8_t{0}; else if constexpr (8 < N && N <= 16) return uint16_t{0}; else if constexpr (16 < N && N <= 32) return uint32_t{0}; else if constexpr (32 < N && N <= 64) return uint64_t{0}; else { static_assert(N > 64, "Bitflag must have 64 or fewer bits"); return 0u; } } // Needed for workaround on MSVC for underlying_t conversion #if defined(_MSC_VER) template<class T> struct id_wrapper { using type = T; }; #endif public: using underlying_t = decltype(Bitflag::underlying_type_helper()); static constexpr std::size_t num_bits = N; protected: class enum_t { private: friend Bitflag<N, Self>; bitset_t mBits{}; public: enum_t() = delete; explicit constexpr enum_t(bitset_t bits) noexcept : mBits{bits} {} explicit constexpr enum_t(underlying_t val) noexcept : mBits{val} {} constexpr /*explicit(false)*/ operator Self() const noexcept { return Self::make(*this); } constexpr enum_t operator~() const noexcept { return enum_t{~mBits}; } }; public: static constexpr auto make(underlying_t val) noexcept { Self tmp{}; tmp.mBits = bitset_t{val}; return tmp; } static constexpr auto make(enum_t bits) noexcept { Self tmp{}; tmp.mBits = bitset_t{bits.mBits}; return tmp; } explicit operator bool() const noexcept { return mBits.any(); } #if defined(_MSC_VER) // MSVC complains about 'operator decltype' unless underlying_t is wrapped in // a type to delay template instantiation. explicit operator typename id_wrapper<underlying_t>::type() const noexcept { return static_cast<underlying_t>(mBits.to_ullong()); } #else explicit operator underlying_t() const noexcept { return static_cast<underlying_t>(mBits.to_ullong()); } #endif friend Self operator&(const Self &lhs, const Self &rhs) noexcept { return enum_t{lhs.mBits & rhs.mBits}; } friend Self operator|(const Self &lhs, const Self &rhs) noexcept { return enum_t{lhs.mBits | rhs.mBits}; } friend Self operator^(const Self &lhs, const Self &rhs) noexcept { return enum_t{lhs.mBits ^ rhs.mBits}; } Self operator~() const noexcept { return enum_t{~mBits}; } friend bool operator==(const Self &lhs, const Self &rhs) noexcept { return lhs.mBits == rhs.mBits; } friend bool operator!=(const Self &lhs, const Self &rhs) noexcept { return lhs.mBits != rhs.mBits; } Self &operator&=(const Self &rhs) noexcept { mBits &= rhs.mBits; return static_cast<Self &>(*this); } Self &operator|=(const Self &rhs) noexcept { mBits |= rhs.mBits; return static_cast<Self &>(*this); } Self &operator^=(const Self &rhs) noexcept { mBits ^= rhs.mBits; return static_cast<Self &>(*this); } }; } // namespace em #endif
24.951724
80
0.668878
EmilyMansfield
43ccc581478c0a371fb766a28030ff37a4124547
335
cpp
C++
Solutions/6.cpp
Ignatoff/Project-Euler
75e2bb74b30ddfe15fc07887c6d9943aa8ddbd87
[ "MIT" ]
1
2018-07-09T14:44:51.000Z
2018-07-09T14:44:51.000Z
Solutions/6.cpp
Ignatoff/Project-Euler
75e2bb74b30ddfe15fc07887c6d9943aa8ddbd87
[ "MIT" ]
null
null
null
Solutions/6.cpp
Ignatoff/Project-Euler
75e2bb74b30ddfe15fc07887c6d9943aa8ddbd87
[ "MIT" ]
null
null
null
/* TASK 6: Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. */ #include <iostream> int main() { int lim = 100; int sqrOfSum = lim * lim * (lim + 1) * (lim + 1) / 4; int sumOfSqr = (2 * lim + 1)*(lim + 1)*lim / 6; std::cout << sqrOfSum - sumOfSqr << '\n'; }
19.705882
118
0.614925
Ignatoff
43d22218e00c98b7c05feeb973b9aa6ffd975a29
1,866
hh
C++
spot/spot/tl/snf.hh
mcc-petrinets/formulas
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
[ "MIT" ]
1
2018-03-02T14:29:57.000Z
2018-03-02T14:29:57.000Z
spot/spot/tl/snf.hh
mcc-petrinets/formulas
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
[ "MIT" ]
null
null
null
spot/spot/tl/snf.hh
mcc-petrinets/formulas
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
[ "MIT" ]
1
2015-06-05T12:42:07.000Z
2015-06-05T12:42:07.000Z
// -*- coding: utf-8 -*- // Copyright (C) 2012, 2013, 2014, 2015 Laboratoire de Recherche et // Developpement de l'Epita (LRDE). // // This file is part of Spot, a model checking library. // // Spot is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // Spot is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public // License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once #include <spot/tl/formula.hh> #include <unordered_map> namespace spot { typedef std::unordered_map<formula, formula> snf_cache; /// Helper to rewrite a sere in Star Normal Form. /// /// This should only be called on children of a Star operator. It /// corresponds to the E° operation defined in the following /// paper. /// /** \verbatim @Article{ bruggeman.96.tcs, author = {Anne Br{\"u}ggemann-Klein}, title = {Regular Expressions into Finite Automata}, journal = {Theoretical Computer Science}, year = {1996}, volume = {120}, pages = {87--98} } \endverbatim */ /// /// \param sere the SERE to rewrite /// \param cache an optional cache SPOT_API formula star_normal_form(formula sere, snf_cache* cache = nullptr); /// A variant of star_normal_form() for r[*0..j] where j < ω. SPOT_API formula star_normal_form_bounded(formula sere, snf_cache* cache = nullptr); }
33.927273
72
0.661308
mcc-petrinets
43d5588b5e46c983a36043a44655d71fd9be6eef
6,784
hpp
C++
util.hpp
darksky1605/accountsimulator
77648a6e2f56ac75a4c327ed0b3eb9fd49787d8b
[ "MIT" ]
null
null
null
util.hpp
darksky1605/accountsimulator
77648a6e2f56ac75a4c327ed0b3eb9fd49787d8b
[ "MIT" ]
null
null
null
util.hpp
darksky1605/accountsimulator
77648a6e2f56ac75a4c327ed0b3eb9fd49787d8b
[ "MIT" ]
null
null
null
#ifndef UTIL_HPP #define UTIL_HPP #include <algorithm> #include <cassert> #include <functional> #include <numeric> #include <omp.h> __inline__ int get_num_omp_threads() { int num_threads = 1; //get available number of threads #pragma omp parallel { #pragma omp master num_threads = omp_get_num_threads(); } return num_threads; } template <int index, int ndims, typename = void> struct IncreasingEnumerator { template <class Func, class Coords> void enumerate(const Coords& bounds, Coords& coords, Func handle_coords) { for (int i = 0; i < int(bounds[index]); i++) { coords[index] = i; IncreasingEnumerator<index + 1, ndims>{}.enumerate(bounds, coords, handle_coords); } } }; template <int index, int ndims> struct IncreasingEnumerator<index, ndims, typename std::enable_if<index == ndims - 1>::type> { template <class Func, class Coords> void enumerate(const Coords& bounds, Coords& coords, Func handle_coords) { for (int i = 0; i < int(bounds[index]); i++) { coords[index] = i; handle_coords(coords); } } }; //enumerate all points with integer coordinates in a grid with dimensions given in bounds //each valid point is consumed by function handle_coords template <int ndims, class Func, class Container> void enumerate_coords_increasing(const Container& bounds, Func handle_coords) { Container coords; std::fill(coords.begin(), coords.end(), 0); IncreasingEnumerator<0, ndims>{}.enumerate(bounds, coords, handle_coords); } template <int index, int ndims, typename = void> struct IncreasingManhattanEnumerator { template <class Func, class Coords, class Prefix> void enumerate(const Coords& dimensions, const Prefix& prefixdiff, int manhattandistance, Coords& coords, Func handle_coords) { const int maxLoopIterInclusive = std::min(int(dimensions[index] - 1), manhattandistance); for (int i = 0; i <= maxLoopIterInclusive; i++) { coords[index] = i; if (prefixdiff[index] >= manhattandistance - i) { IncreasingManhattanEnumerator<index + 1, ndims>{}.enumerate(dimensions, prefixdiff, manhattandistance - i, coords, handle_coords); } } } }; template <int index, int ndims> struct IncreasingManhattanEnumerator<index, ndims, typename std::enable_if<index == ndims - 1>::type> { template <class Func, class Coords, class Prefix> void enumerate(const Coords& dimensions, const Prefix& prefixdiff, int manhattandistance, Coords& coords, Func handle_coords) { if (manhattandistance < dimensions[index]) { coords[index] = manhattandistance; handle_coords(coords); } } }; //enumerate all points with integer coordinates with a manhatten distance of manhattendistance to origin in a grid with dimensions given in bounds //each valid point is consumed by function handle_coords template <int ndims, class Func, class Coords> void enumerate_manhattan_coords_increasing(const Coords& dimensions, int manhattandistance, Func handle_coords, int num_threads = 1) { Coords coords; std::fill(coords.begin(), coords.end(), 0); const int dimsum = std::accumulate(dimensions.begin(), dimensions.end(), 0, std::plus<int>{}); std::array<int, ndims> prefixdiff; prefixdiff[0] = dimsum - dimensions[0]; for (int i = 1; i < ndims; i++) { prefixdiff[i] = prefixdiff[i - 1] - dimensions[i]; } //IncreasingManhattanEnumerator<0, ndims>{}.enumerate(dimensions, prefixdiff, manhattandistance, coords, handle_coords); const int maxLoopIterInclusive = std::min(int(dimensions[0] - 1), manhattandistance); int old_num_threads = get_num_omp_threads(); omp_set_num_threads(num_threads); #pragma omp parallel for private(coords) schedule(dynamic, 1) for (int i = 0; i <= maxLoopIterInclusive; i++) { coords[0] = i; if (prefixdiff[0] >= manhattandistance - i) { IncreasingManhattanEnumerator<0 + 1, ndims>{}.enumerate(dimensions, prefixdiff, manhattandistance - i, coords, handle_coords); } } omp_set_num_threads(old_num_threads); } //convert multi-dimensional index to linear index template <class Container1, class Container2> std::size_t to_linear_index(const Container1& indices, const Container2& bounds) { assert(bounds.size() != 0); std::size_t linear_index = indices.back(); std::size_t factor = 1; for (int i = indices.size() - 2; i >= 0; i--) { factor *= bounds[i + 1]; linear_index += factor * indices[i]; } return linear_index; } //convert linear index to multi-dimensional index template <class Array, class Container2> Array to_multidimensional_index(std::size_t linear_index, const Container2& bounds) { assert(bounds.size() != 0); std::size_t product = std::accumulate(bounds.begin() + 1, bounds.end(), std::size_t(1), std::multiplies<std::size_t>{}); Array result; for (std::size_t i = 0; i < bounds.size() - 1; i++) { result[i] = linear_index / product; linear_index = linear_index - result[i] * product; product = product / bounds[i + 1]; } result.back() = linear_index; return result; } //multiply two polynoms whose coefficients are given in vectors a and b __inline__ std::vector<std::size_t> polynom_mult(const std::vector<std::size_t>& a, const std::vector<std::size_t>& b) { std::vector<std::size_t> result(a.size() + b.size() - 1, 0); for (std::size_t i = 0; i < a.size(); i++) { for (std::size_t j = 0; j < b.size(); j++) { result[i + j] += a[i] * b[j]; } } return result; } //for a grid of certain dimension, for each possible manhattan distance to origin, calculate number of elements with the same manhatten distance template <int n, class T> std::vector<std::size_t> get_numbers_of_coords_with_distance(const T* dimensions) { //see https://math.stackexchange.com/questions/877236/how-to-calculate-the-number-of-integer-solution-of-a-linear-equation-with-constr std::vector<std::size_t> a; std::vector<std::size_t> b; std::vector<std::size_t> c; c.resize(int(dimensions[0])); std::fill(c.begin(), c.end(), 1); for (int dim = 1; dim < n; dim++) { std::swap(b, c); a.clear(); a.resize(dimensions[dim], 1); c = polynom_mult(a, b); } return c; } template <class Container1, class Container2> bool container_less_than_elementwise(const Container1& l, const Container2& r) { auto pair = std::mismatch(l.begin(), l.end(), r.begin()); if (pair.first == l.end() && pair.second == r.end()) return false; return *(pair.first) < *(pair.second); } #endif
34.612245
146
0.666421
darksky1605
43ddc07451870ff6a173576e39f907af6e76bfc4
394
cpp
C++
src/gl_test/Helper.cpp
russkev/opengl
73417d1697d1964cfa001efc8e54eb90da95ed6e
[ "MIT" ]
5
2020-03-26T11:55:55.000Z
2021-07-30T04:14:21.000Z
src/gl_test/Helper.cpp
russkev/opengl
73417d1697d1964cfa001efc8e54eb90da95ed6e
[ "MIT" ]
3
2020-12-05T06:02:07.000Z
2021-06-02T03:42:34.000Z
src/gl_test/Helper.cpp
russkev/opengl
73417d1697d1964cfa001efc8e54eb90da95ed6e
[ "MIT" ]
null
null
null
#include "pch.h" #include "Helper.h" namespace Helper { bool Helper::matrix_is_similar(const glm::mat4& result, const glm::mat4& expected, float tolerance) { bool is_similar = true; for (auto i = 0; i < 4; ++i) { for (auto j = 0; j < 4; ++j) { if ((std::abs(result[i][j] - expected[i][j])) > tolerance) { is_similar = false; } } } return is_similar; } }
17.909091
100
0.576142
russkev
43dee39c446827cec6fb8b4b32dbc9a4fdd96987
330
cpp
C++
CodeForces/ChatRoom.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
3
2021-07-26T15:58:45.000Z
2021-09-08T14:55:11.000Z
CodeForces/ChatRoom.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
null
null
null
CodeForces/ChatRoom.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
2
2021-05-31T11:27:59.000Z
2021-10-03T13:26:00.000Z
/* * 58A ChatRoom * Jiawei Wang * 19 May 2021 */ #include <iostream> #include <string> using namespace::std; int main() { string s; cin >> s; string hello = "hello"; int index = 0; // to find for (char c : s) if (c == hello[index]) index++; if (index == 5) cout << "YES"; else cout << "NO"; }
14.347826
52
0.533333
a4org
43e2d972ddc4b6d1f73b722733a5a16a9b6837c9
4,049
cpp
C++
src/backends/sdl/system/event/original_processor.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/sdl/system/event/original_processor.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/sdl/system/event/original_processor.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
#include <awl/exception.hpp> #include <awl/backends/sdl/system/event/original_processor.hpp> #include <awl/backends/sdl/system/event/poll.hpp> #include <awl/backends/sdl/system/event/processor.hpp> #include <awl/backends/sdl/system/event/register.hpp> #include <awl/backends/sdl/system/event/translate.hpp> #include <awl/backends/sdl/system/event/wait.hpp> #include <awl/backends/sdl/timer/object.hpp> #include <awl/event/base.hpp> #include <awl/event/base_unique_ptr.hpp> #include <awl/event/container.hpp> #include <awl/main/exit_code.hpp> #include <awl/system/event/result.hpp> #include <awl/timer/object.hpp> #include <awl/timer/setting_fwd.hpp> #include <awl/timer/unique_ptr.hpp> #include <fcppt/const.hpp> #include <fcppt/function_impl.hpp> #include <fcppt/make_unique_ptr.hpp> #include <fcppt/text.hpp> #include <fcppt/unique_ptr_to_base.hpp> #include <fcppt/unit.hpp> #include <fcppt/use.hpp> #include <fcppt/container/join.hpp> #include <fcppt/container/make.hpp> #include <fcppt/either/from_optional.hpp> #include <fcppt/either/loop.hpp> #include <fcppt/log/object_reference.hpp> #include <fcppt/optional/maybe.hpp> #include <fcppt/optional/to_exception.hpp> #include <fcppt/config/external_begin.hpp> #include <SDL_events.h> #include <utility> #include <fcppt/config/external_end.hpp> awl::backends::sdl::system::event::original_processor::original_processor( fcppt::log::object_reference const _log) : awl::backends::sdl::system::event::processor{}, log_{_log}, timer_event_{fcppt::optional::to_exception( awl::backends::sdl::system::event::register_(), [] { return awl::exception{FCPPT_TEXT("Unable to register SDL timer event!")}; })}, exit_code_{} { } awl::backends::sdl::system::event::original_processor::~original_processor() = default; awl::system::event::result awl::backends::sdl::system::event::original_processor::poll() { return this->process(awl::backends::sdl::system::event::original_processor::process_function{ [this] { return this->process_events(); }}); } awl::system::event::result awl::backends::sdl::system::event::original_processor::next() { return this->process(awl::backends::sdl::system::event::original_processor::process_function{ [this] { awl::event::base_unique_ptr event{ this->translate(awl::backends::sdl::system::event::wait())}; return fcppt::container::join( fcppt::container::make<awl::event::container>(std::move(event)), this->process_events()); }}); } void awl::backends::sdl::system::event::original_processor::quit(awl::main::exit_code const _code) { this->exit_code_ = awl::main::optional_exit_code{_code}; } awl::timer::unique_ptr awl::backends::sdl::system::event::original_processor::create_timer( awl::timer::setting const &_setting) { return fcppt::unique_ptr_to_base<awl::timer::object>( fcppt::make_unique_ptr<awl::backends::sdl::timer::object>( this->log_, _setting, this->timer_event_)); } awl::system::event::result awl::backends::sdl::system::event::original_processor::process(process_function const &_function) { return fcppt::optional::maybe( this->exit_code_, [&_function] { return awl::system::event::result{_function()}; }, [](awl::main::exit_code const _code) { return awl::system::event::result{_code}; }); } awl::event::container awl::backends::sdl::system::event::original_processor::process_events() { awl::event::container result{}; fcppt::unit const error{fcppt::either::loop( [] { return fcppt::either::from_optional( awl::backends::sdl::system::event::poll(), fcppt::const_(fcppt::unit{})); }, [this, &result](SDL_Event const &_event) { result.push_back(this->translate(_event)); })}; FCPPT_USE(error); return result; } awl::event::base_unique_ptr awl::backends::sdl::system::event::original_processor::translate(SDL_Event const &_event) const { return awl::backends::sdl::system::event::translate(this->timer_event_, _event); }
35.831858
98
0.71104
freundlich
43e3079be3ba0de4b400df152fce403d54fe8f1f
314
hpp
C++
src/audio/decoder.hpp
kounoike/hisui
7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce
[ "Apache-2.0" ]
31
2020-09-25T06:48:51.000Z
2022-03-23T10:34:19.000Z
src/audio/decoder.hpp
kounoike/hisui
7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce
[ "Apache-2.0" ]
17
2021-01-13T04:07:21.000Z
2021-11-25T01:58:25.000Z
src/audio/decoder.hpp
kounoike/hisui
7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce
[ "Apache-2.0" ]
2
2022-02-19T14:42:41.000Z
2022-03-08T10:47:51.000Z
#pragma once #include <cstddef> #include <cstdint> #include <utility> namespace hisui::audio { class Decoder { public: virtual ~Decoder() = default; virtual std::pair<const std::int16_t*, const std::size_t> decode( const unsigned char*, const std::size_t) = 0; }; } // namespace hisui::audio
17.444444
67
0.66879
kounoike
43ef8e33b26ff4a0209ef6640729abbc7e629e1d
4,636
cc
C++
node_modules/nodegit/src/diff_hunk.cc
jiumx60rus/grishyGhost
c56241304da11b9a1307c6261cca50f7546981b1
[ "MIT" ]
null
null
null
node_modules/nodegit/src/diff_hunk.cc
jiumx60rus/grishyGhost
c56241304da11b9a1307c6261cca50f7546981b1
[ "MIT" ]
null
null
null
node_modules/nodegit/src/diff_hunk.cc
jiumx60rus/grishyGhost
c56241304da11b9a1307c6261cca50f7546981b1
[ "MIT" ]
null
null
null
// This is a generated file, modify: generate/templates/class_content.cc. #include <nan.h> #include <string.h> #include <chrono> #include <thread> extern "C" { #include <git2.h> } #include "../include/functions/copy.h" #include "../include/macros.h" #include "../include/diff_hunk.h" #include <iostream> using namespace std; using namespace v8; using namespace node; GitDiffHunk::GitDiffHunk(git_diff_hunk *raw, bool selfFreeing) { this->raw = raw; this->selfFreeing = selfFreeing; } GitDiffHunk::~GitDiffHunk() { // this will cause an error if you have a non-self-freeing object that also needs // to save values. Since the object that will eventually free the object has no // way of knowing to free these values. } void GitDiffHunk::InitializeComponent(Handle<v8::Object> target) { NanScope(); Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(JSNewFunction); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(NanNew<String>("DiffHunk")); NODE_SET_PROTOTYPE_METHOD(tpl, "oldStart", OldStart); NODE_SET_PROTOTYPE_METHOD(tpl, "oldLines", OldLines); NODE_SET_PROTOTYPE_METHOD(tpl, "newStart", NewStart); NODE_SET_PROTOTYPE_METHOD(tpl, "newLines", NewLines); NODE_SET_PROTOTYPE_METHOD(tpl, "headerLen", HeaderLen); NODE_SET_PROTOTYPE_METHOD(tpl, "header", Header); Local<Function> _constructor_template = tpl->GetFunction(); NanAssignPersistent(constructor_template, _constructor_template); target->Set(NanNew<String>("DiffHunk"), _constructor_template); } NAN_METHOD(GitDiffHunk::JSNewFunction) { NanScope(); if (args.Length() == 0 || !args[0]->IsExternal()) { return NanThrowError("A new GitDiffHunk cannot be instantiated."); } GitDiffHunk* object = new GitDiffHunk(static_cast<git_diff_hunk *>(Handle<External>::Cast(args[0])->Value()), args[1]->BooleanValue()); object->Wrap(args.This()); NanReturnValue(args.This()); } Handle<v8::Value> GitDiffHunk::New(void *raw, bool selfFreeing) { NanEscapableScope(); Handle<v8::Value> argv[2] = { NanNew<External>((void *)raw), NanNew<Boolean>(selfFreeing) }; return NanEscapeScope(NanNew<Function>(GitDiffHunk::constructor_template)->NewInstance(2, argv)); } git_diff_hunk *GitDiffHunk::GetValue() { return this->raw; } git_diff_hunk **GitDiffHunk::GetRefValue() { return this->raw == NULL ? NULL : &this->raw; } void GitDiffHunk::ClearValue() { this->raw = NULL; } NAN_METHOD(GitDiffHunk::OldStart) { NanScope(); Handle<v8::Value> to; int old_start = ObjectWrap::Unwrap<GitDiffHunk>(args.This())->GetValue()->old_start; // start convert_to_v8 block to = NanNew<Number>( old_start); // end convert_to_v8 block NanReturnValue(to); } NAN_METHOD(GitDiffHunk::OldLines) { NanScope(); Handle<v8::Value> to; int old_lines = ObjectWrap::Unwrap<GitDiffHunk>(args.This())->GetValue()->old_lines; // start convert_to_v8 block to = NanNew<Number>( old_lines); // end convert_to_v8 block NanReturnValue(to); } NAN_METHOD(GitDiffHunk::NewStart) { NanScope(); Handle<v8::Value> to; int new_start = ObjectWrap::Unwrap<GitDiffHunk>(args.This())->GetValue()->new_start; // start convert_to_v8 block to = NanNew<Number>( new_start); // end convert_to_v8 block NanReturnValue(to); } NAN_METHOD(GitDiffHunk::NewLines) { NanScope(); Handle<v8::Value> to; int new_lines = ObjectWrap::Unwrap<GitDiffHunk>(args.This())->GetValue()->new_lines; // start convert_to_v8 block to = NanNew<Number>( new_lines); // end convert_to_v8 block NanReturnValue(to); } NAN_METHOD(GitDiffHunk::HeaderLen) { NanScope(); Handle<v8::Value> to; size_t header_len = ObjectWrap::Unwrap<GitDiffHunk>(args.This())->GetValue()->header_len; // start convert_to_v8 block to = NanNew<Number>( header_len); // end convert_to_v8 block NanReturnValue(to); } NAN_METHOD(GitDiffHunk::Header) { NanScope(); Handle<v8::Value> to; char * header = ObjectWrap::Unwrap<GitDiffHunk>(args.This())->GetValue()->header; // start convert_to_v8 block if (header){ to = NanNew<String>(header); } else { to = NanNull(); } // end convert_to_v8 block NanReturnValue(to); } Persistent<Function> GitDiffHunk::constructor_template;
28.09697
139
0.653149
jiumx60rus
43f0205db308bcee718c97b8fcda3bc73557b629
74,819
cpp
C++
SCARD-v3/4DPlugin-SCARD.cpp
miyako/4d-plugin-scard-v3
02c8ab02c1b26a44131023bad0302a755b6a26e9
[ "MIT" ]
null
null
null
SCARD-v3/4DPlugin-SCARD.cpp
miyako/4d-plugin-scard-v3
02c8ab02c1b26a44131023bad0302a755b6a26e9
[ "MIT" ]
null
null
null
SCARD-v3/4DPlugin-SCARD.cpp
miyako/4d-plugin-scard-v3
02c8ab02c1b26a44131023bad0302a755b6a26e9
[ "MIT" ]
null
null
null
/* -------------------------------------------------------------------------------- # # 4DPlugin-SCARD.cpp # source generated by 4D Plugin Wizard # Project : SCARD # author : miyako # 2021/11/04 # # --------------------------------------------------------------------------------*/ #include "4DPlugin-SCARD.h" /* mutex protected global object to store status */ static std::mutex scardMutex; static Json::Value scardStorage; static std::map< std::string, std::future<void> >scardTasks; #pragma mark - static void scard_clear(std::string& uuid) { std::map< std::string, std::future<void> >::iterator it = scardTasks.find(uuid); if(it != scardTasks.end()) { scardStorage.removeMember(uuid); it->second.get(); scardTasks.erase(it); } } static void scard_clear_all() { for( auto it = scardTasks.begin(); it != scardTasks.end() ; ++it ) { std::string uuid = it->first; scardStorage.removeMember(uuid); it->second.get(); } scardTasks.clear(); } #pragma mark - void PluginMain(PA_long32 selector, PA_PluginParameters params) { try { switch(selector) { // --- SCARD case 1 : SCARD_Get_readers(params); break; case 2 : SCARD_Read_tag(params); break; case 3 : SCARD_Get_status(params); break; case kDeinitPlugin : case kServerDeinitPlugin : scard_clear_all(); break; } } catch(...) { } } #pragma mark - static void generateUuid(std::string &uuid) { #if VERSIONWIN RPC_WSTR str; UUID uid; if (UuidCreate(&uid) == RPC_S_OK) { if (UuidToString(&uid, &str) == RPC_S_OK) { size_t len = wcslen((const wchar_t *)str); std::vector<wchar_t>buf(len+1); memcpy(&buf[0], str, len * sizeof(wchar_t)); _wcsupr((wchar_t *)&buf[0]); CUTF16String wstr = CUTF16String((const PA_Unichar *)&buf[0], len); u16_to_u8(wstr, uuid); RpcStringFree(&str); } } #else NSString *u = [[[NSUUID UUID]UUIDString]stringByReplacingOccurrencesOfString:@"-" withString:@""]; uuid = [u UTF8String]; #endif } static void print_hex(const uint8_t *pbtData, const size_t szBytes, std::string &hex) { std::vector<uint8_t> buf((szBytes * 2) + 1); memset((char *)&buf[0], 0, buf.size()); for (size_t i = 0; i < szBytes; ++i) { sprintf((char *)&buf[i * 2], "%02x", pbtData[i]); } hex = std::string((char *)&buf[0], (szBytes * 2)); } #if VERSIONMAC static bool get_usb_information(libusb_device_handle *dh, usb_device_info *devinfo) { memset(devinfo, 0, sizeof(usb_device_info)); libusb_device *dev; struct libusb_config_descriptor *conf; const struct libusb_endpoint_descriptor *endp; const struct libusb_interface *intf; const struct libusb_interface_descriptor *intdesc; dev = libusb_get_device(dh); if(dev == NULL){ std::cout << "device get error..." << std::endl; return false; } devinfo->dh = dh; devinfo->dev = dev; libusb_get_config_descriptor(dev, 0, &conf); for(int i = 0; i < (int)conf->bNumInterfaces; i++){ intf = &conf->interface[i]; for(int j = 0; j < intf->num_altsetting; j++){ intdesc = &intf->altsetting[j]; for(int k = 0; k < (int)intdesc->bNumEndpoints; k++){ endp = &intdesc->endpoint[k]; switch(endp->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) { case LIBUSB_TRANSFER_TYPE_BULK: //printf("bulk endpoint: %02x\n", endp->bEndpointAddress); if((endp->bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_IN){ devinfo->ep_in = endp->bEndpointAddress; } if((endp->bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_OUT){ devinfo->ep_out = endp->bEndpointAddress; } break; case LIBUSB_TRANSFER_TYPE_INTERRUPT: //printf("interrupt endpoint: %02x\n", endp->bEndpointAddress); break; } } } } libusb_free_config_descriptor(conf); return true; } static int packet_init(usb_device_info *devinfo, int timeout) { uint8_t cmd[6]; int ret; int len; // ack command memcpy(cmd, "\x00\x00\xff\x00\xff\x00", 6); ret = libusb_bulk_transfer(devinfo->dh, devinfo->ep_out, (unsigned char *)cmd, sizeof(cmd), &len, timeout); if(ret < 0) std::cout << "data send error..." << std::endl; return ret; } static int packet_init_data(usb_device_info *devinfo, int timeout) { uint8_t cmd[2]; int ret; int len; // data command memcpy(cmd, "\xff\xff", 2); ret = libusb_bulk_transfer(devinfo->dh, devinfo->ep_out, (unsigned char *)cmd, sizeof(cmd), &len, timeout); if(ret < 0) std::cout << "data send error..." << std::endl; return ret; } static size_t packet_send(usb_device_info *devinfo, uint8_t *buf, int size, std::vector<uint8_t> *usbbuf, int timeout) { uint8_t rcv[LIBUSB_DATASIZE], rbuf[LIBUSB_DATASIZE]; int len; int ret; ret = libusb_bulk_transfer(devinfo->dh, devinfo->ep_out, (unsigned char *)buf, size, &len, timeout); if(ret < 0){ std::cout << "data send error..." << std::endl; return 0; } // receive ack/nck ret = libusb_bulk_transfer(devinfo->dh, devinfo->ep_in, (unsigned char *)rcv, sizeof(rcv), &len, timeout); if(ret < 0){ std::cout << "data receive error..." << std::endl; return 0; } len = 0; // receive response ret = libusb_bulk_transfer(devinfo->dh, devinfo->ep_in, (unsigned char *)rbuf, sizeof(rbuf), &len, timeout); if(ret < 0){ std::cout << "data receive error..." << std::endl; return 0; } if(len > usbbuf->size()) { usbbuf->resize(len); } memcpy(&usbbuf->at(0), rbuf, len); return len; } static size_t packet_write(usb_device_info *devinfo, uint8_t *buf, int size, std::vector<uint8_t> *usbbuf, int timeout) { uint8_t cmd[LIBUSB_DATASIZE]; int n; short csum; n = size; if(n < 1) return 0; // data = 0xd6 + data // len = len(data) // 00 00 ff ff ff len(L) len(H) checksum(len) data checksum(data) 00 /* header */ cmd[0] = 0x00; cmd[1] = 0x00; cmd[2] = 0xff; cmd[3] = 0xff; cmd[4] = 0xff; /* data length */ cmd[5] = ((n + 1) & 0xff); cmd[6] = ((n + 1) & 0xff00) >> 8; /* checksum */ csum = (0x100 - (cmd[5] + cmd[6])) % 0x100; cmd[7] = csum; /* delimiter */ cmd[8] = 0xd6; /* data */ memcpy(cmd + 9, buf, size); /* checksum */ csum = checksum(cmd[8], buf, size); cmd[9 + n] = csum; /* terminator */ cmd[10 + n] = 0x00; n += 11; return packet_send(devinfo, cmd, n, usbbuf, timeout); } static size_t packet_setcommandtype(usb_device_info *devinfo, std::vector<uint8_t> *usbbuf, int timeout) { uint8_t cmd[2]; memcpy(cmd, "\x2a\x01", 2); return packet_write(devinfo, cmd, sizeof(cmd), usbbuf, timeout); } static size_t packet_switch_rf(usb_device_info *devinfo, std::vector<uint8_t> *usbbuf, int timeout) { uint8_t cmd[2]; memcpy(cmd, "\x06\x00", 2); return packet_write(devinfo, cmd, sizeof(cmd), usbbuf, timeout); } static size_t packet_sens_req(usb_device_info *devinfo, char type, std::vector<uint8_t> *usbbuf, int timeout) { uint8_t cmd[9]; int len; if(type == 'F'){ len = 9; memcpy(cmd, "\x04\x6e\x00\x06\x00\xff\xff\x01\x00", len); } if(type == 'A'){ len = 4; memcpy(cmd, "\x04\x6e\x00\x26", len); } if(type == 'B'){ len = 6; memcpy(cmd, "\x04\x6e\x00\x05\x00\x10", len); } return packet_write(devinfo, cmd, len, usbbuf, timeout); } static size_t packet_inset_rf(usb_device_info *devinfo, char type, std::vector<uint8_t> *usbbuf, int timeout) { uint8_t cmd[5]; if(type == 'F') memcpy(cmd, "\x00\x01\x01\x0f\x01", 5); // 212F if(type == 'A') memcpy(cmd, "\x00\x02\x03\x0f\x03", 5); // 106A if(type == 'B') memcpy(cmd, "\x00\x03\x07\x0f\x07", 5); // 106B return packet_write(devinfo, cmd, sizeof(cmd), usbbuf, timeout); } static size_t packet_inset_protocol_1(usb_device_info *devinfo, std::vector<uint8_t> *usbbuf, int timeout) { uint8_t cmd[39]; memcpy(cmd, "\x02\x00\x18\x01\x01\x02\x01\x03\x00\x04\x00\x05\x00\x06\x00\x07\x08\x08\x00\x09\x00\x0a\x00\x0b\x00\x0c\x00\x0e\x04\x0f\x00\x10\x00\x11\x00\x12\x00\x13\x06", 39); return packet_write(devinfo, cmd, sizeof(cmd), usbbuf, timeout); } static size_t packet_inset_protocol_2(usb_device_info *devinfo, char type, std::vector<uint8_t> *usbbuf, int timeout) { uint8_t cmd[11]; int len; if(type == 'F'){ len = 3; memcpy(cmd, "\x02\x00\x18", len); } if(type == 'A'){ len = 11; memcpy(cmd, "\x02\x00\x06\x01\x00\x02\x00\x05\x01\x07\x07", len); } if(type == 'B'){ len = 11; memcpy(cmd, "\x02\x00\x14\x09\x01\x0a\x01\x0b\x01\x0c\x01", len); } return packet_write(devinfo, cmd, len, usbbuf, timeout); } #endif #pragma mark - static void SCARD_Get_readers(PA_PluginParameters params) { PA_ObjectRef options = PA_GetObjectParameter(params, 1); PA_ObjectRef status = PA_CreateObject(); PA_CollectionRef readers = PA_CreateCollection(); #if VERSIONMAC if(!checkAccess(status)) { ob_set_s(status, L"warning", "com.apple.security.smartcard is missing in app entitlement"); } std::string errorMessage; bool success = false; TKSmartCardSlotManager *manager = [TKSmartCardSlotManager defaultManager]; if(manager) { NSArray<NSString *> *slotNames = [manager slotNames]; for (NSString *slotName in slotNames) { PA_ObjectRef o = PA_CreateObject(); ob_set_s(o, L"slotName", (const char *)[slotName UTF8String]); PA_Variable v = PA_CreateVariable(eVK_Object); PA_SetObjectVariable(&v, o); PA_SetCollectionElement(readers, PA_GetCollectionLength(readers), v); } success = true; }else{ errorMessage = "TKSmartCardSlotManager::defaultManager() failed"; } #else /* windows */ bool success = false; uint32_t scope = SCARD_SCOPE_USER; if (options) { if (ob_is_defined(options, L"scope")) { int _scope = ob_get_n(options, L"scope"); switch (_scope) { case SCARD_SCOPE_USER: case SCARD_SCOPE_TERMINAL: case SCARD_SCOPE_SYSTEM: scope = _scope; break; default: break; } } } SCARDCONTEXT hContext; LONG lResult = SCardEstablishContext(scope, NULL, NULL, &hContext); /* http://eternalwindows.jp/security/scard/scard02.html */ if (lResult == SCARD_E_NO_SERVICE) { HANDLE hEvent = SCardAccessStartedEvent(); DWORD dwResult = WaitForSingleObject(hEvent, DEFAULT_TIMEOUT_MS_FOR_RESOURCE_MANAGER); if (dwResult == WAIT_OBJECT_0) { lResult = SCardEstablishContext(scope, NULL, NULL, &hContext); } SCardReleaseStartedEvent(); } if (lResult == SCARD_S_SUCCESS) { DWORD len; lResult = SCardListReaders(hContext, SCARD_ALL_READERS, NULL, &len); if (lResult == SCARD_S_SUCCESS) { std::vector<TCHAR>buf(len); lResult = SCardListReaders(hContext, SCARD_ALL_READERS, &buf[0], &len); if (lResult == SCARD_S_SUCCESS) { LPTSTR pReader = (LPTSTR)&buf[0]; if (pReader) { while ('\0' != *pReader) { PA_ObjectRef reader = PA_CreateObject(); ob_set_a(reader, L"slotName", pReader); pReader = pReader + wcslen(pReader) + 1; PA_Variable v = PA_CreateVariable(eVK_Object); PA_SetObjectVariable(&v, reader); PA_SetCollectionElement(readers, PA_GetCollectionLength(readers), v); PA_ClearVariable(&v); } success = true; } } } SCardReleaseContext(hContext); } #endif #if VERSIONMAC int libusb_result = libusb_init(NULL); if(libusb_result >= 0) { libusb_device **devs; ssize_t count = libusb_get_device_list(NULL, &devs); if(count > 0) { for(int i = 0; i < count; ++i){ libusb_device *dev = devs[i]; libusb_device_descriptor desc; libusb_result = libusb_get_device_descriptor(dev, &desc); if(libusb_result >= 0) { std::vector<uint8_t> buf(5); memset ((char *)&buf[0], 0, buf.size()); sprintf((char *)&buf[0], "%04x", desc.idVendor); std::string _vid = std::string((char *)&buf[0], 4); memset ((char *)&buf[0], 0, buf.size()); sprintf((char *)&buf[0], "%04x", desc.idProduct); std::string _pid = std::string((char *)&buf[0], 4); char *end; int vid = (int)strtol(_vid.c_str(), &end, 16); int pid = (int)strtol(_pid.c_str(), &end, 16); int libusb_device_id = 0; /* Sony NFC Port-100 chipset. The only product known to use this chipset is the PaSoRi RC-S380. https://github.com/nfcpy/nfcpy/blob/master/src/nfc/clf/rcs380.py */ /* Sony RC-S956 chipset. Products known to use this chipset are the PaSoRi RC-S330, RC-S360, and RC-S370. https://github.com/nfcpy/nfcpy/blob/master/src/nfc/clf/rcs956.py */ if(vid == LIBUSB_SONY) { switch (pid) { case LIBUSB_SONY_RC_S380: case LIBUSB_SONY_RC_S310: case LIBUSB_SONY_RC_S320: case LIBUSB_SONY_RC_S330: libusb_device_id = pid; break; default: break; } if(libusb_device_id != 0) { PA_ObjectRef o = PA_CreateObject(); switch (libusb_device_id) { case LIBUSB_SONY_RC_S380: ob_set_s(o, L"slotName", "Sony FeliCa RC-S380"); break; case LIBUSB_SONY_RC_S310: ob_set_s(o, L"slotName", "Sony FeliCa RC-S310"); break; case LIBUSB_SONY_RC_S320: ob_set_s(o, L"slotName", "Sony FeliCa RC-S320"); break; case LIBUSB_SONY_RC_S330: ob_set_s(o, L"slotName", "Sony FeliCa RC-S330"); break; default: break; } PA_Variable v = PA_CreateVariable(eVK_Object); PA_SetObjectVariable(&v, o); PA_SetCollectionElement(readers, PA_GetCollectionLength(readers), v); success = true; } } } } libusb_free_device_list(devs, 1); } libusb_exit(NULL); } #endif ob_set_b(status, L"success", success); ob_set_c(status, L"readers", readers); PA_ReturnObject(params, status); } static void SCARD_Read_tag(PA_PluginParameters params) { PA_ObjectRef status = PA_CreateObject(); PA_ObjectRef args = PA_GetObjectParameter(params, 1); std::string slotName; char nfc_type = 'F'; unsigned int timeout = 60; bool get_system = false; if (args) { CUTF8String stringValue; if (ob_get_s(args, L"slotName", &stringValue)) { slotName = (const char *)stringValue.c_str(); } if (ob_get_s(args, L"card", &stringValue)) { if (stringValue == (const uint8_t *)"FeliCa") { nfc_type = 'F'; } if (stringValue == (const uint8_t *)"TypeB") { nfc_type = 'B'; } if (stringValue == (const uint8_t *)"TypeA") { nfc_type = 'A'; } } if (ob_is_defined(args, L"timeout")) { int _timeout = ob_get_n(args, L"timeout"); if (_timeout > 0) { timeout = _timeout; } } get_system = ob_get_b(args, L"system"); } std::string uuid; generateUuid(uuid); /* default params */ Json::Value threadCtx(Json::objectValue); threadCtx["complete"] = false; threadCtx["success"] = false; threadCtx["errorMessage"] = ""; threadCtx["slotName"] = ""; threadCtx["protocol"] = ""; threadCtx["IDm"] = ""; threadCtx["PMm"] = ""; threadCtx["nfc_type"] = nfc_type;//for libusb threadCtx["timeout"] = timeout; threadCtx["get_system"] = get_system;//for libpafe if(1) { std::lock_guard<std::mutex> lock(scardMutex); scardStorage[uuid] = threadCtx; } auto func = [](std::string uuid, std::string slotName) { char nfc_type = 'F'; unsigned int timeout = 60; bool get_system = false; if(1) { std::lock_guard<std::mutex> lock(scardMutex); Json::Value threadCtx = scardStorage[uuid]; if(threadCtx.isObject()) { nfc_type = threadCtx["nfc_type"].asInt(); timeout = threadCtx["timeout"].asInt(); get_system = threadCtx["get_system"].asBool(); } } bool is_pasori_s380 = false; if ((slotName == "Sony FeliCa Port/PaSoRi 3.0 0") || (slotName == "Sony FeliCa RC-S380") || (slotName == "Sony RC-S380/P") || (slotName == "Sony RC-S380/S") ) { is_pasori_s380 = true; } std::string errorMessage; #if VERSIONMAC __block bool success = false; __block std::string IDm; __block std::string PMm; __block std::string nfcid; __block std::string appdata; __block std::string pinfo; __block std::string cid; __block std::string serviceDataJson; std::vector<uint8_t>usbbuf(LIBUSB_DATASIZE); int libusb_device_id = 0; if(slotName == "Sony FeliCa RC-S380"){ libusb_device_id = LIBUSB_SONY_RC_S380; }else if( (slotName == "Sony FeliCa RC-S310") || (slotName == "Sony FeliCa RC-S320") || (slotName == "Sony FeliCa RC-S330")){ libusb_device_id = LIBUSB_SONY_RC_S330; } if(libusb_device_id != 0) { /* libpafe */ pasori *p = NULL; felica *f = NULL; /* libusb */ libusb_device_handle *device = NULL; usb_device_info devinfo; usb_device_info *devinfop = &devinfo; std::vector<uint8_t> *usbbufp = &usbbuf; Json::Value serviceData(Json::objectValue); bool isPolling = false; switch (libusb_device_id) { case LIBUSB_SONY_RC_S330: p = pasori_open(); if(p) { if(!pasori_init(p)) { pasori_set_timeout(p, LIBUSB_API_TIMEOUT); pasori_reset(p); isPolling = true; } } break; case LIBUSB_SONY_RC_S380: int libusb_result = libusb_init(NULL); if(libusb_result >= 0) { device = libusb_open_device_with_vid_pid(NULL, LIBUSB_SONY, libusb_device_id); if(device) { // usb interface setting libusb_set_auto_detach_kernel_driver(device, 1); libusb_set_configuration(device, 1); libusb_claim_interface(device, 0); libusb_set_interface_alt_setting(device, 0, 0); // get usb information if(get_usb_information(device, devinfop)) { packet_init(devinfop, LIBUSB_API_TIMEOUT); packet_setcommandtype(devinfop, usbbufp, LIBUSB_API_TIMEOUT); packet_switch_rf(devinfop, usbbufp, LIBUSB_API_TIMEOUT); packet_inset_rf(devinfop, nfc_type, usbbufp, LIBUSB_API_TIMEOUT); packet_inset_protocol_1(devinfop, usbbufp, LIBUSB_API_TIMEOUT); packet_inset_protocol_2(devinfop, nfc_type, usbbufp, LIBUSB_API_TIMEOUT); isPolling = true; } } } break; } if(isPolling) { time_t startTime = time(0); time_t anchorTime = startTime; uint8_t idm[8], pmm[8]; while (isPolling) { time_t now = time(0); time_t elapsedTime = abs(startTime - now); elapsedTime = abs(anchorTime - now); if(elapsedTime < timeout) { size_t len = 0L; switch (libusb_device_id) { case LIBUSB_SONY_RC_S330: if(p){ f = felica_polling(p, FELICA_POLLING_ANY, 0, 0); if(!f) { isPolling = false; }else{ print_hex(f->IDm, 8, IDm); print_hex(f->PMm, 8, PMm); success = true; isPolling = false; if(get_system) { /* 090f */ Json::Value service(Json::objectValue); service["code"] = "090f"; Json::Value data(Json::arrayValue); felica *ff = NULL; uint16 resp[256]; int n = sizeof(resp)/sizeof(*resp); int r = felica_request_system(f, &n, resp); /* https://www.sony.co.jp/Products/felica/business/tech-support/?j-short=tech-support#FeliCa02 https://ja.osdn.net/projects/felicalib/wiki/suica Request System Code コマンドを送信する。FeliCaのもつシステムコードのリストを得る。 https://ja.osdn.net/users/bhbops/pf/libpafe_lite/wiki/FrontPage */ if (!r){ for (int i = 0; i < n; ++i) { /* 00FE :フェリカネットワークス社が管理する共通領域を示すシステムコード 0003 :交通系 802B :交通系(せたまるとIruCa) */ if ((resp[i] == 0x0003) || (resp[i] == 0x80de)) { uint16 systemCode = resp[i]; ff = felica_polling(f->p, systemCode, 0, 0); if (ff == NULL) { break; } uint8_t b[2]; b[0] = systemCode >> 8; b[1] = systemCode & 0x00FF; r = felica_search_service(ff); /* 0xffffがサービスコードとして返却されるまで Search Service Code コマンドを送信する。 */ if(!r){ for (int j = 0; j < ff->service_num; ++j) { uint16 serviceCode = ff->service[j].bin; if(serviceCode == 0x090f) { service["code"] = "090f"; if (ff->service[j].attr & 1) { int k = 0; uint8_t b[16]; while (!felica_read_single(ff, ff->service[j].bin, 0, k, b)) { std::string hex; print_hex(b, 16, hex); data.append(hex); service["data"] = hex; k++; } } break; } } } free(ff); break; } } } service["data"] = data; Json::StreamWriterBuilder writer; writer["indentation"] = ""; serviceDataJson = Json::writeString(writer, service); } } } break; case LIBUSB_SONY_RC_S380: len = packet_sens_req(devinfop, nfc_type, usbbufp, LIBUSB_API_TIMEOUT_FOR_POLLING); if(len >= 0) { if(usbbuf[9] == 0x05 && usbbuf[10] == 0x00) { int rlen = ((usbbuf[6] << 8) + usbbuf[5]); if(rlen == 27) { if(usbbuf[6 + 9] == 0x14 && usbbuf[7 + 9] == 0x01) { uint8_t SW1 = usbbuf[25]; uint8_t SW2 = usbbuf[26]; if((SW1 == 0x10) & (SW2 == 0x0B)){ memcpy(idm, &usbbuf[ 8 + 9], 8); memcpy(pmm, &usbbuf[16 + 9], 8); print_hex(idm, 8, IDm); print_hex(pmm, 8, PMm); success = true; } isPolling = false; } } if(isPolling) { /* ATQB (response to REQB ) */ if(usbbuf[6 + 9] == 0x50) /* response code */ { uint8_t _nfcid[4], _appdata[4], _pinfo[3], _cid[1]; memcpy( _nfcid, &usbbuf[ 7 + 9], 4);/* PUPI */ memcpy(_appdata, &usbbuf[11 + 9], 4);/* Application Data */ memcpy( _pinfo, &usbbuf[15 + 9], 3);/* Protocol Info */ memcpy( _cid, &usbbuf[18 + 9], 1);/* CID */ print_hex(_nfcid, 4, nfcid); print_hex(_appdata, 4, appdata); print_hex(_pinfo, 3, pinfo); print_hex(_cid, 1, cid); success = true; isPolling = false; } } if(isPolling) { /* ATQA incomplete: need to implement SAK anti-collision sequence http://www.ti.com/lit/an/sloa136/sloa136.pdf https://www.nxp.com/docs/en/application-note/AN10833.pdf https://github.com/nfc-tools/libnfc/blob/master/examples/nfc-anticol.c */ } } }else{ /* read/write error */ usleep(LIBUSB_USLEEP_DURATION); } break; } }else{ /* timeout */ isPolling = false; } } switch (libusb_device_id) { case LIBUSB_SONY_RC_S330: if(f) { free(f); } if(p) { pasori_close(p); } break; case LIBUSB_SONY_RC_S380: if(success) { if (get_system) { /* 090f */ uint8_t cmd[21] = { 0x04, 0x86, 0x01, 0x12, /* cmd len */ 0x06, /* cmd_code:0x06 (read_without_encryption) */ idm[0], /* captured tag identifier (IDm) */ idm[1], idm[2], idm[3], idm[4], idm[5], idm[6], idm[7], 0x01, /* count of sc */ 0x0f, 0x09, 0x02, /* count of bc */ 0x80, //0x11 0x00, 0x80, //0x12 0x01 }; packet_inset_rf(devinfop, nfc_type, usbbufp, LIBUSB_API_TIMEOUT); packet_inset_protocol_1(devinfop, usbbufp, LIBUSB_API_TIMEOUT); Json::Value service(Json::objectValue); service["code"] = "090f"; Json::Value data(Json::arrayValue); size_t len; uint8_t bd[16]; std::string hex; packet_write(devinfop, cmd, sizeof(cmd), usbbufp, timeout);//InCommRF isPolling = true; time_t startTime = time(0); time_t anchorTime = startTime; while (isPolling) { time_t now = time(0); time_t elapsedTime = abs(startTime - now); elapsedTime = abs(anchorTime - now); if(elapsedTime < timeout) { len = packet_sens_req(devinfop, nfc_type, usbbufp, LIBUSB_API_TIMEOUT_FOR_POLLING); if(len >= 0) { if(usbbuf[9] == 0x05 && usbbuf[10] == 0x00) { int rlen = ((usbbuf[6] << 8) + usbbuf[5]); switch (rlen) { case 52: memcpy(bd, &usbbuf[28], 16); print_hex(bd, 16, hex); data.append(hex); memcpy(bd, &usbbuf[28+16], 16); print_hex(bd, 16, hex); data.append(hex); cmd[18] = cmd[18] + 2; cmd[20] = cmd[20] + 2; break; case 27: NSLog(@"error"); break; default: break; } if(cmd[20] == 19){ isPolling = false; }else{ packet_write(devinfop, cmd, sizeof(cmd), usbbufp, timeout);//InCommRF } } } }else{ /* timeout */ isPolling = false; } } service["data"] = data; Json::StreamWriterBuilder writer; writer["indentation"] = ""; serviceDataJson = Json::writeString(writer, service); } } // close libusb_release_interface(device, 0); libusb_close(device); libusb_exit(NULL); break; } } }else { TKSmartCardSlotManager *manager = [TKSmartCardSlotManager defaultManager]; if(manager) { NSString *name = [[NSString alloc]initWithUTF8String:slotName.c_str()]; TKSmartCardSlot *slot = [manager slotNamed:name]; [name release]; if(slot) { TKSmartCard *smartCard = [slot makeSmartCard]; if(smartCard) { dispatch_semaphore_t sem = dispatch_semaphore_create(0); [smartCard beginSessionWithReply:^(BOOL _success, NSError *error) { if (_success) { uint8_t pbSendBuffer_GetIDm[5] = { APDU_CLA_GENERIC, APDU_INS_GET_DATA, APDU_P1_GET_UID, APDU_P2_NONE, APDU_LE_MAX_LENGTH }; [smartCard transmitRequest:[NSData dataWithBytes:pbSendBuffer_GetIDm length:sizeof pbSendBuffer_GetIDm] reply:^(NSData *response, NSError *error) { if (error == nil) { uint8_t SW1 = 0; uint8_t SW2 = 0; [response getBytes:&SW1 range:NSMakeRange([response length] - 2, 1)]; [response getBytes:&SW2 range:NSMakeRange([response length] - 1, 1)]; if ( SW1 != 0x90 || SW2 != 0x00 ) { if ( SW1 == 0x63 && SW2 == 0x00 ) { /* data is not available */ } } else { print_hex((const uint8_t *)[response bytes], 8, IDm); success = true; } uint8_t pbSendBuffer_GetPMm[5] = { APDU_CLA_GENERIC, APDU_INS_GET_DATA, APDU_P1_GET_PMm, APDU_P2_NONE, APDU_LE_MAX_LENGTH }; [smartCard transmitRequest:[NSData dataWithBytes:pbSendBuffer_GetPMm length:sizeof pbSendBuffer_GetPMm] reply:^(NSData *response, NSError *error) { if (error == nil) { uint8_t SW1 = 0; uint8_t SW2 = 0; [response getBytes:&SW1 range:NSMakeRange([response length] - 2, 1)]; [response getBytes:&SW2 range:NSMakeRange([response length] - 1, 1)]; if ( SW1 != 0x90 || SW2 != 0x00 ) { if ( SW1 == 0x63 && SW2 == 0x00 ) { /* data is not available */ } } else { print_hex((const uint8_t *)[response bytes], 8, PMm); success = true; } if (get_system) { /* 090f */ __block Json::Value service(Json::objectValue); service["code"] = "090f"; __block Json::Value data(Json::arrayValue); smartCard.cla = 0xFF; uint8_t pbSendBuffer_SelectFile[7] = { APDU_CLA_GENERIC, APDU_INS_SELECT_FILE, /* SelectFile */ 0x00, /* P1 */ 0x01, /* P2 */ 0x02, 0x0f, /* service Hi */ 0x09 /* service Lo */ }; __block int cnt = 0; for (int i = 0; i < 20; ++i) { [smartCard transmitRequest:[NSData dataWithBytes:pbSendBuffer_SelectFile length:sizeof(pbSendBuffer_SelectFile)] reply:^(NSData *response, NSError *error) { if (error == nil) { uint8_t pbSendBuffer_ReadBinary[5] = { APDU_CLA_GENERIC, APDU_INS_READ_BINARY, /*ReadBinary */ 0x00, 0x00, /* block */ 0x00 }; pbSendBuffer_ReadBinary[3] = i; [smartCard transmitRequest:[NSData dataWithBytes:pbSendBuffer_ReadBinary length:sizeof(pbSendBuffer_ReadBinary)] reply:^(NSData *response, NSError *error) { if (error == nil) { if([response length] == 18) { std::string hex; print_hex((const uint8_t *)[response bytes], 16, hex); data.append(hex); } }else{ NSLog(@"transmitRequest(READ BINARY) error!"); } cnt++; if(cnt == 19){ [smartCard endSession]; service["data"] = data; Json::StreamWriterBuilder writer; writer["indentation"] = ""; serviceDataJson = Json::writeString(writer, service); dispatch_semaphore_signal(sem); } }]; usleep(TK_USLEEP_DURATION_FOR_POLLING); }else{ NSLog(@"transmitRequest(SELECT FILE) error!"); } }]; usleep(TK_USLEEP_DURATION); } }else{ //!get_system [smartCard endSession]; dispatch_semaphore_signal(sem); } }else{ //transmitRequest(pbSendBuffer_GetPMm)failed [smartCard endSession]; dispatch_semaphore_signal(sem); } }]; }else{ //transmitRequest(pbSendBuffer_GetIDm)failed [smartCard endSession]; dispatch_semaphore_signal(sem); } }]; }else{ //beginSessionWithReply() failed dispatch_semaphore_signal(sem); } }]; // wait for the asynchronous blocks to finish dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); }else{ errorMessage = "TKSmartCard::makeSmartCard() failed"; } }else{ errorMessage = "TKSmartCardSlotManager::slotNamed() failed"; } }else{ errorMessage = "TKSmartCardSlotManager::defaultManager() failed"; } } #else /* windows */ std::string serviceDataJson; std::string IDm; std::string PMm; bool success = false; LPTSTR lpszReaderName = NULL; CUTF16String name; DWORD protocols = SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1; DWORD mode = SCARD_SHARE_SHARED; DWORD scope = SCARD_SCOPE_USER; /* TODO: options - set protocol, mode, scope */ u8_to_u16(slotName, name); lpszReaderName = (LPTSTR)name.c_str(); if(name.length()) { SCARDCONTEXT hContext; LONG lResult = SCardEstablishContext(scope, NULL, NULL, &hContext); /* http://eternalwindows.jp/security/scard/scard02.html */ if (lResult == SCARD_E_NO_SERVICE) { HANDLE hEvent = SCardAccessStartedEvent(); DWORD dwResult = WaitForSingleObject(hEvent, DEFAULT_TIMEOUT_MS_FOR_RESOURCE_MANAGER); if (dwResult == WAIT_OBJECT_0) { lResult = SCardEstablishContext(scope, NULL, NULL, &hContext); } SCardReleaseStartedEvent(); } if (lResult == SCARD_S_SUCCESS) { SCARD_READERSTATE readerState; readerState.szReader = lpszReaderName; readerState.dwCurrentState = SCARD_STATE_UNAWARE; /* return immediately; check state */ lResult = SCardGetStatusChange(hContext, 0, &readerState, 1); if (lResult == SCARD_S_SUCCESS) { int is_card_present = 0; time_t startTime = time(0); time_t anchorTime = startTime; bool isPolling = true; while (isPolling) { time_t now = time(0); time_t elapsedTime = abs(startTime - now); if(elapsedTime > 0) { startTime = now; } elapsedTime = abs(anchorTime - now); if(elapsedTime < timeout) { if (readerState.dwEventState & SCARD_STATE_EMPTY) { lResult = SCardGetStatusChange(hContext, LIBPCSC_API_TIMEOUT, &readerState, 1); } if (readerState.dwEventState & SCARD_STATE_UNAVAILABLE) { isPolling = false; } if (readerState.dwEventState & SCARD_STATE_PRESENT) { is_card_present = 1; isPolling = false; } }else{ /* timeout */ isPolling = false; } } if(is_card_present) { SCARDHANDLE hCard; DWORD dwActiveProtocol; DWORD dwProtocol; DWORD dwAtrSize; DWORD dwState; BYTE atr[256]; lResult = SCardConnect(hContext, lpszReaderName, mode, protocols, &hCard, &dwActiveProtocol); switch (lResult) { case (LONG)SCARD_W_REMOVED_CARD: /* SCARD_W_REMOVED_CARD */ break; case SCARD_S_SUCCESS: lResult = SCardStatus(hCard, NULL, NULL, &dwState, &dwProtocol, atr, &dwAtrSize); if (lResult == SCARD_S_SUCCESS) { BYTE pbSendBuffer_GetIDm[5] = { APDU_CLA_GENERIC, APDU_INS_GET_DATA, APDU_P1_GET_UID, APDU_P2_NONE, APDU_LE_MAX_LENGTH }; BYTE pbSendBuffer_GetPMm[5] = { APDU_CLA_GENERIC, APDU_INS_GET_DATA, APDU_P1_GET_PMm, APDU_P2_NONE, APDU_LE_MAX_LENGTH }; BYTE pbSendBuffer_SelectFile[7] = { 0xff, 0xA4, /* SelectFile */ 0x00, /* P1 */ 0x01, /* P2 */ 0x0f, /* service Hi */ 0x09, /* service Lo */ 0x00 }; BYTE pbSendBuffer_ReadBinary[5] = { 0xff, 0xb0, /*ReadBinary */ 0x00, 0x00, /* block */ 0x00 }; if (is_pasori_s380) { pbSendBuffer_SelectFile[4] = 0x02; pbSendBuffer_SelectFile[5] = 0x0f; pbSendBuffer_SelectFile[6] = 0x09; } BYTE pbRecvBuffer[2048]; DWORD cbRecvLength; BYTE SW1 = 0; BYTE SW2 = 0; cbRecvLength = 2048; lResult = SCardTransmit(hCard, SCARD_PCI_T1, pbSendBuffer_GetIDm, sizeof(pbSendBuffer_GetIDm), NULL, pbRecvBuffer, &cbRecvLength); switch(lResult) { case SCARD_S_SUCCESS: SW1 = pbRecvBuffer[cbRecvLength - 2]; SW2 = pbRecvBuffer[cbRecvLength - 1]; if ( SW1 != 0x90 || SW2 != 0x00 ) { if ( SW1 == 0x63 && SW2 == 0x00 ) { /* data is not available */ } } else { print_hex(pbRecvBuffer, 8, IDm); success = true; } break; case 0x458: lResult = SCARD_W_REMOVED_CARD; break; case 0x16: lResult = SCARD_E_INVALID_PARAMETER; break; default: break; } cbRecvLength = 2048; lResult = SCardTransmit(hCard, SCARD_PCI_T1, pbSendBuffer_GetPMm, sizeof(pbSendBuffer_GetPMm), NULL, pbRecvBuffer, &cbRecvLength); switch(lResult) { case SCARD_S_SUCCESS: SW1 = pbRecvBuffer[cbRecvLength - 2]; SW2 = pbRecvBuffer[cbRecvLength - 1]; if ( SW1 != 0x90 || SW2 != 0x00 ) { if ( SW1 == 0x63 && SW2 == 0x00 ) { /* data is not available */ } } else { print_hex(pbRecvBuffer, 8, PMm); success = true; } break; case 0x458: lResult = SCARD_W_REMOVED_CARD; break; case 0x16: lResult = SCARD_E_INVALID_PARAMETER; break; default: break; } if (get_system) { /* 090f */ Json::Value service(Json::objectValue); service["code"] = "090f"; Json::Value data(Json::arrayValue); for (int i = 0; i < 20; ++i) { pbSendBuffer_ReadBinary[3] = i; cbRecvLength = 2048; lResult = SCardTransmit(hCard, SCARD_PCI_T1, pbSendBuffer_SelectFile, sizeof(pbSendBuffer_SelectFile), NULL, pbRecvBuffer, &cbRecvLength); if (lResult == SCARD_S_SUCCESS) { cbRecvLength = 2048; SCARD_IO_REQUEST pci; pci.cbPciLength = cbRecvLength; lResult = SCardTransmit(hCard, SCARD_PCI_T1, pbSendBuffer_ReadBinary, sizeof(pbSendBuffer_ReadBinary), &pci, pbRecvBuffer, &cbRecvLength); if (lResult == SCARD_S_SUCCESS) { std::string hex; print_hex(pbRecvBuffer, 16, hex); data.append(hex); service["data"] = hex; } else { break; } } } service["data"] = data; Json::StreamWriterBuilder writer; writer["indentation"] = ""; serviceDataJson = Json::writeString(writer, service); } }/* SCardStatus */ SCardDisconnect(hCard, SCARD_LEAVE_CARD); break; default: break; } } } SCardReleaseContext(hContext); } } #endif if(1) { std::lock_guard<std::mutex> lock(scardMutex); if(scardStorage[uuid].isObject()) { scardStorage[uuid]["IDm"] = IDm; scardStorage[uuid]["PMm"] = PMm; scardStorage[uuid]["errorMessage"] = errorMessage; scardStorage[uuid]["slotName"] = slotName; scardStorage[uuid]["success"] = success; scardStorage[uuid]["complete"] = true; scardStorage[uuid]["serviceDataJson"] = serviceDataJson; } } }; scardTasks.insert(std::map< std::string, std::future<void> >::value_type(uuid, std::async(std::launch::async, func, uuid, slotName))); #if VERSIONMAC if(!checkAccess(status)) { ob_set_s(status, L"warning", "com.apple.security.smartcard is missing in app entitlement"); } #endif ob_set_s(status, L"uuid", uuid.c_str()); PA_ReturnObject(params, status); } static void SCARD_Get_status(PA_PluginParameters params) { PA_ObjectRef status = PA_CreateObject(); PA_Unistring *ustr = PA_GetStringParameter(params, 1); CUTF16String u16 = CUTF16String(ustr->fString, ustr->fLength); std::string uuid; u16_to_u8(u16, uuid); bool complete = false; bool success = false; std::string slotName, errorMessage, IDm, PMm, nfcid, appdata, pinfo, cid, serviceDataJson; Json::Value threadCtx = scardStorage[uuid]; if(threadCtx.isObject()) { std::lock_guard<std::mutex> lock(scardMutex); success = threadCtx["success"].asBool(); complete = threadCtx["complete"].asBool(); slotName = threadCtx["slotName"].asString(); errorMessage = threadCtx["errorMessage"].asString(); IDm = threadCtx["IDm"].asString(); PMm = threadCtx["PMm"].asString(); nfcid = threadCtx["nfcid"].asString(); appdata = threadCtx["appdata"].asString(); pinfo = threadCtx["pinfo"].asString(); cid = threadCtx["cid"].asString(); serviceDataJson = threadCtx["serviceDataJson"].asString(); } ob_set_s(status, L"uuid", uuid.c_str()); ob_set_b(status, L"success", success); ob_set_b(status, L"complete", complete); ob_set_s(status, L"slotName", slotName.c_str()); if(errorMessage.length() != 0) { ob_set_s(status, L"errorMessage", errorMessage.c_str()); } if(serviceDataJson.length() != 0) { CUTF16String jsonString; u8_to_u16(serviceDataJson, jsonString); // ob_set_s(status, L"serviceDataJson", serviceDataJson.c_str()); PA_ulong32 version = PA_Get4DVersion() & 0x0000FFFF; PA_Variable params[2], result; PA_ObjectRef object = NULL; PA_Unistring string; string = PA_CreateUnistring((PA_Unichar *)jsonString.c_str()); PA_SetStringVariable( &params[0], &string ); PA_SetLongintVariable( &params[1], eVK_Object ); result = PA_ExecuteCommandByID( 1218, params, 2 ); // JSON Parse object = PA_GetObjectVariable( result ); PA_DisposeUnistring( &string ); ob_set_o(status, L"serviceData", object); } if(IDm.length() != 0) { ob_set_s(status, L"IDm", IDm.c_str()); } if(PMm.length() != 0) { ob_set_s(status, L"PMm", PMm.c_str()); } if(nfcid.length() != 0) { ob_set_s(status, L"nfcid", nfcid.c_str()); } if(appdata.length() != 0) { ob_set_s(status, L"appdata", appdata.c_str()); } if(cid.length() != 0) { ob_set_s(status, L"cid", cid.c_str()); } if(pinfo.length() != 0) { ob_set_s(status, L"pinfo", pinfo.c_str()); } PA_ReturnObject(params, status); if(complete) { scard_clear(uuid); } } #pragma mark - static short checksum(char cmd, uint8_t *buf, int size) { int sum = (unsigned int)cmd; for(int i = 0; i < size; i++){ sum += buf[i]; } return (0x100 - sum) % 0x100; } #if VERSIONMAC static bool checkAccess(PA_ObjectRef status) { bool entitlement = false; /* https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_smartcard */ SecTaskRef sec = SecTaskCreateFromSelf(kCFAllocatorMalloc); CFErrorRef err = nil; CFBooleanRef boolValue = (CFBooleanRef)SecTaskCopyValueForEntitlement(sec, CFSTR("com.apple.security.smartcard"), &err); if(!err) { if(boolValue) { entitlement = CFBooleanGetValue(boolValue); } } CFRelease(sec); return entitlement; } #endif #pragma mark - static void u16_to_u8(CUTF16String& u16, std::string& u8) { #ifdef _WIN32 int len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)u16.c_str(), u16.length(), NULL, 0, NULL, NULL); if(len){ std::vector<uint8_t> buf(len + 1); if(WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)u16.c_str(), u16.length(), (LPSTR)&buf[0], len, NULL, NULL)){ u8 = std::string((const char *)&buf[0]); } }else{ u8 = std::string((const char *)""); } #else CFStringRef str = CFStringCreateWithCharacters(kCFAllocatorDefault, (const UniChar *)u16.c_str(), u16.length()); if(str){ size_t size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8) + sizeof(uint8_t); std::vector<uint8_t> buf(size); CFIndex len = 0; CFStringGetBytes(str, CFRangeMake(0, CFStringGetLength(str)), kCFStringEncodingUTF8, 0, true, (UInt8 *)&buf[0], size, &len); u8 = std::string((const char *)&buf[0], len); CFRelease(str); } #endif } static void u8_to_u16(std::string& u8, CUTF16String& u16) { #ifdef _WIN32 int len = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)u8.c_str(), u8.length(), NULL, 0); if(len){ std::vector<uint8_t> buf((len + 1) * sizeof(PA_Unichar)); if(MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)u8.c_str(), u8.length(), (LPWSTR)&buf[0], len)){ u16 = CUTF16String((const PA_Unichar *)&buf[0]); } }else{ u16 = CUTF16String((const PA_Unichar *)L""); } #else CFStringRef str = CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8 *)u8.c_str(), u8.length(), kCFStringEncodingUTF8, true); if(str){ CFIndex len = CFStringGetLength(str); std::vector<uint8_t> buf((len+1) * sizeof(PA_Unichar)); CFStringGetCharacters(str, CFRangeMake(0, len), (UniChar *)&buf[0]); u16 = CUTF16String((const PA_Unichar *)&buf[0]); CFRelease(str); } #endif }
43.024152
181
0.345233
miyako
43f021543f14e0202a2c5e5a337d935ab0df4774
8,222
cpp
C++
src/main.cpp
bmstu-gaming/SquaresAndPairs
9f52b0e509c5f46971264ce8f23acf700f184dce
[ "Apache-2.0" ]
null
null
null
src/main.cpp
bmstu-gaming/SquaresAndPairs
9f52b0e509c5f46971264ce8f23acf700f184dce
[ "Apache-2.0" ]
null
null
null
src/main.cpp
bmstu-gaming/SquaresAndPairs
9f52b0e509c5f46971264ce8f23acf700f184dce
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * @file main.cpp * * @brief This file contains the game logic * * Group: BMSTU GaminG * Target Device: PC * ****************************************************************************** Copyright (c) 2019, BMSTU GaminG Incorporated 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 Texas Instruments Incorporated 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. ****************************************************************************** Release Name: Release Date: *****************************************************************************/ /********************************************************************* * INCLUDES */ #include <stdio.h> #include <iostream> #include <SFML/System.hpp> #include <SFML/Graphics.hpp> #include <thread> #include <mutex> /********************************************************************* * CLASSES */ /********************************************************************* * CONSTANTS */ /********************************************************************* * TYPEDEFS */ /********************************************************************* * LOCAL FUNCTIONS */ /***************************************************************** * @fn threadRenderingWindow * * @brief Render each frame in window * */ void threadRenderingWindow(sf::RenderWindow* window) { // activate the window's context window->setActive(true); // Load font sf::Font font; if (!font.loadFromFile("assets/Consolas.ttf")) { std::cerr << "Font load error" << std::endl; } sf::Clock clock; // the rendering loop while ( window->isOpen() ) { // Start the current frame // Add text for FPS counter sf::Text fpsText; fpsText.setFont(font); fpsText.setCharacterSize(24); fpsText.setFillColor(sf::Color::Green); // Add square sf::RectangleShape square(sf::Vector2f(50, 50)); square.setPosition(600, 300); square.setFillColor(sf::Color::Red); // End the current frame sf::Time elapsed = clock.restart(); fpsText.setString(std::to_string(1.f / elapsed.asSeconds())); window->clear(sf::Color::White); window->draw(square); window->draw(fpsText); window->display(); } } /***************************************************************** * @fn main123 * * @brief The main program * */ int main() { std::mutex programEnd; sf::RenderWindow window; window.create(sf::VideoMode(1280, 720), "Game", sf::Style::Default); // change the position of the window (relatively to the desktop) window.setPosition(sf::Vector2i(500, 50)); // vertical synchronization enable window.setVerticalSyncEnabled(true); // deactivate its OpenGL context window.setActive(false); // launch the rendering thread std::thread thread(&threadRenderingWindow, &window); // run the program as long as the window is open while ( window.isOpen() ) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while ( window.pollEvent(event) ) { // "close requested" event: closing the window if ( event.type == sf::Event::Closed ) { thread.detach(); window.close(); } // The Resized event if ( event.type == sf::Event::Resized ) { std::cout << "new width: " << event.size.width << std::endl; std::cout << "new height: " << event.size.height << std::endl; window.setSize(sf::Vector2u(event.size.width, event.size.height)); } // LostFocus events if ( event.type == sf::Event::LostFocus ) { } // GainedFocus events if ( event.type == sf::Event::GainedFocus ) { } // The TextEntered event if ( event.type == sf::Event::TextEntered ) { if ( event.text.unicode < 128 ) { std::cout << "ASCII character typed: " << static_cast<char>(event.text.unicode) << std::endl; } } // The KeyPressed and KeyReleased events if ( event.type == sf::Event::KeyPressed ) { if ( event.key.code == sf::Keyboard::Escape ) { std::cout << "the ESC key was pressed" << std::endl; window.close(); std::thread detach(); } } // The MouseButtonPressed and MouseButtonReleased events if ( event.type == sf::Event::MouseButtonPressed ) { if ( event.mouseButton.button == sf::Mouse::Left ) { std::cout << "the Left button was pressed" << std::endl; std::cout << "mouse x: " << event.mouseButton.x << std::endl; std::cout << "mouse y: " << event.mouseButton.y << std::endl; } if (event.mouseButton.button == sf::Mouse::Right) { std::cout << "the Right button was pressed" << std::endl; std::cout << "mouse x: " << event.mouseButton.x << std::endl; std::cout << "mouse y: " << event.mouseButton.y << std::endl; } if ( event.mouseButton.button == sf::Mouse::Middle ) { std::cout << "the Middle button was pressed" << std::endl; std::cout << "mouse x: " << event.mouseButton.x << std::endl; std::cout << "mouse y: " << event.mouseButton.y << std::endl; } if ( event.mouseButton.button == sf::Mouse::XButton1 ) { std::cout << "the Mouse 4 button was pressed" << std::endl; std::cout << "mouse x: " << event.mouseButton.x << std::endl; std::cout << "mouse y: " << event.mouseButton.y << std::endl; } if ( event.mouseButton.button == sf::Mouse::XButton2 ) { std::cout << "the Mouse 5 button was pressed" << std::endl; std::cout << "mouse x: " << event.mouseButton.x << std::endl; std::cout << "mouse y: " << event.mouseButton.y << std::endl; } } // The MouseMoved event if ( event.type == sf::Event::MouseMoved ) { std::cout << "new mouse x: " << event.mouseMove.x << std::endl; std::cout << "new mouse y: " << event.mouseMove.y << std::endl; } // The MouseWheelScrolled event if ( event.type == sf::Event::MouseWheelScrolled ) { if ( event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel ) { std::cout << "wheel type: vertical" << std::endl; } else if ( event.mouseWheelScroll.wheel == sf::Mouse::HorizontalWheel ) { std::cout << "wheel type: horizontal" << std::endl; } else { std::cout << "wheel type: unknown" << std::endl; std::cout << "wheel movement: " << event.mouseWheelScroll.delta << std::endl; std::cout << "mouse x: " << event.mouseWheelScroll.x << std::endl; std::cout << "mouse y: " << event.mouseWheelScroll.y << std::endl; } } // The MouseEntered and MouseLeft event if ( event.type == sf::Event::MouseEntered ) { std::cout << "the mouse cursor has entered the window" << std::endl; } if ( event.type == sf::Event::MouseLeft ) { std::cout << "the mouse cursor has left the window" << std::endl; } } } return 0; } /********************************************************************* *********************************************************************/
33.422764
98
0.585016
bmstu-gaming
43f3d40f5b6bd59d9cdb75e306a2a7a60c0cf550
2,099
cc
C++
src/lib/fast_erosion.cc
jube/mapmaker
e2eb6b1fbc3d803d56817aea86b350bd26ad5fa4
[ "ISC" ]
15
2015-03-18T18:07:30.000Z
2020-10-15T16:59:19.000Z
src/lib/fast_erosion.cc
jube/mapmaker
e2eb6b1fbc3d803d56817aea86b350bd26ad5fa4
[ "ISC" ]
null
null
null
src/lib/fast_erosion.cc
jube/mapmaker
e2eb6b1fbc3d803d56817aea86b350bd26ad5fa4
[ "ISC" ]
1
2020-01-16T17:37:11.000Z
2020-01-16T17:37:11.000Z
/* * Copyright (c) 2014, Julien Bernard * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <mm/fast_erosion.h> namespace mm { heightmap fast_erosion::operator()(const heightmap& src) const { heightmap map(src); heightmap material(size_only, src); for (size_type k = 0; k < m_iterations; ++k) { // initialize material map material.reset(0.0); // compute material map for (auto x : src.x_range()) { for (auto y : src.y_range()) { double altitude_difference_max = 0.0; position pos_max = { x, y }; const double altitude_here = map(x, y); map.visit8neighbours(x, y, [altitude_here, &altitude_difference_max, &pos_max](position pos, double altitude_there) { double altitude_difference = altitude_here - altitude_there; if (altitude_difference > altitude_difference_max) { altitude_difference_max = altitude_difference; pos_max = pos; } }); if (0 < altitude_difference_max && altitude_difference_max <= m_talus) { material(x, y) -= m_fraction * altitude_difference_max; material(pos_max) += m_fraction * altitude_difference_max; } } } // add material map to the map for (auto fp : map.positions()) { map(fp) += material(fp); } } return map; } }
33.854839
127
0.655074
jube
43f41f1c212f5509167cfc327c221c92834db095
138
hpp
C++
src/gameworld/gameworld/effect/sceneeffect/sceneskill.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/gameworld/gameworld/effect/sceneeffect/sceneskill.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/gameworld/gameworld/effect/sceneeffect/sceneskill.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#ifndef __SCENE_SKILL_HPP__ #define __SCENE_SKILL_HPP__ #include "effect/sceneeffect/sceneskillbase.hpp" #endif // __SCENE_SKILL_HPP__
17.25
48
0.833333
mage-game
43f4aff944b278f80081e25b812db90d3c7c0927
19,496
inl
C++
opencl/test/unit_test/api/cl_get_kernel_sub_group_info_tests.inl
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
778
2017-09-29T20:02:43.000Z
2022-03-31T15:35:28.000Z
opencl/test/unit_test/api/cl_get_kernel_sub_group_info_tests.inl
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
478
2018-01-26T16:06:45.000Z
2022-03-30T10:19:10.000Z
opencl/test/unit_test/api/cl_get_kernel_sub_group_info_tests.inl
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
215
2018-01-30T08:39:32.000Z
2022-03-29T11:08:51.000Z
/* * Copyright (C) 2018-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "opencl/test/unit_test/fixtures/hello_world_fixture.h" #include "opencl/test/unit_test/test_macros/test_checks_ocl.h" using namespace NEO; struct KernelSubGroupInfoFixture : HelloWorldFixture<HelloWorldFixtureFactory> { typedef HelloWorldFixture<HelloWorldFixtureFactory> ParentClass; void SetUp() override { ParentClass::SetUp(); pKernel->maxKernelWorkGroupSize = static_cast<uint32_t>(pDevice->getDeviceInfo().maxWorkGroupSize / 2); maxSimdSize = static_cast<size_t>(pKernel->getKernelInfo().getMaxSimdSize()); ASSERT_LE(8u, maxSimdSize); maxWorkDim = static_cast<size_t>(pClDevice->getDeviceInfo().maxWorkItemDimensions); ASSERT_EQ(3u, maxWorkDim); maxWorkGroupSize = static_cast<size_t>(pKernel->maxKernelWorkGroupSize); ASSERT_GE(1024u, maxWorkGroupSize); largestCompiledSIMDSize = static_cast<size_t>(pKernel->getKernelInfo().getMaxSimdSize()); ASSERT_EQ(32u, largestCompiledSIMDSize); auto requiredWorkGroupSizeX = static_cast<size_t>(pKernel->getKernelInfo().kernelDescriptor.kernelAttributes.requiredWorkgroupSize[0]); auto requiredWorkGroupSizeY = static_cast<size_t>(pKernel->getKernelInfo().kernelDescriptor.kernelAttributes.requiredWorkgroupSize[1]); auto requiredWorkGroupSizeZ = static_cast<size_t>(pKernel->getKernelInfo().kernelDescriptor.kernelAttributes.requiredWorkgroupSize[2]); calculatedMaxWorkgroupSize = requiredWorkGroupSizeX * requiredWorkGroupSizeY * requiredWorkGroupSizeZ; if ((calculatedMaxWorkgroupSize == 0) || (calculatedMaxWorkgroupSize > static_cast<size_t>(pKernel->maxKernelWorkGroupSize))) { calculatedMaxWorkgroupSize = static_cast<size_t>(pKernel->maxKernelWorkGroupSize); } } void TearDown() override { ParentClass::TearDown(); } size_t inputValue[3]; size_t paramValue[3]; size_t paramValueSizeRet; size_t maxSimdSize; size_t maxWorkDim; size_t maxWorkGroupSize; size_t largestCompiledSIMDSize; size_t calculatedMaxWorkgroupSize; }; namespace ULT { typedef Test<KernelSubGroupInfoFixture> KernelSubGroupInfoTest; template <typename ParamType> struct KernelSubGroupInfoParamFixture : KernelSubGroupInfoFixture, ::testing::TestWithParam<ParamType> { void SetUp() override { KernelSubGroupInfoFixture::SetUp(); } void TearDown() override { KernelSubGroupInfoFixture::TearDown(); } }; static size_t WorkDimensions[] = {1, 2, 3}; static struct WorkSizeParam { size_t x; size_t y; size_t z; } KernelSubGroupInfoWGS[] = { {0, 0, 0}, {1, 1, 1}, {1, 5, 1}, {8, 1, 1}, {16, 1, 1}, {32, 1, 1}, {64, 1, 1}, {1, 190, 1}, {1, 510, 1}, {512, 1, 1}}; typedef KernelSubGroupInfoParamFixture<std::tuple<WorkSizeParam, size_t>> KernelSubGroupInfoReturnSizeTest; INSTANTIATE_TEST_CASE_P(wgs, KernelSubGroupInfoReturnSizeTest, ::testing::Combine( ::testing::ValuesIn(KernelSubGroupInfoWGS), ::testing::ValuesIn(WorkDimensions))); TEST_P(KernelSubGroupInfoReturnSizeTest, GivenWorkGroupSizeWhenGettingMaxSubGroupSizeThenReturnIsCalculatedCorrectly) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); WorkSizeParam workSize; size_t workDim; std::tie(workSize, workDim) = GetParam(); memset(inputValue, 0, sizeof(inputValue)); inputValue[0] = workSize.x; if (workDim > 1) { inputValue[1] = workSize.y; } if (workDim > 2) { inputValue[2] = workSize.z; } paramValueSizeRet = 0; retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE, sizeof(size_t) * workDim, inputValue, sizeof(size_t), paramValue, &paramValueSizeRet); EXPECT_EQ(retVal, CL_SUCCESS); EXPECT_EQ(paramValueSizeRet, sizeof(size_t)); EXPECT_EQ(maxSimdSize, paramValue[0]); } typedef KernelSubGroupInfoParamFixture<std::tuple<WorkSizeParam, size_t>> KernelSubGroupInfoReturnCountTest; INSTANTIATE_TEST_CASE_P(wgs, KernelSubGroupInfoReturnCountTest, ::testing::Combine( ::testing::ValuesIn(KernelSubGroupInfoWGS), ::testing::ValuesIn(WorkDimensions))); TEST_P(KernelSubGroupInfoReturnCountTest, GivenWorkGroupSizeWhenGettingSubGroupCountThenReturnIsCalculatedCorrectly) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); WorkSizeParam workSize; size_t workDim; std::tie(workSize, workDim) = GetParam(); memset(inputValue, 0, sizeof(inputValue)); inputValue[0] = workSize.x; if (workDim > 1) { inputValue[1] = workSize.y; } if (workDim > 2) { inputValue[2] = workSize.z; } paramValueSizeRet = 0; retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE, sizeof(size_t) * workDim, inputValue, sizeof(size_t), paramValue, &paramValueSizeRet); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(sizeof(size_t), paramValueSizeRet); auto calculatedWGS = workSize.x; if (workDim > 1) { calculatedWGS *= workSize.y; } if (workDim > 2) { calculatedWGS *= workSize.z; } if (calculatedWGS % maxSimdSize == 0) { EXPECT_EQ(calculatedWGS / maxSimdSize, paramValue[0]); } else { EXPECT_EQ((calculatedWGS / maxSimdSize) + 1, paramValue[0]); } } static size_t SubGroupsNumbers[] = {0, 1, 10, 12, 21, 33, 67, 99}; typedef KernelSubGroupInfoParamFixture<std::tuple<size_t, size_t>> KernelSubGroupInfoReturnLocalSizeTest; INSTANTIATE_TEST_CASE_P(sgn, KernelSubGroupInfoReturnLocalSizeTest, ::testing::Combine( ::testing::ValuesIn(SubGroupsNumbers), ::testing::ValuesIn(WorkDimensions))); TEST_P(KernelSubGroupInfoReturnLocalSizeTest, GivenWorkGroupSizeWhenGettingLocalSizeThenReturnIsCalculatedCorrectly) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); size_t subGroupsNum; size_t workDim; std::tie(subGroupsNum, workDim) = GetParam(); inputValue[0] = subGroupsNum; retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT, sizeof(size_t), inputValue, sizeof(size_t) * workDim, paramValue, &paramValueSizeRet); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(sizeof(size_t) * workDim, paramValueSizeRet); size_t workGroupSize = subGroupsNum * largestCompiledSIMDSize; if (workGroupSize > calculatedMaxWorkgroupSize) { workGroupSize = 0; } EXPECT_EQ(workGroupSize, paramValue[0]); if (workDim > 1) { EXPECT_EQ(workGroupSize ? 1u : 0u, paramValue[1]); } if (workDim > 2) { EXPECT_EQ(workGroupSize ? 1u : 0u, paramValue[2]); } } typedef KernelSubGroupInfoParamFixture<WorkSizeParam> KernelSubGroupInfoReturnMaxNumberTest; TEST_F(KernelSubGroupInfoReturnMaxNumberTest, GivenWorkGroupSizeWhenGettingMaxNumSubGroupsThenReturnIsCalculatedCorrectly) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, CL_KERNEL_MAX_NUM_SUB_GROUPS, 0, nullptr, sizeof(size_t), paramValue, &paramValueSizeRet); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(paramValueSizeRet, sizeof(size_t)); EXPECT_EQ(paramValue[0], Math::divideAndRoundUp(calculatedMaxWorkgroupSize, largestCompiledSIMDSize)); } typedef KernelSubGroupInfoParamFixture<WorkSizeParam> KernelSubGroupInfoReturnCompileNumberTest; TEST_F(KernelSubGroupInfoReturnCompileNumberTest, GivenKernelWhenGettingCompileNumSubGroupThenReturnIsCalculatedCorrectly) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, CL_KERNEL_COMPILE_NUM_SUB_GROUPS, 0, nullptr, sizeof(size_t), paramValue, &paramValueSizeRet); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(paramValueSizeRet, sizeof(size_t)); EXPECT_EQ(paramValue[0], static_cast<size_t>(pKernel->getKernelInfo().kernelDescriptor.kernelMetadata.compiledSubGroupsNumber)); } typedef KernelSubGroupInfoParamFixture<WorkSizeParam> KernelSubGroupInfoReturnCompileSizeTest; TEST_F(KernelSubGroupInfoReturnCompileSizeTest, GivenKernelWhenGettingCompileSubGroupSizeThenReturnIsCalculatedCorrectly) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, CL_KERNEL_COMPILE_SUB_GROUP_SIZE_INTEL, 0, nullptr, sizeof(size_t), paramValue, &paramValueSizeRet); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(paramValueSizeRet, sizeof(size_t)); size_t requiredSubGroupSize = 0; auto start = pKernel->getKernelInfo().kernelDescriptor.kernelMetadata.kernelLanguageAttributes.find("intel_reqd_sub_group_size("); if (start != std::string::npos) { start += strlen("intel_reqd_sub_group_size("); auto stop = pKernel->getKernelInfo().kernelDescriptor.kernelMetadata.kernelLanguageAttributes.find(")", start); requiredSubGroupSize = stoi(pKernel->getKernelInfo().kernelDescriptor.kernelMetadata.kernelLanguageAttributes.substr(start, stop - start)); } EXPECT_EQ(paramValue[0], requiredSubGroupSize); } TEST_F(KernelSubGroupInfoTest, GivenNullKernelWhenGettingSubGroupInfoThenInvalidKernelErrorIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); retVal = clGetKernelSubGroupInfo( nullptr, pClDevice, 0, 0, nullptr, 0, nullptr, nullptr); EXPECT_EQ(CL_INVALID_KERNEL, retVal); } TEST_F(KernelSubGroupInfoTest, GivenInvalidDeviceWhenGettingSubGroupInfoFromSingleDeviceKernelThenInvalidDeviceErrorIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, reinterpret_cast<cl_device_id>(pKernel), CL_KERNEL_COMPILE_SUB_GROUP_SIZE_INTEL, 0, nullptr, sizeof(size_t), paramValue, &paramValueSizeRet); EXPECT_EQ(CL_INVALID_DEVICE, retVal); } TEST_F(KernelSubGroupInfoTest, GivenNullDeviceWhenGettingSubGroupInfoFromSingleDeviceKernelThenSuccessIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, nullptr, CL_KERNEL_COMPILE_SUB_GROUP_SIZE_INTEL, 0, nullptr, sizeof(size_t), paramValue, &paramValueSizeRet); EXPECT_EQ(CL_SUCCESS, retVal); } TEST_F(KernelSubGroupInfoTest, GivenNullDeviceWhenGettingSubGroupInfoFromMultiDeviceKernelThenInvalidDeviceErrorIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); MockUnrestrictiveContext context; auto mockProgram = std::make_unique<MockProgram>(&context, false, context.getDevices()); std::unique_ptr<MultiDeviceKernel> pMultiDeviceKernel(MultiDeviceKernel::create<MockKernel>(mockProgram.get(), this->pMultiDeviceKernel->getKernelInfos(), nullptr)); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel.get(), nullptr, CL_KERNEL_COMPILE_SUB_GROUP_SIZE_INTEL, 0, nullptr, sizeof(size_t), paramValue, &paramValueSizeRet); EXPECT_EQ(CL_INVALID_DEVICE, retVal); } TEST_F(KernelSubGroupInfoTest, GivenInvalidParamNameWhenGettingSubGroupInfoThenInvalidValueErrorIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, 0, sizeof(size_t), inputValue, sizeof(size_t), paramValue, nullptr); EXPECT_EQ(CL_INVALID_VALUE, retVal); } uint32_t /*cl_kernel_sub_group_info*/ KernelSubGroupInfoInputParams[] = { CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE, CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE, CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT, CL_KERNEL_MAX_NUM_SUB_GROUPS, CL_KERNEL_COMPILE_NUM_SUB_GROUPS, CL_KERNEL_COMPILE_SUB_GROUP_SIZE_INTEL}; typedef KernelSubGroupInfoParamFixture<uint32_t /*cl_kernel_sub_group_info*/> KernelSubGroupInfoInputParamsTest; INSTANTIATE_TEST_CASE_P(KernelSubGroupInfoInputParams, KernelSubGroupInfoInputParamsTest, ::testing::ValuesIn(KernelSubGroupInfoInputParams)); TEST_P(KernelSubGroupInfoInputParamsTest, GivenOpenClVersionLowerThan21WhenGettingKenrelSubGroupInfoThenInvalidOperationErrorIsReturned) { bool requireOpenCL21 = (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT) || (GetParam() == CL_KERNEL_MAX_NUM_SUB_GROUPS) || (GetParam() == CL_KERNEL_COMPILE_NUM_SUB_GROUPS); if (requireOpenCL21) { DebugManager.flags.ForceOCLVersion.set(20); pDevice->initializeCaps(); pClDevice->initializeCaps(); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), 0, nullptr, 0, nullptr, nullptr); EXPECT_EQ(CL_INVALID_OPERATION, retVal); DebugManager.flags.ForceOCLVersion.set(0); pDevice->initializeCaps(); pClDevice->initializeCaps(); } } TEST_P(KernelSubGroupInfoInputParamsTest, GivenWorkDimZeroWhenGettingSubGroupInfoThenSuccessOrErrorIsCorrectlyReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); bool requireInput = (GetParam() == CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE) || (GetParam() == CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE) || (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), 0, inputValue, 0, nullptr, nullptr); EXPECT_EQ(requireInput ? CL_INVALID_VALUE : CL_SUCCESS, retVal); } TEST_P(KernelSubGroupInfoInputParamsTest, GivenIndivisibleWorkDimWhenGettingSubGroupInfoThenSuccessOrErrorIsCorrectlyReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); bool requireInput = (GetParam() == CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE) || (GetParam() == CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE) || (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT); size_t workDim = ((GetParam() == CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE) || (GetParam() == CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE)) ? maxWorkDim : 1; retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), (sizeof(size_t) * workDim) - 1, inputValue, 0, nullptr, nullptr); EXPECT_EQ(requireInput ? CL_INVALID_VALUE : CL_SUCCESS, retVal); } TEST_P(KernelSubGroupInfoInputParamsTest, GivenWorkDimGreaterThanMaxWorkDimWhenGettingSubGroupInfoThenSuccessOrErrorIsCorrectlyReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); bool requireInput = (GetParam() == CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE) || (GetParam() == CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE) || (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT); size_t workDim = ((GetParam() == CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE) || (GetParam() == CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE)) ? maxWorkDim : 1; retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), sizeof(size_t) * (workDim + 1), inputValue, 0, nullptr, nullptr); EXPECT_EQ(requireInput ? CL_INVALID_VALUE : CL_SUCCESS, retVal); } TEST_P(KernelSubGroupInfoInputParamsTest, GivenInputValueIsNullWhenGettingSubGroupInfoThenSuccessOrErrorIsCorrectlyReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); bool requireInput = (GetParam() == CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE) || (GetParam() == CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE) || (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT); size_t workDim = ((GetParam() == CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE) || (GetParam() == CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE)) ? maxWorkDim : 1; retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), sizeof(size_t) * (workDim), nullptr, 0, nullptr, nullptr); EXPECT_EQ(requireInput ? CL_INVALID_VALUE : CL_SUCCESS, retVal); } TEST_P(KernelSubGroupInfoInputParamsTest, GivenParamValueSizeZeroWhenGettingSubGroupInfoThenInvalidValueErrorIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), sizeof(size_t), inputValue, 0, paramValue, nullptr); EXPECT_EQ(CL_INVALID_VALUE, retVal); } TEST_P(KernelSubGroupInfoInputParamsTest, GivenUnalignedParamValueSizeWhenGettingSubGroupInfoThenInvalidValueErrorIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); size_t workDim = (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT) ? maxWorkDim : 1; retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), sizeof(size_t), inputValue, (sizeof(size_t) * workDim) - 1, paramValue, nullptr); EXPECT_EQ(CL_INVALID_VALUE, retVal); } TEST_P(KernelSubGroupInfoInputParamsTest, GivenTooLargeParamValueSizeWhenGettingSubGroupInfoThenCorrectRetValIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); bool requireOutputArray = (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT); size_t workDim = (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT) ? maxWorkDim : 1; // paramValue size / sizeof(size_t) > MaxWorkDim retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), sizeof(size_t), inputValue, sizeof(size_t) * (workDim + 1), paramValue, nullptr); EXPECT_EQ(requireOutputArray ? CL_INVALID_VALUE : CL_SUCCESS, retVal); } TEST_P(KernelSubGroupInfoInputParamsTest, GivenNullPtrForReturnWhenGettingKernelSubGroupInfoThenSuccessIsReturned) { REQUIRE_OCL_21_OR_SKIP(defaultHwInfo); bool requireOutputArray = (GetParam() == CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT); retVal = clGetKernelSubGroupInfo( pMultiDeviceKernel, pClDevice, GetParam(), sizeof(size_t), inputValue, 0, nullptr, nullptr); EXPECT_EQ(requireOutputArray ? CL_INVALID_VALUE : CL_SUCCESS, retVal); } } // namespace ULT
33.212947
169
0.690501
troels
43fa97fe09d6d1b3145683f98b27e17a7c802436
2,261
hpp
C++
Sources/Models/Model.hpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
1
2019-03-13T08:26:38.000Z
2019-03-13T08:26:38.000Z
Sources/Models/Model.hpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
null
null
null
Sources/Models/Model.hpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include "Renderer/Buffers/IndexBuffer.hpp" #include "Renderer/Buffers/VertexBuffer.hpp" #include "Resources/Resources.hpp" #include "IVertex.hpp" namespace acid { /// <summary> /// Class that represents a OBJ model. /// </summary> class ACID_EXPORT Model : public IResource { private: std::string m_filename; std::shared_ptr<VertexBuffer> m_vertexBuffer; std::shared_ptr<IndexBuffer> m_indexBuffer; std::vector<float> m_pointCloud; Vector3 m_minExtents; Vector3 m_maxExtents; public: /// <summary> /// Creates a new empty model. /// </summary> Model(); /// <summary> /// Creates a new model. /// </summary> /// <param name="vertices"> The model vertices. </param> /// <param name="indices"> The model indices. </param> /// <param name="name"> The model name. </param> Model(std::vector<IVertex *> &vertices, std::vector<uint32_t> &indices, const std::string &name = ""); /// <summary> /// Creates a new model without indices. /// </summary> /// <param name="vertices"> The model vertices. </param> /// <param name="name"> The model name. </param> Model(std::vector<IVertex *> &vertices, const std::string &name = ""); /// <summary> /// Deconstructor for the model. /// </summary> ~Model(); void CmdRender(const CommandBuffer &commandBuffer, const uint32_t &instances = 1); std::string GetFilename() override { return m_filename; } Vector3 GetMinExtents() const { return m_minExtents; } Vector3 GetMaxExtents() const { return m_maxExtents; } std::vector<float> GetPointCloud() const { return m_pointCloud; } float GetWidth() const { return m_maxExtents.m_x - m_minExtents.m_x; } float GetHeight() const { return m_maxExtents.m_y - m_minExtents.m_y; } float GetDepth() const { return m_maxExtents.m_z - m_minExtents.m_z; } float GetRadius() const; std::shared_ptr<VertexBuffer> GetVertexBuffer() const { return m_vertexBuffer; } std::shared_ptr<IndexBuffer> GetIndexBuffer() const { return m_indexBuffer; } protected: void Set(std::vector<IVertex *> &vertices, std::vector<uint32_t> &indices, const std::string &name = ""); private: void CalculateBounds(const std::vector<IVertex *> &vertices); }; }
27.240964
107
0.688633
hhYanGG
43fef5d10e4d4fc82f09d5468593b67c60f98ed9
6,812
cpp
C++
ventana_03/ventana_03.cpp
asm128/101_graphics
8bcdc6cdd7c471e6fdb00df777a05f6afdb7f986
[ "Apache-2.0" ]
1
2020-02-06T00:48:35.000Z
2020-02-06T00:48:35.000Z
ventana_03/ventana_03.cpp
asm128/101_graphics
8bcdc6cdd7c471e6fdb00df777a05f6afdb7f986
[ "Apache-2.0" ]
null
null
null
ventana_03/ventana_03.cpp
asm128/101_graphics
8bcdc6cdd7c471e6fdb00df777a05f6afdb7f986
[ "Apache-2.0" ]
null
null
null
#include <Windows.h> #include "framework.h" // Callback for window events (required to handle window events such as click or closing the window) LRESULT WINAPI WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_DESTROY: // Catch the window's DESTROY message which is posted to the queue when the window is closed. PostQuitMessage(0); // Signal the WM_QUIT message. } return DefWindowProc(hWnd, uMsg, wParam, lParam); } // Use this to convert from our color format to MS Windows' format. COLORREF toColorRef (SColor color) { return ((int)color.r) | (((int)color.g) << 8) | (((int)color.b) << 16); } // Assigns a color value to the target pixel array void setPixel (SColor * target, SCoord sizeTarget, SCoord position, SColor color) { if( position.x >= 0 && position.x < sizeTarget.x && position.y >= 0 && position.y < sizeTarget.y ) // Make sure the pixel is inside the array boundaries before assigning in order to prevent a memory access violation. target[position.x + sizeTarget.x * position.y] = color; } int drawRectangle (SColor * target, SCoord sizeTarget, SCoord position, SCoord size, SColor color) { for(int y = 0; y < size.y; ++y) // bajo un y for(int x = 0; x < size.x; ++x) { // dibujo todos los x SCoord finalPosition = {position.x + x, position.y + y}; setPixel(target, sizeTarget, finalPosition, color); } return 0; } int drawCircle (SColor * target, SCoord sizeTarget, SCoord position, double radius, SColor color) { for(int y = -(int)radius; y < radius; ++y) // bajo un y for(int x = -(int)radius; x < radius; ++x) { // dibujo todos los x SCoord testPosition = {x, y}; if(testPosition.Length() < radius) { SCoord finalPosition = {position.x + x, position.y + y}; setPixel(target, sizeTarget, finalPosition, color); } } return 0; } // Copy pixels to window's client area. int drawTarget (HDC dc, SColor * pixels, SCoord size) { for(int y = 0; y < size.y; ++y) // bajo un y for(int x = 0; x < size.x; ++x) // dibujo todos los x SetPixel(dc, x, y, toColorRef(pixels[y * size.x + x])); // Call the WinAPI SetPixel() function (which is very slow). return 0; } // Generate a 64-bit pseudorandom value. uint64_t noise (uint64_t x, uint64_t noiseSeed = 16381) noexcept { x = (x << 13) ^ x; x = (x * (x * x * noiseSeed + 715827883ULL) + 10657331232548839ULL); return x ^ (x >> 16); } int WINAPI WinMain ( _In_ HINSTANCE hInstance , _In_opt_ HINSTANCE //hPrevInstance , _In_ LPSTR //lpCmdLine , _In_ int nShowCmd ) { // Specify window class parameters. WNDCLASSEX wndClass = {sizeof(WNDCLASSEX)}; const char className [] = "ventana_main"; wndClass.lpfnWndProc = WndProc; wndClass.lpszClassName = className; wndClass.hInstance = hInstance; RegisterClassEx(&wndClass); // Registers the class // Create the window SCoord windowSize = {640, 480}; SCoord windowPosition = {100, 100}; const char windowTitle [] = "Ventana 0"; HWND newWindow = CreateWindowExA(0, className, windowTitle, WS_OVERLAPPEDWINDOW , windowPosition.x , windowPosition.y , windowSize.x , windowSize.y , 0, 0, hInstance, 0 ); ShowWindow(newWindow, nShowCmd); // The window is hidden by default. Show the window with the SW_SHOW parameter. bool running = true; // ----- Set some variables to enable changing the shape of things during execution SColor color = {0, 0, 0xFF}; double factor = 1; SCoord rectanglePosition = {100, 100}; // SCoord circlePosition = {400, 400}; // int circleRadius = 64; uint64_t iStep = 0; // The iteration step of the main loop SColor * targetPixels = 0; // Store here the memory address of our local pixel area while(running) { // Loop until the window is closed MSG msg = {}; while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { // Retrieve the first message from the event queue TranslateMessage(&msg); DispatchMessage(&msg); // This function causes our WndProc() function to be called with the message as parameter if(msg.message == WM_QUIT) // This message is sent by PostQuitMessage(0) used in the window event processor running = false; // Stop execution by ending the main loop } // ----- Adjust target pixels memory size to match the window size in case it's changed. RECT rc = {}; GetClientRect(newWindow, &rc); if(windowSize.x != rc.right || windowSize.y != rc.bottom) { windowSize = {rc.right, rc.bottom}; free(targetPixels); // Free the previous memory used for drawing (if any). targetPixels = (SColor*)malloc(windowSize.x * (uint64_t)windowSize.y * sizeof(SColor)); // Get memory for drawing. } if(0 == targetPixels) return EXIT_FAILURE; // ----- Change some parameters on each iteration (also called "frame") to animate the resulting shapes. factor += .05; if(factor > 1) factor = 0; circlePosition.x += int(10 * factor); if(circlePosition.x >= windowSize.x) circlePosition.x = -circleRadius * 2; // ----- Draw random noise background. const int pixelCount = windowSize.x * windowSize.y; for(uint64_t iPixel = 0; iPixel < pixelCount; ++iPixel) targetPixels[iPixel] = { (uint8_t)(noise(iStep * pixelCount * 3 + iPixel * 3 + 0)) // Don't care about this formula right now , (uint8_t)(noise(iStep * pixelCount * 3 + iPixel * 3 + 1)) // But essentially what it does is to call noise() making sure it gets a different parameter value on each iteration, , (uint8_t)(noise(iStep * pixelCount * 3 + iPixel * 3 + 2)) // for each frame, during the entire execution of the program. }; // ----- Draw some shapes to our in-memory image. drawRectangle (targetPixels, windowSize, rectanglePosition , {(int)(256 * factor), 8}, color * factor); drawCircle (targetPixels, windowSize, circlePosition , circleRadius * factor, color * factor); // ----- Copy the resulting in-memory image to the client area memory of the window. HDC dc = GetDC(newWindow); // Get the window's Device Context, which provides access to the drawing device and to the client area of the window. drawBuffer (dc, targetPixels, windowSize); // Copy the target to the window's client area (fast version). //drawTarget (dc, targetPixels, windowSize); // Copy the target to the window's client area (slow version). ReleaseDC(newWindow, dc); // The device context needs to be unlocked after use. ++iStep; // Increase our frame counter. } free(targetPixels); // Free the memory used for drawing UnregisterClass(className, hInstance); return EXIT_SUCCESS; }
43.948387
181
0.659718
asm128
43fffefb06ef4149b1f413c347bf67e6badaf05e
4,990
cpp
C++
nanosrv/nanosoft/snmp/snmpparser.cpp
zolotov-av/nanosoft
2aebb09d7d8a424d4de9b57d7586dbb72eed9fa0
[ "MIT" ]
1
2019-11-19T14:31:37.000Z
2019-11-19T14:31:37.000Z
nanosrv/nanosoft/snmp/snmpparser.cpp
zolotov-av/nanosoft
2aebb09d7d8a424d4de9b57d7586dbb72eed9fa0
[ "MIT" ]
null
null
null
nanosrv/nanosoft/snmp/snmpparser.cpp
zolotov-av/nanosoft
2aebb09d7d8a424d4de9b57d7586dbb72eed9fa0
[ "MIT" ]
1
2020-01-14T10:30:59.000Z
2020-01-14T10:30:59.000Z
#include <nanosoft/snmp/snmpparser.h> #include <stdio.h> #include <string.h> SNMPParser::SNMPParser() { } SNMPParser::~SNMPParser() { } /** * Обработчик чтения переменной */ void SNMPParser::onGetValue(const int *oid, size_t len) { printf(" GET(%d.%d", oid[0], oid[1]); for(size_t i = 2; i < len; i++) printf(".%d", oid[i]); printf(")\n"); } /** * GET-request oid binding */ bool SNMPParser::parseGetValue(const unsigned char *&data, const unsigned char *limit) { printf(" GET value\n"); asn1_header_t h; if ( ! readHeader(h, data, limit) ) return false; const unsigned char *p = h.data; const unsigned char *end = h.limit; int oid[ASN1_OID_MAXLEN]; size_t len; if ( ! readOID(oid, len, p, end) ) return false; printf(" OID: %d.%d", oid[0], oid[1]); for(size_t i = 2; i < len ; i++) { printf(".%d", oid[i]); } printf("\n"); if ( ! readNULL(p, end) ) return false; onGetValue(oid, len); data = end; return true; } /** * GET-request oid bindings */ bool SNMPParser::parseGetBindings(const unsigned char *&data, const unsigned char *limit) { printf(" GET bindings, 0x%02X\n", data[0]); asn1_header_t h; if ( ! readHeader(h, data, limit) ) return false; const unsigned char *p = h.data; const unsigned char *end = h.limit; while ( p < end ) { if ( ! parseGetValue(p, end) ) return false; } data = end; return true; } /** * GET-request */ bool SNMPParser::parseGetRequest(const unsigned char *data, const unsigned char *limit) { printf(" parse SNMP GET-request\n"); if ( ! readInt(requestID, data, limit) ) return false; printf(" requestID: %d\n", requestID); if ( ! readInt(errorStatus, data, limit) ) return false; printf(" errorStatus: %d\n", errorStatus); if ( ! readInt(errorIndex, data, limit) ) return false; printf(" errorIndex: %d\n", errorIndex); if ( ! parseGetBindings(data, limit) ) return false; return true; } /** * Обработчик чтения переменной */ void SNMPParser::onResponseValueInt(const int *oid, size_t len, int value) { printf(" GET(%d.%d", oid[0], oid[1]); for(size_t i = 2; i < len; i++) printf(".%d", oid[i]); printf(") = %u\n", value); } /** * GET-response oid binding */ bool SNMPParser::parseResponseValue(const unsigned char *&data, const unsigned char *limit) { printf(" Response value\n"); asn1_header_t h; if ( ! readHeader(h, data, limit) ) return false; if ( h.type != 0x30 ) return false; const unsigned char *p = h.data; const unsigned char *end = h.limit; int oid[ASN1_OID_MAXLEN]; size_t len; if ( ! readOID(oid, len, p, end) ) return false; printf(" OID: %d.%d", oid[0], oid[1]); for(size_t i = 2; i < len ; i++) { printf(".%d", oid[i]); } printf("\n"); int value; if ( ! readInt(value, p, end) ) return false; onResponseValueInt(oid, len, value); data = end; return true; } /** * GET-response oid bindings */ bool SNMPParser::parseResponseBindings(const unsigned char *&data, const unsigned char *limit) { printf(" Response bindings, 0x%02X\n", data[0]); asn1_header_t h; if ( ! readHeader(h, data, limit) ) return false; if ( h.type != 0x30 ) return false; const unsigned char *p = h.data; const unsigned char *end = h.limit; while ( p < end ) { if ( ! parseResponseValue(p, end) ) return false; } data = end; return true; } /** * GET-response */ bool SNMPParser::parseResponse(const unsigned char *data, const unsigned char *limit) { printf(" parse SNMP GET-response\n"); if ( ! readInt(requestID, data, limit) ) return false; printf(" requestID: %d\n", requestID); if ( ! readInt(errorStatus, data, limit) ) return false; printf(" errorStatus: %d\n", errorStatus); if ( ! readInt(errorIndex, data, limit) ) return false; printf(" errorIndex: %d\n", errorIndex); if ( ! parseResponseBindings(data, limit) ) return false; return true; } /** * Парсинг пакета */ bool SNMPParser::parse(const unsigned char *data, const unsigned char *limit) { printf("parse SNMP packet\n"); asn1_header_t h; if ( ! readHeader(h, data, limit) ) return false; printf("SNMP packet, type: 0x%02X\n", h.type); if ( ! readInt(version, data, limit) ) return false; printf("SNMP version: %d\n", version); if ( version != 1 ) return false; if ( ! readString(community, data, limit) ) return false; printf("SNMP community: '%s'\n", community); if ( ! readHeader(h, data, limit) ) return false; printf("SNMP sub-packet, type: 0x%02X\n", h.type); switch ( h.type ) { case 0xA0: if ( ! parseGetRequest(data, limit) ) return false; break; case 0xA2: if ( ! parseResponse(data, limit) ) return false; break; default: printf("unknown SNMP command: 0x%02X\n", h.type); return false; } return true; } /** * Парсинг пакета */ bool SNMPParser::parse(const unsigned char *data, size_t size) { bool status = parse(data, data + size); printf("%s", status ? "parse ok\n" : "parse fail\n"); return status; }
21.324786
94
0.635872
zolotov-av
a103d8269181b254d00b4da00abb8df864503e76
115,230
cpp
C++
asm/vm.cpp
janm31415/skiwi
851a006c2964d527cc38b7a71f3e835b8dab52b5
[ "MIT" ]
4
2020-10-06T14:09:13.000Z
2020-10-24T17:34:53.000Z
asm/vm.cpp
janm31415/skiwi
851a006c2964d527cc38b7a71f3e835b8dab52b5
[ "MIT" ]
null
null
null
asm/vm.cpp
janm31415/skiwi
851a006c2964d527cc38b7a71f3e835b8dab52b5
[ "MIT" ]
null
null
null
#include "vm.h" #include <iostream> #include <sstream> #include <cassert> #include <cmath> #include <algorithm> ASM_BEGIN namespace { bool is_8_bit(uint64_t number) { int8_t b = int8_t(number); return int64_t(b) == (int64_t)number; } bool is_16_bit(uint64_t number) { int16_t b = int16_t(number); return int64_t(b) == (int64_t)number; } bool is_32_bit(uint64_t number) { int32_t b = int32_t(number); return int64_t(b) == (int64_t)number; } int number_of_operands(const asmcode::operation& op) { switch (op) { case asmcode::ADD: return 2; case asmcode::ADDSD: return 2; case asmcode::AND: return 2; case asmcode::CALLEXTERNAL:return 1; case asmcode::CALL:return 1; case asmcode::COMMENT: return 0; case asmcode::CMP: return 2; case asmcode::CMPEQPD: return 2; case asmcode::CMPLTPD: return 2; case asmcode::CMPLEPD: return 2; case asmcode::CQO: return 0; case asmcode::CVTSI2SD: return 2; case asmcode::CVTTSD2SI:return 2; case asmcode::DEC: return 1; case asmcode::DIV: return 1; case asmcode::DIVSD: return 2; case asmcode::EXTERN: return 0; case asmcode::F2XM1:return 0; case asmcode::FADD: return 2; case asmcode::FADDP: return 0; case asmcode::FISTPQ: return 1; case asmcode::FILD:return 1; case asmcode::FLD: return 1; case asmcode::FLD1:return 0; case asmcode::FLDPI: return 0; case asmcode::FLDLN2:return 0; case asmcode::FMUL:return 2; case asmcode::FSIN:return 0; case asmcode::FCOS:return 0; case asmcode::FPATAN:return 0; case asmcode::FPTAN: return 0; case asmcode::FRNDINT:return 0; case asmcode::FSCALE: return 0; case asmcode::FSQRT:return 0; case asmcode::FSTP: return 1; case asmcode::FSUB: return 2; case asmcode::FSUBP: return 0; case asmcode::FSUBRP:return 0; case asmcode::FXCH: return 0; case asmcode::FYL2X: return 0; case asmcode::GLOBAL:return 0; case asmcode::LABEL:return 0; case asmcode::LABEL_ALIGNED:return 0; case asmcode::IDIV:return 1; case asmcode::IMUL:return 1; case asmcode::INC: return 1; case asmcode::JE: return 1; case asmcode::JL: return 1; case asmcode::JLE:return 1; case asmcode::JA: return 1; case asmcode::JB: return 1; case asmcode::JG: return 1; case asmcode::JGE:return 1; case asmcode::JNE:return 1; case asmcode::JMP:return 1; case asmcode::JES:return 1; case asmcode::JLS:return 1; case asmcode::JLES:return 1; case asmcode::JAS: return 1; case asmcode::JBS: return 1; case asmcode::JGS: return 1; case asmcode::JGES:return 1; case asmcode::JNES:return 1; case asmcode::JMPS:return 1; case asmcode::MOV: return 2; case asmcode::MOVQ: return 2; case asmcode::MOVMSKPD: return 2; case asmcode::MOVSD:return 2; case asmcode::MOVZX:return 2; case asmcode::MUL: return 1; case asmcode::MULSD:return 2; case asmcode::NEG:return 1; case asmcode::NOP:return 0; case asmcode::OR:return 2; case asmcode::POP: return 1; case asmcode::PUSH: return 1; case asmcode::RET: return 0; case asmcode::SAL: return 2; case asmcode::SAR: return 2; case asmcode::SETE: return 1; case asmcode::SETNE:return 1; case asmcode::SETL: return 1; case asmcode::SETG: return 1; case asmcode::SETLE:return 1; case asmcode::SETGE:return 1; case asmcode::SHL: return 2; case asmcode::SHR:return 2; case asmcode::SQRTPD:return 2; case asmcode::SUB: return 2; case asmcode::SUBSD: return 2; case asmcode::TEST: return 2; case asmcode::UCOMISD: return 2; case asmcode::XOR: return 2; case asmcode::XORPD: return 2; default: { std::stringstream str; str << asmcode::operation_to_string(op) << " number of operands unknown!"; throw std::logic_error(str.str()); } } } enum operand_immediate_type { _VARIABLE, _8BIT, _32BIT, _64BIT }; operand_immediate_type get_operand_immediate_type(const asmcode::operation& op) { switch (op) { case asmcode::CALL: return _32BIT; case asmcode::JE: return _32BIT; case asmcode::JL: return _32BIT; case asmcode::JLE:return _32BIT; case asmcode::JA: return _32BIT; case asmcode::JB: return _32BIT; case asmcode::JG: return _32BIT; case asmcode::JGE:return _32BIT; case asmcode::JNE:return _32BIT; case asmcode::JMP:return _32BIT; case asmcode::JES: return _8BIT; case asmcode::JLS: return _8BIT; case asmcode::JLES: return _8BIT; case asmcode::JAS: return _8BIT; case asmcode::JBS: return _8BIT; case asmcode::JGS: return _8BIT; case asmcode::JGES: return _8BIT; case asmcode::JNES: return _8BIT; case asmcode::JMPS: return _8BIT; default: return _VARIABLE; } } bool ignore_operation_as_bytecode(const asmcode::operation& op) { switch (op) { case asmcode::LABEL: return true; case asmcode::LABEL_ALIGNED: return true; case asmcode::GLOBAL: return true; case asmcode::COMMENT: return true; default: return false; } } void get_memory_size_type(uint8_t& opmem, bool& save_mem_size, const asmcode::operation& op, const asmcode::operand& oprnd, uint64_t oprnd_mem) { save_mem_size = false; opmem = 0; switch (oprnd) { case asmcode::EMPTY: case asmcode::AL: case asmcode::AH: case asmcode::BL: case asmcode::BH: case asmcode::CL: case asmcode::CH: case asmcode::DL: case asmcode::DH: case asmcode::RAX: case asmcode::RBX: case asmcode::RCX: case asmcode::RDX: case asmcode::RSI: case asmcode::RDI: case asmcode::RSP: case asmcode::RBP: case asmcode::R8: case asmcode::R9: case asmcode::R10: case asmcode::R11: case asmcode::R12: case asmcode::R13: case asmcode::R14: case asmcode::R15: case asmcode::ST0: case asmcode::ST1: case asmcode::ST2: case asmcode::ST3: case asmcode::ST4: case asmcode::ST5: case asmcode::ST6: case asmcode::ST7: case asmcode::XMM0: case asmcode::XMM1: case asmcode::XMM2: case asmcode::XMM3: case asmcode::XMM4: case asmcode::XMM5: case asmcode::XMM6: case asmcode::XMM7: case asmcode::XMM8: case asmcode::XMM9: case asmcode::XMM10: case asmcode::XMM11: case asmcode::XMM12: case asmcode::XMM13: case asmcode::XMM14: case asmcode::XMM15: return; case asmcode::NUMBER: { auto memtype = get_operand_immediate_type(op); switch (memtype) { case _VARIABLE: break; case _8BIT: opmem = 1; return; case _32BIT: opmem = 3; return; case _64BIT: opmem = 4; return; } } default: break; } if (is_8_bit(oprnd_mem)) opmem = 1; else if (is_16_bit(oprnd_mem)) { save_mem_size = true; opmem = 2; } else if (is_32_bit(oprnd_mem)) { save_mem_size = true; opmem = 3; } else { save_mem_size = true; opmem = 4; } if (oprnd == asmcode::LABELADDRESS) { save_mem_size = true; opmem = 4; } } /* byte 1: operation opcode: equal to (int)asmcode::operation value of instr.oper byte 2: first operand: equal to (int)asmcode::operand of instr.operand1 byte 3: second operand: equal to (int)asmcode::operand of instr.operand2 byte 4: information on operand1_mem and operand2_mem First four bits equal to: 0 => instr.operand1_mem equals zero : 1 => instr.operand1_mem needs 8 bits : 2 => instr.operand1_mem needs 16 bits : 3 => instr.operand1_mem needs 32 bits : 4 => instr.operand1_mem needs 64 bits Last four bits equal to : 0 => instr.operand2_mem equals zero : 1 => instr.operand2_mem needs 8 bits : 2 => instr.operand2_mem needs 16 bits : 3 => instr.operand2_mem needs 32 bits : 4 => instr.operand2_mem needs 64 bits byte 5+: instr.operand1_mem using as many bytes as warranted by byte 4, followed by instr.operand2_mem using as many bytes as warranted by byte4. */ uint64_t fill_vm_bytecode(const asmcode::instruction& instr, uint8_t* opcode_stream) { uint64_t sz = 0; if (ignore_operation_as_bytecode(instr.oper)) return sz; opcode_stream[sz++] = (uint8_t)instr.oper; uint8_t op1mem = 0; uint8_t op2mem = 0; int nr_ops = number_of_operands(instr.oper); if (nr_ops == 1) { bool savemem = true; get_memory_size_type(op1mem, savemem, instr.oper, instr.operand1, instr.operand1_mem); if (savemem) { opcode_stream[sz++] = (uint8_t)instr.operand1; opcode_stream[sz++] = op1mem; } else { opcode_stream[sz++] = (uint8_t)instr.operand1 | operand_has_8bit_mem; } } else if (nr_ops == 2) { bool savemem1 = true; bool savemem2 = true; get_memory_size_type(op1mem, savemem1, instr.oper, instr.operand1, instr.operand1_mem); get_memory_size_type(op2mem, savemem2, instr.oper, instr.operand2, instr.operand2_mem); if (savemem1 || savemem2) { opcode_stream[sz++] = (uint8_t)instr.operand1; opcode_stream[sz++] = (uint8_t)instr.operand2; opcode_stream[sz++] = (uint8_t)(op2mem << 4) | op1mem; } else { opcode_stream[sz++] = (uint8_t)instr.operand1 | operand_has_8bit_mem; opcode_stream[sz++] = (uint8_t)instr.operand2 | operand_has_8bit_mem; } } switch (op1mem) { case 1: opcode_stream[sz++] = (uint8_t)instr.operand1_mem; break; case 2: *(reinterpret_cast<uint16_t*>(opcode_stream + sz)) = (uint16_t)instr.operand1_mem; sz += 2; break; case 3: *(reinterpret_cast<uint32_t*>(opcode_stream + sz)) = (uint32_t)instr.operand1_mem; sz += 4; break; case 4: *(reinterpret_cast<uint64_t*>(opcode_stream + sz)) = (uint64_t)instr.operand1_mem; sz += 8; break; default: break; } switch (op2mem) { case 1: opcode_stream[sz++] = (uint8_t)instr.operand2_mem; break; case 2: *(reinterpret_cast<uint16_t*>(opcode_stream + sz)) = (uint16_t)instr.operand2_mem; sz += 2; break; case 3: *(reinterpret_cast<uint32_t*>(opcode_stream + sz)) = (uint32_t)instr.operand2_mem; sz += 4; break; case 4: *(reinterpret_cast<uint64_t*>(opcode_stream + sz)) = (uint64_t)instr.operand2_mem; sz += 8; break; default: break; } return sz; /* switch (instr.oper) { case asmcode::LABEL: return 0; case asmcode::LABEL_ALIGNED: return 0; case asmcode::GLOBAL: return 0; case asmcode::COMMENT: return 0; case asmcode::NOP: { opcode_stream[0] = (uint8_t)instr.oper; return 1; } default: break; } opcode_stream[0] = (uint8_t)instr.oper; opcode_stream[1] = (uint8_t)instr.operand1; opcode_stream[2] = (uint8_t)instr.operand2; uint8_t op1mem = 0; uint8_t op2mem = 0; if (instr.operand1_mem != 0) { if (is_8_bit(instr.operand1_mem)) op1mem = 1; else if (is_16_bit(instr.operand1_mem)) op1mem = 2; else if (is_32_bit(instr.operand1_mem)) op1mem = 3; else op1mem = 4; } if (op1mem < 4) { if (instr.operand1 == asmcode::LABELADDRESS) op1mem = 4; } if (op1mem < 3) { if (instr.oper == asmcode::CALL) op1mem = 3; if (instr.oper == asmcode::JMP) op1mem = 3; if (instr.oper == asmcode::JA) op1mem = 3; if (instr.oper == asmcode::JB) op1mem = 3; if (instr.oper == asmcode::JE) op1mem = 3; if (instr.oper == asmcode::JL) op1mem = 3; if (instr.oper == asmcode::JLE) op1mem = 3; if (instr.oper == asmcode::JG) op1mem = 3; if (instr.oper == asmcode::JGE) op1mem = 3; if (instr.oper == asmcode::JNE) op1mem = 3; } if (instr.operand2_mem != 0) { if (is_8_bit(instr.operand2_mem)) op2mem = 1; else if (is_16_bit(instr.operand2_mem)) op2mem = 2; else if (is_32_bit(instr.operand2_mem)) op2mem = 3; else op2mem = 4; } if (op2mem < 4) { if (instr.operand2 == asmcode::LABELADDRESS) op2mem = 4; } opcode_stream[3] = (uint8_t)(op2mem << 4) | op1mem; uint64_t sz = 4; switch (op1mem) { case 1: opcode_stream[sz++] = (uint8_t)instr.operand1_mem; break; case 2: *(reinterpret_cast<uint16_t*>(opcode_stream + sz)) = (uint16_t)instr.operand1_mem; sz += 2; break; case 3: *(reinterpret_cast<uint32_t*>(opcode_stream + sz)) = (uint32_t)instr.operand1_mem; sz += 4; break; case 4: *(reinterpret_cast<uint64_t*>(opcode_stream + sz)) = (uint64_t)instr.operand1_mem; sz += 8; break; default: break; } switch (op2mem) { case 1: opcode_stream[sz++] = (uint8_t)instr.operand2_mem; break; case 2: *(reinterpret_cast<uint16_t*>(opcode_stream + sz)) = (uint16_t)instr.operand2_mem; sz += 2; break; case 3: *(reinterpret_cast<uint32_t*>(opcode_stream + sz)) = (uint32_t)instr.operand2_mem; sz += 4; break; case 4: *(reinterpret_cast<uint64_t*>(opcode_stream + sz)) = (uint64_t)instr.operand2_mem; sz += 8; break; default: break; } return sz; */ } void first_pass(first_pass_data& data, asmcode& code, const std::map<std::string, uint64_t>& externals) { uint8_t buffer[255]; data.size = 0; data.label_to_address.clear(); for (auto it = code.get_instructions_list().begin(); it != code.get_instructions_list().end(); ++it) { std::vector<std::pair<size_t, int>> nops_to_add; for (size_t i = 0; i < it->size(); ++i) { auto instr = (*it)[i]; switch (instr.oper) { case asmcode::CALLEXTERNAL: { auto it2 = externals.find(instr.text); if (it2 != externals.end()) { instr.oper = asmcode::MOV; instr.operand1 = asmcode::RAX; instr.operand2 = asmcode::NUMBER; instr.operand2_mem = it2->second; data.size += fill_vm_bytecode(instr, buffer); instr.oper = asmcode::CALLEXTERNAL; instr.operand1 = asmcode::RAX; instr.operand2 = asmcode::EMPTY; data.size += fill_vm_bytecode(instr, buffer); } else { if (instr.operand1 == asmcode::EMPTY || instr.operand1 == asmcode::NUMBER) throw std::logic_error("CALLEXTERNAL used for non external call"); data.size += fill_vm_bytecode(instr, buffer); } break; } case asmcode::CALL: { auto it2 = externals.find(instr.text); if (it2 != externals.end()) { instr.oper = asmcode::MOV; instr.operand1 = asmcode::RAX; instr.operand2 = asmcode::NUMBER; instr.operand2_mem = it2->second; data.size += fill_vm_bytecode(instr, buffer); instr.oper = asmcode::CALL; instr.operand1 = asmcode::RAX; instr.operand2 = asmcode::EMPTY; data.size += fill_vm_bytecode(instr, buffer); } else { if (instr.operand1 == asmcode::EMPTY) { instr.operand1 = asmcode::NUMBER; instr.operand1_mem = 0x11111111; } data.size += fill_vm_bytecode(instr, buffer); } break; } case asmcode::JMP: case asmcode::JE: case asmcode::JL: case asmcode::JLE: case asmcode::JG: case asmcode::JA: case asmcode::JB: case asmcode::JGE: case asmcode::JNE: { if (instr.operand1 == asmcode::EMPTY) { instr.operand1 = asmcode::NUMBER; instr.operand1_mem = 0x11111111; } data.size += fill_vm_bytecode(instr, buffer); break; } case asmcode::JMPS: case asmcode::JES: case asmcode::JLS: case asmcode::JLES: case asmcode::JGS: case asmcode::JAS: case asmcode::JBS: case asmcode::JGES: case asmcode::JNES: { instr.operand1 = asmcode::NUMBER; instr.operand1_mem = 0x11; data.size += fill_vm_bytecode(instr, buffer); break; } case asmcode::LABEL: data.label_to_address[instr.text] = data.size; break; case asmcode::LABEL_ALIGNED: if (data.size & 7) { int nr_of_nops = 8 - (data.size & 7); data.size += nr_of_nops; nops_to_add.emplace_back(i, nr_of_nops); } data.label_to_address[instr.text] = data.size; break; case asmcode::GLOBAL: if (data.size & 7) { int nr_of_nops = 8 - (data.size & 7); data.size += nr_of_nops; nops_to_add.emplace_back(i, nr_of_nops); } data.label_to_address[instr.text] = data.size; break; case asmcode::EXTERN: { auto it2 = externals.find(instr.text); if (it2 == externals.end()) throw std::logic_error("error: external is not defined"); data.external_to_address[instr.text] = it2->second; break; } default: data.size += fill_vm_bytecode(instr, buffer); break; } } size_t nops_offset = 0; for (auto nops : nops_to_add) { std::vector<asmcode::instruction> nops_instructions(nops.second, asmcode::instruction(asmcode::NOP)); it->insert(it->begin() + nops_offset + nops.first, nops_instructions.begin(), nops_instructions.end()); nops_offset += nops.second; } } } uint8_t* second_pass(uint8_t* func, const first_pass_data& data, const asmcode& code) { uint64_t address_start = (uint64_t)(reinterpret_cast<uint64_t*>(func)); uint8_t* start = func; for (auto it = code.get_instructions_list().begin(); it != code.get_instructions_list().end(); ++it) { for (asmcode::instruction instr : *it) { if (instr.operand1 == asmcode::LABELADDRESS) { auto it2 = data.label_to_address.find(instr.text); if (it2 == data.label_to_address.end()) throw std::logic_error("error: label is not defined"); instr.operand1_mem = address_start + it2->second; } if (instr.operand2 == asmcode::LABELADDRESS) { auto it2 = data.label_to_address.find(instr.text); if (it2 == data.label_to_address.end()) throw std::logic_error("error: label is not defined"); instr.operand2_mem = address_start + it2->second; } switch (instr.oper) { case asmcode::CALL: { if (instr.operand1 != asmcode::EMPTY) break; auto it_label = data.label_to_address.find(instr.text); auto it_external = data.external_to_address.find(instr.text); if (it_external != data.external_to_address.end()) { asmcode::instruction extra_instr(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, it_external->second); func += fill_vm_bytecode(extra_instr, func); instr.operand1 = asmcode::RAX; } else if (it_label != data.label_to_address.end()) { int64_t address = (int64_t)it_label->second; int64_t current = (int64_t)(func - start); instr.operand1 = asmcode::NUMBER; instr.operand1_mem = (int64_t(address - current)); } else throw std::logic_error("second_pass error: call target does not exist"); break; } case asmcode::JE: case asmcode::JL: case asmcode::JLE: case asmcode::JG: case asmcode::JA: case asmcode::JB: case asmcode::JGE: case asmcode::JNE: { if (instr.operand1 != asmcode::EMPTY) break; auto it2 = data.label_to_address.find(instr.text); if (it2 == data.label_to_address.end()) throw std::logic_error("second_pass error: label does not exist"); int64_t address = (int64_t)it2->second; int64_t current = (int64_t)(func - start); instr.operand1 = asmcode::NUMBER; instr.operand1_mem = (int64_t(address - current)); break; } case asmcode::JMP: { if (instr.operand1 != asmcode::EMPTY) break; auto it2 = data.label_to_address.find(instr.text); if (it2 == data.label_to_address.end()) throw std::logic_error("second_pass error: label does not exist"); int64_t address = (int64_t)it2->second; int64_t current = (int64_t)(func - start); instr.operand1 = asmcode::NUMBER; instr.operand1_mem = (int64_t(address - current)); break; } case asmcode::JES: case asmcode::JLS: case asmcode::JLES: case asmcode::JGS: case asmcode::JAS: case asmcode::JBS: case asmcode::JGES: case asmcode::JNES: case asmcode::JMPS: { if (instr.operand1 != asmcode::EMPTY) break; auto it2 = data.label_to_address.find(instr.text); if (it2 == data.label_to_address.end()) throw std::logic_error("second_pass error: label does not exist"); int64_t address = (int64_t)it2->second; int64_t current = (int64_t)(func - start); instr.operand1 = asmcode::NUMBER; instr.operand1_mem = (int64_t(address - current)); if ((int64_t)instr.operand1_mem > 127 || (int64_t)instr.operand1_mem < -128) throw std::logic_error("second_pass error: jump short is too far"); break; } } func += fill_vm_bytecode(instr, func); } } while ((uint64_t)(func - start) < data.size) { asmcode::instruction dummy(asmcode::NOP); func += fill_vm_bytecode(dummy, func); } return func; } } void* vm_bytecode(uint64_t& size, first_pass_data& d, asmcode& code, const std::map<std::string, uint64_t>& externals) { d.external_to_address.clear(); d.label_to_address.clear(); first_pass(d, code, externals); uint8_t* compiled_func = new uint8_t[d.size + d.data_size]; if (!compiled_func) throw std::runtime_error("Could not allocate virtual memory"); uint8_t* func_end = second_pass((uint8_t*)compiled_func, d, code); uint64_t size_used = func_end - (uint8_t*)compiled_func; if (size_used != d.size) { throw std::logic_error("error: error in size computation."); } size = d.size + d.data_size; return (void*)compiled_func; } void* vm_bytecode(uint64_t& size, asmcode& code, const std::map<std::string, uint64_t>& externals) { first_pass_data d; return vm_bytecode(size, d, code, externals); } void* vm_bytecode(uint64_t& size, first_pass_data& d, asmcode& code) { std::map<std::string, uint64_t> externals; return vm_bytecode(size, d, code, externals); } void* vm_bytecode(uint64_t& size, asmcode& code) { std::map<std::string, uint64_t> externals; return vm_bytecode(size, code, externals); } void free_bytecode(void* f, uint64_t size) { (void*)size; delete[] (uint8_t*)f; } /* byte 1: operation opcode: equal to (int)asmcode::operation value of instr.oper byte 2: first operand: equal to (int)asmcode::operand of instr.operand1 byte 3: second operand: equal to (int)asmcode::operand of instr.operand2 byte 4: information on operand1_mem and operand2_mem First four bits equal to: 0 => instr.operand1_mem equals zero : 1 => instr.operand1_mem needs 8 bits : 2 => instr.operand1_mem needs 16 bits : 3 => instr.operand1_mem needs 32 bits : 4 => instr.operand1_mem needs 64 bits Last four bits equal to : 0 => instr.operand2_mem equals zero : 1 => instr.operand2_mem needs 8 bits : 2 => instr.operand2_mem needs 16 bits : 3 => instr.operand2_mem needs 32 bits : 4 => instr.operand2_mem needs 64 bits byte 5+: instr.operand1_mem using as many bytes as warranted by byte 4, followed by instr.operand2_mem using as many bytes as warranted by byte4. */ uint64_t disassemble_bytecode(asmcode::operation& op, asmcode::operand& operand1, asmcode::operand& operand2, uint64_t& operand1_mem, uint64_t& operand2_mem, const uint8_t* bytecode) { operand1 = asmcode::EMPTY; operand2 = asmcode::EMPTY; operand1_mem = 0; operand2_mem = 0; uint64_t sz = 0; uint8_t op1mem = 0; uint8_t op2mem = 0; op = (asmcode::operation)bytecode[sz++]; int nr_ops = number_of_operands(op); if (nr_ops == 0) return sz; if (nr_ops == 1) { uint8_t op1 = bytecode[sz++]; //bool savemem = true; //get_memory_size_type(op1mem, savemem, op, operand1, 0); //if (savemem) if ((op1 & operand_has_8bit_mem) == 0) { op1mem = bytecode[sz++]; operand1 = (asmcode::operand)op1; } else { op1 &= ~operand_has_8bit_mem; operand1 = (asmcode::operand)op1; bool savemem; get_memory_size_type(op1mem, savemem, op, operand1, 0); } } else { assert(nr_ops == 2); uint8_t op1 = bytecode[sz++]; uint8_t op2 = bytecode[sz++]; //bool savemem1 = true; //get_memory_size_type(op1mem, savemem1, op, operand1, 0); //bool savemem2 = true; //get_memory_size_type(op2mem, savemem2, op, operand2, 0); //if (savemem1 || savemem2) if ((op1 & operand_has_8bit_mem) == 0) { op1mem = bytecode[sz] & 15; op2mem = bytecode[sz] >> 4; operand1 = (asmcode::operand)op1; operand2 = (asmcode::operand)op2; ++sz; } else { op1 &= ~operand_has_8bit_mem; op2 &= ~operand_has_8bit_mem; operand1 = (asmcode::operand)op1; operand2 = (asmcode::operand)op2; bool savemem; get_memory_size_type(op1mem, savemem, op, operand1, 0); get_memory_size_type(op2mem, savemem, op, operand2, 0); } } switch (op1mem) { case 1: operand1_mem = (int8_t)bytecode[sz++]; break; case 2: operand1_mem = (int16_t)(*reinterpret_cast<const uint16_t*>(bytecode + sz)); sz += 2; break; case 3: operand1_mem = (int32_t)(*reinterpret_cast<const uint32_t*>(bytecode + sz)); sz += 4; break; case 4: operand1_mem = *reinterpret_cast<const uint64_t*>(bytecode + sz); sz += 8; break; default: operand1_mem = 0; break; } switch (op2mem) { case 1: operand2_mem = (int8_t)bytecode[sz++]; break; case 2: operand2_mem = (int16_t)(*reinterpret_cast<const uint16_t*>(bytecode + sz)); sz += 2; break; case 3: operand2_mem = (int32_t)(*reinterpret_cast<const uint32_t*>(bytecode + sz)); sz += 4; break; case 4: operand2_mem = *reinterpret_cast<const uint64_t*>(bytecode + sz); sz += 8; break; default: operand2_mem = 0; break; } return sz; /* op = (asmcode::operation)bytecode[0]; if (op == asmcode::NOP) return 1; operand1 = (asmcode::operand)bytecode[1]; operand2 = (asmcode::operand)bytecode[2]; uint8_t op1mem = bytecode[3] & 15; uint8_t op2mem = bytecode[3] >> 4; uint64_t sz = 4; switch (op1mem) { case 1: operand1_mem = (int8_t)bytecode[sz++]; break; case 2: operand1_mem = (int16_t)(*reinterpret_cast<const uint16_t*>(bytecode + sz)); sz += 2; break; case 3: operand1_mem = (int32_t)(*reinterpret_cast<const uint32_t*>(bytecode + sz)); sz += 4; break; case 4: operand1_mem = *reinterpret_cast<const uint64_t*>(bytecode + sz); sz += 8; break; default: operand1_mem = 0; break; } switch (op2mem) { case 1: operand2_mem = (int8_t)bytecode[sz++]; break; case 2: operand2_mem = (int16_t)(*reinterpret_cast<const uint16_t*>(bytecode+sz)); sz += 2; break; case 3: operand2_mem = (int32_t)(*reinterpret_cast<const uint32_t*>(bytecode+sz)); sz += 4; break; case 4: operand2_mem = *reinterpret_cast<const uint64_t*>(bytecode+sz); sz += 8; break; default: operand2_mem = 0; break; } return sz; */ } registers::registers() { rbp = (uint64_t)(&stack[0]); rsp = (uint64_t)(&stack[256]); fpstackptr = &fpstack[16]; eflags = 0; } namespace { uint8_t* get_address_8bit(asmcode::operand oper, uint64_t operand_mem, registers& regs) { switch (oper) { case asmcode::EMPTY: return nullptr; case asmcode::AL: return (uint8_t*)&regs.rax; case asmcode::AH: return (uint8_t*)(((uint8_t*)(&regs.rax)) + 1); case asmcode::BL: return (uint8_t*)&regs.rbx; case asmcode::BH: return (uint8_t*)(((uint8_t*)(&regs.rbx)) + 1); case asmcode::CL: return (uint8_t*)&regs.rcx; case asmcode::CH: return (uint8_t*)(((uint8_t*)(&regs.rcx)) + 1); case asmcode::DL: return (uint8_t*)&regs.rdx; case asmcode::DH: return (uint8_t*)(((uint8_t*)(&regs.rdx)) + 1); case asmcode::RAX: return nullptr; case asmcode::RBX: return nullptr; case asmcode::RCX: return nullptr; case asmcode::RDX: return nullptr; case asmcode::RDI: return nullptr; case asmcode::RSI: return nullptr; case asmcode::RSP: return nullptr; case asmcode::RBP: return nullptr; case asmcode::R8: return nullptr; case asmcode::R9: return nullptr; case asmcode::R10: return nullptr; case asmcode::R11: return nullptr; case asmcode::R12: return nullptr; case asmcode::R13: return nullptr; case asmcode::R14: return nullptr; case asmcode::R15: return nullptr; case asmcode::MEM_RAX: return nullptr; case asmcode::MEM_RBX: return nullptr; case asmcode::MEM_RCX: return nullptr; case asmcode::MEM_RDX: return nullptr; case asmcode::MEM_RDI: return nullptr; case asmcode::MEM_RSI: return nullptr; case asmcode::MEM_RSP: return nullptr; case asmcode::MEM_RBP: return nullptr; case asmcode::MEM_R8: return nullptr; case asmcode::MEM_R9: return nullptr; case asmcode::MEM_R10: return nullptr; case asmcode::MEM_R11: return nullptr; case asmcode::MEM_R12: return nullptr; case asmcode::MEM_R13: return nullptr; case asmcode::MEM_R14: return nullptr; case asmcode::MEM_R15: return nullptr; case asmcode::BYTE_MEM_RAX: return (uint8_t*)(regs.rax + operand_mem); case asmcode::BYTE_MEM_RBX: return (uint8_t*)(regs.rbx + operand_mem); case asmcode::BYTE_MEM_RCX: return (uint8_t*)(regs.rcx + operand_mem); case asmcode::BYTE_MEM_RDX: return (uint8_t*)(regs.rdx + operand_mem); case asmcode::BYTE_MEM_RDI: return (uint8_t*)(regs.rdi + operand_mem); case asmcode::BYTE_MEM_RSI: return (uint8_t*)(regs.rsi + operand_mem); case asmcode::BYTE_MEM_RSP: return (uint8_t*)(regs.rsp + operand_mem); case asmcode::BYTE_MEM_RBP: return (uint8_t*)(regs.rbp + operand_mem); case asmcode::BYTE_MEM_R8: return (uint8_t*)(regs.r8 + operand_mem); case asmcode::BYTE_MEM_R9: return (uint8_t*)(regs.r9 + operand_mem); case asmcode::BYTE_MEM_R10: return (uint8_t*)(regs.r10 + operand_mem); case asmcode::BYTE_MEM_R11: return (uint8_t*)(regs.r11 + operand_mem); case asmcode::BYTE_MEM_R12: return (uint8_t*)(regs.r12 + operand_mem); case asmcode::BYTE_MEM_R13: return (uint8_t*)(regs.r13 + operand_mem); case asmcode::BYTE_MEM_R14: return (uint8_t*)(regs.r14 + operand_mem); case asmcode::BYTE_MEM_R15: return (uint8_t*)(regs.r15 + operand_mem); case asmcode::NUMBER: return nullptr; case asmcode::ST0: return nullptr; case asmcode::ST1: return nullptr; case asmcode::ST2: return nullptr; case asmcode::ST3: return nullptr; case asmcode::ST4: return nullptr; case asmcode::ST5: return nullptr; case asmcode::ST6: return nullptr; case asmcode::ST7: return nullptr; case asmcode::XMM0: return nullptr; case asmcode::XMM1: return nullptr; case asmcode::XMM2: return nullptr; case asmcode::XMM3: return nullptr; case asmcode::XMM4: return nullptr; case asmcode::XMM5: return nullptr; case asmcode::XMM6: return nullptr; case asmcode::XMM7: return nullptr; case asmcode::XMM8: return nullptr; case asmcode::XMM9: return nullptr; case asmcode::XMM10:return nullptr; case asmcode::XMM11:return nullptr; case asmcode::XMM12:return nullptr; case asmcode::XMM13:return nullptr; case asmcode::XMM14:return nullptr; case asmcode::XMM15:return nullptr; case asmcode::LABELADDRESS: return nullptr; default: return nullptr; } } uint64_t* get_address_64bit(asmcode::operand oper, uint64_t operand_mem, registers& regs) { switch (oper) { case asmcode::EMPTY: return nullptr; case asmcode::AL: return nullptr; case asmcode::AH: return nullptr; case asmcode::BL: return nullptr; case asmcode::BH: return nullptr; case asmcode::CL: return nullptr; case asmcode::CH: return nullptr; case asmcode::DL: return nullptr; case asmcode::DH: return nullptr; case asmcode::RAX: return &regs.rax; case asmcode::RBX: return &regs.rbx; case asmcode::RCX: return &regs.rcx; case asmcode::RDX: return &regs.rdx; case asmcode::RDI: return &regs.rdi; case asmcode::RSI: return &regs.rsi; case asmcode::RSP: return &regs.rsp; case asmcode::RBP: return &regs.rbp; case asmcode::R8: return &regs.r8; case asmcode::R9: return &regs.r9; case asmcode::R10: return &regs.r10; case asmcode::R11: return &regs.r11; case asmcode::R12: return &regs.r12; case asmcode::R13: return &regs.r13; case asmcode::R14: return &regs.r14; case asmcode::R15: return &regs.r15; case asmcode::MEM_RAX: return (uint64_t*)(regs.rax + operand_mem); case asmcode::MEM_RBX: return (uint64_t*)(regs.rbx + operand_mem); case asmcode::MEM_RCX: return (uint64_t*)(regs.rcx + operand_mem); case asmcode::MEM_RDX: return (uint64_t*)(regs.rdx + operand_mem); case asmcode::MEM_RDI: return (uint64_t*)(regs.rdi + operand_mem); case asmcode::MEM_RSI: return (uint64_t*)(regs.rsi + operand_mem); case asmcode::MEM_RSP: return (uint64_t*)(regs.rsp + operand_mem); case asmcode::MEM_RBP: return (uint64_t*)(regs.rbp + operand_mem); case asmcode::MEM_R8: return (uint64_t*)(regs.r8 + operand_mem); case asmcode::MEM_R9: return (uint64_t*)(regs.r9 + operand_mem); case asmcode::MEM_R10: return (uint64_t*)(regs.r10 + operand_mem); case asmcode::MEM_R11: return (uint64_t*)(regs.r11 + operand_mem); case asmcode::MEM_R12: return (uint64_t*)(regs.r12 + operand_mem); case asmcode::MEM_R13: return (uint64_t*)(regs.r13 + operand_mem); case asmcode::MEM_R14: return (uint64_t*)(regs.r14 + operand_mem); case asmcode::MEM_R15: return (uint64_t*)(regs.r15 + operand_mem); case asmcode::BYTE_MEM_RAX: return nullptr; case asmcode::BYTE_MEM_RBX: return nullptr; case asmcode::BYTE_MEM_RCX: return nullptr; case asmcode::BYTE_MEM_RDX: return nullptr; case asmcode::BYTE_MEM_RDI: return nullptr; case asmcode::BYTE_MEM_RSI: return nullptr; case asmcode::BYTE_MEM_RSP: return nullptr; case asmcode::BYTE_MEM_RBP: return nullptr; case asmcode::BYTE_MEM_R8: return nullptr; case asmcode::BYTE_MEM_R9: return nullptr; case asmcode::BYTE_MEM_R10: return nullptr; case asmcode::BYTE_MEM_R11: return nullptr; case asmcode::BYTE_MEM_R12: return nullptr; case asmcode::BYTE_MEM_R13: return nullptr; case asmcode::BYTE_MEM_R14: return nullptr; case asmcode::BYTE_MEM_R15: return nullptr; case asmcode::NUMBER: return nullptr; case asmcode::ST0: return (uint64_t*)(regs.fpstackptr); case asmcode::ST1: return (uint64_t*)(regs.fpstackptr+1); case asmcode::ST2: return (uint64_t*)(regs.fpstackptr+2); case asmcode::ST3: return (uint64_t*)(regs.fpstackptr+3); case asmcode::ST4: return (uint64_t*)(regs.fpstackptr+4); case asmcode::ST5: return (uint64_t*)(regs.fpstackptr+5); case asmcode::ST6: return (uint64_t*)(regs.fpstackptr+6); case asmcode::ST7: return (uint64_t*)(regs.fpstackptr+7); case asmcode::XMM0: return (uint64_t*)(&regs.xmm0); case asmcode::XMM1: return (uint64_t*)(&regs.xmm1); case asmcode::XMM2: return (uint64_t*)(&regs.xmm2); case asmcode::XMM3: return (uint64_t*)(&regs.xmm3); case asmcode::XMM4: return (uint64_t*)(&regs.xmm4); case asmcode::XMM5: return (uint64_t*)(&regs.xmm5); case asmcode::XMM6: return (uint64_t*)(&regs.xmm6); case asmcode::XMM7: return (uint64_t*)(&regs.xmm7); case asmcode::XMM8: return (uint64_t*)(&regs.xmm8); case asmcode::XMM9: return (uint64_t*)(&regs.xmm9); case asmcode::XMM10:return (uint64_t*)(&regs.xmm10); case asmcode::XMM11:return (uint64_t*)(&regs.xmm11); case asmcode::XMM12:return (uint64_t*)(&regs.xmm12); case asmcode::XMM13:return (uint64_t*)(&regs.xmm13); case asmcode::XMM14:return (uint64_t*)(&regs.xmm14); case asmcode::XMM15:return (uint64_t*)(&regs.xmm15); case asmcode::LABELADDRESS: return nullptr; default: return nullptr; } } struct AddOper { static void apply(uint64_t& left, uint64_t right) { left += right; } static void apply(uint64_t& left, uint8_t right) { left += (uint64_t)right; } static void apply(uint8_t& left, uint8_t right) { left += right; } static void apply(uint8_t& left, uint64_t right) { left += (uint8_t)right; } }; struct AndOper { static void apply(uint64_t& left, uint64_t right) { left &= right; } static void apply(uint64_t& left, uint8_t right) { left &= (uint64_t)right; } static void apply(uint8_t& left, uint8_t right) { left &= right; } static void apply(uint8_t& left, uint64_t right) { left &= (uint8_t)right; } }; struct MovOper { static void apply(uint64_t& left, uint64_t right) { left = right; } static void apply(uint64_t& left, uint8_t right) { left = (uint64_t)right; } static void apply(uint8_t& left, uint8_t right) { left = right; } static void apply(uint8_t& left, uint64_t right) { left = (uint8_t)right; } }; struct OrOper { static void apply(uint64_t& left, uint64_t right) { left |= right; } static void apply(uint64_t& left, uint8_t right) { left |= (uint64_t)right; } static void apply(uint8_t& left, uint8_t right) { left |= right; } static void apply(uint8_t& left, uint64_t right) { left |= (uint8_t)right; } }; struct ShlOper { static void apply(uint64_t& left, uint64_t right) { left <<= right; } static void apply(uint64_t& left, uint8_t right) { left <<= (uint64_t)right; } static void apply(uint8_t& left, uint8_t right) { left <<= right; } static void apply(uint8_t& left, uint64_t right) { left <<= (uint8_t)right; } }; struct SarOper { static void apply(uint64_t& left, uint64_t right) { int64_t l = (int64_t)left; l >>= right; left = (uint64_t)l; } static void apply(uint64_t& left, uint8_t right) { int64_t l = (int64_t)left; l >>= (uint64_t)right; left = (uint64_t)l; } static void apply(uint8_t& left, uint8_t right) { int8_t l = (int8_t)left; l >>= right; left = (uint8_t)l; } static void apply(uint8_t& left, uint64_t right) { int8_t l = (int8_t)left; l >>= (uint8_t)right; left = (uint8_t)l; } }; struct ShrOper { static void apply(uint64_t& left, uint64_t right) { left >>= right; } static void apply(uint64_t& left, uint8_t right) { left >>= (uint64_t)right; } static void apply(uint8_t& left, uint8_t right) { left >>= right; } static void apply(uint8_t& left, uint64_t right) { left >>= (uint8_t)right; } }; struct SubOper { static void apply(uint64_t& left, uint64_t right) { left -= right; } static void apply(uint64_t& left, uint8_t right) { left -= (uint64_t)right; } static void apply(uint8_t& left, uint8_t right) { left -= right; } static void apply(uint8_t& left, uint64_t right) { left -= (uint8_t)right; } }; struct XorOper { static void apply(uint64_t& left, uint64_t right) { left ^= right; } static void apply(uint64_t& left, uint8_t right) { left ^= (uint64_t)right; } static void apply(uint8_t& left, uint8_t right) { left ^= right; } static void apply(uint8_t& left, uint64_t right) { left ^= (uint8_t)right; } }; struct AddsdOper { static void apply(double& left, double right) { left += right; } }; struct DivsdOper { static void apply(double& left, double right) { left /= right; } }; struct MulsdOper { static void apply(double& left, double right) { left *= right; } }; struct SubsdOper { static void apply(double& left, double right) { left -= right; } }; struct SqrtpdOper { static void apply(double& left, double right) { left = std::sqrt(right); } }; struct XorpdOper { static void apply(double& left, double right) { uint64_t l = *reinterpret_cast<uint64_t*>(&left); uint64_t r = *reinterpret_cast<uint64_t*>(&right); l ^= r; left = *reinterpret_cast<double*>(&l); } }; template <class TOper> inline void execute_operation(asmcode::operand operand1, asmcode::operand operand2, uint64_t operand1_mem, uint64_t operand2_mem, registers& regs) { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); if (oprnd2) TOper::apply(*oprnd1, *oprnd2); else if (operand2 == asmcode::NUMBER || operand2 == asmcode::LABELADDRESS) TOper::apply(*oprnd1, operand2_mem); else { uint8_t* oprnd2_8 = get_address_8bit(operand2, operand2_mem, regs); if (oprnd2_8) TOper::apply(*oprnd1, *oprnd2_8); } } else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); if (oprnd1_8) { uint8_t* oprnd2_8 = get_address_8bit(operand2, operand2_mem, regs); if (oprnd2_8) TOper::apply(*oprnd1_8, *oprnd2_8); else if (operand2 == asmcode::NUMBER) TOper::apply(*oprnd1_8, operand2_mem); } } } template <class TOper> inline void execute_double_operation(asmcode::operand operand1, asmcode::operand operand2, uint64_t operand1_mem, uint64_t operand2_mem, registers& regs) { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); if (oprnd2) TOper::apply(*reinterpret_cast<double*>(oprnd1), *reinterpret_cast<double*>(oprnd2)); } } template <class TOper> inline uint64_t execute_operation_const(asmcode::operand operand1, asmcode::operand operand2, uint64_t operand1_mem, uint64_t operand2_mem, registers& regs) { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { uint64_t left = *oprnd1; uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); if (oprnd2) { TOper::apply(left, *oprnd2); return left; } else if (operand2 == asmcode::NUMBER || operand2 == asmcode::LABELADDRESS) { TOper::apply(left, operand2_mem); return left; } else { uint8_t* oprnd2_8 = get_address_8bit(operand2, operand2_mem, regs); if (oprnd2_8) { TOper::apply(left, *oprnd2_8); return left; } } } else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); uint8_t left = *oprnd1_8; if (oprnd1_8) { uint8_t* oprnd2_8 = get_address_8bit(operand2, operand2_mem, regs); if (oprnd2_8) { TOper::apply(left, *oprnd2_8); return (uint64_t)left; } else if (operand2 == asmcode::NUMBER) { TOper::apply(left, operand2_mem); return (uint64_t)left; } } } throw std::logic_error("Invalid bytecode"); } inline void get_values(int64_t& left_signed, int64_t& right_signed, uint64_t& left_unsigned, uint64_t right_unsigned, asmcode::operand operand1, asmcode::operand operand2, uint64_t operand1_mem, uint64_t operand2_mem, registers& regs) { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { left_unsigned = *oprnd1; left_signed = (int64_t)left_unsigned; } else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); left_unsigned = *oprnd1_8; left_signed = (int8_t)(*oprnd1_8); } uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); if (oprnd2) { right_unsigned = *oprnd2; right_signed = (int64_t)right_unsigned; } else if (operand2 == asmcode::NUMBER || operand2 == asmcode::LABELADDRESS) { right_unsigned = operand2_mem; right_signed = (int64_t)right_unsigned; } else { uint8_t* oprnd2_8 = get_address_8bit(operand2, operand2_mem, regs); right_unsigned = *oprnd2_8; right_signed = (int8_t)(*oprnd2_8); } } inline void compare_operation(asmcode::operand operand1, asmcode::operand operand2, uint64_t operand1_mem, uint64_t operand2_mem, registers& regs) { regs.eflags = 0; int64_t left_signed = 0; int64_t right_signed = 0; uint64_t left_unsigned = 0; uint64_t right_unsigned = 0; get_values(left_signed, right_signed, left_unsigned, right_unsigned, operand1, operand2, operand1_mem, operand2_mem, regs); if (left_signed == right_signed) regs.eflags |= zero_flag; if (left_unsigned < right_unsigned) regs.eflags |= carry_flag; int64_t temp = left_signed - right_signed; if ((temp < left_signed) != (right_signed > 0)) regs.eflags |= overflow_flag; if (temp < 0) regs.eflags |= sign_flag; } void print(asmcode::operation op, asmcode::operand operand1, asmcode::operand operand2, uint64_t operand1_mem, uint64_t operand2_mem) { asmcode::instruction i; i.oper = op; i.operand1 = operand1; i.operand2 = operand2; i.operand1_mem = operand1_mem; i.operand2_mem = operand2_mem; i.stream(std::cout); } std::vector<asmcode::operand> get_windows_calling_registers() { std::vector<asmcode::operand> calling_registers; calling_registers.push_back(asmcode::RCX); calling_registers.push_back(asmcode::RDX); calling_registers.push_back(asmcode::R8); calling_registers.push_back(asmcode::R9); return calling_registers; } std::vector<asmcode::operand> get_linux_calling_registers() { std::vector<asmcode::operand> calling_registers; calling_registers.push_back(asmcode::RDI); calling_registers.push_back(asmcode::RSI); calling_registers.push_back(asmcode::RDX); calling_registers.push_back(asmcode::RCX); calling_registers.push_back(asmcode::R8); calling_registers.push_back(asmcode::R9); return calling_registers; } std::vector<asmcode::operand> get_floating_point_registers() { std::vector<asmcode::operand> calling_registers; calling_registers.push_back(asmcode::XMM0); calling_registers.push_back(asmcode::XMM1); calling_registers.push_back(asmcode::XMM2); calling_registers.push_back(asmcode::XMM3); calling_registers.push_back(asmcode::XMM4); calling_registers.push_back(asmcode::XMM5); return calling_registers; } uint64_t get_integer_register_value(asmcode::operand reg, const registers& regs) { switch (reg) { case asmcode::RDI: return regs.rdi; case asmcode::RSI: return regs.rsi; case asmcode::RDX: return regs.rdx; case asmcode::RCX: return regs.rcx; case asmcode::R8: return regs.r8; case asmcode::R9: return regs.r9; default: throw std::runtime_error("Invalid integer register as argument used"); } } double get_floating_register_value(asmcode::operand reg, const registers& regs) { switch (reg) { case asmcode::XMM0: return regs.xmm0; case asmcode::XMM1: return regs.xmm1; case asmcode::XMM2: return regs.xmm2; case asmcode::XMM3: return regs.xmm3; case asmcode::XMM4: return regs.xmm4; case asmcode::XMM5: return regs.xmm5; default: throw std::runtime_error("Invalid floating point register as argument used"); } } bool is_floating_point_register(asmcode::operand reg) { switch (reg) { case asmcode::XMM0: return true; case asmcode::XMM1: return true; case asmcode::XMM2: return true; case asmcode::XMM3: return true; case asmcode::XMM4: return true; case asmcode::XMM5: return true; case asmcode::XMM6: return true; case asmcode::XMM7: return true; case asmcode::XMM8: return true; case asmcode::XMM9: return true; case asmcode::XMM10: return true; case asmcode::XMM11: return true; case asmcode::XMM12: return true; case asmcode::XMM13: return true; case asmcode::XMM14: return true; case asmcode::XMM15: return true; default: return false; } } std::vector<asmcode::operand> _get_arguments(const external_function& f) { #ifdef _WIN32 static std::vector<asmcode::operand> arg_reg = get_windows_calling_registers(); #else static std::vector<asmcode::operand> arg_reg = get_linux_calling_registers(); #endif static std::vector<asmcode::operand> arg_float_reg = get_floating_point_registers(); #ifndef _WIN32 std::vector<asmcode::operand> arg_regs; int regular_arg_id = 0; int floating_arg_id = 0; for (size_t i = 0; i < f.arguments.size(); ++i) { if (f.arguments[i] == external_function::T_DOUBLE) { arg_regs.push_back(arg_float_reg[floating_arg_id]); ++floating_arg_id; } else { arg_regs.push_back(arg_reg[regular_arg_id]); ++regular_arg_id; } } #endif std::vector<asmcode::operand> args; for (size_t i = 0; i < f.arguments.size(); ++i) { switch (f.arguments[i]) { case external_function::T_CHAR_POINTER: case external_function::T_INT64: case external_function::T_BOOL: { #ifdef _WIN32 auto reg = arg_reg[i]; #else auto reg = arg_regs[i]; #endif args.push_back(reg); break; } case external_function::T_DOUBLE: { #ifdef _WIN32 auto reg = arg_float_reg[i]; #else auto reg = arg_regs[i]; #endif args.push_back(reg); break; } } } return args; } template <class T> T _call_external_0(const external_function& f) { typedef T(*fun_ptr)(); fun_ptr fun = (fun_ptr)f.address; return fun(); } template <> void _call_external_0<void>(const external_function& f) { typedef void(*fun_ptr)(); fun_ptr fun = (fun_ptr)f.address; fun(); } template <class T, class T1, class V1> T _call_external_1(const external_function& f, V1 value) { typedef T(*fun_ptr)(T1); fun_ptr fun = (fun_ptr)f.address; return fun((T1)value); } template <class T1, class V1> void _call_external_1_void(const external_function& f, V1 value) { typedef void(*fun_ptr)(T1); fun_ptr fun = (fun_ptr)f.address; fun((T1)value); } template <class T> T _call_external_1(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 1); switch (f.arguments[0]) { case external_function::T_BOOL: return _call_external_1<T, bool, uint64_t>(f, get_integer_register_value(args[0], regs)); case external_function::T_CHAR_POINTER: return _call_external_1<T, char*, uint64_t>(f, get_integer_register_value(args[0], regs)); case external_function::T_DOUBLE: return _call_external_1<T, double, double>(f, get_floating_register_value(args[0], regs)); case external_function::T_INT64: return _call_external_1<T, int64_t, uint64_t>(f, get_integer_register_value(args[0], regs)); case external_function::T_VOID: return 0; } } template <> void _call_external_1<void>(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 1); switch (f.arguments[0]) { case external_function::T_BOOL: _call_external_1_void<bool, uint64_t>(f, get_integer_register_value(args[0], regs));break; case external_function::T_CHAR_POINTER: _call_external_1_void<char*, uint64_t>(f, get_integer_register_value(args[0], regs));break; case external_function::T_DOUBLE: _call_external_1_void<double, double>(f, get_floating_register_value(args[0], regs));break; case external_function::T_INT64: _call_external_1_void<int64_t, uint64_t>(f, get_integer_register_value(args[0], regs));break; case external_function::T_VOID: break; } } template <class T> T get_value(const asmcode::operand& arg, registers& regs) { return (T)get_integer_register_value(arg, regs); } template <> double get_value<double>(const asmcode::operand& arg, registers& regs) { return (double)get_floating_register_value(arg, regs); } template <class T, class T1, class T2> T _call_external_2_2(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { typedef T(*fun_ptr)(T1, T2); fun_ptr fun = (fun_ptr)f.address; return fun(get_value<T1>(args[0], regs), get_value<T2>(args[1], regs)); } template <class T, class T1> T _call_external_2_1(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 2); switch (f.arguments[1]) { case external_function::T_BOOL: return _call_external_2_2<T,T1, bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_2_2<T,T1, char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_2_2<T, T1,double>(f, args, regs); case external_function::T_INT64: return _call_external_2_2<T, T1,int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template < class T1, class T2> void _call_external_2_2_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { typedef void(*fun_ptr)(T1, T2); fun_ptr fun = (fun_ptr)f.address; fun(get_value<T1>(args[0], regs), get_value<T2>(args[1], regs)); } template <class T1> void _call_external_2_1_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 2); switch (f.arguments[1]) { case external_function::T_BOOL: _call_external_2_2_void<T1, bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_2_2_void<T1, char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_2_2_void<T1,double>(f, args, regs); break; case external_function::T_INT64: _call_external_2_2_void<T1,int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <class T> T _call_external_2(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 2); switch (f.arguments[0]) { case external_function::T_BOOL: return _call_external_2_1<T, bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_2_1<T, char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_2_1<T, double>(f, args, regs); case external_function::T_INT64: return _call_external_2_1<T, int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template <> void _call_external_2<void>(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 2); switch (f.arguments[0]) { case external_function::T_BOOL: _call_external_2_1_void<bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_2_1_void<char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_2_1_void<double>(f, args, regs); break; case external_function::T_INT64: _call_external_2_1_void<int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <class T, class T1, class T2, class T3> T _call_external_3_3(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { typedef T(*fun_ptr)(T1, T2, T3); fun_ptr fun = (fun_ptr)f.address; return fun(get_value<T1>(args[0], regs), get_value<T2>(args[1], regs), get_value<T3>(args[2], regs)); } template <class T, class T1, class T2> T _call_external_3_2(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 3); switch (f.arguments[2]) { case external_function::T_BOOL: return _call_external_3_3<T,T1, T2,bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_3_3<T,T1, T2,char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_3_3<T, T1,T2,double>(f, args, regs); case external_function::T_INT64: return _call_external_3_3<T, T1,T2,int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template <class T, class T1> T _call_external_3_1(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 3); switch (f.arguments[1]) { case external_function::T_BOOL: return _call_external_3_2<T,T1, bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_3_2<T,T1, char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_3_2<T, T1,double>(f, args, regs); case external_function::T_INT64: return _call_external_3_2<T, T1,int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template <class T1, class T2, class T3> void _call_external_3_3_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { typedef void(*fun_ptr)(T1, T2, T3); fun_ptr fun = (fun_ptr)f.address; fun(get_value<T1>(args[0], regs), get_value<T2>(args[1], regs), get_value<T3>(args[2], regs)); } template <class T1, class T2> void _call_external_3_2_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 3); switch (f.arguments[2]) { case external_function::T_BOOL: _call_external_3_3_void<T1, T2, bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_3_3_void<T1, T2, char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_3_3_void<T1,T2, double>(f, args, regs); break; case external_function::T_INT64: _call_external_3_3_void<T1,T2,int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <class T1> void _call_external_3_1_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 3); switch (f.arguments[1]) { case external_function::T_BOOL: _call_external_3_2_void<T1, bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_3_2_void<T1, char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_3_2_void<T1,double>(f, args, regs); break; case external_function::T_INT64: _call_external_3_2_void<T1,int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <class T> T _call_external_3(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 3); switch (f.arguments[0]) { case external_function::T_BOOL: return _call_external_3_1<T, bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_3_1<T, char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_3_1<T, double>(f, args, regs); case external_function::T_INT64: return _call_external_3_1<T, int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template <> void _call_external_3<void>(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 3); switch (f.arguments[0]) { case external_function::T_BOOL: _call_external_3_1_void<bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_3_1_void<char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_3_1_void<double>(f, args, regs); break; case external_function::T_INT64: _call_external_3_1_void<int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <class T, class T1, class T2, class T3, class T4> T _call_external_4_4(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { typedef T(*fun_ptr)(T1, T2, T3, T4); fun_ptr fun = (fun_ptr)f.address; return fun(get_value<T1>(args[0], regs), get_value<T2>(args[1], regs), get_value<T3>(args[2], regs), get_value<T4>(args[3], regs)); } template <class T, class T1, class T2, class T3> T _call_external_4_3(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 4); switch (f.arguments[3]) { case external_function::T_BOOL: return _call_external_4_4<T,T1, T2,T3,bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_4_4<T,T1, T2,T3,char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_4_4<T, T1,T2,T3,double>(f, args, regs); case external_function::T_INT64: return _call_external_4_4<T, T1,T2,T3,int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template <class T, class T1, class T2> T _call_external_4_2(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 4); switch (f.arguments[2]) { case external_function::T_BOOL: return _call_external_4_3<T,T1, T2,bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_4_3<T,T1, T2,char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_4_3<T, T1,T2,double>(f, args, regs); case external_function::T_INT64: return _call_external_4_3<T, T1,T2,int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template <class T, class T1> T _call_external_4_1(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 4); switch (f.arguments[1]) { case external_function::T_BOOL: return _call_external_4_2<T,T1, bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_4_2<T,T1, char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_4_2<T, T1,double>(f, args, regs); case external_function::T_INT64: return _call_external_4_2<T, T1,int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template <class T> T _call_external_4(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 4); switch (f.arguments[0]) { case external_function::T_BOOL: return _call_external_4_1<T, bool>(f, args, regs); case external_function::T_CHAR_POINTER: return _call_external_4_1<T, char*>(f, args, regs); case external_function::T_DOUBLE: return _call_external_4_1<T, double>(f, args, regs); case external_function::T_INT64: return _call_external_4_1<T, int64_t>(f, args, regs); case external_function::T_VOID: return 0; } } template <class T1, class T2, class T3, class T4> void _call_external_4_4_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { typedef void(*fun_ptr)(T1, T2, T3, T4); fun_ptr fun = (fun_ptr)f.address; fun(get_value<T1>(args[0], regs), get_value<T2>(args[1], regs), get_value<T3>(args[2], regs), get_value<T4>(args[3], regs)); } template <class T1, class T2, class T3> void _call_external_4_3_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 2); switch (f.arguments[3]) { case external_function::T_BOOL: _call_external_4_4_void<T1, T2, T3, bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_4_4_void<T1, T2, T3, char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_4_4_void<T1,T2, T3, double>(f, args, regs); break; case external_function::T_INT64: _call_external_4_4_void<T1,T2,T3, int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <class T1, class T2> void _call_external_4_2_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 2); switch (f.arguments[2]) { case external_function::T_BOOL: _call_external_4_3_void<T1, T2, bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_4_3_void<T1, T2, char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_4_3_void<T1,T2, double>(f, args, regs); break; case external_function::T_INT64: _call_external_4_3_void<T1,T2,int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <class T1> void _call_external_4_1_void(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 2); switch (f.arguments[1]) { case external_function::T_BOOL: _call_external_4_2_void<T1, bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_4_2_void<T1, char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_4_2_void<T1,double>(f, args, regs); break; case external_function::T_INT64: _call_external_4_2_void<T1,int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <> void _call_external_4<void>(const external_function& f, std::vector<asmcode::operand>& args, registers& regs) { assert(args.size() == 4); switch (f.arguments[0]) { case external_function::T_BOOL: _call_external_4_1_void<bool>(f, args, regs); break; case external_function::T_CHAR_POINTER: _call_external_4_1_void<char*>(f, args, regs); break; case external_function::T_DOUBLE: _call_external_4_1_void<double>(f, args, regs); break; case external_function::T_INT64: _call_external_4_1_void<int64_t>(f, args, regs); break; case external_function::T_VOID: break; } } template <class T> T _call_external(const external_function& f, registers& regs) { auto args = _get_arguments(f); switch (args.size()) { case 0: return _call_external_0<T>(f); case 1: return _call_external_1<T>(f, args, regs); case 2: return _call_external_2<T>(f, args, regs); case 3: return _call_external_3<T>(f, args, regs); case 4: return _call_external_4<T>(f, args, regs); default: break; } return 0; } template <> void _call_external(const external_function& f, registers& regs) { auto args = _get_arguments(f); switch (args.size()) { case 0: _call_external_0<void>(f); break; case 1: _call_external_1<void>(f, args, regs); break; case 2: _call_external_2<void>(f, args, regs); break; case 3: _call_external_3<void>(f, args, regs); break; case 4: _call_external_4<void>(f, args, regs); break; default: break; } } /* template <class T> T _call_external(const external_function& f, registers& regs) { auto args = _get_arguments(f); //typedef T(*fun_ptr)(...); //fun_ptr fun = (fun_ptr)f.address; T return_value = 0; switch (args.size()) { case 0: { typedef T(*fun_ptr)(); fun_ptr fun = (fun_ptr)f.address; return_value = fun(); break; } case 1: { if (is_floating_point_register(args[0])) { typedef T(*fun_ptr)(double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs)); } else { typedef T(*fun_ptr)(uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs)); } break; } case 2: { if (is_floating_point_register(args[0])) { if (is_floating_point_register(args[1])) { typedef T(*fun_ptr)(double, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs)); } else { typedef T(*fun_ptr)(double, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs)); } } else { if (is_floating_point_register(args[1])) { typedef T(*fun_ptr)(uint64_t, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs)); } else { typedef T(*fun_ptr)(uint64_t, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs)); } } break; } case 3: { if (is_floating_point_register(args[0])) { if (is_floating_point_register(args[1])) { if (is_floating_point_register(args[2])) { typedef T(*fun_ptr)(double, double, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs)); } else { typedef T(*fun_ptr)(double, double, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs)); } } else { if (is_floating_point_register(args[2])) { typedef T(*fun_ptr)(double, uint64_t, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs)); } else { typedef T(*fun_ptr)(double, uint64_t, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs)); } } } else { if (is_floating_point_register(args[1])) { if (is_floating_point_register(args[2])) { typedef T(*fun_ptr)(uint64_t, double, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs)); } else { typedef T(*fun_ptr)(uint64_t, double, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs)); } } else { if (is_floating_point_register(args[2])) { typedef T(*fun_ptr)(uint64_t, uint64_t, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs)); } else { typedef T(*fun_ptr)(uint64_t, uint64_t, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs)); } } } break; } case 4: { if (is_floating_point_register(args[0])) { if (is_floating_point_register(args[1])) { if (is_floating_point_register(args[2])) { if (is_floating_point_register(args[3])) { typedef T(*fun_ptr)(double, double, double, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_floating_register_value(args[3], regs)); } else { typedef T(*fun_ptr)(double, double, double, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } else { if (is_floating_point_register(args[3])) { typedef T(*fun_ptr)(double, double, uint64_t, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_floating_register_value(args[3], regs)); } else { typedef T(*fun_ptr)(double, double, uint64_t, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } } else { if (is_floating_point_register(args[2])) { if (is_floating_point_register(args[3])) { typedef T(*fun_ptr)(double, uint64_t, double, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_floating_register_value(args[3], regs)); } else { typedef T(*fun_ptr)(double, uint64_t, double, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } else { if (is_floating_point_register(args[3])) { typedef T(*fun_ptr)(double, uint64_t, uint64_t, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_floating_register_value(args[3], regs)); } else { typedef T(*fun_ptr)(double, uint64_t, uint64_t, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } } } else { if (is_floating_point_register(args[1])) { if (is_floating_point_register(args[2])) { if (is_floating_point_register(args[3])) { typedef T(*fun_ptr)(uint64_t, double, double, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_floating_register_value(args[3], regs)); } else { typedef T(*fun_ptr)(uint64_t, double, double, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } else { if (is_floating_point_register(args[3])) { typedef T(*fun_ptr)(uint64_t, double, uint64_t, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_floating_register_value(args[3], regs)); } else { typedef T(*fun_ptr)(uint64_t, double, uint64_t, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } } else { if (is_floating_point_register(args[2])) { if (is_floating_point_register(args[3])) { typedef T(*fun_ptr)(uint64_t, uint64_t, double, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_floating_register_value(args[3], regs)); } else { typedef T(*fun_ptr)(uint64_t, uint64_t, double, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } else { if (is_floating_point_register(args[3])) { typedef T(*fun_ptr)(uint64_t, uint64_t, uint64_t, double); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_floating_register_value(args[3], regs)); } else { typedef T(*fun_ptr)(uint64_t, uint64_t, uint64_t, uint64_t); fun_ptr fun = (fun_ptr)f.address; return_value = fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } } } break; } default: { throw std::logic_error("Cannot deal with external functions that need this many arguments"); } } return return_value; } template <> void _call_external<void>(const external_function& f, registers& regs) { auto args = _get_arguments(f); typedef void(*fun_ptr)(...); fun_ptr fun = (fun_ptr)f.address; switch (args.size()) { case 0: { fun(); break; } case 1: { if (is_floating_point_register(args[0])) fun(get_floating_register_value(args[0], regs)); else fun(get_integer_register_value(args[0], regs)); break; } case 2: { if (is_floating_point_register(args[0])) { if (is_floating_point_register(args[1])) fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs)); else fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs)); } else { if (is_floating_point_register(args[1])) fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs)); else fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs)); } break; } case 3: { if (is_floating_point_register(args[0])) { if (is_floating_point_register(args[1])) { if (is_floating_point_register(args[2])) fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs)); else fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs)); } else { if (is_floating_point_register(args[2])) fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs)); else fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs)); } } else { if (is_floating_point_register(args[1])) { if (is_floating_point_register(args[2])) fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs)); else fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs)); } else { if (is_floating_point_register(args[2])) fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs)); else fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs)); } } break; } case 4: { if (is_floating_point_register(args[0])) { if (is_floating_point_register(args[1])) { if (is_floating_point_register(args[2])) { if (is_floating_point_register(args[3])) fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_floating_register_value(args[3], regs)); else fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } else { if (is_floating_point_register(args[3])) fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_floating_register_value(args[3], regs)); else fun(get_floating_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } else { if (is_floating_point_register(args[2])) { if (is_floating_point_register(args[3])) fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_floating_register_value(args[3], regs)); else fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } else { if (is_floating_point_register(args[3])) fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_floating_register_value(args[3], regs)); else fun(get_floating_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } } else { if (is_floating_point_register(args[1])) { if (is_floating_point_register(args[2])) { if (is_floating_point_register(args[3])) fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_floating_register_value(args[3], regs)); else fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } else { if (is_floating_point_register(args[3])) fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_floating_register_value(args[3], regs)); else fun(get_integer_register_value(args[0], regs), get_floating_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } else { if (is_floating_point_register(args[2])) { if (is_floating_point_register(args[3])) fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_floating_register_value(args[3], regs)); else fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_floating_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } else { if (is_floating_point_register(args[3])) fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_floating_register_value(args[3], regs)); else fun(get_integer_register_value(args[0], regs), get_integer_register_value(args[1], regs), get_integer_register_value(args[2], regs), get_integer_register_value(args[3], regs)); } } } break; } default: { throw std::logic_error("Cannot deal with external functions that need this many arguments"); } } } */ void call_external(const external_function& f, registers& regs) { switch (f.return_type) { case external_function::T_BOOL: case external_function::T_CHAR_POINTER: case external_function::T_INT64: { regs.rax = _call_external<uint64_t>(f, regs); break; } case external_function::T_DOUBLE: { regs.xmm0 = _call_external<double>(f, regs); break; } case external_function::T_VOID: { _call_external<void>(f, regs); break; } } } } // namespace void run_bytecode(const uint8_t* bytecode, uint64_t size, registers& regs, const std::vector<external_function>& externals) { (void*)size; regs.rsp -= 8; *((uint64_t*)regs.rsp) = 0xffffffffffffffff; // this address means the function call representing this bytecode const uint8_t* bytecode_ptr = bytecode; for (;;) { asmcode::operation op; asmcode::operand operand1; asmcode::operand operand2; uint64_t operand1_mem; uint64_t operand2_mem; uint64_t sz = disassemble_bytecode(op, operand1, operand2, operand1_mem, operand2_mem, bytecode_ptr); //print(op, operand1, operand2, operand1_mem, operand2_mem); switch (op) { case asmcode::ADD: { execute_operation<AddOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::ADDSD: { execute_double_operation<AddsdOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::AND: { execute_operation<AndOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::CALLEXTERNAL: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint64_t address = *oprnd1; auto it = std::find_if(externals.begin(), externals.end(), [&](const external_function& f) { return f.address == address; }); if (it == externals.end()) throw std::logic_error("Call to unknown external function\n"); call_external(*it, regs); break; } case asmcode::CALL: { if (operand1 == asmcode::NUMBER) // local call { regs.rsp -= 8; *((uint64_t*)regs.rsp) = (uint64_t)(bytecode_ptr + sz); // save address right after call on stack uint32_t local_offset = (uint32_t)operand1_mem; bytecode_ptr += (int32_t)local_offset; sz = 0; } else // external call { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); regs.rsp -= 8; *((uint64_t*)regs.rsp) = (uint64_t)(bytecode_ptr + sz); // save address right after call on stack bytecode_ptr = (const uint8_t*)(*oprnd1); sz = 0; //throw std::logic_error("external call not implemented"); } break; } case asmcode::CMP: { compare_operation(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::CQO: { if (regs.rax & 0x8000000000000000) regs.rdx = 0xffffffffffffffff; else regs.rdx = 0; break; } case asmcode::CMPEQPD: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); double v1 = *reinterpret_cast<double*>(oprnd1); double v2 = *reinterpret_cast<double*>(oprnd2); *oprnd1 = (v1 == v2) ? 0xffffffffffffffff : 0; break; } case asmcode::CMPLTPD: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); double v1 = *reinterpret_cast<double*>(oprnd1); double v2 = *reinterpret_cast<double*>(oprnd2); *oprnd1 = (v1 < v2) ? 0xffffffffffffffff : 0; break; } case asmcode::CMPLEPD: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); double v1 = *reinterpret_cast<double*>(oprnd1); double v2 = *reinterpret_cast<double*>(oprnd2); *oprnd1 = (v1 <= v2) ? 0xffffffffffffffff : 0; break; } case asmcode::CVTSI2SD: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); double v = (double)((int64_t)*oprnd2); *reinterpret_cast<double*>(oprnd1) = v; break; } case asmcode::CVTTSD2SI: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); double v = *reinterpret_cast<double*>(oprnd2); *oprnd1 = (int64_t)v; break; } case asmcode::DEC: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { *oprnd1 -= 1; if (*oprnd1) regs.eflags &= ~zero_flag; else regs.eflags |= zero_flag; } else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); if (oprnd1_8) { *oprnd1_8 -= 1; if (*oprnd1_8) regs.eflags &= ~zero_flag; else regs.eflags |= zero_flag; } } break; } case asmcode::DIV: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint64_t divider = *oprnd1; uint64_t result = regs.rax / divider; uint64_t remainder = regs.rax % divider; regs.rax = result; regs.rdx = remainder; break; } case asmcode::DIVSD: { execute_double_operation<DivsdOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::F2XM1: { double v = std::pow(2.0, *regs.fpstackptr) - 1.0; *regs.fpstackptr = v; break; } case asmcode::FADD: { if (operand2 == asmcode::EMPTY) { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); double v = *reinterpret_cast<double*>(oprnd1); *regs.fpstackptr += v; } else { double* oprnd1 = (double*)get_address_64bit(operand1, operand1_mem, regs); double* oprnd2 = (double*)get_address_64bit(operand2, operand2_mem, regs); *oprnd1 += *oprnd2; } break; } case asmcode::FADDP: { double tmp = *(regs.fpstackptr); regs.fpstackptr += 1; *regs.fpstackptr += tmp; break; } case asmcode::FILD: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); regs.fpstackptr -= 1; *regs.fpstackptr = (double)((int64_t)(*oprnd1)); break; } case asmcode::FISTPQ: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); *oprnd1 = (int64_t)(*regs.fpstackptr); regs.fpstackptr += 1; break; } case asmcode::FLD: { double* oprnd1 = (double*)get_address_64bit(operand1, operand1_mem, regs); regs.fpstackptr -= 1; *regs.fpstackptr = *oprnd1; break; } case asmcode::FLD1: { regs.fpstackptr -= 1; *regs.fpstackptr = 1.0; break; } case asmcode::FLDLN2: { regs.fpstackptr -= 1; *regs.fpstackptr = std::log(2.0); break; } case asmcode::FLDPI: { regs.fpstackptr -= 1; *regs.fpstackptr = 3.141592653589793238462643383; break; } case asmcode::FMUL: { if (operand2 == asmcode::EMPTY) { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); double v = *reinterpret_cast<double*>(oprnd1); *regs.fpstackptr *= v; } else { double* oprnd1 = (double*)get_address_64bit(operand1, operand1_mem, regs); double* oprnd2 = (double*)get_address_64bit(operand2, operand2_mem, regs); *oprnd1 *= *oprnd2; } break; } case asmcode::FSIN: { *regs.fpstackptr = std::sin(*regs.fpstackptr); break; } case asmcode::FCOS: { *regs.fpstackptr = std::cos(*regs.fpstackptr); break; } case asmcode::FPATAN: { double y = *(regs.fpstackptr + 1); double x = *(regs.fpstackptr); regs.fpstackptr += 1; *regs.fpstackptr = std::atan2(y,x); break; } case asmcode::FPTAN: { *regs.fpstackptr = std::tan(*regs.fpstackptr); regs.fpstackptr -= 1; *regs.fpstackptr = 1.0; break; } case asmcode::FRNDINT: { *regs.fpstackptr = std::round(*regs.fpstackptr); break; } case asmcode::FSCALE: { double s = std::trunc(*(regs.fpstackptr + 1)); *regs.fpstackptr *= std::pow(2.0, s); break; } case asmcode::FSQRT: { *regs.fpstackptr = std::sqrt(*regs.fpstackptr); break; } case asmcode::FSTP: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); *oprnd1 = *reinterpret_cast<uint64_t*>(regs.fpstackptr); regs.fpstackptr += 1; break; } case asmcode::FSUB: { if (operand2 == asmcode::EMPTY) { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); double v = *reinterpret_cast<double*>(oprnd1); *regs.fpstackptr -= v; } else { double* oprnd1 = (double*)get_address_64bit(operand1, operand1_mem, regs); double* oprnd2 = (double*)get_address_64bit(operand2, operand2_mem, regs); *oprnd1 -= *oprnd2; } break; } case asmcode::FSUBP: { double tmp = *(regs.fpstackptr); regs.fpstackptr += 1; *regs.fpstackptr -= tmp; break; } case asmcode::FSUBRP: { double tmp = *(regs.fpstackptr); regs.fpstackptr += 1; *regs.fpstackptr = tmp - *regs.fpstackptr; break; } case asmcode::FXCH: { double* oprnd1 = (double*)get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { double tmp = *(regs.fpstackptr); *(regs.fpstackptr) = *oprnd1; *oprnd1 = tmp; } else { double tmp = *(regs.fpstackptr); *(regs.fpstackptr) = *(regs.fpstackptr + 1); *(regs.fpstackptr + 1) = tmp; } break; } case asmcode::FYL2X: { double tmp = std::log2(*(regs.fpstackptr)); regs.fpstackptr += 1; *regs.fpstackptr *= tmp; break; } case asmcode::IDIV: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); int64_t divider = (int64_t)*oprnd1; int64_t result = (int64_t)regs.rax / divider; int64_t remainder = (int64_t)regs.rax % divider; regs.rax = result; regs.rdx = remainder; break; } case asmcode::IMUL: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { int64_t rax = (int64_t)regs.rax; rax *= (int64_t)(*oprnd1); regs.rax = rax; } else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); int8_t rax = ((int64_t)regs.rax) & 255; rax *= (int8_t)(*oprnd1_8); regs.rax &= 0xffffffffffffff00; regs.rax |= rax; } break; } case asmcode::INC: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { *oprnd1 += 1; if (*oprnd1) regs.eflags &= ~zero_flag; else regs.eflags |= zero_flag; } else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); if (oprnd1_8) { *oprnd1_8 += 1; if (*oprnd1_8) regs.eflags &= ~zero_flag; else regs.eflags |= zero_flag; } } break; } case asmcode::JA: case asmcode::JAS: { if (((regs.eflags & zero_flag) | (regs.eflags & carry_flag)) == 0) { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("ja(s) not implemented"); } } break; } case asmcode::JB: case asmcode::JBS: { if (regs.eflags & carry_flag) { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("jb(s) not implemented"); } } break; } case asmcode::JE: case asmcode::JES: { if (regs.eflags & zero_flag) { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("je(s) not implemented"); } } break; } case asmcode::JG: case asmcode::JGS: { if ((((regs.eflags & sign_flag) ^ (regs.eflags & overflow_flag)) | (regs.eflags & zero_flag)) == 0) { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("jg(s) not implemented"); } } break; } case asmcode::JGE: case asmcode::JGES: { if (((regs.eflags & sign_flag) ^ (regs.eflags & overflow_flag)) == 0) { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("jge(s) not implemented"); } } break; } case asmcode::JL: case asmcode::JLS: { if (((regs.eflags & sign_flag) ^ (regs.eflags & overflow_flag))) { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("jl(s) not implemented"); } } break; } case asmcode::JLE: case asmcode::JLES: { if ((((regs.eflags & sign_flag) ^ (regs.eflags & overflow_flag)) | (regs.eflags & zero_flag))) { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("jle(s) not implemented"); } } break; } case asmcode::JNE: case asmcode::JNES: { if ((regs.eflags & zero_flag) == 0) { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("jne(s) not implemented"); } } break; } case asmcode::JMPS: { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { throw std::logic_error("jmps not implemented"); } break; } case asmcode::JMP: { if (operand1 == asmcode::NUMBER) { int32_t local_offset = (int32_t)operand1_mem; bytecode_ptr += local_offset; sz = 0; } else { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); bytecode_ptr = (const uint8_t*)(*oprnd1); sz = 0; } break; } case asmcode::MOVMSKPD: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint64_t* oprnd2 = get_address_64bit(operand2, operand2_mem, regs); *oprnd1 = (*oprnd2) ? 1 : 0; break; } case asmcode::MOVSD: case asmcode::MOVQ: case asmcode::MOV: { execute_operation<MovOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::MOVZX: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); uint8_t* oprnd2 = get_address_8bit(operand2, operand2_mem, regs); *oprnd1 = *oprnd2; break; } case asmcode::MUL: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { regs.rax *= (uint64_t)(*oprnd1); } else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); uint8_t rax = regs.rax & 255; rax *= (uint8_t)(*oprnd1_8); regs.rax &= 0xffffffffffffff00; regs.rax |= rax; } break; } case asmcode::MULSD: { execute_double_operation<MulsdOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::NEG: { uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) { int64_t val = (int64_t)(*oprnd1); *oprnd1 = -val; } else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); int8_t val = (int8_t)(*oprnd1_8); *oprnd1_8 = -val; } break; } case asmcode::NOP: break; case asmcode::OR: { execute_operation<OrOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::POP: { uint64_t address = *((uint64_t*)regs.rsp); regs.rsp += 8; uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); *oprnd1 = address; break; } case asmcode::PUSH: { regs.rsp -= 8; uint64_t* oprnd1 = get_address_64bit(operand1, operand1_mem, regs); if (oprnd1) *((uint64_t*)regs.rsp) = *oprnd1; else if (operand1 == asmcode::NUMBER || operand1 == asmcode::LABELADDRESS) *((uint64_t*)regs.rsp) = operand1_mem; else { uint8_t* oprnd1_8 = get_address_8bit(operand1, operand1_mem, regs); *((uint64_t*)regs.rsp) = (int8_t)(*oprnd1_8); } break; } case asmcode::RET: { uint64_t address = *((uint64_t*)regs.rsp); regs.rsp += 8; // to check, might need to pop more if (address == 0xffffffffffffffff) // we're at the end of this bytecode function call return; bytecode_ptr = (const uint8_t*)address; sz = 0; break; } case asmcode::SAL: { execute_operation<ShlOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::SAR: { execute_operation<SarOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::SETE: { uint8_t* oprnd1 = get_address_8bit(operand1, operand1_mem, regs); if (regs.eflags & zero_flag) *oprnd1 = 1; else *oprnd1 = 0; break; } case asmcode::SETNE: { uint8_t* oprnd1 = get_address_8bit(operand1, operand1_mem, regs); if (regs.eflags & zero_flag) *oprnd1 = 0; else *oprnd1 = 1; break; } case asmcode::SETL: { uint8_t* oprnd1 = get_address_8bit(operand1, operand1_mem, regs); if (((regs.eflags & sign_flag) ^ (regs.eflags & overflow_flag))) *oprnd1 = 1; else *oprnd1 = 0; break; } case asmcode::SETLE: { uint8_t* oprnd1 = get_address_8bit(operand1, operand1_mem, regs); if ((((regs.eflags & sign_flag) ^ (regs.eflags & overflow_flag)) | (regs.eflags & zero_flag)) == 0) *oprnd1 = 0; else *oprnd1 = 1; break; } case asmcode::SETG: { uint8_t* oprnd1 = get_address_8bit(operand1, operand1_mem, regs); if ((((regs.eflags & sign_flag) ^ (regs.eflags & overflow_flag)) | (regs.eflags & zero_flag)) == 0) *oprnd1 = 1; else *oprnd1 = 0; break; } case asmcode::SETGE: { uint8_t* oprnd1 = get_address_8bit(operand1, operand1_mem, regs); if (((regs.eflags & sign_flag) ^ (regs.eflags & overflow_flag))) *oprnd1 = 0; else *oprnd1 = 1; break; } case asmcode::SHL: { execute_operation<ShlOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::SHR: { execute_operation<ShrOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::SQRTPD: { execute_double_operation<SqrtpdOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::SUB: { execute_operation<SubOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::SUBSD: { execute_double_operation<SubsdOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::TEST: { uint64_t tmp = execute_operation_const<AndOper>(operand1, operand2, operand1_mem, operand2_mem, regs); if (tmp) { regs.eflags &= ~zero_flag; if ((int64_t)tmp < 0) regs.eflags |= sign_flag; else regs.eflags &= ~sign_flag; } else { regs.eflags |= zero_flag; regs.eflags &= ~sign_flag; } break; } case asmcode::UCOMISD: { double* oprnd1 = (double*)get_address_64bit(operand1, operand1_mem, regs); double* oprnd2 = (double*)get_address_64bit(operand2, operand2_mem, regs); if (*oprnd1 != *oprnd1 || *oprnd2 != *oprnd2) { regs.eflags = zero_flag | carry_flag; } else if (*oprnd1 < *oprnd2) { regs.eflags = carry_flag; } else if (*oprnd2 < *oprnd1) { regs.eflags = 0; } else { regs.eflags = zero_flag; } break; } case asmcode::XOR: { execute_operation<XorOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } case asmcode::XORPD: { execute_double_operation<XorpdOper>(operand1, operand2, operand1_mem, operand2_mem, regs); break; } default: { std::stringstream str; str << asmcode::operation_to_string(op) << " is not implemented yet!"; throw std::logic_error(str.str()); } } bytecode_ptr += sz; } } ASM_END
34.366239
209
0.599835
janm31415
a10c117e24c6cea7a02aa70464d14205d11f468b
145
hpp
C++
src/common.hpp
caobo1994/FourierSeries
e6b3cab9409aaaa8071adc82276dc22d82c0575c
[ "MIT" ]
null
null
null
src/common.hpp
caobo1994/FourierSeries
e6b3cab9409aaaa8071adc82276dc22d82c0575c
[ "MIT" ]
35
2019-09-18T21:51:33.000Z
2019-12-20T17:54:25.000Z
src/common.hpp
caobo1994/FourierSeries
e6b3cab9409aaaa8071adc82276dc22d82c0575c
[ "MIT" ]
null
null
null
#ifndef FSL_COMMON_HPP #define FSL_COMMON_HPP #include <vector> namespace FSL { template<class T> using seq = std::vector<T>; } #endif
12.083333
31
0.703448
caobo1994
a10c444fbdb2c3018a6326464180e471a6f102a8
3,988
cpp
C++
LTSketchbook/libraries/LTC2482/LTC2482.cpp
LinduinoBob/Linduino
a6465b549ee8daee4eec11c36cabf5487bd2a3bc
[ "FSFAP" ]
null
null
null
LTSketchbook/libraries/LTC2482/LTC2482.cpp
LinduinoBob/Linduino
a6465b549ee8daee4eec11c36cabf5487bd2a3bc
[ "FSFAP" ]
null
null
null
LTSketchbook/libraries/LTC2482/LTC2482.cpp
LinduinoBob/Linduino
a6465b549ee8daee4eec11c36cabf5487bd2a3bc
[ "FSFAP" ]
null
null
null
/*! LTC2482: 16-Bit Delta-Sigma ADC with Easy Drive Input Current Cancellation. @verbatim The LTC2480 is a 16-Bit Delta-Sigma ADC with Easy Drive Input Current Cancellation. The LTC2482 allows a wide common mode input range (0V to VCC) independent of the reference voltage. The reference can be as low as 100mV or can be tied directly to VCC. The noise level is 600nV RMS independent of VREF . This allows direct digitization of low level signals with 16-bit accuracy. The LTC2482 includes an on-chip trimmed oscillator, eliminating the need for external crystals or oscillators and provides 87dB rejection of 50Hz and 60Hz line frequency noise. Absolute accuracy and low drift are automatically maintained through continuous, transparent, offset and full-scale calibration. @endverbatim http://www.linear.com/product/LTC2482 http://www.linear.com/product/LTC2482#demoboards Copyright 2018(c) Analog Devices, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Analog Devices, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - The use of this software may or may not infringe the patent rights of one or more patent holders. This license does not release you from the requirement that you obtain separate licenses from these patent holders to use this software. - Use of the software either in source or binary form, must be run on or directly connected to an Analog Devices Inc. component. THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, INTELLECTUAL PROPERTY RIGHTS, 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. */ //! @ingroup Analog_to_Digital_Converters //! @{ //! @defgroup LTC2482 LTC2482: 16-Bit Delta-Sigma ADC with Easy Drive Input Current Cancellation. //! @} /*! @file @ingroup LTC2482 Library for LTC2482: 16-Bit Delta-Sigma ADC with Easy Drive Input Current Cancellation. */ #include <stdint.h> #include "Linduino.h" #include "LT_SPI.h" // Reads the LTC2482 and returns 24-bit data void LTC2482_read(uint8_t cs, uint32_t *ptr_adc_code) { LT_union_int32_4bytes data, command; // LTC24XX data and command command.LT_uint32 = 0; data.LT_uint32 = 0; spi_transfer_block(cs, command.LT_byte, data.LT_byte, (uint8_t)3); *ptr_adc_code = data.LT_uint32; } // Calculates the LTC2482 input voltage given the binary data, reference voltage and input gain. float LTC2482_code_to_voltage(uint32_t adc_code, float vref) { float voltage; voltage = (float)adc_code; voltage = voltage / (pow(2,16)-1); //! 2) This calculates the input as a fraction of the reference voltage (dimensionless) voltage = voltage * vref; //! 3) Multiply fraction by Vref to get the actual voltage at the input (in volts) return(voltage); }
42.88172
128
0.759027
LinduinoBob
e16041a1d927d389dbe71b359bd05553877b2c3c
1,374
cpp
C++
Adapter/adapter.cpp
UbertoNowak/Head-First_Design-Patterns_cpp
2dd3ddcc981c2f31f5a4fc087337a501da69a7a1
[ "MIT" ]
null
null
null
Adapter/adapter.cpp
UbertoNowak/Head-First_Design-Patterns_cpp
2dd3ddcc981c2f31f5a4fc087337a501da69a7a1
[ "MIT" ]
null
null
null
Adapter/adapter.cpp
UbertoNowak/Head-First_Design-Patterns_cpp
2dd3ddcc981c2f31f5a4fc087337a501da69a7a1
[ "MIT" ]
null
null
null
#include <iostream> #include "adapter.h" int EuropeanSocket::voltage() { return 230; } int EuropeanSocket::frequency() { return 50; } int AmericanSocket::voltage_110() { return 110; } int AmericanSocket::voltage_120() { return 120; } double AmericanSocket::freq_60Hz() { return 60.001; } void BatteryCharger::plugIn(EuropeanSocket *apSocket) { m_pSocket = apSocket; } void BatteryCharger::charge() { std::cout<< "Voltage " << m_pSocket->voltage() << ", frequency " << m_pSocket->frequency() << std::endl; } ObjectAdapter::ObjectAdapter(AmericanSocket* apSocket) : m_pSocket(apSocket) {} int ObjectAdapter::voltage() { return m_pSocket->voltage_110(); } int ObjectAdapter::frequency() { return static_cast<int>(m_pSocket->freq_60Hz()); } ClassAdapter::ClassAdapter() {} int ClassAdapter::voltage() { return AmericanSocket::voltage_120(); } int ClassAdapter::frequency() { return static_cast<int>(AmericanSocket::freq_60Hz()); } int main() { BatteryCharger charger; EuropeanSocket compatible_socket; charger.plugIn(&compatible_socket); charger.charge(); AmericanSocket incompatible_socket; ObjectAdapter adapter(&incompatible_socket); charger.plugIn(&adapter); charger.charge(); ClassAdapter diff_adapter; charger.plugIn(&diff_adapter); charger.charge(); return 0; }
16.554217
108
0.697962
UbertoNowak
e162a8cd78ec5c93a05bb704957b29674d6e7a90
1,973
hpp
C++
src/include/client/input/input_processor.hpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
6
2018-05-11T23:16:02.000Z
2019-06-13T01:35:07.000Z
src/include/client/input/input_processor.hpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
33
2018-05-11T14:12:22.000Z
2022-03-12T00:55:25.000Z
src/include/client/input/input_processor.hpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
1
2018-12-06T23:39:55.000Z
2018-12-06T23:39:55.000Z
#pragma once /** * Input processor * Processes SDL inputs, and convert them to actions, so * we do not have to fill the code with SDL-specific functions. * * However, we retain SDL keycode constants, because it is easier * * Copyright (C) 2020 Arthur Mendes */ #include <queue> #include <thread> #include <string> #include "input_actions.hpp" namespace familyline::input { /** * Processes input from SDL and generate input actions * * Usually will not generate events that have something to do with game * objects, like BuildAction or ObjectClickAction, but you can enable * it when the game starts */ class InputProcessor { private: // InputPicker& _ip; std::queue<HumanInputAction> _actions; std::thread _runThread; bool _isRunning = false; void enqueueEvent(const SDL_Event& e, int& lastX, int& lastY); public: // InputProcessor(InputPicker& ip) // : _ip(ip) // {} /** * Starts a thread to receive input, so we do not lose input * even if the primary thread hangs * * We might not be able to process it, but the system will never * treat this game as non-responding. */ void startInputReceiver(); /** * Stops the input receiver thread */ void stopInputReceiver(); /** * Get the next action * * Return true if we have a next action, false if the action queue is * empty */ bool pollAction(HumanInputAction& a); /** * Start receiving text events * * Call this if, for example, you are inserting text in a * textbox */ void enableTextEvents(); /** * Stop receiving text events * * Call this if, for example, you moved focus from a combobox to * another control */ void disableTextEvents(); std::string getClipboardText(); ~InputProcessor() { this->stopInputReceiver(); } }; } // namespace familyline::input
22.168539
73
0.635073
arthurmco
e1648c7b55885ab619d951a42f2a8345f5d89bc0
167
cpp
C++
Ch01/Ex1_16.cpp
boscotsang/CppPrimerCode
65eed86652f5ec475dec593bd731b7752cb46c51
[ "MIT" ]
4
2015-04-20T10:04:49.000Z
2018-04-19T12:46:01.000Z
Ch01/Ex1_16.cpp
boscotsang/CppPrimerCode
65eed86652f5ec475dec593bd731b7752cb46c51
[ "MIT" ]
null
null
null
Ch01/Ex1_16.cpp
boscotsang/CppPrimerCode
65eed86652f5ec475dec593bd731b7752cb46c51
[ "MIT" ]
null
null
null
#include <iostream> int main(){ int val = 0, sum = 0; while (std::cin >> val) sum += val; std::cout << "The sum is " << sum << std::endl; return 0; }
18.555556
51
0.508982
boscotsang
e1698007a0b467b16c84c26e2d880463aa27d035
2,496
cpp
C++
mbed-os/events/mbed_shared_queues.cpp
h7ga40/LycheeCam
10ee0ed948a02ccbe5f9a008e7c371ba5bd84478
[ "Apache-2.0" ]
1
2019-12-13T05:51:34.000Z
2019-12-13T05:51:34.000Z
mbed-os/events/mbed_shared_queues.cpp
h7ga40/LycheeCam
10ee0ed948a02ccbe5f9a008e7c371ba5bd84478
[ "Apache-2.0" ]
null
null
null
mbed-os/events/mbed_shared_queues.cpp
h7ga40/LycheeCam
10ee0ed948a02ccbe5f9a008e7c371ba5bd84478
[ "Apache-2.0" ]
1
2021-09-17T15:41:36.000Z
2021-09-17T15:41:36.000Z
/* events * Copyright (c) 2017 ARM Limited * * 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 "events/mbed_shared_queues.h" #include "mbed.h" using namespace events; namespace mbed { #ifdef MBED_CONF_RTOS_PRESENT /* Create an event queue, and start the thread that dispatches it. Static * variables mean this happens once the first time each template instantiation * is called. This is currently instantiated no more than twice. */ template <osPriority Priority, size_t QueueSize, size_t StackSize> EventQueue *do_shared_event_queue_with_thread() { static uint64_t queue_buffer[QueueSize / sizeof(uint64_t)]; static EventQueue queue(sizeof queue_buffer, (unsigned char *) queue_buffer); static uint64_t stack[StackSize / sizeof(uint64_t)]; static Thread thread(Priority, StackSize, (unsigned char *) stack); Thread::State state = thread.get_state(); if (state == Thread::Inactive || state == Thread::Deleted) { osStatus status = thread.start(callback(&queue, &EventQueue::dispatch_forever)); MBED_ASSERT(status == osOK); if (status != osOK) { return NULL; } } return &queue; } #endif EventQueue *mbed_event_queue() { #if MBED_CONF_EVENTS_SHARED_DISPATCH_FROM_APPLICATION || !defined MBED_CONF_RTOS_PRESENT /* Only create the EventQueue, but no dispatching thread */ static unsigned char queue_buffer[MBED_CONF_EVENTS_SHARED_EVENTSIZE]; static EventQueue queue(sizeof queue_buffer, queue_buffer); return &queue; #else return do_shared_event_queue_with_thread<osPriorityNormal, MBED_CONF_EVENTS_SHARED_EVENTSIZE, MBED_CONF_EVENTS_SHARED_STACKSIZE>(); #endif } #ifdef MBED_CONF_RTOS_PRESENT EventQueue *mbed_highprio_event_queue() { return do_shared_event_queue_with_thread<osPriorityHigh, MBED_CONF_EVENTS_SHARED_HIGHPRIO_EVENTSIZE, MBED_CONF_EVENTS_SHARED_HIGHPRIO_STACKSIZE>(); } #endif }
34.191781
152
0.733173
h7ga40
e16b8a3e9a8c4f75207c37b3f1fa5424bf6574d8
1,903
cpp
C++
game/tileview/tileobject_scenery.cpp
AndO3131/OpenApoc
9dea1895e273a1da5a7d8eda173255f6b364e626
[ "MIT" ]
null
null
null
game/tileview/tileobject_scenery.cpp
AndO3131/OpenApoc
9dea1895e273a1da5a7d8eda173255f6b364e626
[ "MIT" ]
null
null
null
game/tileview/tileobject_scenery.cpp
AndO3131/OpenApoc
9dea1895e273a1da5a7d8eda173255f6b364e626
[ "MIT" ]
null
null
null
#include "game/tileview/tileobject_scenery.h" #include "game/rules/scenerytiledef.h" namespace OpenApoc { void TileObjectScenery::draw(Renderer &r, TileView &view, Vec2<float> screenPosition, TileViewMode mode) { std::ignore = view; // Mode isn't used as TileView::tileToScreenCoords already transforms according to the mode auto scenery = this->scenery.lock(); if (!scenery) { LogError("Called with no owning scenery object"); return; } auto &tileDef = scenery->damaged ? *scenery->tileDef.getDamagedTile() : scenery->tileDef; sp<Image> sprite; sp<Image> overlaySprite; Vec2<float> transformedScreenPos = screenPosition; switch (mode) { case TileViewMode::Isometric: sprite = tileDef.getSprite(); overlaySprite = tileDef.getOverlaySprite(); transformedScreenPos -= tileDef.getImageOffset(); break; case TileViewMode::Strategy: sprite = tileDef.getStrategySprite(); // All strategy sprites so far are 8x8 so offset by 4 to draw from the center // FIXME: Not true for large sprites (2x2 UFOs?) transformedScreenPos -= Vec2<float>{4, 4}; break; default: LogError("Unsupported view mode"); } if (sprite) r.draw(sprite, transformedScreenPos); // FIXME: Should be drawn at 'later' Z than scenery (IE on top of any vehicles on tile?) if (overlaySprite) r.draw(overlaySprite, transformedScreenPos); } TileObjectScenery::~TileObjectScenery() {} TileObjectScenery::TileObjectScenery(TileMap &map, sp<Scenery> scenery) : TileObject(map, TileObject::Type::Scenery, scenery->getPosition(), Vec3<float>{1, 1, 1}), scenery(scenery) { } sp<Scenery> TileObjectScenery::getOwner() { auto s = this->scenery.lock(); if (!s) { LogError("Owning scenery object disappeared"); } return s; } sp<VoxelMap> TileObjectScenery::getVoxelMap() { return this->getOwner()->tileDef.getVoxelMap(); } } // namespace OpenApoc
28.833333
97
0.71361
AndO3131
e16d7d221aaa897e8c315bef28ecff50c0e05667
2,018
hpp
C++
src/modbuscli/ModbusWriteRegisterCommand.hpp
gkarvounis/libmodbusc-
9b74a62e9945c8ef3e76d0dc244303fbc3f34dca
[ "MIT" ]
2
2017-04-24T10:11:27.000Z
2019-09-20T10:37:35.000Z
src/modbuscli/ModbusWriteRegisterCommand.hpp
gkarvounis/libmodbusc-
9b74a62e9945c8ef3e76d0dc244303fbc3f34dca
[ "MIT" ]
null
null
null
src/modbuscli/ModbusWriteRegisterCommand.hpp
gkarvounis/libmodbusc-
9b74a62e9945c8ef3e76d0dc244303fbc3f34dca
[ "MIT" ]
1
2020-03-23T01:12:14.000Z
2020-03-23T01:12:14.000Z
#ifndef MODBUS_WRITE_REGISTER_COMMAND_HPP #define MODBUS_WRITE_REGISTER_COMMAND_HPP class ModbusWriteRegisterCommand : public ModbusCommand { public: ModbusWriteRegisterCommand(); void exec(ModbusClient& client, const std::vector<std::string>& args) override; std::string getShortHelpText() const override; std::string getHelpText() const override; private: using OptionsDescription = boost::program_options::options_description; using PositionalOptionsDescription = boost::program_options::positional_options_description; uint16_t m_address; uint16_t m_value; OptionsDescription m_options; PositionalOptionsDescription m_positional_options; }; ModbusWriteRegisterCommand::ModbusWriteRegisterCommand() { namespace po = boost::program_options; m_options.add_options() ("address,a", po::value<uint16_t>(&m_address)->required(), "address of target register") ("value,v", po::value<uint16_t>(&m_value)->required(), "new value for target register"); m_positional_options.add("address", 1); m_positional_options.add("value", 1); } void ModbusWriteRegisterCommand::exec(ModbusClient& client, const std::vector<std::string>& args) { namespace po = boost::program_options; po::variables_map vm; po::store(po::command_line_parser(args).options(m_options).positional(m_positional_options).run(), vm); po::notify(vm); client.writeRegister(modbus::tcp::Address(m_address), m_value); } std::string ModbusWriteRegisterCommand::getShortHelpText() const { return "Write a register of the modbus device"; } std::string ModbusWriteRegisterCommand::getHelpText() const { std::stringstream ss; ss << getShortHelpText() << std::endl << "Usage:" << std::endl << " writeregister <address> <value>" << std::endl; return ss.str(); } #endif
33.081967
110
0.671457
gkarvounis
e16faace971697339d2bb9d6ceb6ede170ca3351
3,028
cpp
C++
src/filebrowser/progress-dialog.cpp
vitlav/seafile-client
911aaf69ab10d65c6a6d461c1d6ca0722364098b
[ "Apache-2.0" ]
null
null
null
src/filebrowser/progress-dialog.cpp
vitlav/seafile-client
911aaf69ab10d65c6a6d461c1d6ca0722364098b
[ "Apache-2.0" ]
null
null
null
src/filebrowser/progress-dialog.cpp
vitlav/seafile-client
911aaf69ab10d65c6a6d461c1d6ca0722364098b
[ "Apache-2.0" ]
1
2021-11-02T18:40:14.000Z
2021-11-02T18:40:14.000Z
#include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #include <QProgressBar> #include <QPushButton> #include <QDesktopServices> #include <QDebug> #include "utils/utils.h" #include "progress-dialog.h" FileBrowserProgressDialog::FileBrowserProgressDialog(FileNetworkTask *task, QWidget *parent) : QProgressDialog(parent), task_(task->sharedFromThis()) { setWindowModality(Qt::WindowModal); QVBoxLayout *layout_ = new QVBoxLayout; progress_bar_ = new QProgressBar; description_label_ = new QLabel; layout_->addWidget(description_label_); layout_->addWidget(progress_bar_); QHBoxLayout *hlayout_ = new QHBoxLayout; more_details_label_ = new QLabel; more_details_label_->setText("Pending"); QPushButton *cancel_button_ = new QPushButton(tr("Cancel")); QWidget *spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); hlayout_->addWidget(more_details_label_); hlayout_->addWidget(spacer); hlayout_->addWidget(cancel_button_); hlayout_->setContentsMargins(-1, 0, -1, 6); layout_->setContentsMargins(-1, 0, -1, 6); layout_->addLayout(hlayout_); setLayout(layout_); setLabel(description_label_); setBar(progress_bar_); setCancelButton(cancel_button_); initTaskInfo(); } FileBrowserProgressDialog::~FileBrowserProgressDialog() { } void FileBrowserProgressDialog::initTaskInfo() { QString title, label; if (task_->type() == FileNetworkTask::Upload) { title = tr("Upload"); label = tr("Uploading %1"); } else { title = tr("Download"); label = tr("Downloading %1"); } setWindowTitle(title); setLabelText(label.arg(task_->fileName())); more_details_label_->setText(""); setMaximum(0); setValue(0); connect(task_.data(), SIGNAL(progressUpdate(qint64, qint64)), this, SLOT(onProgressUpdate(qint64, qint64))); connect(task_.data(), SIGNAL(finished(bool)), this, SLOT(onTaskFinished(bool))); connect(this, SIGNAL(canceled()), task_.data(), SLOT(cancel())); show(); } void FileBrowserProgressDialog::onProgressUpdate(qint64 processed_bytes, qint64 total_bytes) { // if the value is less than the maxmium, this dialog will close itself // add this guard for safety if (processed_bytes >= total_bytes) total_bytes = processed_bytes + 1; if (maximum() != total_bytes) setMaximum(total_bytes); setValue(processed_bytes); more_details_label_->setText(tr("%1 of %2") .arg(::readableFileSizeV2(processed_bytes)) .arg(::readableFileSizeV2(total_bytes))); } void FileBrowserProgressDialog::onTaskFinished(bool success) { if (success) { // printf ("progress dialog: task success\n"); accept(); } else { // printf ("progress dialog: task failed\n"); reject(); } } void FileBrowserProgressDialog::cancel() { task_->cancel(); reject(); }
27.527273
92
0.672391
vitlav
e173212699457f957d7207982633b679834dfac5
3,065
hpp
C++
tests/src/Mocks/Griddly/Core/MockGrid.hpp
Thaigun/Griddly
de5972a608a2928172510a0ac81a977c48af6b1f
[ "MIT" ]
null
null
null
tests/src/Mocks/Griddly/Core/MockGrid.hpp
Thaigun/Griddly
de5972a608a2928172510a0ac81a977c48af6b1f
[ "MIT" ]
null
null
null
tests/src/Mocks/Griddly/Core/MockGrid.hpp
Thaigun/Griddly
de5972a608a2928172510a0ac81a977c48af6b1f
[ "MIT" ]
null
null
null
#pragma once #include "Griddly/Core/Grid.hpp" #include "gmock/gmock.h" namespace griddly { class MockGrid : public Grid { public: MockGrid() : Grid() {} MOCK_METHOD(void, resetMap, (uint32_t width, uint32_t height), ()); MOCK_METHOD(void, setGlobalVariables, ((std::unordered_map<std::string, std::unordered_map<uint32_t, int32_t>>)), ()); MOCK_METHOD(void, resetGlobalVariables, ((std::unordered_map<std::string, GlobalVariableDefinition>)), ()); MOCK_METHOD((std::unordered_map<uint32_t, int32_t>), update, (), ()); MOCK_METHOD((const std::unordered_set<glm::ivec2>&), getUpdatedLocations, (uint32_t playerId), (const)); MOCK_METHOD(void, purgeUpdatedLocations, (uint32_t playerId), ()); MOCK_METHOD(uint32_t, getWidth, (), (const)); MOCK_METHOD(uint32_t, getHeight, (), (const)); MOCK_METHOD(bool, invalidateLocation, (glm::ivec2 location)); MOCK_METHOD(bool, updateLocation, (std::shared_ptr<Object> object, glm::ivec2 previousLocation, glm::ivec2 newLocation), ()); MOCK_METHOD((std::unordered_map<uint32_t, int32_t>), performActions, (uint32_t playerId, std::vector<std::shared_ptr<Action>> actions), ()); MOCK_METHOD(void, initObject, (std::string, std::vector<std::string>), ()); MOCK_METHOD(void, addObject, (glm::ivec2 location, std::shared_ptr<Object> object, bool applyInitialActions, std::shared_ptr<Action> originatingAction, DiscreteOrientation orientation), ()); MOCK_METHOD(void, addPlayerDefaultObject, (std::shared_ptr<Object> object)); MOCK_METHOD(std::shared_ptr<Object>, getPlayerDefaultObject, (uint32_t playerId), (const)); MOCK_METHOD(bool, removeObject, (std::shared_ptr<Object> object), ()); MOCK_METHOD((std::unordered_map<uint32_t, std::shared_ptr<int32_t>>), getObjectCounter, (std::string), ()); MOCK_METHOD((const std::unordered_map<std::string, uint32_t>&), getObjectIds, (), (const)); MOCK_METHOD((const std::unordered_map<std::string, uint32_t>&), getObjectVariableIds, (), (const)); MOCK_METHOD((const std::vector<std::string>), getAllObjectVariableNames, (), (const)); MOCK_METHOD((const std::vector<std::string>), getObjectNames, (), (const)); MOCK_METHOD((const std::map<std::string, std::unordered_map<uint32_t, std::shared_ptr<int32_t>>>&), getGlobalVariables, (), (const)); MOCK_METHOD((const std::unordered_set<std::shared_ptr<Object>>&), getObjects, (), ()); MOCK_METHOD(std::shared_ptr<Object>, getObject, (glm::ivec2 location), (const)); MOCK_METHOD((const TileObjects&), getObjectsAt, (glm::ivec2 location), (const)); MOCK_METHOD((std::unordered_map<uint32_t, std::shared_ptr<Object>>), getPlayerAvatarObjects, (), (const)); MOCK_METHOD(void, setPlayerCount, (int32_t), ()); MOCK_METHOD(uint32_t, getPlayerCount, (), (const)); MOCK_METHOD(void, addCollisionDetector, (std::vector<std::string> objectNames, std::string actionName, std::shared_ptr<CollisionDetector> collisionDetector), ()); MOCK_METHOD(std::shared_ptr<int32_t>, getTickCount, (), (const)); MOCK_METHOD(std::mt19937, getRandomGenerator, (), ()); }; } // namespace griddly
54.732143
192
0.726917
Thaigun
e179b9a60acaea8b164a6b4fc47e39e8eb06e432
1,919
cpp
C++
Olympiad Programs/Helli Lader #2/C.cpp
mirtaba/ACMICPC-INOI_Archive
ea06e4e40e984f0807410e4f9b5f7042580da2e3
[ "MIT" ]
1
2020-12-08T11:21:34.000Z
2020-12-08T11:21:34.000Z
Olympiad Programs/Helli Lader #2/C.cpp
mirtaba/ACMICPC-INOI_Archive
ea06e4e40e984f0807410e4f9b5f7042580da2e3
[ "MIT" ]
null
null
null
Olympiad Programs/Helli Lader #2/C.cpp
mirtaba/ACMICPC-INOI_Archive
ea06e4e40e984f0807410e4f9b5f7042580da2e3
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <cctype> #include <stack> #include <queue> #include <list> #include <vector> #include <map> #include <sstream> #include <cmath> #include <bitset> #include <utility> #include <set> #include <numeric> #include <cmath> #define MAX(a,b) (((a) > (b))? (a) : (b)) #define MIN(a,b) (((a) < (b))? (a) : (b)) #define MEM(a,b) (memset((a),(b),sizeof(a))) #define FOR(i,a,b) for(int i=a;i<b;i++) #define pb push_back #define mp make_pair #define f1 first #define f2 second #define X first #define Y second using namespace std; typedef long long LL; typedef pair <int, int> PII; typedef pair <LL,LL> PLL; const int Maxn = 2*100 + 25; const int Mod = 1000 * 1000 * 1000 + 7; //ofstream fout ("greetings.out"); //ifstream fin ("greetings.in"); bool mat [Maxn][Maxn];// ماتریس مجاورت گراف vector < int > G[Maxn]; vector <PII> E; int N,tmp1,tmp2; long Ans; bool mark[Maxn]; PII dfs (int V) { int sze=0,leaf=V; mark[V]=true; FOR(i,0,G[V].size()) { if( (!mark[G[V][i]]) && (mat[V][G[V][i]]) ) { PII U=dfs(G[V][i]); if( (U.Y+1) > sze ) { leaf=U.X; sze=U.Y+1; } } } return mp(leaf,sze); } int main() { ios::sync_with_stdio(0); cin >> N ; FOR(i,0,N-1) { cin >> tmp1 >> tmp2;tmp1--;tmp2--; G[tmp1].pb(tmp2); G[tmp2].pb(tmp1); mat[tmp1][tmp2]=true; mat[tmp2][tmp1]=true; E.pb(mp(tmp1,tmp2)); } PII leaf1,path1,leaf2,path2; FOR (i,0,E.size()) { tmp1=E[i].X; tmp2=E[i].Y; mat[tmp1][tmp2]=false; mat[tmp2][tmp1]=false; MEM(mark,0); PII leaf1=dfs(tmp1); MEM(mark,0); PII path1=dfs(leaf1.X); MEM(mark,0); PII leaf2=dfs(tmp2); MEM(mark,0); PII path2=dfs(leaf2.X); Ans= MAX(Ans,(long)(path1.Y *path2.Y) ); mat[tmp1][tmp2]=true; mat[tmp2][tmp1]=true; } cout << Ans << endl; }
18.27619
45
0.576863
mirtaba
e17b6ccd750b277f5978ca6dd64c20553a812599
2,053
cpp
C++
LoginServer/Source/ServerGroupManager.cpp
KaleoFeng/MetazionWorld
2790ef2cdef2e698687725d816e2f490da5150e0
[ "MIT" ]
4
2019-08-30T22:58:41.000Z
2020-10-20T06:27:08.000Z
LoginServer/Source/ServerGroupManager.cpp
KaleoFeng/MetazionWorld
2790ef2cdef2e698687725d816e2f490da5150e0
[ "MIT" ]
null
null
null
LoginServer/Source/ServerGroupManager.cpp
KaleoFeng/MetazionWorld
2790ef2cdef2e698687725d816e2f490da5150e0
[ "MIT" ]
1
2020-02-29T02:50:31.000Z
2020-02-29T02:50:31.000Z
#include "ServerGroupManager.hpp" #include <Common/Xml/rapidxml.hpp> #include <Common/Xml/rapidxml_utils.hpp> ServerGroupManager::ServerGroupManager() {} ServerGroupManager::~ServerGroupManager() {} void ServerGroupManager::Initialize() { LoadAllServerGroup(); } void ServerGroupManager::Finalize() { RemoveAllServerGroup(); } int ServerGroupManager::GetServerGroupSize() const { return m_serverGroupMap.GetSize(); } ServerGroup* ServerGroupManager::GetServerGroup(int id) { auto iter = m_serverGroupMap.Find(id); if (iter != m_serverGroupMap.End()) { return &iter->second; } return nullptr; } const ServerGroupManager::ServerGroupMap_t& ServerGroupManager::GetAllServerGroup() const { return m_serverGroupMap; } void ServerGroupManager::AddServerGroup(const ServerGroup& serverGroup) { m_serverGroupMap.Insert(serverGroup.GetId(), serverGroup); } void ServerGroupManager::RemoveServerGroup(int id) { auto iter = m_serverGroupMap.Find(id); if (iter != m_serverGroupMap.End()) { m_serverGroupMap.Erase(iter); } } void ServerGroupManager::RemoveAllServerGroup() { m_serverGroupMap.Clear(); } void ServerGroupManager::LoadAllServerGroup() { NS_MZ_NET::Host host; host.SetFamily(AF_INET); rapidxml::file<> file("../Resources/Config/ServerGroupList.xml"); auto data = file.data(); rapidxml::xml_document<> doc; doc.parse<0>(data); auto docName = doc.name(); rapidxml::xml_node<>* root = doc.first_node(); auto rootName = root->name(); for (auto node = root->first_node("ServerGroup") ; !NS_MZ::IsNull(node); node = node->next_sibling()) { auto idAttr = node->first_attribute("id"); auto nameAttr = node->first_attribute("name"); const auto szId = idAttr->value(); const auto szName = nameAttr->value(); const auto id = atoi(szId); ServerGroup serverGroup; serverGroup.SetId(id); serverGroup.SetName(szName); AddServerGroup(serverGroup); } }
26.320513
91
0.687287
KaleoFeng
e187acc78dc5fcb2c592a755d2fcaef31f9ce098
20,328
cpp
C++
pedump/COMMON.cpp
sarangbaheti/misc-code
d47a8d1cc41f19701ce628c9f15976bb5baa239d
[ "Unlicense" ]
1
2020-10-22T12:58:55.000Z
2020-10-22T12:58:55.000Z
pedump/COMMON.cpp
sarangbaheti/misc-code
d47a8d1cc41f19701ce628c9f15976bb5baa239d
[ "Unlicense" ]
null
null
null
pedump/COMMON.cpp
sarangbaheti/misc-code
d47a8d1cc41f19701ce628c9f15976bb5baa239d
[ "Unlicense" ]
2
2020-10-19T23:36:26.000Z
2020-10-22T12:59:37.000Z
//================================== // PEDUMP - Matt Pietrek 1997 // FILE: COMMON.C //================================== #include <windows.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "common.h" #include "symboltablesupport.h" #include "extrnvar.h" PIMAGE_DEBUG_MISC g_pMiscDebugInfo = 0; PDWORD g_pCVHeader = 0; PIMAGE_COFF_SYMBOLS_HEADER g_pCOFFHeader = 0; COFFSymbolTable * g_pCOFFSymbolTable = 0; /*----------------------------------------------------------------------------*/ // // Header related stuff // /*----------------------------------------------------------------------------*/ typedef struct { WORD flag; PSTR name; } WORD_FLAG_DESCRIPTIONS; typedef struct { DWORD flag; PSTR name; } DWORD_FLAG_DESCRIPTIONS; // Bitfield values and names for the IMAGE_FILE_HEADER flags WORD_FLAG_DESCRIPTIONS ImageFileHeaderCharacteristics[] = { { IMAGE_FILE_RELOCS_STRIPPED, "RELOCS_STRIPPED" }, { IMAGE_FILE_EXECUTABLE_IMAGE, "EXECUTABLE_IMAGE" }, { IMAGE_FILE_LINE_NUMS_STRIPPED, "LINE_NUMS_STRIPPED" }, { IMAGE_FILE_LOCAL_SYMS_STRIPPED, "LOCAL_SYMS_STRIPPED" }, { IMAGE_FILE_AGGRESIVE_WS_TRIM, "AGGRESIVE_WS_TRIM" }, // { IMAGE_FILE_MINIMAL_OBJECT, "MINIMAL_OBJECT" }, // Removed in NT 3.5 // { IMAGE_FILE_UPDATE_OBJECT, "UPDATE_OBJECT" }, // Removed in NT 3.5 // { IMAGE_FILE_16BIT_MACHINE, "16BIT_MACHINE" }, // Removed in NT 3.5 { IMAGE_FILE_BYTES_REVERSED_LO, "BYTES_REVERSED_LO" }, { IMAGE_FILE_32BIT_MACHINE, "32BIT_MACHINE" }, { IMAGE_FILE_DEBUG_STRIPPED, "DEBUG_STRIPPED" }, // { IMAGE_FILE_PATCH, "PATCH" }, { IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "REMOVABLE_RUN_FROM_SWAP" }, { IMAGE_FILE_NET_RUN_FROM_SWAP, "NET_RUN_FROM_SWAP" }, { IMAGE_FILE_SYSTEM, "SYSTEM" }, { IMAGE_FILE_DLL, "DLL" }, { IMAGE_FILE_UP_SYSTEM_ONLY, "UP_SYSTEM_ONLY" }, { IMAGE_FILE_BYTES_REVERSED_HI, "BYTES_REVERSED_HI" } }; #define NUMBER_IMAGE_HEADER_FLAGS \ (sizeof(ImageFileHeaderCharacteristics) / sizeof(WORD_FLAG_DESCRIPTIONS)) // // Dump the IMAGE_FILE_HEADER for a PE file or an OBJ // void DumpHeader(PIMAGE_FILE_HEADER pImageFileHeader) { UINT headerFieldWidth = 30; UINT i; printf("File Header\n"); printf(" %-*s%04X (%s)\n", headerFieldWidth, "Machine:", pImageFileHeader->Machine, GetMachineTypeName(pImageFileHeader->Machine) ); printf(" %-*s%04X\n", headerFieldWidth, "Number of Sections:", pImageFileHeader->NumberOfSections); printf(" %-*s%08X -> %s", headerFieldWidth, "TimeDateStamp:", pImageFileHeader->TimeDateStamp, ctime((long *)&pImageFileHeader->TimeDateStamp)); printf(" %-*s%08X\n", headerFieldWidth, "PointerToSymbolTable:", pImageFileHeader->PointerToSymbolTable); printf(" %-*s%08X\n", headerFieldWidth, "NumberOfSymbols:", pImageFileHeader->NumberOfSymbols); printf(" %-*s%04X\n", headerFieldWidth, "SizeOfOptionalHeader:", pImageFileHeader->SizeOfOptionalHeader); printf(" %-*s%04X\n", headerFieldWidth, "Characteristics:", pImageFileHeader->Characteristics); for ( i=0; i < NUMBER_IMAGE_HEADER_FLAGS; i++ ) { if ( pImageFileHeader->Characteristics & ImageFileHeaderCharacteristics[i].flag ) printf( " %s\n", ImageFileHeaderCharacteristics[i].name ); } } #ifndef IMAGE_DLLCHARACTERISTICS_WDM_DRIVER #define IMAGE_DLLCHARACTERISTICS_WDM_DRIVER 0x2000 // Driver uses WDM model #endif // Marked as obsolete in MSDN CD 9 // Bitfield values and names for the DllCharacteritics flags WORD_FLAG_DESCRIPTIONS DllCharacteristics[] = { { IMAGE_DLLCHARACTERISTICS_WDM_DRIVER, "WDM_DRIVER" }, }; #define NUMBER_DLL_CHARACTERISTICS \ (sizeof(DllCharacteristics) / sizeof(WORD_FLAG_DESCRIPTIONS)) #if 0 // Marked as obsolete in MSDN CD 9 // Bitfield values and names for the LoaderFlags flags DWORD_FLAG_DESCRIPTIONS LoaderFlags[] = { { IMAGE_LOADER_FLAGS_BREAK_ON_LOAD, "BREAK_ON_LOAD" }, { IMAGE_LOADER_FLAGS_DEBUG_ON_LOAD, "DEBUG_ON_LOAD" } }; #define NUMBER_LOADER_FLAGS \ (sizeof(LoaderFlags) / sizeof(DWORD_FLAG_DESCRIPTIONS)) #endif // Names of the data directory elements that are defined char *ImageDirectoryNames[] = { "EXPORT", "IMPORT", "RESOURCE", "EXCEPTION", "SECURITY", "BASERELOC", "DEBUG", "COPYRIGHT", "GLOBALPTR", "TLS", "LOAD_CONFIG", "BOUND_IMPORT", "IAT", // These two entries added for NT 3.51 "DELAY_IMPORT" }; // This entry added in NT 5 #define NUMBER_IMAGE_DIRECTORY_ENTRYS \ (sizeof(ImageDirectoryNames)/sizeof(char *)) // // Dump the IMAGE_OPTIONAL_HEADER from a PE file // void DumpOptionalHeader(PIMAGE_OPTIONAL_HEADER optionalHeader) { UINT width = 30; char *s; UINT i; printf("Optional Header\n"); printf(" %-*s%04X\n", width, "Magic", optionalHeader->Magic); printf(" %-*s%u.%02u\n", width, "linker version", optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion); printf(" %-*s%X\n", width, "size of code", optionalHeader->SizeOfCode); printf(" %-*s%X\n", width, "size of initialized data", optionalHeader->SizeOfInitializedData); printf(" %-*s%X\n", width, "size of uninitialized data", optionalHeader->SizeOfUninitializedData); printf(" %-*s%X\n", width, "entrypoint RVA", optionalHeader->AddressOfEntryPoint); printf(" %-*s%X\n", width, "base of code", optionalHeader->BaseOfCode); printf(" %-*s%X\n", width, "base of data", optionalHeader->BaseOfData); printf(" %-*s%X\n", width, "image base", optionalHeader->ImageBase); printf(" %-*s%X\n", width, "section align", optionalHeader->SectionAlignment); printf(" %-*s%X\n", width, "file align", optionalHeader->FileAlignment); printf(" %-*s%u.%02u\n", width, "required OS version", optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion); printf(" %-*s%u.%02u\n", width, "image version", optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion); printf(" %-*s%u.%02u\n", width, "subsystem version", optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion); printf(" %-*s%X\n", width, "Win32 Version", optionalHeader->Win32VersionValue); printf(" %-*s%X\n", width, "size of image", optionalHeader->SizeOfImage); printf(" %-*s%X\n", width, "size of headers", optionalHeader->SizeOfHeaders); printf(" %-*s%X\n", width, "checksum", optionalHeader->CheckSum); switch( optionalHeader->Subsystem ) { case IMAGE_SUBSYSTEM_NATIVE: s = "Native"; break; case IMAGE_SUBSYSTEM_WINDOWS_GUI: s = "Windows GUI"; break; case IMAGE_SUBSYSTEM_WINDOWS_CUI: s = "Windows character"; break; case IMAGE_SUBSYSTEM_OS2_CUI: s = "OS/2 character"; break; case IMAGE_SUBSYSTEM_POSIX_CUI: s = "Posix character"; break; default: s = "unknown"; } printf(" %-*s%04X (%s)\n", width, "Subsystem", optionalHeader->Subsystem, s); // Marked as obsolete in MSDN CD 9 printf(" %-*s%04X\n", width, "DLL flags", optionalHeader->DllCharacteristics); for ( i=0; i < NUMBER_DLL_CHARACTERISTICS; i++ ) { if ( optionalHeader->DllCharacteristics & DllCharacteristics[i].flag ) printf( " %-*s%s", width, " ", DllCharacteristics[i].name ); } if ( optionalHeader->DllCharacteristics ) printf("\n"); printf(" %-*s%X\n", width, "stack reserve size", optionalHeader->SizeOfStackReserve); printf(" %-*s%X\n", width, "stack commit size", optionalHeader->SizeOfStackCommit); printf(" %-*s%X\n", width, "heap reserve size", optionalHeader->SizeOfHeapReserve); printf(" %-*s%X\n", width, "heap commit size", optionalHeader->SizeOfHeapCommit); #if 0 // Marked as obsolete in MSDN CD 9 printf(" %-*s%08X\n", width, "loader flags", optionalHeader->LoaderFlags); for ( i=0; i < NUMBER_LOADER_FLAGS; i++ ) { if ( optionalHeader->LoaderFlags & LoaderFlags[i].flag ) printf( " %s", LoaderFlags[i].name ); } if ( optionalHeader->LoaderFlags ) printf("\n"); #endif printf(" %-*s%X\n", width, "RVAs & sizes", optionalHeader->NumberOfRvaAndSizes); printf("\nData Directory\n"); for ( i=0; i < optionalHeader->NumberOfRvaAndSizes; i++) { printf( " %-12s rva: %08X size: %08X\n", (i >= NUMBER_IMAGE_DIRECTORY_ENTRYS) ? "unused" : ImageDirectoryNames[i], optionalHeader->DataDirectory[i].VirtualAddress, optionalHeader->DataDirectory[i].Size); } } PSTR GetMachineTypeName( WORD wMachineType ) { switch( wMachineType ) { case IMAGE_FILE_MACHINE_I386: return "i386"; // case IMAGE_FILE_MACHINE_I860:return "i860"; case IMAGE_FILE_MACHINE_R3000: return "R3000"; case 160: return "R3000 big endian"; case IMAGE_FILE_MACHINE_R4000: return "R4000"; case IMAGE_FILE_MACHINE_R10000: return "R10000"; case IMAGE_FILE_MACHINE_ALPHA: return "Alpha"; case IMAGE_FILE_MACHINE_POWERPC:return "PowerPC"; default: return "unknown"; } } /*----------------------------------------------------------------------------*/ // // Section related stuff // /*----------------------------------------------------------------------------*/ // // These aren't defined in the NT 4.0 WINNT.H, so we'll define them here // #ifndef IMAGE_SCN_TYPE_DSECT #define IMAGE_SCN_TYPE_DSECT 0x00000001 // Reserved. #endif #ifndef IMAGE_SCN_TYPE_NOLOAD #define IMAGE_SCN_TYPE_NOLOAD 0x00000002 // Reserved. #endif #ifndef IMAGE_SCN_TYPE_GROUP #define IMAGE_SCN_TYPE_GROUP 0x00000004 // Reserved. #endif #ifndef IMAGE_SCN_TYPE_COPY #define IMAGE_SCN_TYPE_COPY 0x00000010 // Reserved. #endif #ifndef IMAGE_SCN_TYPE_OVER #define IMAGE_SCN_TYPE_OVER 0x00000400 // Reserved. #endif #ifndef IMAGE_SCN_MEM_PROTECTED #define IMAGE_SCN_MEM_PROTECTED 0x00004000 #endif #ifndef IMAGE_SCN_MEM_SYSHEAP #define IMAGE_SCN_MEM_SYSHEAP 0x00010000 #endif // Bitfield values and names for the IMAGE_SECTION_HEADER flags DWORD_FLAG_DESCRIPTIONS SectionCharacteristics[] = { { IMAGE_SCN_TYPE_DSECT, "DSECT" }, { IMAGE_SCN_TYPE_NOLOAD, "NOLOAD" }, { IMAGE_SCN_TYPE_GROUP, "GROUP" }, { IMAGE_SCN_TYPE_NO_PAD, "NO_PAD" }, { IMAGE_SCN_TYPE_COPY, "COPY" }, { IMAGE_SCN_CNT_CODE, "CODE" }, { IMAGE_SCN_CNT_INITIALIZED_DATA, "INITIALIZED_DATA" }, { IMAGE_SCN_CNT_UNINITIALIZED_DATA, "UNINITIALIZED_DATA" }, { IMAGE_SCN_LNK_OTHER, "OTHER" }, { IMAGE_SCN_LNK_INFO, "INFO" }, { IMAGE_SCN_TYPE_OVER, "OVER" }, { IMAGE_SCN_LNK_REMOVE, "REMOVE" }, { IMAGE_SCN_LNK_COMDAT, "COMDAT" }, { IMAGE_SCN_MEM_PROTECTED, "PROTECTED" }, { IMAGE_SCN_MEM_FARDATA, "FARDATA" }, { IMAGE_SCN_MEM_SYSHEAP, "SYSHEAP" }, { IMAGE_SCN_MEM_PURGEABLE, "PURGEABLE" }, { IMAGE_SCN_MEM_LOCKED, "LOCKED" }, { IMAGE_SCN_MEM_PRELOAD, "PRELOAD" }, { IMAGE_SCN_LNK_NRELOC_OVFL, "NRELOC_OVFL" }, { IMAGE_SCN_MEM_DISCARDABLE, "DISCARDABLE" }, { IMAGE_SCN_MEM_NOT_CACHED, "NOT_CACHED" }, { IMAGE_SCN_MEM_NOT_PAGED, "NOT_PAGED" }, { IMAGE_SCN_MEM_SHARED, "SHARED" }, { IMAGE_SCN_MEM_EXECUTE, "EXECUTE" }, { IMAGE_SCN_MEM_READ, "READ" }, { IMAGE_SCN_MEM_WRITE, "WRITE" }, }; #define NUMBER_SECTION_CHARACTERISTICS \ (sizeof(SectionCharacteristics) / sizeof(DWORD_FLAG_DESCRIPTIONS)) // // Dump the section table from a PE file or an OBJ // void DumpSectionTable(PIMAGE_SECTION_HEADER section, unsigned cSections, BOOL IsEXE) { unsigned i, j; PSTR pszAlign; printf("Section Table\n"); for ( i=1; i <= cSections; i++, section++ ) { printf( " %02X %-8.8s %s: %08X VirtAddr: %08X\n", i, section->Name, IsEXE ? "VirtSize" : "PhysAddr", section->Misc.VirtualSize, section->VirtualAddress); printf( " raw data offs: %08X raw data size: %08X\n", section->PointerToRawData, section->SizeOfRawData ); printf( " relocation offs: %08X relocations: %08X\n", section->PointerToRelocations, section->NumberOfRelocations ); printf( " line # offs: %08X line #'s: %08X\n", section->PointerToLinenumbers, section->NumberOfLinenumbers ); printf( " characteristics: %08X\n", section->Characteristics); printf(" "); for ( j=0; j < NUMBER_SECTION_CHARACTERISTICS; j++ ) { if ( section->Characteristics & SectionCharacteristics[j].flag ) printf( " %s", SectionCharacteristics[j].name ); } switch( section->Characteristics & IMAGE_SCN_ALIGN_64BYTES ) { case IMAGE_SCN_ALIGN_1BYTES: pszAlign = "ALIGN_1BYTES"; break; case IMAGE_SCN_ALIGN_2BYTES: pszAlign = "ALIGN_2BYTES"; break; case IMAGE_SCN_ALIGN_4BYTES: pszAlign = "ALIGN_4BYTES"; break; case IMAGE_SCN_ALIGN_8BYTES: pszAlign = "ALIGN_8BYTES"; break; case IMAGE_SCN_ALIGN_16BYTES: pszAlign = "ALIGN_16BYTES"; break; case IMAGE_SCN_ALIGN_32BYTES: pszAlign = "ALIGN_32BYTES"; break; case IMAGE_SCN_ALIGN_64BYTES: pszAlign = "ALIGN_64BYTES"; break; default: pszAlign = "ALIGN_DEFAULT(16)"; break; } printf( " %s", pszAlign ); printf("\n\n"); } } // // Given a section name, look it up in the section table and return a // pointer to the start of its raw data area. // LPVOID GetSectionPtr(PSTR name, PIMAGE_NT_HEADERS pNTHeader, DWORD imageBase) { PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNTHeader); unsigned i; for ( i=0; i < pNTHeader->FileHeader.NumberOfSections; i++, section++ ) { if (strncmp((char *)section->Name, name, IMAGE_SIZEOF_SHORT_NAME) == 0) return (LPVOID)(section->PointerToRawData + imageBase); } return 0; } LPVOID GetPtrFromRVA( DWORD rva, PIMAGE_NT_HEADERS pNTHeader, DWORD imageBase ) { PIMAGE_SECTION_HEADER pSectionHdr; INT delta; pSectionHdr = GetEnclosingSectionHeader( rva, pNTHeader ); if ( !pSectionHdr ) return 0; delta = (INT)(pSectionHdr->VirtualAddress-pSectionHdr->PointerToRawData); return (PVOID) ( imageBase + rva - delta ); } // // Given a section name, look it up in the section table and return a // pointer to its IMAGE_SECTION_HEADER // PIMAGE_SECTION_HEADER GetSectionHeader(PSTR name, PIMAGE_NT_HEADERS pNTHeader) { PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNTHeader); unsigned i; for ( i=0; i < pNTHeader->FileHeader.NumberOfSections; i++, section++ ) { if ( 0 == strncmp((char *)section->Name,name,IMAGE_SIZEOF_SHORT_NAME) ) return section; } return 0; } // // Given an RVA, look up the section header that encloses it and return a // pointer to its IMAGE_SECTION_HEADER // PIMAGE_SECTION_HEADER GetEnclosingSectionHeader(DWORD rva, PIMAGE_NT_HEADERS pNTHeader) { PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNTHeader); unsigned i; for ( i=0; i < pNTHeader->FileHeader.NumberOfSections; i++, section++ ) { // Is the RVA within this section? if ( (rva >= section->VirtualAddress) && (rva < (section->VirtualAddress + section->Misc.VirtualSize))) return section; } return 0; } PIMAGE_COFF_SYMBOLS_HEADER PCOFFDebugInfo = 0; char *SzDebugFormats[] = { "UNKNOWN/BORLAND","COFF","CODEVIEW","FPO","MISC","EXCEPTION","FIXUP", "OMAP_TO_SRC", "OMAP_FROM_SRC"}; // // Dump the debug directory array // void DumpDebugDirectory(PIMAGE_DEBUG_DIRECTORY debugDir, DWORD size, DWORD base) { DWORD cDebugFormats = size / sizeof(IMAGE_DEBUG_DIRECTORY); PSTR szDebugFormat; unsigned i; if ( cDebugFormats == 0 ) return; printf( "Debug Formats in File\n" " Type Size Address FilePtr Charactr TimeDate Version\n" " --------------- -------- -------- -------- -------- -------- --------\n" ); for ( i=0; i < cDebugFormats; i++ ) { szDebugFormat = (debugDir->Type <= IMAGE_DEBUG_TYPE_OMAP_FROM_SRC ) ? SzDebugFormats[debugDir->Type] : "???"; printf(" %-15s %08X %08X %08X %08X %08X %u.%02u\n", szDebugFormat, debugDir->SizeOfData, debugDir->AddressOfRawData, debugDir->PointerToRawData, debugDir->Characteristics, debugDir->TimeDateStamp, debugDir->MajorVersion, debugDir->MinorVersion); switch( debugDir->Type ) { case IMAGE_DEBUG_TYPE_COFF: g_pCOFFHeader = (PIMAGE_COFF_SYMBOLS_HEADER)(base+ debugDir->PointerToRawData); break; case IMAGE_DEBUG_TYPE_MISC: g_pMiscDebugInfo = (PIMAGE_DEBUG_MISC)(base + debugDir->PointerToRawData); break; case IMAGE_DEBUG_TYPE_CODEVIEW: g_pCVHeader = (PDWORD)(base + debugDir->PointerToRawData); break; } debugDir++; } } /*----------------------------------------------------------------------------*/ // // Other assorted stuff // /*----------------------------------------------------------------------------*/ // // Do a hexadecimal dump of the raw data for all the sections. You // could just dump one section by adjusting the PIMAGE_SECTION_HEADER // and cSections parameters // void DumpRawSectionData(PIMAGE_SECTION_HEADER section, PVOID base, unsigned cSections) { unsigned i; char name[IMAGE_SIZEOF_SHORT_NAME + 1]; printf("Section Hex Dumps\n"); for ( i=1; i <= cSections; i++, section++ ) { // Make a copy of the section name so that we can ensure that // it's null-terminated memcpy(name, section->Name, IMAGE_SIZEOF_SHORT_NAME); name[IMAGE_SIZEOF_SHORT_NAME] = 0; // Don't dump sections that don't exist in the file! if ( section->PointerToRawData == 0 ) continue; printf( "section %02X (%s) size: %08X file offs: %08X\n", i, name, section->SizeOfRawData, section->PointerToRawData); HexDump( MakePtr(PBYTE, base, section->PointerToRawData), section->SizeOfRawData ); printf("\n"); } } // Number of hex values displayed per line #define HEX_DUMP_WIDTH 16 // // Dump a region of memory in a hexadecimal format // void HexDump(PBYTE ptr, DWORD length) { char buffer[256]; PSTR buffPtr, buffPtr2; unsigned cOutput, i; DWORD bytesToGo=length; while ( bytesToGo ) { cOutput = bytesToGo >= HEX_DUMP_WIDTH ? HEX_DUMP_WIDTH : bytesToGo; buffPtr = buffer; buffPtr += sprintf(buffPtr, "%08X: ", length-bytesToGo ); buffPtr2 = buffPtr + (HEX_DUMP_WIDTH * 3) + 1; for ( i=0; i < HEX_DUMP_WIDTH; i++ ) { BYTE value = *(ptr+i); if ( i >= cOutput ) { // On last line. Pad with spaces *buffPtr++ = ' '; *buffPtr++ = ' '; *buffPtr++ = ' '; } else { if ( value < 0x10 ) { *buffPtr++ = '0'; itoa( value, buffPtr++, 16); } else { itoa( value, buffPtr, 16); buffPtr+=2; } *buffPtr++ = ' '; *buffPtr2++ = isprint(value) ? value : '.'; } // Put an extra space between the 1st and 2nd half of the bytes // on each line. if ( i == (HEX_DUMP_WIDTH/2)-1 ) *buffPtr++ = ' '; } *buffPtr2 = 0; // Null terminate it. puts(buffer); // Can't use printf(), since there may be a '%' // in the string. bytesToGo -= cOutput; ptr += HEX_DUMP_WIDTH; } }
33.655629
80
0.618752
sarangbaheti
e189671ea5b6c4efaf7b130103fa21e6851569e5
5,821
hpp
C++
plugins/parcelport/verbs/header.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
plugins/parcelport/verbs/header.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
plugins/parcelport/verbs/header.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2015-2016 John Biddiscombe // Copyright (c) 2013-2015 Thomas Heller // Copyright (c) 2013-2014 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef HPX_PARCELSET_POLICIES_VERBS_HEADER_HPP #define HPX_PARCELSET_POLICIES_VERBS_HEADER_HPP #include <hpx/assertion.hpp> #include <hpx/runtime/parcelset/parcel_buffer.hpp> // #include <array> #include <cstdint> #include <cstddef> #include <cstring> #include <utility> #include <vector> // A generic header structure that can be used by parcelports // currently, the verbs parcelports make use of it namespace hpx { namespace parcelset { namespace policies { namespace verbs { namespace detail { struct rdma_region { std::size_t size; uint32_t key; const void * addr; }; struct piggy_back { uint32_t offset; uint32_t bytes; }; union rdma_info { piggy_back piggyback; rdma_region region; }; typedef std::pair<uint16_t, uint16_t> num_chunks_type; struct header_block { uint32_t tag; uint32_t size; num_chunks_type num_chunks; uint32_t flags; rdma_info chunk_info; rdma_info message_info; }; } template <int SIZE> struct header { static constexpr unsigned int header_block_size = sizeof(detail::header_block); static constexpr unsigned int data_size_ = SIZE - header_block_size; static const unsigned int chunk_flag = 0x01; static const unsigned int message_flag = 0x02; // private: detail::header_block message_header; std::array<char, data_size_> data_; public: // template <typename Buffer> header(Buffer const & buffer, uint32_t tag) { message_header.flags = 0; message_header.tag = tag; message_header.size = static_cast<uint32_t>(buffer.size_); message_header.num_chunks = std::make_pair(buffer.num_chunks_.first, buffer.num_chunks_.second); // find out how much space is needed for chunk information const std::vector<serialization::serialization_chunk>& chunks = buffer.chunks_; size_t chunkbytes = chunks.size() * sizeof(serialization::serialization_chunk); // can we send the chunk info inside the header if (chunkbytes <= data_size_) { message_header.flags |= chunk_flag; message_header.chunk_info.piggyback.offset = 0; message_header.chunk_info.piggyback.bytes = chunkbytes; std::memcpy(&data_[0], chunks.data(), chunkbytes); LOG_DEBUG_MSG("Chunkbytes is " << decnumber(chunkbytes) << "header_block_size " << decnumber(sizeof(detail::header_block))); } else { message_header.flags &= ~chunk_flag; chunkbytes = 0; } // the end of header position will be start of piggyback data message_header.message_info.piggyback.offset = chunkbytes; // can we send main message chunk as well as other information if (buffer.data_.size() <= (data_size_ - chunkbytes)) { message_header.flags |= message_flag; } else { message_header.flags &= ~message_flag; } } inline char *data() const { return &data_[0]; } inline uint32_t tag() const { return message_header.tag; } inline uint32_t size() const { return message_header.size; } inline std::pair<uint32_t, uint32_t> num_chunks() const { return message_header.num_chunks; } inline char * chunk_data() { if ((message_header.flags & chunk_flag) !=0) { return &data_[0]; } return 0; } inline char * piggy_back() { if ((message_header.flags & message_flag) !=0) { return &data_[message_header.message_info.piggyback.offset]; } return 0; } inline std::size_t header_length() const { // if chunks are included in header, return header + chunkbytes if ((message_header.flags & chunk_flag) !=0) return sizeof(detail::header_block) + message_header.chunk_info.piggyback.bytes; // otherwise, just end of normal header else return sizeof(detail::header_block); } inline void set_message_rdma_key(uint32_t v) { message_header.chunk_info.region.key = v; } inline uint32_t get_message_rdma_key() const { return message_header.chunk_info.region.key; } inline void set_message_rdma_addr(const void *v) { message_header.chunk_info.region.addr = v; } inline const void * get_message_rdma_addr() const { return message_header.chunk_info.region.addr; } inline void set_message_rdma_size(std::size_t v) { message_header.chunk_info.region.size = v; } inline std::size_t get_message_rdma_size() const { return message_header.chunk_info.region.size; } }; }}}} #endif
30.962766
87
0.573956
McKillroy
e18e7d918425e71109652cbd9727fa70f5c5ceeb
4,117
cpp
C++
Modules/Meshing/VolumeFromSTL/src/surfacefromimage_main.cpp
vivabrain/angiotk
56187d726691576bc90ac727f28ed08bb0633830
[ "Apache-2.0" ]
4
2016-06-26T18:47:22.000Z
2020-06-20T20:54:38.000Z
Modules/Meshing/VolumeFromSTL/src/surfacefromimage_main.cpp
feelpp/angiotk
3faac75cc6eeeb49e9c85dc20ad44038f185e5f6
[ "Apache-2.0" ]
7
2018-05-10T18:31:22.000Z
2018-07-20T09:19:31.000Z
Modules/Meshing/VolumeFromSTL/src/surfacefromimage_main.cpp
feelpp/angiotk
3faac75cc6eeeb49e9c85dc20ad44038f185e5f6
[ "Apache-2.0" ]
3
2015-07-06T08:07:46.000Z
2021-02-01T16:01:25.000Z
#include <feel/feelcore/environment.hpp> #include <volumefromstl.hpp> int main( int argc, char** argv ) { using namespace AngioTk; std::ostringstream oss; for( int i = 1; i < argc; i++) { oss << argv[i] << " "; } std::cout << "SurfaceFromImage: Using the following commandline arguments: " << std::endl << oss.str() << std::endl; po::options_description myoptions = SurfaceFromImage::options(""); myoptions. add( SubdivideSurface::options("subdivide-surface") ). add( SmoothSurface::options("smooth-surface") ). add( RemeshSurface::options("remesh-surface") ); myoptions.add_options() ("post-process.subdivide-surface", Feel::po::value<bool>()->default_value(false), "subdivide-surface") ("post-process.smooth-surface", Feel::po::value<bool>()->default_value(false), "smooth-surface") ("post-process.remesh-surface", Feel::po::value<bool>()->default_value(false), "remesh-surface"); AngioTkEnvironment env( _argc=argc, _argv=argv, _desc=myoptions, _about=about(_name="meshing_surfacefromimage", _author="Feel++ Consortium", _email="feelpp-devel@feelpp.org")); bool postProcessSubdivideSurface = boption(_name="post-process.subdivide-surface"); bool postProcessSmoothSurface = boption(_name="post-process.smooth-surface"); bool postProcessRemeshSurface = boption(_name="post-process.remesh-surface"); SurfaceFromImage surfaceFromImage(""); std::string finalOutputPath = surfaceFromImage.outputPath(); std::string finalOutputFileName = fs::path(finalOutputPath).stem().string(); std::string lastOutputPath = finalOutputPath; if ( postProcessSubdivideSurface || postProcessSmoothSurface || postProcessRemeshSurface ) { surfaceFromImage.setOutputPath( (fs::path(finalOutputPath).parent_path()/ fs::path(finalOutputFileName+"_surfaceFromImage.stl")).string() ); } /* If we get a return code different of 0 -> error */ if(surfaceFromImage.run()) { return 1; } SubdivideSurface mySubdivideSurface("subdivide-surface"); if ( postProcessSubdivideSurface ) { mySubdivideSurface.setInputSurfacePath( surfaceFromImage.outputPath() ); if ( !postProcessSmoothSurface && !postProcessRemeshSurface ) mySubdivideSurface.setOutputPath( finalOutputPath ); else mySubdivideSurface.setOutputPath( (fs::path(finalOutputPath).parent_path()/ fs::path(finalOutputFileName+"_subdivideSurface.stl")).string() ); if ( surfaceFromImage.forceRebuild() ) mySubdivideSurface.setForceRebuild( true ); mySubdivideSurface.run(); } SmoothSurface mySmoothSurface("smooth-surface"); if ( postProcessSmoothSurface ) { if ( postProcessSubdivideSurface ) mySmoothSurface.setInputSurfacePath( mySubdivideSurface.outputPath() ); else mySmoothSurface.setInputSurfacePath( surfaceFromImage.outputPath() ); if ( !postProcessRemeshSurface ) mySmoothSurface.setOutputPath( finalOutputPath ); else mySmoothSurface.setOutputPath( (fs::path(finalOutputPath).parent_path()/ fs::path(finalOutputFileName+"_smoothSurface.stl")).string() ); if ( surfaceFromImage.forceRebuild() || ( postProcessSubdivideSurface && mySubdivideSurface.forceRebuild() ) ) mySmoothSurface.setForceRebuild( true ); mySmoothSurface.run(); } RemeshSurface myRemeshSurface("remesh-surface"); if ( postProcessRemeshSurface ) { myRemeshSurface.setPackageType("vmtk"); if ( postProcessSmoothSurface ) myRemeshSurface.setInputSurfacePath( mySmoothSurface.outputPath() ); else if ( postProcessSubdivideSurface ) myRemeshSurface.setInputSurfacePath( mySubdivideSurface.outputPath() ); else myRemeshSurface.setInputSurfacePath( surfaceFromImage.outputPath() ); myRemeshSurface.setOutputPath( finalOutputPath ); if ( surfaceFromImage.forceRebuild() || ( postProcessSubdivideSurface && mySubdivideSurface.forceRebuild() ) || ( postProcessSmoothSurface && mySmoothSurface.forceRebuild() ) ) myRemeshSurface.setForceRebuild( true ); myRemeshSurface.run(); } return 0; }
36.433628
145
0.721642
vivabrain
e18f5e0fe6b3dcb7b0850e87184b720c43dcbac4
7,405
hpp
C++
simple_demo_chain_version/main_program_logic/MainProgramLogicProvider.hpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
1
2020-05-22T08:47:00.000Z
2020-05-22T08:47:00.000Z
simple_demo_chain_version/main_program_logic/MainProgramLogicProvider.hpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
simple_demo_chain_version/main_program_logic/MainProgramLogicProvider.hpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
#ifndef MAIN_PROGRAM_LOGIC_PROVIDER_HPP_ #define MAIN_PROGRAM_LOGIC_PROVIDER_HPP_ #include "simple_demo_chain_version/main_program_logic/MainProgramStateFolder.hpp" #include "simple_demo_chain_version/main_program_logic/MainProgramFacilityInputHandler.hpp" #include "simple_demo_chain_version/main_program_logic/OperationLogic.hpp" #include "simple_demo_chain_version/main_program_logic/ProgressReporter.hpp" #include "simple_demo_chain_version/main_program_logic/MainProgramChainDataReader.hpp" #include "simple_demo_chain_version/main_program_logic/MainProgramIDAndFinalFlagExtractor.hpp" #include "defs.pb.h" #include <tm_kit/basic/simple_shared_chain/ChainWriter.hpp> #include <tm_kit/basic/CommonFlowUtils.hpp> #include <tm_kit/basic/simple_shared_chain/ChainBackedFacility.hpp> #include <boost/hana/functional/curry.hpp> #include <iostream> #include <sstream> #include <cmath> namespace simple_demo_chain_version { namespace main_program_logic { template <class R, template <class M> class ChainCreator> std::tuple< typename R::template FacilitioidConnector<double, std::optional<ChainData>> , std::string > chainBasedRequestHandler( R &r , ChainCreator<typename R::AppType> &chainCreator , std::string const &chainLocatorStr , std::string const &graphPrefix ) { auto res = basic::simple_shared_chain::createChainBackedFacility< R , ChainData , MainProgramStateFolder , MainProgramFacilityInputHandler<typename R::EnvironmentType> , MainProgramIDAndFinalFlagExtractor<typename R::EnvironmentType> >( r , chainCreator.template writerFactory< ChainData , MainProgramStateFolder , MainProgramFacilityInputHandler<typename R::EnvironmentType> >( r.environment() , chainLocatorStr ) , chainCreator.template readerFactory< ChainData , TrivialChainDataFolder >( r.environment() , chainLocatorStr ) , std::make_shared<MainProgramIDAndFinalFlagExtractor<typename R::EnvironmentType>>() , graphPrefix+"/facility_combo" ); return {res.facility, res.registeredNameForFacilitioidConnector}; } template <class R> void mainProgramLogicMain( R &r , typename R::template FacilitioidConnector< double, std::optional<ChainData> > requestHandler , typename R::template ConvertibleToSourceoid<InputData> &&dataSource , std::optional<typename R::template Source<bool>> const &enabledSource , std::string const &graphPrefix , std::function<void(bool)> const &statusUpdater = [](bool x) {} ) { using M = typename R::AppType; auto *env = r.environment(); auto operationLogicPtr = std::make_shared<OperationLogic>( [env](std::string const &s) { env->log(infra::LogLevel::Info, s); } , statusUpdater ); r.preservePointer(operationLogicPtr); auto extractDouble = infra::KleisliUtils<M> ::template liftPure<InputData>( [](InputData &&d) -> double { return d.value(); } ); auto duplicator = basic::CommonFlowUtilComponents<M> ::template duplicateInput<double>(); auto exponentialAverage = basic::CommonFlowUtilComponents<M> ::template wholeHistoryFold<double>( ExponentialAverage(std::log(0.5)) ); auto exponentialAverageWithInputAttached = basic::CommonFlowUtilComponents<M> ::template preserveLeft<double, double>(std::move(exponentialAverage)); auto filterValue = basic::CommonFlowUtilComponents<M> ::template pureFilter<std::tuple<double, double>>( [](std::tuple<double,double> const &input) -> bool { return std::get<0>(input) >= 1.05*std::get<1>(input); } ); auto assembleOperationLogicInput = basic::CommonFlowUtilComponents<M> ::template dropRight<double,double>(); auto upToOperationLogicInputKleisli = infra::KleisliUtils<M>::compose( std::move(extractDouble) , infra::KleisliUtils<M>::compose( std::move(duplicator) , infra::KleisliUtils<M>::compose( std::move(exponentialAverageWithInputAttached) , infra::KleisliUtils<M>::compose( std::move(filterValue) , std::move(assembleOperationLogicInput) ) ) ) ); auto upToOperationLogicInput = M::template kleisli<InputData>(std::move(upToOperationLogicInputKleisli)); auto logic = M::template liftMaybe<double>( boost::hana::curry<2>(std::mem_fn(&OperationLogic::runLogic))(operationLogicPtr.get()) , infra::LiftParameters<std::chrono::system_clock::time_point>() .DelaySimulator( [](int , std::chrono::system_clock::time_point const &) -> std::chrono::system_clock::duration { return std::chrono::milliseconds(100); } ) ); r.registerAction(graphPrefix+"/preprocess", upToOperationLogicInput); r.registerAction(graphPrefix+"/operation_logic", logic); auto keyify = infra::KleisliUtils<M>::action( basic::CommonFlowUtilComponents<M>::template keyify<double>() ); auto extractIDAndData = infra::KleisliUtils<M>::action( basic::CommonFlowUtilComponents<M>::template extractIDStringAndDataFromKeyedData<double, std::optional<ChainData>>() ); r.convertToSourceoid(std::move(dataSource))(r, r.actionAsSink(upToOperationLogicInput)); requestHandler( r , r.execute(graphPrefix+"/keyify", keyify, r.execute(logic, r.actionAsSource(upToOperationLogicInput)) ) , r.actionAsSink(graphPrefix+"/extractIDAndData", extractIDAndData) ); if (enabledSource) { auto enabledSetter = M::template pureExporter<bool>( [operationLogicPtr](bool &&x) { operationLogicPtr->setEnabled(x); } ); r.registerExporter(graphPrefix+"/setEnabled", enabledSetter); r.exportItem(enabledSetter, enabledSource->clone()); } auto progressReporter = M::template liftMulti< std::tuple<std::string, std::optional<ChainData>> >(&ProgressReporter::reportProgress); r.registerAction(graphPrefix+"/progressReporter", progressReporter); r.execute(progressReporter, r.actionAsSource(extractIDAndData)); auto printExporter = M::template pureExporter<std::string>( [env](std::string &&s) { env->log(infra::LogLevel::Info, s); } ); r.registerExporter(graphPrefix+"/printExporter", printExporter); r.exportItem(printExporter, r.actionAsSource(progressReporter)); } } } #endif
41.368715
128
0.617151
cd606
e1932d34ad2ad1e4ccad1105e9bc7c1ab62661f2
13,036
hpp
C++
plugins/style_charcoal.hpp
Yleroimar/3D-Comic-Rendering
8c3221625dfbb5a4d5efc92b235d547a4e6e66ad
[ "MIT" ]
1
2021-10-05T09:22:39.000Z
2021-10-05T09:22:39.000Z
plugins/style_charcoal.hpp
Yleroimar/3D-Comic-Rendering
8c3221625dfbb5a4d5efc92b235d547a4e6e66ad
[ "MIT" ]
null
null
null
plugins/style_charcoal.hpp
Yleroimar/3D-Comic-Rendering
8c3221625dfbb5a4d5efc92b235d547a4e6e66ad
[ "MIT" ]
null
null
null
#pragma once /////////////////////////////////////////////////////////////////////////////////// // _ _ // ___| |__ __ _ _ __ ___ ___ __ _| | // / __| '_ \ / _` | '__/ __/ _ \ / _` | | // | (__| | | | (_| | | | (_| (_) | (_| | | // \___|_| |_|\__,_|_| \___\___/ \__,_|_| // // \brief Charcoal stylization pipeline // Contains the charcoal stylization pipeline with all necessary targets and operations // // Developed by: Yee Xin Chiew // /////////////////////////////////////////////////////////////////////////////////// #include "mnpr_renderer.h" namespace ch { void addTargets(MRenderTargetList &targetList) { // add style specific targets unsigned int tWidth = targetList[0]->width(); unsigned int tHeight = targetList[0]->height(); int MSAA = targetList[0]->multiSampleCount(); unsigned arraySliceCount = 0; bool isCubeMap = false; MHWRender::MRasterFormat rgba8 = MHWRender::kR8G8B8A8_SNORM; MHWRender::MRasterFormat rgb8 = MHWRender::kR8G8B8X8; targetList.append(MHWRender::MRenderTargetDescription( "offsetTarget", tWidth, tHeight, MSAA, rgba8, arraySliceCount, isCubeMap)); targetList.append(MHWRender::MRenderTargetDescription( "granulateTarget", tWidth, tHeight, MSAA, rgba8, arraySliceCount, isCubeMap)); targetList.append(MHWRender::MRenderTargetDescription( "blendTarget", tWidth, tHeight, MSAA, rgba8, arraySliceCount, isCubeMap)); targetList.append(MHWRender::MRenderTargetDescription( "edgeBlurControl", tWidth, tHeight, 1, rgba8, arraySliceCount, isCubeMap)); targetList.append(MHWRender::MRenderTargetDescription( "edgeBlurTarget", tWidth, tHeight, MSAA, rgba8, arraySliceCount, isCubeMap)); } void addOperations(MHWRender::MRenderOperationList &mOperations, MRenderTargetList &mRenderTargets, EngineSettings &mEngSettings, FXParameters &mFxParams) { MString opName = ""; opName = "[quad] offset Output"; auto opShader = new MOperationShader("ch", "quadOffset", "offsetOutput"); // quadCharcoalOffset opShader->addSamplerState("gSampler", MHWRender::MSamplerState::kTexClamp, MHWRender::MSamplerState::kMinMagMipPoint); opShader->addTargetParameter("gAbstractionControlTex", mRenderTargets.getTarget("abstractCtrlTarget")); // controlTargetAbstraction auto quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "offsetTarget" }); opName = "[quad] offset H"; opShader = new MOperationShader("ch", "quadOffsetBlend", "offsetH"); // quadCharcoalBlend opShader->addSamplerState("gSampler", MHWRender::MSamplerState::kTexClamp, MHWRender::MSamplerState::kMinMagMipPoint); opShader->addTargetParameter("gDepthTex", mRenderTargets.getTarget("linearDepth")); opShader->addTargetParameter("gOffsetTex", mRenderTargets.getTarget("offsetTarget")); opShader->addTargetParameter("gControlTex", mRenderTargets.getTarget("abstractCtrlTarget")); // controlTargetSubstrate quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "offsetTarget" }); opName = "[quad] offset V"; opShader = new MOperationShader("ch", "quadOffsetBlend", "offsetV"); opShader->addSamplerState("gSampler", MHWRender::MSamplerState::kTexClamp, MHWRender::MSamplerState::kMinMagMipPoint); opShader->addTargetParameter("gDepthTex", mRenderTargets.getTarget("linearDepth")); opShader->addTargetParameter("gOffsetTex", mRenderTargets.getTarget("offsetTarget")); opShader->addTargetParameter("gControlTex", mRenderTargets.getTarget("abstractCtrlTarget")); // controlTargetSubstrate ??? quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "offsetTarget" }); opName = "[quad] blur H"; opShader = new MOperationShader("ch", "quadBlur", "blurH"); // quadCharcoalBlur opShader->addSamplerState("gSampler", MHWRender::MSamplerState::kTexClamp, MHWRender::MSamplerState::kMinMagMipPoint); opShader->addTargetParameter("gStylizationTex", mRenderTargets.getTarget("stylizationTarget")); opShader->addTargetParameter("gControlTex", mRenderTargets.getTarget("pigmentCtrlTarget")); opShader->addTargetParameter("gOffsetTex", mRenderTargets.getTarget("offsetTarget")); quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "blendTarget" }); opName = "[quad] blur V"; opShader = new MOperationShader("ch", "quadBlur", "blurV"); opShader->addSamplerState("gSampler", MHWRender::MSamplerState::kTexClamp, MHWRender::MSamplerState::kMinMagMipPoint); opShader->addTargetParameter("gStylizationTex", mRenderTargets.getTarget("blendTarget")); opShader->addTargetParameter("gControlTex", mRenderTargets.getTarget("pigmentCtrlTarget")); opShader->addTargetParameter("gOffsetTex", mRenderTargets.getTarget("offsetTarget")); quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "blendTarget" }); opName = "[quad] mixing"; opShader = new MOperationShader("ch", "quadOffset", "mixing"); opShader->addSamplerState("gSampler", MHWRender::MSamplerState::kTexClamp, MHWRender::MSamplerState::kMinMagMipPoint); opShader->addTargetParameter("gStylizationTex", mRenderTargets.getTarget("stylizationTarget")); opShader->addTargetParameter("gBlendTex", mRenderTargets.getTarget("blendTarget")); opShader->addTargetParameter("gAbstractionControlTex", mRenderTargets.getTarget("abstractCtrlTarget")); // controlTargetSubstrate opShader->addTargetParameter("gOffsetTex", mRenderTargets.getTarget("offsetTarget")); quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "stylizationTarget" }); opName = "[quad] edge blur H"; opShader = new MOperationShader("ch", "quadEdgeBlur", "edgeBlurH"); opShader->addSamplerState("gSampler", MHWRender::MSamplerState::kTexClamp, MHWRender::MSamplerState::kMinMagMipPoint); opShader->addTargetParameter("gStylizationTex", mRenderTargets.getTarget("stylizationTarget")); opShader->addTargetParameter("gEdgeBlurTex", mRenderTargets.getTarget("edgeTarget")); opShader->addTargetParameter("gOffsetTex", mRenderTargets.getTarget("offsetTarget")); opShader->addTargetParameter("gControlTex", mRenderTargets.getTarget("edgeCtrlTarget")); // controlTargetEdges quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "edgeBlurTarget", "edgeBlurControl" }); opName = "[quad] edge blur V"; opShader = new MOperationShader("ch", "quadEdgeBlur", "edgeBlurV"); ////opShader = new MOperationShader("quadBlur", "dynamicBlurV"); opShader->addSamplerState("gSampler", MHWRender::MSamplerState::kTexClamp, MHWRender::MSamplerState::kMinMagMipPoint); opShader->addTargetParameter("gStylizationTex", mRenderTargets.getTarget("edgeBlurTarget")); // use the one with horizontal blur opShader->addTargetParameter("gEdgeBlurTex", mRenderTargets.getTarget("edgeBlurControl")); opShader->addTargetParameter("gOffsetTex", mRenderTargets.getTarget("offsetTarget")); opShader->addTargetParameter("gControlTex", mRenderTargets.getTarget("edgeCtrlTarget")); // controlTargetEdges quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "edgeBlurTarget", "edgeBlurControl" }); opName = "[quad] edge filter"; opShader = new MOperationShader("ch", "quadEdgeManipulation", "edgeFilter"); // quadCharcoalEdge opShader->addTargetParameter("gEdgeSoftenTex", mRenderTargets.getTarget("edgeBlurTarget")); opShader->addTargetParameter("gStylizationTex", mRenderTargets.getTarget("stylizationTarget")); opShader->addTargetParameter("gEdgeBlurControlTex", mRenderTargets.getTarget("edgeBlurControl")); quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "stylizationTarget" }); // charcoal opName = "[quad] dry brush op"; opShader = new MOperationShader("ch", "quadCharcoal", "dryMedia"); opShader->addTargetParameter("gLightingTex", mRenderTargets.getTarget("diffuseTarget")); opShader->addTargetParameter("gStylizationTex", mRenderTargets.getTarget("stylizationTarget")); opShader->addTargetParameter("gSubstrateTex", mRenderTargets.getTarget("substrateTarget")); opShader->addTargetParameter("gCtrlPigmentTex", mRenderTargets.getTarget("pigmentCtrlTarget")); opShader->addParameter("gSubstrateRoughness", mEngSettings.substrateRoughness); opShader->addParameter("gDryMediaThreshold", mFxParams.dryMediaThreshold); opShader->addParameter("gSubstrateColor", mEngSettings.substrateColor); quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "stylizationTarget" }); opName = "[quad] smudging"; opShader = new MOperationShader("ch", "quadSmudging", "smudging"); opShader->addTargetParameter("gStylizationTex", mRenderTargets.getTarget("stylizationTarget")); opShader->addTargetParameter("gBlendTex", mRenderTargets.getTarget("blendTarget")); opShader->addTargetParameter("gEdgeBlurTex", mRenderTargets.getTarget("edgeBlurTarget")); opShader->addTargetParameter("gControlTex", mRenderTargets.getTarget("abstractCtrlTarget")); // smudging control opShader->addTargetParameter("gOffsetTex", mRenderTargets.getTarget("offsetTarget")); quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "stylizationTarget" }); opName = "[quad] pigment density"; opShader = new MOperationShader("quadPigmentManipulation", "pigmentDensityCC"); opShader->addTargetParameter("gColorTex", mRenderTargets.getTarget("stylizationTarget")); opShader->addTargetParameter("gControlTex", mRenderTargets.getTarget("pigmentCtrlTarget")); quadOp = new QuadRender(opName, MHWRender::MClearOperation::kClearNone, mRenderTargets, *opShader); mOperations.append(quadOp); mRenderTargets.setOperationOutputs(opName, { "stylizationTarget" }); } };
59.798165
130
0.629641
Yleroimar
e1975f4f02ab0837e2de074a022fcfd8f2c46930
477
cc
C++
BOJ/2606.cc
Yaminyam/Algorithm
fe49b37b4b310f03273864bcd193fe88139f1c01
[ "MIT" ]
1
2019-05-18T00:02:12.000Z
2019-05-18T00:02:12.000Z
BOJ/2606.cc
siontama/Algorithm
bb419e0d4dd09682bd4542f90038b492ee232bd2
[ "MIT" ]
null
null
null
BOJ/2606.cc
siontama/Algorithm
bb419e0d4dd09682bd4542f90038b492ee232bd2
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> using namespace std; vector<int> node[101]; bool check[101]; int cnt = 0; void dfs(int idx) { check[idx] = true; cnt++; for (int i = 0; i < node[idx].size(); i++) { if (!check[node[idx][i]]) { dfs(node[idx][i]); } } } int main() { int n; cin >> n; int k; cin >> k; for (int i = 0; i < k; i++) { int a, b; cin >> a >> b; node[a].push_back(b); node[b].push_back(a); } dfs(1); cout << cnt-1; }
13.628571
45
0.538784
Yaminyam
e19b77cb4f23486d5a964a10ed1a77c029d423fe
3,673
cpp
C++
src/main/cpp/widgets/Text.cpp
Dalphat/blame
567a75c1d0d0306e8b28b750556de77646d9d0f9
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/widgets/Text.cpp
Dalphat/blame
567a75c1d0d0306e8b28b750556de77646d9d0f9
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/widgets/Text.cpp
Dalphat/blame
567a75c1d0d0306e8b28b750556de77646d9d0f9
[ "BSD-3-Clause" ]
null
null
null
#include <styles/StyleText.hpp> #include "Text.hpp" // TODO: Add support for multiple text caret's // TODO: Add support for selecting text Blame::Widgets::Text::Text(Blame::Console *console, Blame::Widgets::Widget *parent) : Widget(console, parent) { this->height = 6; this->width = 12; this->symbol_caret = "_"; this->colour_caret = Blame::Util::EscapeCodes::foregroundMagenta(); this->style = Blame::Styles::StyleText(); this->caret_x = 0; this->caret_y = 0; this->content.emplace_back(""); } void Blame::Widgets::Text::redraw() { Widget::redraw(); this->console->moveCaret(this->widget_stream, this->client_area.left, this->client_area.top); this->widget_stream << this->getCurrentColour(this->style.colours.background_content); this->widget_stream << this->getCurrentColour(this->style.colours.text); int iteration = 0; for (const auto &i : this->content) { this->console->moveCaret(this->widget_stream, this->client_area.left, this->client_area.top + iteration); this->widget_stream << i; iteration++; } if (this->state != Blame::Util::State::DISABLED) { this->console->moveCaret(this->widget_stream, this->client_area.left + this->caret_x, this->client_area.top + this->caret_y); this->widget_stream << this->colour_caret; this->widget_stream << this->symbol_caret; } this->widget_stream << Blame::Util::EscapeCodes::reset(); *this->console->buffer_list[!this->console->current_buffer] << this->widget_stream.str(); this->widget_stream.str(std::string()); this->is_redrawn.exchange(true); } void Blame::Widgets::Text::move(Blame::Util::Direction direction) { if (this != this->console->focused_widget || this->state == Blame::Util::State::DISABLED) return; switch (direction) { case Blame::Util::Direction::UP: if (this->caret_y - 1 > -1) { this->caret_x = 0; this->caret_y--; } break; case Blame::Util::Direction::DOWN: if (this->caret_y + 1 < this->height - 2) { this->caret_y++; } break; case Blame::Util::Direction::LEFT: if (this->caret_x - 1 > -1) { this->caret_x--; } break; case Blame::Util::Direction::RIGHT: if (this->caret_x + 1 < this->width) { this->caret_x++; } break; } Widget::move(direction); } void Blame::Widgets::Text::text(std::string text) { if (this->state == Blame::Util::State::DISABLED) return; switch (text.c_str()[0]) { // Enter case '\n': this->caret_x = 0; this->caret_y++; if (this->caret_y >= this->content.size()) { this->content.emplace_back(""); } break; // Space case ' ': this->content[this->caret_y].insert((unsigned long)this->caret_x, " "); this->caret_x++; break; // Backspace case 127: // FIXME: Doesn't work with multiline text if (this->caret_x - 1 > -1) { this->caret_x--; } this->content[this->caret_y].erase((unsigned long)this->caret_x, 1); break; // Everything else default: // this->console->setTitle(std::to_string(text.c_str()[0])); this->content[this->caret_y].insert((unsigned long)this->caret_x, text); this->caret_x++; break; } Widget::text(text); }
29.861789
133
0.556493
Dalphat
e19ba8d4cb3a227241847bc55880e07d6e30f1bc
607
cpp
C++
vcp.cpp
mimaki/momo-mruby
8b17212cc375a8c83d2516c01daa88e1d08e4a59
[ "MIT" ]
3
2017-10-11T13:11:47.000Z
2018-12-29T01:56:10.000Z
vcp.cpp
mimaki/momo-mruby
8b17212cc375a8c83d2516c01daa88e1d08e4a59
[ "MIT" ]
null
null
null
vcp.cpp
mimaki/momo-mruby
8b17212cc375a8c83d2516c01daa88e1d08e4a59
[ "MIT" ]
null
null
null
#include "mbed.h" #include "BufferedSerial.h" #include <stdio.h> #include <stdarg.h> #include "mbedapi.h" static BufferedSerial vcp(USBTX, USBRX, 1024); MBEDAPI int mbedPrintf(const char *format, ...) { va_list args; int len; static char buf[1024]; va_start(args, format); len = vsnprintf(buf, sizeof(buf), format, args); va_end(args); vcp.write(buf, len); return len; } MBEDAPI void mbedPutc(char c) { vcp.putc(c); } MBEDAPI int mbedGetc(void) { while (!vcp.readable()) { wait_us(1); } return vcp.getc(); } MBEDAPI void mbedSetVCPBaudrate(int rate) { vcp.baud(rate); }
13.795455
50
0.667216
mimaki
e1a45977d9820a01082d3f3f3bf2eb3d529043cc
2,192
hpp
C++
include/elp_camera.hpp
matheusns/ros_elp_stereo_camera
ff54f3a0e66247ce4830fb7b9439f598372ca4b7
[ "BSD-3-Clause" ]
null
null
null
include/elp_camera.hpp
matheusns/ros_elp_stereo_camera
ff54f3a0e66247ce4830fb7b9439f598372ca4b7
[ "BSD-3-Clause" ]
null
null
null
include/elp_camera.hpp
matheusns/ros_elp_stereo_camera
ff54f3a0e66247ce4830fb7b9439f598372ca4b7
[ "BSD-3-Clause" ]
null
null
null
#ifndef ELIR_STEREO_CAMERA_ELP_CAMERA_HPP #define ELIR_STEREO_CAMERA_ELP_CAMERA_HPP #include <thread> #include <exception> #include "opencv2/core/core.hpp" #include "opencv2/core/version.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/opencv.hpp" #include <ros/ros.h> namespace elp { class ElpCameraException: public std::exception { public: explicit ElpCameraException(const char* msg) :msg_(msg) {} virtual ~ElpCameraException(){} virtual const char* what() const throw() { return msg_.c_str(); } protected: std::string msg_; }; class ElpCamera { public: /** * brief Default Constructor for ElpCamera. * * Default Constructor for ElpCamera. * * @return nothing * */ explicit ElpCamera(); /** * brief Default Constructor for ElpCamera. * * Default Constructor for ElpCamera. * * @return nothing * */ typedef std::function<void(const cv::Mat&)> GrabCallback; virtual ~ElpCamera(); /** * brief Configures the camera callback method. * * This method configures the camera callback method that will receive the images from streaming. * * @param callback Function pointer to the desired callback. * @return void. * */ void setupCallback(const GrabCallback frame_callback); /** * brief Starts the camera streaming. * * This method starts the camera streaming. * * @return void. * */ void startStreaming(); /** * brief Stops the camera streaming. * * This method stops the camera streaming. * * @return void. * */ void stopStreaming(); protected: /** * brief Stops the camera streaming. * * This method stops the camera streaming. * * @return void. * */ void imageAcquisition(); int image_width_; int image_height_; bool is_streaming_; std::thread *img_aqt_th_; GrabCallback callback_; ros::NodeHandle nh_; }; } // elp namespace #endif //ELIR_STEREO_CAMERA_ELP_CAMERA_HPP
21.076923
101
0.609033
matheusns
e1a55b5b7e1696b959e375faa3d16aa29556ecce
5,717
cpp
C++
ScriptHookDotNet/Main.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
3
2021-11-14T20:59:58.000Z
2021-12-16T16:41:31.000Z
ScriptHookDotNet/Main.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
2
2021-11-29T14:41:23.000Z
2021-11-30T13:13:51.000Z
ScriptHookDotNet/Main.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
3
2021-11-21T12:41:55.000Z
2021-12-22T16:17:52.000Z
/* * Copyright (c) 2009-2011 Hazard (hazard_x@gmx.net / twitter.com/HazardX) * * 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 "stdafx.h" //#include "NetHook.h" int hModule; bool _stdcall isPrimary() { if (System::AppDomain::CurrentDomain->FriendlyName == "SHDN_ScriptDomain") return false; System::String^ ExecPath = System::Reflection::Assembly::GetExecutingAssembly()->Location; System::String^ TempPath = System::Environment::ExpandEnvironmentVariables("%TEMP%") + "\\shdn_"; if (ExecPath->StartsWith(TempPath,System::StringComparison::InvariantCultureIgnoreCase)) return false; return true; } unsigned int _stdcall ManagedEntryPoint(void*) { bool bPrimary = isPrimary(); //true; //if (System::AppDomain::CurrentDomain->FriendlyName == "SHDN_ScriptDomain") bPrimary = false; // //System::String^ ExecPath = System::Reflection::Assembly::GetExecutingAssembly()->Location; //System::String^ TempPath = System::Environment::ExpandEnvironmentVariables("%TEMP%") + "\\shdn_"; //if (ExecPath->StartsWith(TempPath,System::StringComparison::InvariantCultureIgnoreCase)) bPrimary = false; //SetDllDirectoryA("D:\\Spiele\\Vollversionen\\GTA4mod1040\\plugins"); if (!bPrimary) return 0; GTA::NetHook::Initialize(bPrimary, hModule); return 0; } unsigned int _stdcall ManagedEndPoint(void*) { //GTA::NetHook::GameEnded(); return 0; } //[System::STAThreadAttribute] //int main(array<System::String ^> ^args) { // //// Enabling Windows XP visual effects before any controls are created // //Application::EnableVisualStyles(); // //Application::SetCompatibleTextRenderingDefault(false); // // // Create the main window and run it // //Application::Run(gcnew Form1()); // // bool bPrimary = isPrimary(); // if (bPrimary) return 0; // GTA::NetHook::Initialize(bPrimary); // // return 0; //} #pragma unmanaged //#ifdef DEBUG //extern "C" { //HACK: allow the use of mixed debug/non-debug code // void __cdecl _invalid_parameter_noinfo(void) { } //} //#endif BOOL WINAPI DllMain( HINSTANCE dllInstHandle, DWORD reason, LPVOID reserved ) { switch (reason) { case DLL_PROCESS_ATTACH: { hModule = (int)dllInstHandle; (void)DisableThreadLibraryCalls(dllInstHandle); // fix for random mscorwks.dll crashes // Launch a thread to get a managed entry point unsigned int threadId = 0; HANDLE threadHandle; threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ManagedEntryPoint, 0, 0, (LPDWORD)&threadId); if (threadHandle == 0 || threadHandle == INVALID_HANDLE_VALUE) return FALSE; CloseHandle(threadHandle); return TRUE; } case DLL_PROCESS_DETACH: { // Shutdown the script hook manager //ScriptHookManager::Shutdown(); unsigned int threadId = 0; HANDLE threadHandle; threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ManagedEndPoint, 0, 0, (LPDWORD)&threadId); if (threadHandle == 0 || threadHandle == INVALID_HANDLE_VALUE) return FALSE; CloseHandle(threadHandle); return TRUE; } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: return FALSE; // fix for random mscorwks.dll crashes - return false on thread calls } return TRUE; } #pragma managed /* // ##### FIRST WAY TO TRIGGER MANAGED CODE FROM UNMANAGED DLLMAIN ##### int _stdcall ManagedEntryPoint(ptr) { System::Windows::Forms::MessageBox::Show("IT WORKS!\n"); return 0; } #pragma unmanaged BOOL APIENTRY DllMain( HANDLE hModule, DWORD fdwReason, LPVOID lpReserved) { // Launch a new thread which then allows managed code u32 threadId = 0; HANDLE threadHandle; threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ManagedEntryPoint, 0, 0, (LPDWORD)&threadId); if (threadHandle == 0 || threadHandle == INVALID_HANDLE_VALUE) return FALSE; CloseHandle(threadHandle); } // ##### SECOND WAY TO TRIGGER MANAGED CODE FROM UNMANAGED DLLMAIN ##### struct __declspec(dllexport) dllLoaderManagedStruct { dllLoaderManagedStruct() { System::Windows::Forms::MessageBox::Show("Module ctor initializing based on global instance of class.\n"); } void TriggerConstructor() { int i = 1; } }; static dllLoaderManagedStruct dllLoaderManaged; #pragma unmanaged struct __declspec(dllexport) dllLoaderUnmanagedStruct { dllLoaderUnmanagedStruct() { dllLoaderManaged.TriggerConstructor(); } void TriggerConstructor() { int i = 1; } }; static dllLoaderUnmanagedStruct dllLoaderUnmanaged; BOOL APIENTRY DllMain( HANDLE hModule, DWORD fdwReason, LPVOID lpReserved) { // Trigger Constructor of a static unmanaged struct, // which triggers the constructor of a static managed struct, // which can then execute managed code dllLoaderUnmanaged.TriggerConstructor(); } */
30.736559
110
0.737275
HazardX
e1a89e7030568d81b79ecf4459748f061537629c
920
cpp
C++
ftp_client/Buffer.cpp
wxk6b1203/ftp_exercise
a17ea519d1725b2c3f6b5454fda889604593138f
[ "MIT" ]
null
null
null
ftp_client/Buffer.cpp
wxk6b1203/ftp_exercise
a17ea519d1725b2c3f6b5454fda889604593138f
[ "MIT" ]
null
null
null
ftp_client/Buffer.cpp
wxk6b1203/ftp_exercise
a17ea519d1725b2c3f6b5454fda889604593138f
[ "MIT" ]
null
null
null
#include "Buffer.h" using std::move; local::Buffer::Buffer(size_t s) : len(s), buf(new char[s]) { memset(buf.get(), 0, sizeof(char) * len); } string local::Buffer::ReadString() { string a = buf.get(); return a; } unique_ptr<char> local::Buffer::Read() { unique_ptr<char> uchstring(new char[len]); memcpy(uchstring.get(), buf.get(), len); return move(uchstring); } void local::Buffer::Flush() { memset(buf.get(), 0, sizeof(char) * len); } int local::Buffer::Write(char* s, int length) { memset(buf.get(), 0, sizeof(char) * len); int stt = 0; if (length < len) /** * status code: * > 0 : bytes copied; * = 0 : all in; * < 0 : error; */ { stt = length; } int min = length > len ? len : length; memset(buf.get(), 0, sizeof(char) * len); memcpy(buf.get(), s, sizeof(char) * len); return stt; } local::Buffer::~Buffer() {}
22.439024
73
0.558696
wxk6b1203
e1ac09692a53c78ca0aeabf67662b63f17db200b
1,874
cpp
C++
TESTS/assumptions/DigitalIO/DigitalIO.cpp
vmedcy/ci-test-shield
befdcc2a4ea758122a0d4326c8893b062e79bab9
[ "Apache-2.0" ]
11
2016-10-25T13:33:43.000Z
2020-11-14T17:51:01.000Z
TESTS/assumptions/DigitalIO/DigitalIO.cpp
vmedcy/ci-test-shield
befdcc2a4ea758122a0d4326c8893b062e79bab9
[ "Apache-2.0" ]
79
2016-10-07T03:10:21.000Z
2021-06-03T08:10:57.000Z
TESTS/assumptions/DigitalIO/DigitalIO.cpp
vmedcy/ci-test-shield
befdcc2a4ea758122a0d4326c8893b062e79bab9
[ "Apache-2.0" ]
40
2016-10-17T13:19:42.000Z
2021-09-22T14:42:42.000Z
#include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" using namespace utest::v1; template <PinName d_pin> void test_DigitalIO_NC() { TEST_ASSERT_MESSAGE(d_pin != NC, "Pin is NC"); } utest::v1::status_t test_setup(const size_t number_of_cases) { // Setup Greentea using a reasonable timeout in seconds GREENTEA_SETUP(5, "default_auto"); return verbose_test_setup_handler(number_of_cases); } utest::v1::status_t greentea_failure_handler(const Case* const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } Case cases[] = { Case("DigitalIO - is pin 0 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_0>, greentea_failure_handler), Case("DigitalIO - is pin 1 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_1>, greentea_failure_handler), Case("DigitalIO - is pin 2 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_2>, greentea_failure_handler), Case("DigitalIO - is pin 3 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_3>, greentea_failure_handler), Case("DigitalIO - is pin 4 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_4>, greentea_failure_handler), Case("DigitalIO - is pin 5 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_5>, greentea_failure_handler), Case("DigitalIO - is pin 6 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_6>, greentea_failure_handler), Case("DigitalIO - is pin 7 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_7>, greentea_failure_handler), Case("DigitalIO - is pin 8 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_8>, greentea_failure_handler), Case("DigitalIO - is pin 9 connected?", test_DigitalIO_NC<MBED_CONF_APP_DIO_9>, greentea_failure_handler), }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); }
39.87234
110
0.771612
vmedcy
e1af42740cad31f5a331e06dd55c82a3633669b4
18,711
cpp
C++
GPUPerfStudio/Server/Common/NamedEvent.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
1
2017-03-25T02:09:15.000Z
2017-03-25T02:09:15.000Z
GPUPerfStudio/Server/Common/NamedEvent.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
null
null
null
GPUPerfStudio/Server/Common/NamedEvent.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
3
2017-03-15T03:35:13.000Z
2022-02-23T06:29:02.000Z
//============================================================================== // Copyright (c) 2013-2015 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief a named event class. The event is /// global systemwide, so can be accessed across threads and processes /// by its name. Each process will need its own copy of the event //============================================================================== #include <AMDTOSWrappers/Include/osProcess.h> #include <AMDTOSWrappers/Include/osThread.h> #if defined (_WIN32) #include <Windows.h> #elif defined (_LINUX) #include <boost/interprocess/sync/named_recursive_mutex.hpp> #include <boost/interprocess/sync/named_condition.hpp> #include <boost/thread/locks.hpp> #include "WinDefs.h" using namespace boost::interprocess; #endif #include "NamedEvent.h" #include "SharedMemory.h" #include "defines.h" #include "misc.h" /// Base Implementation abstract data type class NamedEventImpl { public: NamedEventImpl() {}; virtual ~NamedEventImpl() {}; virtual bool Create(const char* eventName, bool signaled) = 0; virtual bool Open(const char* eventname, bool inherit) = 0; virtual bool Wait() = 0; virtual bool Signal() = 0; virtual bool IsSignaled() = 0; virtual void Reset() = 0; virtual void Close() { } private: /// copy constructor made private; Cannon make copies of this object NamedEventImpl(const NamedEventImpl& rhs) { PS_UNREFERENCED_PARAMETER(rhs); } /// assignment operator made private; Cannon make copies of this object NamedEventImpl& operator= (const NamedEventImpl& rhs) { PS_UNREFERENCED_PARAMETER(rhs); return *this; } }; /// Windows-specific implementation #if defined (_WIN32) class NamedEventWindows : public NamedEventImpl { public: /// default constructor NamedEventWindows() : m_hEvent(NULL) { } /// destructor ~NamedEventWindows() { Close(); } //-------------------------------------------------------------------------- /// Create a system-wide event /// \param eventName the name this event will be known by /// \param signaled if true, the event will be created in the signaled state /// /// \return true if Create succeeded, false if error //-------------------------------------------------------------------------- virtual bool Create(const char* eventName, bool signaled) { m_hEvent = CreateEvent(NULL, TRUE, signaled, eventName); if (m_hEvent == NULL) { return false; } #ifdef DEBUG_PRINT printf("** Creating event %s (%d)\n", eventName, m_hEvent); #endif return true; } //-------------------------------------------------------------------------- /// Open a previously created system-wide event /// \param eventName the name this event is be known by (the name it was /// given when created) /// \param inherit if true, processes created by this process will inherit /// the event handle /// /// \return true if Open succeeded, false if event doesn't exist //-------------------------------------------------------------------------- virtual bool Open(const char* eventName, bool inherit) { m_hEvent = OpenEvent(EVENT_MODIFY_STATE | SYNCHRONIZE, inherit, eventName); if (m_hEvent == NULL) { return false; } #ifdef DEBUG_PRINT printf("** Opening event %s (%d)\n", eventName, m_hEvent); #endif return true; } //-------------------------------------------------------------------------- /// Wait for a signal/event to happen. This function won't return until it /// receives a signal /// /// \return true if successful, false if error //-------------------------------------------------------------------------- virtual bool Wait() { #ifdef DEBUG_PRINT printf("** Waiting ... (%d)\n", m_hEvent); #endif if (WAIT_OBJECT_0 != WaitForSingleObject(m_hEvent, INFINITE)) { return false; } #ifdef DEBUG_PRINT printf("** Wait done (%d)\n", m_hEvent); #endif return true; } //-------------------------------------------------------------------------- /// Set the event to the signaled state. Any other threads/processes waiting /// for the signal can now proceed. /// /// \return true if successful, false if error //-------------------------------------------------------------------------- virtual bool Signal() { #ifdef DEBUG_PRINT printf("** Signal (%d)\n", m_hEvent); #endif if (SetEvent(m_hEvent) == FALSE) { return false; } return true; } //-------------------------------------------------------------------------- /// Is the event in the Signaled state. Does not block or wait but returns /// immediately /// /// \return true if currently signaled, false if not //-------------------------------------------------------------------------- virtual bool IsSignaled() { DWORD dwObject = WaitForSingleObject(m_hEvent, 0); if (WAIT_OBJECT_0 == dwObject) { return true; } if (dwObject == WAIT_FAILED) { Log(logERROR, "Failed to wait on an event (Error %d).\n", GetLastError()); } return false; } //-------------------------------------------------------------------------- /// reset the event to non-signaled //-------------------------------------------------------------------------- virtual void Reset() { #ifdef DEBUG_PRINT printf("** Reset (%d)\n", m_hEvent); #endif ResetEvent(m_hEvent); } //-------------------------------------------------------------------------- /// close the event //-------------------------------------------------------------------------- virtual void Close() { #ifdef DEBUG_PRINT printf("** Close (%d)\n", m_hEvent); #endif if (m_hEvent != NULL) { CloseHandle(m_hEvent); m_hEvent = NULL; } } private: void* m_hEvent; ///< Windows pointer to event handle }; #endif // _WIN32 #if defined (_LINUX) // Boost implementation. Uses a condition variable and a mutex // The condition variable is used by the OS to detect signals // the signal state, which is used by this implementation is in // shared memory, so can be accessed by all threads and processes static const int BUFFER_SIZE = 16; ///< size of shared memory buffer, in bytes // Because of the way that boost implements condition variables and mutexes // (with shared memory), 32 and 64-bit versions need to be unique, since the // shared memory consists of a data structure whose size is dependent on // the bitsize. #if defined X64 static const char* EXT = "_x64"; #else static const char* EXT = "_x86"; #endif class NamedEventBoost : public NamedEventImpl { public: /// default constructor NamedEventBoost() : m_mutex(NULL) , m_condition(NULL) , m_owner(false) { m_signalState = new SharedMemory(); } /// destructor ~NamedEventBoost() { m_signalState->Close(); delete m_condition; delete m_mutex; delete m_signalState; } //-------------------------------------------------------------------------- /// Create a system-wide event /// \param eventName the name this event will be known by /// \param signaled if true, the event will be created in the signaled state /// /// \return true if Create succeeded, false if error //-------------------------------------------------------------------------- virtual bool Create(const char* eventName, bool signaled) { #ifdef DEBUG_PRINT printf("NamedEvent: Create\n"); #endif char strTemp[PS_MAX_PATH]; sprintf_s(m_mutexName, PS_MAX_PATH, "%s_mutex%s", eventName, EXT); if (m_mutex == NULL) { try { m_mutex = new named_mutex(open_only, m_mutexName); } catch (interprocess_exception&) { m_mutex = new named_mutex(open_or_create, m_mutexName); m_owner = true; } } sprintf_s(m_conditionName, PS_MAX_PATH, "%s_condition%s", eventName, EXT); if (m_condition == NULL) { m_condition = new named_condition(open_or_create, m_conditionName); } sprintf_s(strTemp, PS_MAX_PATH, "%s_memory", eventName); SharedMemory::MemStatus status = m_signalState->OpenOrCreate(BUFFER_SIZE, strTemp); if (SharedMemory::SUCCESS != status && SharedMemory::SUCCESS_ALREADY_CREATED != status) { return false; } if (signaled) { Signal(); } else { Reset(); } #ifdef DEBUG_PRINT printf("NamedEvent: Create done\n"); #endif return true; } //-------------------------------------------------------------------------- /// Open a previously created system-wide event /// \param eventName the name this event is be known by (the name it was /// given when created) /// \param inherit if true, processes created by this process will inherit /// the event (currently unused) /// /// \return true if Open succeeded, false if event doesn't exist //-------------------------------------------------------------------------- virtual bool Open(const char* eventName, bool inherit) { PS_UNREFERENCED_PARAMETER(inherit); #ifdef DEBUG_PRINT printf("NamedEvent: Open\n"); #endif char strTemp[PS_MAX_PATH]; sprintf_s(strTemp, PS_MAX_PATH, "%s_mutex%s", eventName, EXT); if (m_mutex == NULL) { try { #ifdef DEBUG_PRINT printf("*** try to open_only mutex\n"); #endif m_mutex = new named_mutex(open_only, strTemp); } catch (interprocess_exception&) { #ifdef DEBUG_PRINT printf("*** mutex open_only exception caught\n"); #endif return false; } } sprintf_s(strTemp, PS_MAX_PATH, "%s_condition%s", eventName, EXT); if (m_condition == NULL) { try { #ifdef DEBUG_PRINT printf("*** try to open_only condition variable %s\n", strTemp); #endif m_condition = new named_condition(open_only, strTemp); } catch (interprocess_exception&) { #ifdef DEBUG_PRINT printf("*** condition var open_only exception caught\n"); #endif return false; } } sprintf_s(strTemp, PS_MAX_PATH, "%s_memory", eventName); if (SharedMemory::SUCCESS != m_signalState->Open(strTemp)) { return false; } return true; } //-------------------------------------------------------------------------- /// Wait for a signal/event to happen. This function won't return until it /// receives a signal /// /// \return true if successful, false if error //-------------------------------------------------------------------------- virtual bool Wait() { #ifdef DEBUG_PRINT printf("NamedEvent: Wait\n"); #endif boost::interprocess::scoped_lock<named_mutex> lock(*m_mutex); bool* state = (bool*)m_signalState->Get(); while (! *state) { #ifdef DEBUG_PRINT printf("NamedEvent: waiting\n"); #endif m_condition->wait(lock); state = (bool*)m_signalState->Get(); } #ifdef DEBUG_PRINT printf("NamedEvent: Wait done\n"); #endif return true; } //-------------------------------------------------------------------------- /// Set the event to the signaled state. Any other threads/processes waiting /// for the signal can now proceed. /// /// \return true if successful, false if error //-------------------------------------------------------------------------- virtual bool Signal() { #ifdef DEBUG_PRINT printf("NamedEvent: Signal\n"); #endif boost::interprocess::scoped_lock<named_mutex> lock(*m_mutex); bool* state = (bool*)m_signalState->Get(); *state = true; m_condition->notify_all(); return true; } //-------------------------------------------------------------------------- /// Is the event in the Signaled state. Does not block or wait but returns /// immediately /// /// \return true if currently signaled, false if not //-------------------------------------------------------------------------- virtual bool IsSignaled() { #ifdef DEBUG_PRINT printf("NamedEvent: IsSignaled\n"); #endif boost::interprocess::scoped_lock<named_mutex> lock(*m_mutex); bool* state = (bool*)m_signalState->Get(); return *state; } //-------------------------------------------------------------------------- /// reset the event to non-signaled //-------------------------------------------------------------------------- virtual void Reset() { #ifdef DEBUG_PRINT printf("NamedEvent: Reset\n"); #endif boost::interprocess::scoped_lock<named_mutex> lock(*m_mutex); bool* state = (bool*)m_signalState->Get(); *state = false; } //-------------------------------------------------------------------------- /// close the event //-------------------------------------------------------------------------- virtual void Close() { if (m_owner) { boost::interprocess::named_mutex::remove(m_mutexName); boost::interprocess::named_condition::remove(m_conditionName); } m_signalState->Close(); } private: named_mutex* m_mutex; ///< The mutex object used to protect the condition variable named_condition* m_condition; ///< The condition variable used by the OS to detect signals SharedMemory* m_signalState; ///< The state of the signal. Used by this implementation to set or reset the signal state. bool m_owner; ///< Did this object create the event char m_mutexName[PS_MAX_PATH]; char m_conditionName[PS_MAX_PATH]; }; // POSIX implementation // Documentation would suggest using a semaphore // Win32 function Linux threads Linux processes // CreateMutex -> pthreads_mutex_init semget / semctl // OpenMutex -> n/a semget // WaitForSingleObject -> pThreads_mutex_lock/..tex_trylock semop // ReleaseMutex -> pthreads_mutex_unlock semop // CloseHandle -> pthreads_mutex_destroy senctl // There's also boost::named_condition // Poco.NamedEvent (though these are auto-resetting) /* class NamedEventLinux : public NamedEventImpl { public: NamedEventLinux() { } ~NamedEventLinux() { } bool Create(const char* eventName) { eventName; return true; } bool Open(const char* eventName) { eventName; return true; } bool Wait() { return true; } bool Signal() { return true; } void Reset() { } }; */ #endif // _LINUX /// Main Implementation methods. /// default constructor /// Pick an implementation based on platform NamedEvent::NamedEvent() { #if defined (_WIN32) m_pImpl = new NamedEventWindows(); #else m_pImpl = new NamedEventBoost(); #endif } /// destructor NamedEvent::~NamedEvent() { delete m_pImpl; } //-------------------------------------------------------------------------- /// Create a system-wide event /// \param eventName the name this event will be known by /// \param signaled if true, the event will be created in the signaled state /// /// \return true if Create succeeded, false if error //-------------------------------------------------------------------------- bool NamedEvent::Create(const char* eventName, bool signaled) { return m_pImpl->Create(eventName, signaled); } //-------------------------------------------------------------------------- /// Open a previously created system-wide event /// \param eventName the name this event is be known by (the name it was /// given when created) /// \param inherit if true, processes created by this process will inherit /// the event /// /// \return true if Open succeeded, false if event doesn't exist //-------------------------------------------------------------------------- bool NamedEvent::Open(const char* eventName, bool inherit) { return m_pImpl->Open(eventName, inherit); } //-------------------------------------------------------------------------- /// Wait for a signal/event to happen. This function won't return until it /// receives a signal /// /// \return true if successful, false if error //-------------------------------------------------------------------------- bool NamedEvent::Wait() { return m_pImpl->Wait(); } //-------------------------------------------------------------------------- /// Set the event to the signaled state. Any other threads/processes waiting /// for the signal can now proceed. /// /// \return true if successful, false if error //-------------------------------------------------------------------------- bool NamedEvent::Signal() { return m_pImpl->Signal(); } //-------------------------------------------------------------------------- /// Is the event in the Signaled state. Does not block or wait but returns /// immediately /// /// \return true if currently signaled, false if not //-------------------------------------------------------------------------- bool NamedEvent::IsSignaled() { return m_pImpl->IsSignaled(); } //-------------------------------------------------------------------------- /// reset the event to non-signaled //-------------------------------------------------------------------------- void NamedEvent::Reset() { m_pImpl->Reset(); } //-------------------------------------------------------------------------- /// close the event //-------------------------------------------------------------------------- void NamedEvent::Close() { m_pImpl->Close(); }
29.7
128
0.497194
davidlee80
e1af4fb4a82db28d4218e5e45343f4bb77d4d5d2
6,357
cc
C++
cryptohome/stateful_recovery.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
null
null
null
cryptohome/stateful_recovery.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
null
null
null
cryptohome/stateful_recovery.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Provides the implementation of StatefulRecovery. #include "cryptohome/stateful_recovery.h" #include <linux/reboot.h> #include <sys/reboot.h> #include <unistd.h> #include <string> #include <base/files/file_path.h> #include <base/json/json_writer.h> #include <base/strings/string_util.h> #include <base/values.h> #include "cryptohome/platform.h" using base::FilePath; namespace cryptohome { const char StatefulRecovery::kRecoverSource[] = "/mnt/stateful_partition/encrypted"; const char StatefulRecovery::kRecoverDestination[] = "/mnt/stateful_partition/decrypted"; const char StatefulRecovery::kRecoverBlockUsage[] = "/mnt/stateful_partition/decrypted/block-usage.txt"; const char StatefulRecovery::kRecoverFilesystemDetails[] = "/mnt/stateful_partition/decrypted/filesystem-details.txt"; const char StatefulRecovery::kFlagFile[] = "/mnt/stateful_partition/decrypt_stateful"; StatefulRecovery::StatefulRecovery(Platform* platform, MountFunction mountfn, UnmountFunction unmountfn, IsOwnerFunction isownerfn) : requested_(false), platform_(platform), mountfn_(mountfn), unmountfn_(unmountfn), isownerfn_(isownerfn) {} bool StatefulRecovery::Requested() { requested_ = ParseFlagFile(); return requested_; } bool StatefulRecovery::CopyPartitionInfo() { struct statvfs vfs; if (!platform_->StatVFS(FilePath(kRecoverSource), &vfs)) return false; base::Value dv(base::Value::Type::DICTIONARY); dv.SetStringKey("filesystem", FilePath(kRecoverSource).value()); dv.SetIntKey("blocks-total", vfs.f_blocks); dv.SetIntKey("blocks-free", vfs.f_bfree); dv.SetIntKey("blocks-avail", vfs.f_bavail); dv.SetIntKey("inodes-total", vfs.f_files); dv.SetIntKey("inodes-free", vfs.f_ffree); dv.SetIntKey("inodes-avail", vfs.f_favail); std::string output; base::JSONWriter::WriteWithOptions(dv, base::JSONWriter::OPTIONS_PRETTY_PRINT, &output); if (!platform_->WriteStringToFile(FilePath(kRecoverBlockUsage), output)) return false; if (!platform_->ReportFilesystemDetails(FilePath(kRecoverSource), FilePath(kRecoverFilesystemDetails))) return false; return true; } bool StatefulRecovery::CopyUserContents() { int rc; FilePath path; if (!mountfn_.Run(user_, passkey_, &path)) { // mountfn_ logged the error already. return false; } rc = platform_->Copy(path, FilePath(kRecoverDestination)); unmountfn_.Run(); // If it failed, unmountfn_ would log the error. if (rc) return true; LOG(ERROR) << "Failed to copy " << path.value(); return false; } bool StatefulRecovery::CopyPartitionContents() { int rc; rc = platform_->Copy(FilePath(kRecoverSource), FilePath(kRecoverDestination)); if (rc) return true; LOG(ERROR) << "Failed to copy " << FilePath(kRecoverSource).value(); return false; } bool StatefulRecovery::RecoverV1() { // Version 1 requires write protect be disabled. if (platform_->FirmwareWriteProtected()) { LOG(ERROR) << "Refusing v1 recovery request: firmware is write protected."; return false; } if (!CopyPartitionContents()) return false; if (!CopyPartitionInfo()) return false; return true; } bool StatefulRecovery::RecoverV2() { bool wrote_data = false; bool is_authenticated_owner = false; // If possible, copy user contents. if (CopyUserContents()) { wrote_data = true; // If user authenticated, check if they are the owner. if (isownerfn_.Run(user_)) { is_authenticated_owner = true; } } // Version 2 requires either write protect disabled or system owner. if (!platform_->FirmwareWriteProtected() || is_authenticated_owner) { if (!CopyPartitionContents() || !CopyPartitionInfo()) { // Even if we wrote out user data, claim failure here if the // encrypted-stateful partition couldn't be extracted. return false; } wrote_data = true; } return wrote_data; } bool StatefulRecovery::Recover() { if (!requested_) return false; // Start with a clean slate. Note that there is a window of opportunity for // another process to create the directory with funky permissions after the // delete takes place but before we manage to recreate. Since the parent // directory is root-owned though, this isn't a problem in practice. const FilePath kDestinationPath(kRecoverDestination); if (!platform_->DeleteFile(kDestinationPath, true) || !platform_->CreateDirectory(kDestinationPath)) { PLOG(ERROR) << "Failed to create fresh " << kDestinationPath.value(); return false; } if (version_ == "2") { return RecoverV2(); } else if (version_ == "1") { return RecoverV1(); } else { LOG(ERROR) << "Unknown recovery version: " << version_; return false; } } void StatefulRecovery::PerformReboot() { // TODO(wad) Replace with a mockable helper. if (system("/usr/bin/crossystem recovery_request=1") != 0) { LOG(ERROR) << "Failed to set recovery request!"; } platform_->Sync(); reboot(LINUX_REBOOT_CMD_RESTART); } bool StatefulRecovery::ParseFlagFile() { std::string contents; size_t delim, pos; if (!platform_->ReadFileToString(FilePath(kFlagFile), &contents)) return false; // Make sure there is a trailing newline. contents += "\n"; do { pos = 0; delim = contents.find("\n", pos); if (delim == std::string::npos) break; version_ = contents.substr(pos, delim); if (version_ == "1") return true; if (version_ != "2") break; pos = delim + 1; delim = contents.find("\n", pos); if (delim == std::string::npos) break; user_ = contents.substr(pos, delim - pos); pos = delim + 1; delim = contents.find("\n", pos); if (delim == std::string::npos) break; passkey_ = contents.substr(pos, delim - pos); return true; } while (0); // TODO(ellyjones): UMA stat? LOG(ERROR) << "Bogus stateful recovery request file:" << contents; return false; } } // namespace cryptohome
27.759825
80
0.674689
kalyankondapally
e1b426a47a288e3c5bf1306615c4f1f015fd325d
1,443
cpp
C++
test/testlist.cpp
zenomt/rtmfp-cpp
e85d8928d5192c5e16f963ca281a4c5a701dae7b
[ "MIT" ]
21
2021-01-25T07:33:12.000Z
2022-02-09T08:08:51.000Z
test/testlist.cpp
zenomt/rtmfp-cpp
e85d8928d5192c5e16f963ca281a4c5a701dae7b
[ "MIT" ]
2
2021-04-25T15:30:27.000Z
2021-06-26T22:56:31.000Z
test/testlist.cpp
zenomt/rtmfp-cpp
e85d8928d5192c5e16f963ca281a4c5a701dae7b
[ "MIT" ]
null
null
null
#include <cstdio> #include <cassert> #include "rtmfp/List.hpp" using namespace com::zenomt; static size_t mysize(const int& val) { return 2 * (val < 0 ? -val : val); } int main(int argc, char *argv[]) { SumList<int> l(mysize, 0); printf("%ld ", l.prepend(1)); printf("%ld ", l.prepend(2)); printf("%ld ", l.prepend(3)); printf("%ld ", l.append(6)); printf("%ld ", l.append(7)); printf("%ld ", l.append(8)); printf("sum: %lu\n", l.sum()); assert(l.sum() == 54); // times two printf("find 6: %ld\n", l.find(6)); long name = l.SENTINEL; while((name = l.next(name)) > l.SENTINEL) { printf("%ld=%d ", name, l.at(name)); } printf("\n"); printf("size: %lu\n", l.size()); l.clear(); printf("size: %lu\n", l.size()); for(int x = 0; x < 50; x++) printf("%ld ", l.append(x)); printf("\n"); l.rotateNameToHead(30); l.moveNameToHead(35); printf("safeValuesDo: "); l.safeValuesDo([] (int v) { printf("%d ", v); return true; }); printf(" sum: %lu\n", l.sum()); while(not l.empty()) { printf("%d ", l.firstValue()); l.removeFirst(); } printf("sum: %lu\n", l.sum()); assert(0 == l.sum()); printf("---\n"); for(int x = 0; x < 10000000; x++) l.append(x); printf("size: %lu sum: %lu\n", l.size(), l.sum()); l.clear(); printf("size: %lu sum: %lu\n", l.size(), l.sum()); for(int x = 0; x < 10000000; x++) l.append(x); printf("size: %lu sum: %lu\n", l.size(), l.sum()); printf("---\n"); return 0; }
20.041667
63
0.550243
zenomt
e1b4c0141e6f0e57072b8e2954cbb0f9a6d2da0e
1,462
hpp
C++
include/cglass/definitions.hpp
Betterton-Lab/C-GLASS
56f7b93cd7383e4487b4c6ba5a1d8c556d9937cc
[ "BSD-3-Clause" ]
4
2020-05-23T18:56:31.000Z
2022-01-13T04:06:50.000Z
include/cglass/definitions.hpp
Betterton-Lab/C-GLASS
56f7b93cd7383e4487b4c6ba5a1d8c556d9937cc
[ "BSD-3-Clause" ]
5
2020-06-30T17:32:03.000Z
2021-04-02T20:18:33.000Z
include/cglass/definitions.hpp
Betterton-Lab/C-GLASS
56f7b93cd7383e4487b4c6ba5a1d8c556d9937cc
[ "BSD-3-Clause" ]
2
2020-11-11T19:57:11.000Z
2021-03-18T01:55:37.000Z
#ifndef _CGLASS_DEFINITIONS_H_ #define _CGLASS_DEFINITIONS_H_ #include "macros.hpp" #include "logger.hpp" #include <math.h> #define BETTER_ENUMS_DEFAULT_CONSTRUCTOR(Enum) \ public: \ Enum() = default; #include "enum.hpp" #if defined(_OPENMP) #define ENABLE_OPENMP #endif BETTER_ENUM(species_id, unsigned char, br_bead, filament, rigid_filament, spherocylinder, spindle, crosslink, receptor, point_cover, none); BETTER_ENUM(draw_type, unsigned char, fixed, orientation, bw, none); BETTER_ENUM(potential_type, unsigned char, none, wca, soft, lj); BETTER_ENUM(boundary_type, unsigned char, none = 0, box = 1, sphere = 2, budding = 3, wall = 4); BETTER_ENUM(poly_state, unsigned char, grow, shrink, pause); BETTER_ENUM(bind_state, unsigned char, unbound, singly, doubly); BETTER_ENUM(obj_type, unsigned char, generic, bond, site, cortex); BETTER_ENUM(comp_type, unsigned char, generic, mesh, point_cover); BETTER_ENUM(density_type, unsigned char, linear, surface, volume); BETTER_ENUM(shape, unsigned char, sphere, rod, generic) struct graph_struct { double r[3]; double u[3]; double length; double diameter; double color; draw_type draw; }; /* For unit testing */ // namespace unit_test { // class Tester; //} #ifdef TESTS #define UNIT_TEST \ template <typename T> \ friend class UnitTest; template <typename T> class UnitTest {}; #else #define UNIT_TEST #endif #endif
26.107143
77
0.716826
Betterton-Lab
e1ba1d3488e1e68c30c9bc60436b7f1d6d995de5
3,331
cpp
C++
Active/CodeForces/C_Pair_Programming.cpp
pawan-nirpal-031/Algorithms-And-ProblemSolving
24ce9649345dabe7275920f6912e410efc2c8e84
[ "Apache-2.0" ]
2
2021-03-05T08:40:01.000Z
2021-04-25T13:58:42.000Z
Active/CodeForces/C_Pair_Programming.cpp
pawan-nirpal-031/Algorithms-And-ProblemSolving
24ce9649345dabe7275920f6912e410efc2c8e84
[ "Apache-2.0" ]
null
null
null
Active/CodeForces/C_Pair_Programming.cpp
pawan-nirpal-031/Algorithms-And-ProblemSolving
24ce9649345dabe7275920f6912e410efc2c8e84
[ "Apache-2.0" ]
null
null
null
// Problem Link : https://codeforces.com/contest/1547/problem/C #include <bits/stdc++.h> using namespace std; typedef unsigned long long int ull; typedef long long int ll; typedef long double ld; #define Mod 1000000007 #define Infinity (ll)1e18 #define Append(a) push_back(a) #define Pair(a,b) make_pair(a,b) #define Clear(a) for(ll &x : a){x=0;} #define Point(x) std::fixed<<setprecision(15)<<x #define SetBits(x) __builtin_popcount(x); #define DebugCase(i,x) cout<<"Case #"<<i<<": "<<x<<'\n' #define FastIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define Status(b) (cout<<(b?"YES\n":"NO\n")); #define Print(x) cout<<x #define Input(x) cin>>x /* Problem Statement : Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming. It's known that they have worked together on the same file for n+m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file. Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines. Monocarp worked in total for n minutes and performed the sequence of actions [a1,a2,…,an]. If ai=0, then he adds a new line to the end of the file. If ai>0, then he changes the line with the number ai. Monocarp performed actions strictly in this order: a1, then a2, ..., an. Polycarp worked in total for m minutes and performed the sequence of actions [b1,b2,…,bm]. If bj=0, then he adds a new line to the end of the file. If bj>0, then he changes the line with the number bj. Polycarp performed actions strictly in this order: b1, then b2, ..., bm. Restore their common sequence of actions of length n+m such that all actions would be correct — there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a1,a2,…,an] and Polycarp's — subsequence [b1,b2,…,bm]. They can replace each other at the computer any number of times. Let's look at an example. Suppose k=3. Monocarp first changed the line with the number 2 and then added a new line (thus, n=2,a=[2,0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m=2,b=[0,5]). Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0,2,0,5] and [2,0,0,5]. Changes [0,0,5,2] (wrong order of actions) and [0,5,2,0] (line 5 cannot be edited yet) are not correct. Input The first line contains an integer t (1≤t≤1000). Then t test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains three integers k, n, m (0≤k≤100, 1≤n,m≤100) — the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively. The second line contains n integers a1,a2,…,an (0≤ai≤300). The third line contains m integers b1,b2,…,bm (0≤bj≤300). Output For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n+m or -1 if such sequence doesn't exist. */ /* Author's solution : */ int main(){ FastIO; return 0; } // If Solved Mark (0/1) here => []
49.716418
363
0.732213
pawan-nirpal-031