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
108
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
67k
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
902da8ebf18cc52e8154d8340308434776985734
514
cpp
C++
SharpMedia.Graphics.Driver.Direct3D10/RenderTargetView.cpp
zigaosolin/SharpMedia
b7b594a4c9c64a03d94862877ba642b0460d1067
[ "Apache-2.0" ]
null
null
null
SharpMedia.Graphics.Driver.Direct3D10/RenderTargetView.cpp
zigaosolin/SharpMedia
b7b594a4c9c64a03d94862877ba642b0460d1067
[ "Apache-2.0" ]
null
null
null
SharpMedia.Graphics.Driver.Direct3D10/RenderTargetView.cpp
zigaosolin/SharpMedia
b7b594a4c9c64a03d94862877ba642b0460d1067
[ "Apache-2.0" ]
null
null
null
#include "RenderTargetView.h" #include "Helper.h" namespace SharpMedia { namespace Graphics { namespace Driver { namespace Direct3D10 { D3D10RenderTargetView::D3D10RenderTargetView(ID3D10RenderTargetView* view) { this->view = view; } D3D10RenderTargetView::~D3D10RenderTargetView() { this->view->Release(); } void D3D10RenderTargetView::Clear(ID3D10Device* device, Colour colour) { float c[] = { colour.R, colour.G, colour.B, colour.A }; device->ClearRenderTargetView(view, c); } } } } }
16.580645
75
0.72179
zigaosolin
903103ab69cc91a1fc14c36b93042c3775559100
470
cpp
C++
Problems/Array/squareSortedArray.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
Problems/Array/squareSortedArray.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
Problems/Array/squareSortedArray.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> sortedSquares(vector<int> &nums) { priority_queue<int, vector<int>, greater<int>> q; vector<int> res; for (int i : nums) { q.push(i * i); } while (!q.empty()) { res.push_back(q.top()); q.pop(); } return res; } };
19.583333
48
0.444681
vishwajeet-hogale
9031263f8cbc650f99e928e654511839a814face
3,314
cpp
C++
Source Code/GUI/GUIMessageBox.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/GUI/GUIMessageBox.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/GUI/GUIMessageBox.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Headers/GUIMessageBox.h" namespace Divide { GUIMessageBox::GUIMessageBox(const string& name, const string& title, const string& message, const vec2<I32>& offsetFromCentre, CEGUI::Window* parent) : GUIElementBase(name, parent) { if (parent != nullptr) { // Get a local pointer to the CEGUI Window Manager, Purely for convenience // to reduce typing CEGUI::WindowManager* pWindowManager = CEGUI::WindowManager::getSingletonPtr(); // load the messageBox Window from the layout file _msgBoxWindow = pWindowManager->loadLayoutFromFile("messageBox.layout"); _msgBoxWindow->setName((title + "_MesageBox").c_str()); _msgBoxWindow->setTextParsingEnabled(false); _parent->addChild(_msgBoxWindow); CEGUI::PushButton* confirmBtn = dynamic_cast<CEGUI::PushButton*>(_msgBoxWindow->getChild("ConfirmBtn")); _confirmEvent = confirmBtn->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GUIMessageBox::onConfirm, this)); } setTitle(title); setMessage(message); setOffset(offsetFromCentre); GUIMessageBox::active(true); GUIMessageBox::visible(false); } GUIMessageBox::~GUIMessageBox() { if (_parent != nullptr) { _parent->removeChild(_msgBoxWindow); CEGUI::WindowManager::getSingletonPtr()->destroyWindow(_msgBoxWindow); } } bool GUIMessageBox::onConfirm(const CEGUI::EventArgs& /*e*/) noexcept { active(false); visible(false); return true; } void GUIMessageBox::visible(const bool& visible) noexcept { if (_parent != nullptr) { _msgBoxWindow->setVisible(visible); _msgBoxWindow->setModalState(visible); } GUIElement::visible(visible); } void GUIMessageBox::active(const bool& active) noexcept { if (_parent != nullptr) { _msgBoxWindow->setEnabled(active); } GUIElement::active(active); } void GUIMessageBox::setTitle(const string& titleText) { if (_parent != nullptr) { _msgBoxWindow->setText(titleText.c_str()); } } void GUIMessageBox::setMessage(const string& message) { if (_parent != nullptr) { _msgBoxWindow->getChild("MessageText")->setText(message.c_str()); } } void GUIMessageBox::setOffset(const vec2<I32>& offsetFromCentre) { if (_parent != nullptr) { CEGUI::UVector2 crtPosition(_msgBoxWindow->getPosition()); crtPosition.d_x.d_offset += offsetFromCentre.x; crtPosition.d_y.d_offset += offsetFromCentre.y; _msgBoxWindow->setPosition(crtPosition); } } void GUIMessageBox::setMessageType(const MessageType type) { if (_parent != nullptr) { switch (type) { case MessageType::MESSAGE_INFO: { _msgBoxWindow->setProperty("CaptionColour", "FFFFFFFF"); } break; case MessageType::MESSAGE_WARNING: { _msgBoxWindow->setProperty("CaptionColour", "00FFFFFF"); } break; case MessageType::MESSAGE_ERROR: { _msgBoxWindow->setProperty("CaptionColour", "FF0000FF"); } break; } } } };
33.816327
144
0.63096
IonutCava
90324190c5b67bd39c5f4884f3ad838afffe1788
1,322
cpp
C++
tests/clustering_tests.cpp
lgruelas/Graph
079ec1d42a30e66c47ecbce1228b6581ca56cf34
[ "MIT" ]
7
2016-08-25T07:42:10.000Z
2019-10-30T09:05:29.000Z
tests/clustering_tests.cpp
lgruelas/Graph
079ec1d42a30e66c47ecbce1228b6581ca56cf34
[ "MIT" ]
1
2018-08-16T20:38:26.000Z
2018-08-16T22:11:32.000Z
tests/clustering_tests.cpp
lgruelas/Graph
079ec1d42a30e66c47ecbce1228b6581ca56cf34
[ "MIT" ]
10
2018-01-31T15:10:16.000Z
2018-08-16T18:15:20.000Z
#include "Clustering.hpp" #include "CommonGraphs.hpp" #include <gtest/gtest.h> #include <iostream> void assert_are_same_float(const std::vector<double>& A, const std::vector<double>& B) { ASSERT_EQ(A.size(), B.size()); for (auto i : indices(A)) { ASSERT_FLOAT_EQ(A[i], B[i]); } } TEST(Clustering, Empty3) { Graph G(3); ASSERT_EQ(num_triangles(G), 0); ASSERT_EQ(clustering_global(G), 0); std::vector<double> cl = {0, 0, 0}; assert_are_same_float(clustering_local(G), cl); } TEST(Clustering, K3) { Graph G = graphs::Complete(3); ASSERT_EQ(num_triangles(G), 1); ASSERT_EQ(clustering_global(G), 1); std::vector<double> cl = {1, 1, 1}; assert_are_same_float(clustering_local(G), cl); } TEST(Clustering, K4minusedge) { Graph G = graphs::Complete(4); G.remove_edge(1, 3); ASSERT_EQ(num_triangles(G), 2); ASSERT_EQ(clustering_global(G), 0.75); std::vector<double> cl = {2.0/3.0, 1, 2.0/3.0, 1}; assert_are_same_float(clustering_local(G), cl); } TEST(Clustering, Petersen) { Graph G = graphs::Petersen(); std::vector<double> cl = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; ASSERT_EQ(num_triangles(G), 0); ASSERT_EQ(clustering_global(G), 0); assert_are_same_float(clustering_local(G), cl); }
20.984127
60
0.624811
lgruelas
903f9b1c677294829f94fbf55e9f8dc2ba5ed48a
4,926
cpp
C++
Source Code/Editor/Widgets/EditorOptionsWindow.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Editor/Widgets/EditorOptionsWindow.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Editor/Widgets/EditorOptionsWindow.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Headers/UndoManager.h" #include "Headers/Utils.h" #include "Editor/Headers/Editor.h" #include "Headers/EditorOptionsWindow.h" #include "Core/Headers/PlatformContext.h" #include <IconFontCppHeaders/IconsForkAwesome.h> namespace Divide { EditorOptionsWindow::EditorOptionsWindow(PlatformContext& context) : PlatformContextComponent(context), _fileOpenDialog(false, true) { } void EditorOptionsWindow::update([[maybe_unused]] const U64 deltaTimeUS) { } void EditorOptionsWindow::draw(bool& open) { if (!open) { return; } OPTICK_EVENT(); const U32 flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking | (_openDialog ? ImGuiWindowFlags_NoBringToFrontOnFocus : ImGuiWindowFlags_Tooltip); Util::CenterNextWindow(); if (!ImGui::Begin("Editor options", nullptr, flags)) { ImGui::End(); return; } F32 axisWidth = _context.editor().infiniteGridAxisWidth(); ImGui::Text(ICON_FK_PLUS_SQUARE_O); ImGui::SameLine(); if (ImGui::SliderFloat("Grid axis width", &axisWidth, 0.01f, 10.0f, "%.3f")) { _context.editor().infiniteGridAxisWidth(axisWidth); } ImGui::SameLine(); F32 gridLineWidth = 10.1f - _context.editor().infiniteGridScale(); if (ImGui::SliderFloat("Grid scale", &gridLineWidth, 1.f, 10.f, "%.3f")) { _context.editor().infiniteGridScale(10.1f - gridLineWidth); } static UndoEntry<I32> undo = {}; const I32 crtThemeIdx = to_I32(Attorney::EditorOptionsWindow::getTheme(_context.editor())); I32 selection = crtThemeIdx; if (ImGui::Combo("Editor Theme", &selection, ImGui::GetDefaultStyleNames(), ImGuiStyle_Count)) { ImGui::ResetStyle(static_cast<ImGuiStyleEnum>(selection)); Attorney::EditorOptionsWindow::setTheme(_context.editor(), static_cast<ImGuiStyleEnum>(selection)); undo._type = GFX::PushConstantType::INT; undo._name = "Theme Selection"; undo._oldVal = crtThemeIdx; undo._newVal = selection; undo._dataSetter = [this](const I32& data) { const ImGuiStyleEnum style = static_cast<ImGuiStyleEnum>(data); ImGui::ResetStyle(style); Attorney::EditorOptionsWindow::setTheme(_context.editor(), style); }; _context.editor().registerUndoEntry(undo); ++_changeCount; } ImGui::Separator(); string externalTextEditorPath = Attorney::EditorOptionsWindow::externalTextEditorPath(_context.editor()); ImGui::InputText("Text Editor", externalTextEditorPath.data(), externalTextEditorPath.size(), ImGuiInputTextFlags_ReadOnly); ImGui::SameLine(); const bool openDialog = ImGui::Button("Select"); if (openDialog) { ImGuiFs::Dialog::WindowLTRBOffsets.x = 20; ImGuiFs::Dialog::WindowLTRBOffsets.y = 20; _openDialog = true; } ImGui::Separator(); ImGui::Separator(); if (ImGui::Button("Cancel", ImVec2(120, 0))) { open = false; assert(_changeCount <= _context.editor().UndoStackSize()); for (U16 i = 0; i < _changeCount; ++i) { if (!_context.editor().Undo()) { NOP(); } } _changeCount = 0u; } ImGui::SetItemDefaultFocus(); ImGui::SameLine(); if (ImGui::Button(ICON_FK_FLOPPY_O" Save", ImVec2(120, 0))) { open = false; _changeCount = 0u; if (!_context.editor().saveToXML()) { Attorney::EditorGeneralWidget::showStatusMessage(_context.editor(), "Save failed!", Time::SecondsToMilliseconds<F32>(3.0f), true); } } ImGui::SameLine(); if (ImGui::Button("Defaults", ImVec2(120, 0))) { _changeCount = 0u; Attorney::EditorOptionsWindow::setTheme(_context.editor(), ImGuiStyle_DarkCodz01); ImGui::ResetStyle(ImGuiStyle_DarkCodz01); } ImGui::End(); if (_openDialog) { Util::CenterNextWindow(); const char* chosenPath = _fileOpenDialog.chooseFileDialog(openDialog, nullptr, nullptr, "Choose text editor", ImVec2(-1, -1), ImGui::GetMainViewport()->WorkPos); if (strlen(chosenPath) > 0) { Attorney::EditorOptionsWindow::externalTextEditorPath(_context.editor(), chosenPath); } if (_fileOpenDialog.hasUserJustCancelledDialog()) { _openDialog = false; } } } }
38.787402
173
0.591758
IonutCava
903fadf042ed4431ad4c69cef2c56090e4b424d3
3,060
cpp
C++
test/test_disk_space_widget/widget.cpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
test/test_disk_space_widget/widget.cpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
test/test_disk_space_widget/widget.cpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \file /// /// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n /// Licensed under the Apache License, Version 2.0 (the "License");\n /// you may not use this file except in compliance with the License.\n /// You may obtain a copy of the License at\n /// http://www.apache.org/licenses/LICENSE-2.0\n /// Unless required by applicable law or agreed to in writing, software\n /// distributed under the License is distributed on an "AS IS" BASIS,\n /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n /// See the License for the specific language governing permissions and\n /// limitations under the License.\n /// Please see the file COPYING. /// /// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "widget.hpp" #include <cppdevtk/base/logger.hpp> #include <cppdevtk/base/cassert.hpp> #include <cppdevtk/base/verify.h> #include <cppdevtk/base/dbc.hpp> #include <cppdevtk/base/info_tr.hpp> #include <QtGui/QIcon> #include <QtCore/QDir> #define CPPDEVTK_DETAIL_TEST_DISK_SPACE_WIDGET_PATH_EMPTY 0 namespace cppdevtk { namespace test_disk_space_widget { Widget::Widget(QWidget* pParent): QWidget(pParent), WidgetBase(), Ui::Widget() { CPPDEVTK_LOG_TRACE_FUNCTION(); setupUi(this); SetStyleSheetFromFileCross(":/cppdevtk/test_disk_space_widget/res/qss", "widget"); setWindowIcon(QIcon(":/cppdevtk/test_disk_space_widget/res/ico/application.ico")); pDiskSpaceWidget_->SetDiskNameColor(Qt::darkRed); pDiskSpaceWidget_->SetSpaceInfoColor(Qt::darkBlue); pDiskSpaceWidget_->SetBold(true); # if (!CPPDEVTK_DETAIL_TEST_DISK_SPACE_WIDGET_PATH_EMPTY) const QString kPath = QDir::currentPath(); CPPDEVTK_LOG_DEBUG("setting path to: " << kPath); pDiskSpaceWidget_->SetPath(kPath); # endif pSpinBoxAutoRefreshInterval_->setValue(pDiskSpaceWidget_->GetAutoRefreshInterval()); CPPDEVTK_VERIFY(connect(pPushButtonRefresh_, SIGNAL(clicked()), pDiskSpaceWidget_, SLOT(Refresh()))); CPPDEVTK_VERIFY(connect(pGroupBoxAutoRefresh_, SIGNAL(toggled(bool)), pDiskSpaceWidget_, SLOT(SetAutoRefreshEnabled(bool)))); CPPDEVTK_VERIFY(connect(pSpinBoxAutoRefreshInterval_, SIGNAL(valueChanged(int)), SLOT(SetAutoRefreshInterval(int)))); adjustSize(); } Widget::~Widget() { CPPDEVTK_LOG_TRACE_FUNCTION(); } void Widget::SetAutoRefreshInterval(int sec) { pDiskSpaceWidget_->SetAutoRefreshInterval(sec); } void Widget::changeEvent(QEvent* pEvent) { CPPDEVTK_DBC_CHECK_NON_NULL_ARGUMENT(pEvent); QWidget::changeEvent(pEvent); switch (pEvent->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } } // namespace test_disk_space_widget } // namespace cppdevtk
33.626374
126
0.677124
CoSoSys
9042d74edca4658fd03267e0203c940ca3e8f3f3
11,531
cpp
C++
csgo-crow/AntiCheatServer/NoCheatZ/server-plugin/Code/Systems/Testers/JumpTester.cpp
im6705/csgo_full
6c50221c5b6441ebf689e3a1cb4978510fab0b27
[ "Apache-2.0" ]
1
2021-04-17T17:20:44.000Z
2021-04-17T17:20:44.000Z
server-plugin/Code/Systems/Testers/JumpTester.cpp
Jalorussian/NoCheatZ-4
9ba3cf2faabe76a66b46d837d2cc0ff73931f950
[ "Apache-2.0" ]
1
2019-03-03T16:44:09.000Z
2019-03-03T16:44:09.000Z
server-plugin/Code/Systems/Testers/JumpTester.cpp
Jalorussian/NoCheatZ-4
9ba3cf2faabe76a66b46d837d2cc0ff73931f950
[ "Apache-2.0" ]
4
2020-02-15T12:05:29.000Z
2021-01-14T02:58:35.000Z
/* Copyright 2012 - Le Padellec Sylvain 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 <stdio.h> #include "JumpTester.h" #include "Preprocessors.h" #include "Systems/Logger.h" /* Test each player to see if they use any script to help BunnyHop. Some players jumps just-in-time without using any script. We have to make the difference by using statistics. */ JumpTester::JumpTester () : BaseTesterSystem ( "JumpTester", "Enable - Disable - Verbose - SetAction - DetectScripts" ), OnGroundHookListener (), playerdata_class (), PlayerRunCommandHookListener (), Singleton (), convar_sv_enablebunnyhopping ( nullptr ), convar_sv_autobunnyhopping ( nullptr ), detect_scripts(false) {} JumpTester::~JumpTester () { Unload (); } void JumpTester::Init () { InitDataStruct (); convar_sv_enablebunnyhopping = SourceSdk::InterfacesProxy::ICvar_FindVar ( "sv_enablebunnyhopping" ); if( convar_sv_enablebunnyhopping == nullptr ) { g_Logger.Msg<MSG_WARNING> ( "JumpTester::Init : Unable to locate ConVar sv_enablebunnyhopping" ); } if( SourceSdk::InterfacesProxy::m_game == SourceSdk::CounterStrikeGlobalOffensive ) { convar_sv_autobunnyhopping = SourceSdk::InterfacesProxy::ICvar_FindVar ( "sv_autobunnyhopping" ); if( convar_sv_enablebunnyhopping == nullptr ) { g_Logger.Msg<MSG_WARNING> ( "JumpTester::Init : Unable to locate ConVar sv_enablebunnyhopping" ); } } } bool JumpTester::sys_cmd_fn(const SourceSdk::CCommand & args) { if (!BaseTesterSystem::sys_cmd_fn(args)) { if (args.ArgC() >= 4) { if (stricmp(args.Arg(2), "detectscripts") == 0) { if (Helpers::IsArgTrue(args.Arg(3))) { detect_scripts = true; g_Logger.Msg<MSG_CMD_REPLY>("DetectScripts is Yes"); return true; } else if (Helpers::IsArgFalse(args.Arg(3))) { detect_scripts = false; g_Logger.Msg<MSG_CMD_REPLY>("DetectScripts is No"); return true; } else { g_Logger.Msg<MSG_CMD_REPLY>("DetectScripts Usage : Yes / No"); return false; } } } } else { return true; } return false; } void JumpTester::Load () { for( PlayerHandler::iterator it ( PlayerHandler::begin () ); it != PlayerHandler::end (); ++it ) { ResetPlayerDataStructByIndex ( it.GetIndex () ); } OnGroundHookListener::RegisterOnGroundHookListener ( this ); PlayerRunCommandHookListener::RegisterPlayerRunCommandHookListener ( this, SystemPriority::JumpTester ); } void JumpTester::Unload () { OnGroundHookListener::RemoveOnGroundHookListener ( this ); PlayerRunCommandHookListener::RemovePlayerRunCommandHookListener ( this ); } bool JumpTester::GotJob () const { if( convar_sv_enablebunnyhopping != nullptr ) { if( SourceSdk::InterfacesProxy::ConVar_GetBool ( convar_sv_enablebunnyhopping ) ) { return false; } } if( convar_sv_autobunnyhopping != nullptr ) { if( SourceSdk::InterfacesProxy::ConVar_GetBool ( convar_sv_autobunnyhopping ) ) { return false; } } // Create a filter ProcessFilter::HumanAtLeastConnected const filter_class; // Initiate the iterator at the first match in the filter PlayerHandler::iterator it ( &filter_class ); // Return if we have job to do or not ... return it != PlayerHandler::end (); } void JumpTester::RT_m_hGroundEntityStateChangedCallback ( PlayerHandler::iterator ph, bool new_isOnGround ) { if( new_isOnGround ) { OnPlayerTouchGround ( ph, Helpers::GetGameTickCount () ); } else { OnPlayerLeaveGround ( ph, Helpers::GetGameTickCount () ); } } PlayerRunCommandRet JumpTester::RT_PlayerRunCommandCallback ( PlayerHandler::iterator ph, void* pCmd, double const & curtime) { PlayerRunCommandRet const constexpr drop_cmd ( PlayerRunCommandRet::CONTINUE ); if( convar_sv_enablebunnyhopping != nullptr ) { if( SourceSdk::InterfacesProxy::ConVar_GetBool ( convar_sv_enablebunnyhopping ) ) { SetActive ( false ); return PlayerRunCommandRet::CONTINUE; } } if( convar_sv_autobunnyhopping != nullptr ) { if( SourceSdk::InterfacesProxy::ConVar_GetBool ( convar_sv_autobunnyhopping ) ) { SetActive ( false ); return PlayerRunCommandRet::CONTINUE; } } JumpInfoT * const playerData(GetPlayerDataStructByIndex(ph.GetIndex())); bool cur_jump_button_state; if( SourceSdk::InterfacesProxy::m_game == SourceSdk::CounterStrikeGlobalOffensive ) { cur_jump_button_state = ( static_cast< SourceSdk::CUserCmd_csgo* >( pCmd )->buttons & IN_JUMP ) != 0; } else { cur_jump_button_state = ( static_cast< SourceSdk::CUserCmd* >( pCmd )->buttons & IN_JUMP ) != 0; } bool const jump_button_changed (playerData->prev_jump ^ cur_jump_button_state ); if( !jump_button_changed ) { return drop_cmd; } else { if( cur_jump_button_state ) { OnPlayerJumpButtonDown ( ph, Helpers::GetGameTickCount () ); } else { OnPlayerJumpButtonUp ( ph, Helpers::GetGameTickCount () ); } } playerData->prev_jump = cur_jump_button_state; return drop_cmd; } void JumpTester::OnPlayerTouchGround ( PlayerHandler::iterator ph, int game_tick ) { JumpInfoT * const playerData ( GetPlayerDataStructByIndex ( ph.GetIndex () ) ); playerData->onGroundHolder.onGround_Tick = game_tick; playerData->isOnGround = true; SystemVerbose1 ( Helpers::format ( "Player %s touched the ground.", ph->GetName () ) ); // Detect bunny hop scripts // Compute the average number of time a second the player is pushing the jump button, detect if it's too high float const fly_time = ( game_tick - playerData->onGroundHolder.notOnGround_Tick ) * SourceSdk::InterfacesProxy::Call_GetTickInterval (); if( fly_time >= 0.25f ) // this is to prevent collision bugs to make fake detections, and also prevents divide by zero crash below. { float const avg_jmp_per_second = ( float ) ( playerData->jumpCmdHolder.outsideJumpCmdCount ) / fly_time; if( avg_jmp_per_second > 10.0f && playerData->total_bhopCount > 1 ) { if (detect_scripts) { ProcessDetectionAndTakeAction<Detection_BunnyHopScript::data_type>(Detection_BunnyHopScript(), playerData, ph, this); } } } if( playerData->jumpCmdHolder.outsideJumpCmdCount == 0 && playerData->perfectBhopsCount > 5 && playerData->perfectBhopsPercent >= std::max (0, ( 100 - std::min ( 95, playerData->perfectBhopsCount * 2 ) ) ) ) { ProcessDetectionAndTakeAction<Detection_BunnyHopProgram::data_type>(Detection_BunnyHopProgram(), playerData, ph, this); } playerData->jumpCmdHolder.outsideJumpCmdCount = 0; } void JumpTester::OnPlayerLeaveGround ( PlayerHandler::iterator ph, int game_tick ) { JumpInfoT * const playerData ( GetPlayerDataStructByIndex ( ph.GetIndex () ) ); playerData->onGroundHolder.notOnGround_Tick = Helpers::GetGameTickCount (); ++playerData->onGroundHolder.jumpCount; playerData->isOnGround = false; SystemVerbose1 ( Helpers::format ( "Player %s leaved the ground.", ph->GetName () ) ); } void JumpTester::OnPlayerJumpButtonDown ( PlayerHandler::iterator ph, int game_tick ) { JumpInfoT * const playerData ( GetPlayerDataStructByIndex ( ph.GetIndex () ) ); playerData->jumpCmdHolder.JumpDown_Tick = game_tick; playerData->jumpCmdHolder.lastJumpCmdState = true; int const cmd_diff ( game_tick - playerData->jumpCmdHolder.JumpUp_Tick ); int const wd_diff ( game_tick - playerData->onGroundHolder.onGround_Tick ); if( cmd_diff > 1 && cmd_diff <= 3 ) { if (detect_scripts) { ProcessDetectionAndTakeAction<Detection_BunnyHopScript::data_type>(Detection_BunnyHopScript(), playerData, ph, this); } } if( playerData->isOnGround ) { if( wd_diff >= 0 && wd_diff < 10 ) { ++playerData->total_bhopCount; SystemVerbose1 ( Helpers::format ( "Player %s : total_bhopCount = %d\n", ph->GetName (), playerData->total_bhopCount ) ); if( wd_diff <= 1 ) { ++playerData->perfectBhopsCount; __assume ( playerData->perfectBhopsCount <= playerData->total_bhopCount ); playerData->perfectBhopsPercent = ( (float)(playerData->perfectBhopsCount) / (float)(playerData->total_bhopCount) ) * 100.0f; SystemVerbose1 ( Helpers::format ( "Player %s : perfectBhopsCount = %d\n", ph->GetName (), playerData->perfectBhopsCount ) ); } else if( wd_diff < 3 ) { ++playerData->goodBhopsCount; __assume (playerData->perfectBhopsCount <= playerData->total_bhopCount); playerData->perfectBhopsPercent = ((float)(playerData->perfectBhopsCount) / (float)(playerData->total_bhopCount)) * 100.0f; SystemVerbose1 ( Helpers::format ( "Player %s : goodBhopsCount = %d\n", ph->GetName (), playerData->goodBhopsCount ) ); } } } else { ++playerData->jumpCmdHolder.outsideJumpCmdCount; ++playerData->total_outside_jump; if (playerData->total_bhopCount != 0) // Yes it can happen ... { playerData->totaloutsidepercent = ((float)(playerData->total_outside_jump) / (float)(playerData->total_bhopCount)) * 100.0f; } } SystemVerbose1 ( Helpers::format ( "Player %s pushed the jump button.", ph->GetName () ) ); } void JumpTester::OnPlayerJumpButtonUp ( PlayerHandler::iterator ph, int game_tick ) { JumpInfoT * const playerData ( GetPlayerDataStructByIndex ( ph.GetIndex () ) ); SystemVerbose1 ( Helpers::format ( "Player %s released the jump button.", ph->GetName () ) ); playerData->jumpCmdHolder.JumpUp_Tick = game_tick; playerData->jumpCmdHolder.lastJumpCmdState = false; } JumpTester g_JumpTester; const char * ConvertButton ( bool v ) { if( v ) return "Button Down"; else return "Button Up"; } basic_string Detection_BunnyHopScript::GetDataDump () { return Helpers::format ( ":::: BunnyHopInfoT {\n" ":::::::: OnGroundHolderT {\n" ":::::::::::: On Ground At (Tick #) : %d,\n" ":::::::::::: Leave Ground At (Tick #) : %d,\n" ":::::::::::: Jump Count : %d\n" ":::::::: },\n" ":::::::: JumpCmdHolderT {\n" ":::::::::::: Last Jump Command : %s s,\n" ":::::::::::: Jump Button Down At (Tick #) : %d,\n" ":::::::::::: Jump Button Up At (Tick #) : %d,\n" ":::::::::::: Jump Commands Done While Flying : %d\n" ":::::::: },\n" ":::::::: Total Bunny Hop Count : %d,\n" ":::::::: Good Bunny Hop Count : %d,\n" ":::::::: Total Jump Commands Done While Flying : %d,\n" ":::::::: Total Jump Commands Done While Flying Ratio : %f,\n" ":::::::: Perfect Bunny Hop Ratio : %f %%,\n" ":::::::: Perfect Bunny Hop Count : %d\n" ":::: }", GetDataStruct ()->onGroundHolder.onGround_Tick, GetDataStruct ()->onGroundHolder.notOnGround_Tick, GetDataStruct ()->onGroundHolder.jumpCount, ConvertButton ( GetDataStruct ()->jumpCmdHolder.lastJumpCmdState ), GetDataStruct ()->jumpCmdHolder.JumpDown_Tick, GetDataStruct ()->jumpCmdHolder.JumpUp_Tick, GetDataStruct ()->jumpCmdHolder.outsideJumpCmdCount, GetDataStruct ()->total_bhopCount, GetDataStruct ()->goodBhopsCount, GetDataStruct()->total_outside_jump, GetDataStruct()->totaloutsidepercent, GetDataStruct ()->perfectBhopsPercent, GetDataStruct ()->perfectBhopsCount ); }
32.209497
220
0.699939
im6705
9044db185229421b97182ff0a27aa1ce2f73216f
7,758
cpp
C++
cpp/benchmarks/string/repeat_strings.cpp
res-life/cudf
94a5d4180b1281d4250e9f915e547789d8da3ce0
[ "Apache-2.0" ]
1
2022-03-04T16:36:48.000Z
2022-03-04T16:36:48.000Z
cpp/benchmarks/string/repeat_strings.cpp
res-life/cudf
94a5d4180b1281d4250e9f915e547789d8da3ce0
[ "Apache-2.0" ]
1
2022-02-28T05:17:59.000Z
2022-02-28T05:17:59.000Z
cpp/benchmarks/string/repeat_strings.cpp
res-life/cudf
94a5d4180b1281d4250e9f915e547789d8da3ce0
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "string_bench_args.hpp" #include <benchmark/benchmark.h> #include <benchmarks/common/generate_input.hpp> #include <benchmarks/fixture/benchmark_fixture.hpp> #include <benchmarks/synchronization/synchronization.hpp> #include <cudf/strings/repeat_strings.hpp> #include <cudf/strings/strings_column_view.hpp> static constexpr cudf::size_type default_repeat_times = 16; static constexpr cudf::size_type min_repeat_times = -16; static constexpr cudf::size_type max_repeat_times = 16; static std::unique_ptr<cudf::table> create_data_table(cudf::size_type n_cols, cudf::size_type n_rows, cudf::size_type max_str_length) { CUDF_EXPECTS(n_cols == 1 || n_cols == 2, "Invalid number of columns."); std::vector<cudf::type_id> dtype_ids{cudf::type_id::STRING}; data_profile table_profile; table_profile.set_distribution_params( cudf::type_id::STRING, distribution_id::NORMAL, 0, max_str_length); if (n_cols == 2) { dtype_ids.push_back(cudf::type_id::INT32); table_profile.set_distribution_params( cudf::type_id::INT32, distribution_id::NORMAL, min_repeat_times, max_repeat_times); } return create_random_table(dtype_ids, row_count{n_rows}, table_profile); } static void BM_repeat_strings_scalar_times(benchmark::State& state) { auto const n_rows = static_cast<cudf::size_type>(state.range(0)); auto const max_str_length = static_cast<cudf::size_type>(state.range(1)); auto const table = create_data_table(1, n_rows, max_str_length); auto const strings_col = cudf::strings_column_view(table->view().column(0)); for ([[maybe_unused]] auto _ : state) { [[maybe_unused]] cuda_event_timer raii(state, true, rmm::cuda_stream_default); cudf::strings::repeat_strings(strings_col, default_repeat_times); } state.SetBytesProcessed(state.iterations() * strings_col.chars_size()); } static void BM_repeat_strings_column_times(benchmark::State& state) { auto const n_rows = static_cast<cudf::size_type>(state.range(0)); auto const max_str_length = static_cast<cudf::size_type>(state.range(1)); auto const table = create_data_table(2, n_rows, max_str_length); auto const strings_col = cudf::strings_column_view(table->view().column(0)); auto const repeat_times_col = table->view().column(1); for ([[maybe_unused]] auto _ : state) { [[maybe_unused]] cuda_event_timer raii(state, true, rmm::cuda_stream_default); cudf::strings::repeat_strings(strings_col, repeat_times_col); } state.SetBytesProcessed(state.iterations() * (strings_col.chars_size() + repeat_times_col.size() * sizeof(int32_t))); } static void BM_compute_output_strings_sizes(benchmark::State& state) { auto const n_rows = static_cast<cudf::size_type>(state.range(0)); auto const max_str_length = static_cast<cudf::size_type>(state.range(1)); auto const table = create_data_table(2, n_rows, max_str_length); auto const strings_col = cudf::strings_column_view(table->view().column(0)); auto const repeat_times_col = table->view().column(1); for ([[maybe_unused]] auto _ : state) { [[maybe_unused]] cuda_event_timer raii(state, true, rmm::cuda_stream_default); cudf::strings::repeat_strings_output_sizes(strings_col, repeat_times_col); } state.SetBytesProcessed(state.iterations() * (strings_col.chars_size() + repeat_times_col.size() * sizeof(int32_t))); } static void BM_repeat_strings_column_times_precomputed_sizes(benchmark::State& state) { auto const n_rows = static_cast<cudf::size_type>(state.range(0)); auto const max_str_length = static_cast<cudf::size_type>(state.range(1)); auto const table = create_data_table(2, n_rows, max_str_length); auto const strings_col = cudf::strings_column_view(table->view().column(0)); auto const repeat_times_col = table->view().column(1); [[maybe_unused]] auto const [sizes, total_bytes] = cudf::strings::repeat_strings_output_sizes(strings_col, repeat_times_col); for ([[maybe_unused]] auto _ : state) { [[maybe_unused]] cuda_event_timer raii(state, true, rmm::cuda_stream_default); cudf::strings::repeat_strings(strings_col, repeat_times_col, *sizes); } state.SetBytesProcessed(state.iterations() * (strings_col.chars_size() + repeat_times_col.size() * sizeof(int32_t))); } static void generate_bench_args(benchmark::internal::Benchmark* b) { int const min_rows = 1 << 8; int const max_rows = 1 << 18; int const row_mult = 4; int const min_strlen = 1 << 4; int const max_strlen = 1 << 8; int const len_mult = 4; generate_string_bench_args(b, min_rows, max_rows, row_mult, min_strlen, max_strlen, len_mult); } class RepeatStrings : public cudf::benchmark { }; #define REPEAT_STRINGS_SCALAR_TIMES_BENCHMARK_DEFINE(name) \ BENCHMARK_DEFINE_F(RepeatStrings, name) \ (::benchmark::State & st) { BM_repeat_strings_scalar_times(st); } \ BENCHMARK_REGISTER_F(RepeatStrings, name) \ ->Apply(generate_bench_args) \ ->UseManualTime() \ ->Unit(benchmark::kMillisecond); #define REPEAT_STRINGS_COLUMN_TIMES_BENCHMARK_DEFINE(name) \ BENCHMARK_DEFINE_F(RepeatStrings, name) \ (::benchmark::State & st) { BM_repeat_strings_column_times(st); } \ BENCHMARK_REGISTER_F(RepeatStrings, name) \ ->Apply(generate_bench_args) \ ->UseManualTime() \ ->Unit(benchmark::kMillisecond); #define COMPUTE_OUTPUT_STRINGS_SIZES_BENCHMARK_DEFINE(name) \ BENCHMARK_DEFINE_F(RepeatStrings, name) \ (::benchmark::State & st) { BM_compute_output_strings_sizes(st); } \ BENCHMARK_REGISTER_F(RepeatStrings, name) \ ->Apply(generate_bench_args) \ ->UseManualTime() \ ->Unit(benchmark::kMillisecond); #define REPEAT_STRINGS_COLUMN_TIMES_PRECOMPUTED_SIZES_BENCHMARK_DEFINE(name) \ BENCHMARK_DEFINE_F(RepeatStrings, name) \ (::benchmark::State & st) { BM_repeat_strings_column_times_precomputed_sizes(st); } \ BENCHMARK_REGISTER_F(RepeatStrings, name) \ ->Apply(generate_bench_args) \ ->UseManualTime() \ ->Unit(benchmark::kMillisecond); REPEAT_STRINGS_SCALAR_TIMES_BENCHMARK_DEFINE(scalar_times) REPEAT_STRINGS_COLUMN_TIMES_BENCHMARK_DEFINE(column_times) COMPUTE_OUTPUT_STRINGS_SIZES_BENCHMARK_DEFINE(compute_output_strings_sizes) REPEAT_STRINGS_COLUMN_TIMES_PRECOMPUTED_SIZES_BENCHMARK_DEFINE(precomputed_sizes)
45.905325
98
0.667827
res-life
904520de086348cf21afed8a702dc451e3b99645
3,346
cpp
C++
src/zipstream.cpp
robinmoussu/fastzip
85f71b7862af0940cadbafb44f80856581ecb023
[ "RSA-MD" ]
2
2019-02-08T16:53:53.000Z
2021-03-21T05:09:13.000Z
src/zipstream.cpp
robinmoussu/fastzip
85f71b7862af0940cadbafb44f80856581ecb023
[ "RSA-MD" ]
null
null
null
src/zipstream.cpp
robinmoussu/fastzip
85f71b7862af0940cadbafb44f80856581ecb023
[ "RSA-MD" ]
3
2017-05-08T04:44:56.000Z
2018-12-01T16:12:44.000Z
#include "zipstream.h" #include "utils.h" #include "zipformat.h" #include <cassert> #include <ctime> #include <sys/stat.h> template <int BYTES> struct getType; template <> struct getType<4> { using type = int32_t; }; template <int BYTES, typename T = typename getType<BYTES>::type> T readBytes(uint8_t const* ptr) { const T t = *(T*)ptr; return t; } int64_t decodeInt(uint8_t const** ptr) { auto* data = *ptr; auto sz = data[0]; *ptr = &data[sz + 1]; int64_t val = 0; while (sz > 0) { val <<= 8; val |= data[sz]; sz--; } return val; } ZipStream::ZipStream(const std::string& zipName) : zipName_(zipName), f_{zipName} { uint32_t id = 0; // Find CD by scanning backwards from end f_.seek(-22 + 5, SEEK_END); int counter = 64 * 1024 + 8; while (id != EndOfCD_SIG && counter > 0) { f_.seek(-5, SEEK_CUR); id = f_.Read<uint32_t>(); counter--; } if (counter <= 0) { f_.close(); return; } auto start = f_.tell(); f_.seek(4, SEEK_CUR); int64_t entryCount = f_.Read<uint16_t>(); f_.seek(2, SEEK_CUR); /* auto cdSize = */ f_.Read<uint32_t>(); int64_t cdOffset = f_.Read<uint32_t>(); auto commentLen = f_.Read<uint16_t>(); if (commentLen > 0) { comment_ = std::make_unique<char[]>(commentLen + 1); f_.Read(comment_.get(), commentLen); comment_[commentLen] = 0; } if (entryCount == 0xffff || cdOffset == 0xffffffff) { // Find zip64 data f_.seek(start - 6 * 4, SEEK_SET); id = f_.Read<uint32_t>(); if (id != EndOfCD64Locator_SIG) { return; } f_.seek(4, SEEK_CUR); auto cdStart = f_.Read<int64_t>(); f_.seek(cdStart, SEEK_SET); auto eocd64 = f_.Read<EndOfCentralDir64>(); cdOffset = eocd64.cdoffset; entryCount = eocd64.entries; } entries_.reserve(entryCount); f_.seek(cdOffset, SEEK_SET); char fileName[65536]; for (auto i = 0L; i < entryCount; i++) { auto const cd = f_.Read<CentralDirEntry>(); auto const rc = f_.Read(&fileName, cd.nameLen); fileName[rc] = 0; f_.seek(cd.nameLen - rc, SEEK_CUR); int64_t offset = cd.offset; int exLen = cd.exLen; Extra extra{}; while (exLen > 0) { f_.Read((uint8_t*)&extra, 4); f_.Read(extra.data, extra.size); if (extra.id == 0x01) { offset = extra.zip64.offset; } else if (extra.id == 0x7875) { auto const* ptr = &extra.data[1]; uint32_t const uid = decodeInt(&ptr); uint32_t const gid = decodeInt(&ptr); printf("UID %x GID %x\n", uid, gid); } else if (extra.id == 0x5455) { // TODO: Read timestamps } else printf("**Warning: Ignoring extra block %04x\n", extra.id); exLen -= (extra.size + 4); } f_.seek(cd.commLen, SEEK_CUR); auto const flags = ((cd.attr1 & (S_IFREG >> 16)) == 0) ? // Some archives have broken attributes 0 : cd.attr1 >> 16; entries_.emplace_back(fileName, offset, flags); } }
27.652893
75
0.5263
robinmoussu
9047e37f26d1e3cb5450419c8beb41ae4248369f
28,136
cpp
C++
tools/lapg/src/srcgen.cpp
linz/snap
1505880b282290fc28bbbe0c4d4f69088ad81de0
[ "BSD-3-Clause" ]
7
2018-09-17T06:49:30.000Z
2020-10-10T19:12:31.000Z
tools/lapg/src/srcgen.cpp
linz/snap
1505880b282290fc28bbbe0c4d4f69088ad81de0
[ "BSD-3-Clause" ]
81
2016-11-09T01:18:19.000Z
2022-03-31T04:34:12.000Z
tools/lapg/src/srcgen.cpp
linz/snap
1505880b282290fc28bbbe0c4d4f69088ad81de0
[ "BSD-3-Clause" ]
5
2017-07-03T03:00:29.000Z
2022-01-25T07:05:08.000Z
/* srcgen.cpp * * Lapg (Lexical Analyzer and Parser Generator) * Copyright (C) 2002-07 Evgeny Gryaznov (inspirer@inbox.ru) * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <time.h> #include "common.h" #include "srcgen.h" extern const char *templ_cpp, *default_cpp; extern const char *templ_c, *default_c; extern const char *templ_cs, *default_cs; extern const char *templ_js, *default_js; extern const char *templ_java, *default_java; extern const char *templ_text; #ifdef RUN_IN_DEBUG #define CPPDEF "parse1.cpp" #else #define CPPDEF "parse.cpp" #endif const language langs[] = { { "c++", templ_cpp, NULL, default_cpp, CPPDEF, "{", "}", 1}, { "c", templ_c, NULL, default_c, "parse.c", "{", "}", 1}, { "cs", templ_cs, NULL, default_cs, "parse.cs", "{", "}", 1}, { "js", templ_js, NULL, default_js, "parse.js", "[", "]", 0}, { "java", templ_java, NULL, default_java, "Parser.java", "{", "}", 0}, { "text", templ_text, NULL, NULL, "tables.txt", "{", "}", 1}, { NULL } }; enum{ MAXINDENT = 80 }; // put the formatted string to the stream #0, #1 or #2 void SourceGenerator::error( int e, char *r, ... ) { va_list arglist; va_start( arglist, r ); switch( e ) { case 0: case 3: if( e == 0 ) fprintf( stderr, "lapg: " ); vfprintf( stderr, r, arglist ); break; case 1: if( !err ) err = fopen( "errors", "w" ); if( err ) vfprintf( err, r, arglist ); break; case 2: if( !dbg ) dbg = fopen( "states", "w" ); if( dbg ) vfprintf( dbg, r, arglist ); break; } } // processes language independent directive void SourceGenerator::process_directive( char *id, char *value, int line, int column ) { if( !strcmp( id, "class" ) ) { classn = value; } else if( !strcmp( id, "getsym" ) ) { getsym = value; } else if( !strcmp( id, "parsefunc" ) ) { parsefunc = value; } else if( !strcmp( id, "parseargs" ) ) { parseargs = value; } else if( !strcmp( id, "errorfunc" ) ) { errorfunc = value; } else if( !strcmp( id, "errorprefix" ) ) { errprefix = value; } else if( !strcmp( id, "namespace" ) ) { ns = value; } else if( !strcmp( id, "target" ) ) { targetname = value; } else if( !strcmp( id, "template" ) ) { templatefile = value; FILE *tmpl = fopen(templatefile,"r"); if( ! tmpl ) { error( 0, "lapg: %s, %i(%i) cannot open template file %s\n", sourcename,line,column,value); } else { long l; fseek(tmpl,0,SEEK_END); l = ftell(tmpl); fseek(tmpl,0,SEEK_SET); if( l > 0 ) { char *t = templatedata = new char[l+1]; *t = 0; while( fgets(t, l, tmpl)) { int nc = strlen(t); t += nc; l -= nc; if( ! l ) break; } } fclose(tmpl); } } else if( !strcmp( id, "lang" ) ) { int i; for( i = 0; langs[i].lang; i++ ) if( !strcmp( langs[i].lang, value ) ) break; if( langs[i].lang ) { language = i; } else { error( 0, "lapg: %s, %i(%i) unknown language %s\n", sourcename, line, column, value ); } } else if( !strcmp( id, "positioning" ) ) { if( !strcmp( value, "none" ) ) positioning = 0; else if( !strcmp( value, "line" ) ) positioning = 1; else if( !strcmp( value, "full" ) ) positioning = 2; else if( !strcmp( value, "offset" ) ) positioning = 3; else error( 0, "lapg: %s, %i(%i) unknown positioning value %s\n", sourcename, line, column, value ); delete[] value; } else if( !strcmp( id, "lexemend" ) ) { if( !strcmp( value, "on" ) ) lexemend = 1; else if( !strcmp( value, "off" ) ) lexemend = 0; else error( 0, "lapg: %s, %i(%i) unknown lexemend value %s (can be on/off)\n", sourcename, line, column, value ); delete[] value; } else if( !strcmp( id, "breaks" ) ) { if( !strcmp( value, "on" ) ) genbreaks = 1; else if( !strcmp( value, "off" ) ) genbreaks = 0; else error( 0, "lapg: %s, %i(%i) unknown breaks value %s (can be on/off)\n", sourcename, line, column, value ); delete[] value; } else lalr1::process_directive( id, value, line, column ); } // fills: buffer void SourceGenerator::fillb() { int size = fread( b, 1, 1024, stdin ); b[size] = 0; end = b + size; l = b; } // reads the input and generate output void SourceGenerator::process( int debug ) { debuglev = debug; err = dbg = NULL; // init ns = errprefix = classn = getsym = errorfunc = parsefunc = parseargs = NULL; templatefile = templatedata = NULL; lapgversion = NULL; lexemend = positioning = 0; genbreaks = 1; fillb(); if( run() ) { if( language == -1 ) language = 0; if( !targetname ) targetname = langs[language].output; if( *targetname && targetname[0]!='-' && targetname[1]!=0 ) if( !freopen( targetname, "w", stdout ) ) { perror( targetname ); goto skip_printout; } printout(); skip_printout: clear(); } if( err ) fclose( err ); if( dbg ) fclose( dbg ); // clean if( classn ) delete[] classn; if( getsym ) delete[] getsym; if( parsefunc ) delete [] parsefunc; if( errorfunc ) delete [] errorfunc; if( parseargs ) delete [] parseargs; if( errprefix ) delete[] errprefix; if( ns ) delete[] ns; if( templatefile ) delete [] templatefile; if( templatedata ) delete [] templatedata; } // prints rule's action to stdout void SourceGenerator::print_action( char *action, int rule, int expand_cpp, char *indent ) { char *m, *p, *l = action; char c; int *rl, length, i, e, k, num; int rpos; if( !langs[language].addLineInfo ) { /* skip #line */ while( *l && strncmp(l,"#line",5) == 0 ) { while( *l && *l != '\n' ) l++; if( *l == '\n' ) l++; } } for( length = 0, rl = gr.rright+gr.rindex[rule]; *rl >= 0; length++, rl++ ); rpos = gr.rindex[rule]; if( gr.sym[gr.rleft[rule]].is_attr ) { ASSERT( length == 0 ); length = gr.sym[gr.rleft[rule]].length; rpos = gr.sym[gr.rleft[rule]].rpos; } while( *l ) { if( *l == '\n' ){ if( !langs[language].addLineInfo && strncmp(l+1,"#line",5) == 0 ) { l++; while( *l && *l != '\n' ) l++; } else { printf( "\n%s", indent ); l++; } } else if( *l == '$' ) { l++; if( *l == '$' ) printf( "lapg_gg.sym" ), l++; else if( *l == '#' ) { l++; if( gr.sym[gr.rleft[rule]].has_attr ) { i = gr.sym[gr.rleft[rule]].sibling; ASSERT( i>=-2 ); if( i >= 0 && gr.sym[i].type ) printf( "((%s)lapg_m[lapg_head-%i].sym)", gr.sym[i].type, length ); else if( i==-1 && gr.sym[gr.rleft[rule]].type ) printf( "((%s)lapg_m[lapg_head-%i].sym)", gr.sym[gr.rleft[rule]].type, length ); else printf( "lapg_m[lapg_head-%i].sym", length ); } else error( 0, "in rule, defined at line %i:\n\twarning: %s has no attributes, $# skipped\n", gr.rlines[rule], gr.sym[gr.rleft[rule]].name ); } else if( *l >= '0' && *l <= '9' ) { for( i = 0; *l >= '0' && *l <= '9'; l++ ) i = i * 10 + (*l - '0'); if( i >= length ) error( 0, "in rule, defined at line %i:\n\telement $%i is absent, skipped\n", gr.rlines[rule], i ); else printf( "lapg_m[lapg_head-%i].sym", length-i-1 ); } else if( *l>='a' && *l<='z' || *l>='A' && *l<='Z' || *l=='_' ) { p = l; while( *l>='a' && *l<='z' || *l>='A' && *l<='Z' || *l>='0' && *l<='9' || *l=='_' ) l++; m = l; i = 0; if( *l == '#' && l[1] >= '0' && l[1] <= '9' ) for( l++; *l >= '0' && *l <= '9'; l++ ) i = i * 10 + (*l - '0'); c = *m; *m = 0; num = i++; if( !strcmp( gr.sym[gr.rleft[rule]].name, p ) ) { i--; e = 0; k = gr.rleft[rule]; } if( i ) for( e = 1, rl = gr.rright+rpos; e <= length; rl++, e++ ) if( !strcmp( gr.sym[*rl].name, p ) ) { k = *rl; if( --i == 0 ) break; } if( !i ) { p = gr.sym[k].type; if( p && !e && expand_cpp ) printf( "*(%s *)&lapg_gg.sym", p ); else { if( p ) printf( "((%s)", p ); if( e ) printf( "lapg_m[lapg_head-%i].sym", length-e ); else printf( "lapg_gg.sym" ); if( p ) printf( ")" ); } } else { error( 0, "in rule, defined at line %i:\n\tidentifier $%s#%i was not found, skipped\n", gr.rlines[rule], p, num ); } *m = c; } else { error( 0, "in rule, defined at line %i:\n\tthe $ sign is skipped\n", gr.rlines[rule] ); } } else if( *l == '@' ) { int endpos = 0; l++; if( *l == '~' ) { l++; endpos = 1; } if( *l == '$' ) { printf( endpos ? "lapg_gg.endpos" : "lapg_gg.pos" ); l++; } else if( *l >= '0' && *l <= '9' ) { for( i = 0; *l >= '0' && *l <= '9'; l++ ) i = i * 10 + (*l - '0'); if( i >= length ) error( 0, "in rule, defined at line %i:\n\telement @%i is absent, skipped\n", gr.rlines[rule], i ); else printf( "lapg_m[lapg_head-%i].%spos", length-i-1, endpos ? "end" : "" ); } else error( 0, "in rule, defined at line %i:\n\tthe @ sign is skipped\n", gr.rlines[rule] ); } else { p = l; while( *l && *l != '$' && *l != '@' && *l != '\n' ) l++; c = *l; *l = 0; printf( "%s", p ); *l = c; } } } // writes preprocessed semantic action for lexem to file void SourceGenerator::print_lexem_action( char *action, char *type, int expand_at, char *indent ) { int i; char *p, *l = action; char c; if( !langs[language].addLineInfo ) { /* skip #line */ while( *l && strncmp(l,"#line",5) == 0 ) { while( *l && *l != '\n' ) l++; if( *l == '\n' ) l++; } } while( *l ) { if( *l == '\n' ){ if( !langs[language].addLineInfo && strncmp(l+1,"#line",5) == 0 ) { l++; while( *l && *l != '\n' ) l++; } else { printf( "\n%s", indent ); l++; } } else if( *l == '$' ) { l++; if( *l == '$' ) printf( "lapg_n.lexem" ), l++; else if( *l == '@' ) printf( "lapg_n.pos" ), l++; else if( *l>='a' && *l<='z' || *l>='A' && *l<='Z' || *l=='_' ) { p = l; while( *l>='a' && *l<='z' || *l>='A' && *l<='Z' || *l>='0' && *l<='9' || *l=='_' ) l++; c = *l; *l = 0; for( i = 0; i < gr.nsyms; i++ ) if( !strcmp( gr.sym[i].name, p ) ) break; if( i == gr.nsyms ) error( 0, "in lexem action: $%s symbol is unknown, skipped\n", p ); else printf( "%i", i ); *l = c; } else error( 0, "in lexem action: the $ sign is skipped\n" ); } else if( *l == '@' ) { l++; if( *l >= '0' && *l <= '9' ) { for( i = 0; *l >= '0' && *l <= '9'; l++ ) i = i * 10 + (*l - '0'); if( i >= BITS || lr.groupset[i] == -1 ) error( 0, "in lexem action: @%i group was not found, skipped\n", i ); else printf( "%i", lr.groupset[i] ); } else { if( type && expand_at ) printf( "*(%s *)&lapg_n.sym", type ); else printf( "lapg_n.sym" ); } } else { p = l; while( *l && *l != '$' && *l != '@' && *l != '\n' ) l++; c = *l; *l = 0; printf( "%s", p ); *l = c; } } } // print part of code void SourceGenerator::print_code( bool last, char *indent ) { enum { SIZE = 16384, LINE = 4096}; char *buffer = new char[SIZE], *maxline = buffer + SIZE; char lineindent[MAXINDENT]; int firstline = 1; int nskip = 0; int nindent = 0; char *p = buffer, *lastline = buffer, *p0 = buffer; while( l < end ) { if( firstline ) { if( *l && (*l == ' ' || *l == '\t') && nindent < MAXINDENT-1) { lineindent[nindent++] = *l; } else { lineindent[nindent] = 0; firstline = 0; } } if( *l == '\n' ) { if( !last && p - lastline == 2 && lastline[0] == '%' && lastline[1] == '%' ) { p = lastline; l++; break; } if( maxline - p <= 2*LINE ) { fwrite( buffer, 1, p - buffer, stdout ); p = lastline = buffer; } *p++ = *l++; nskip = 0; p0 = p; for( char *pfx = indent; *pfx; pfx++ ){ *p++ = *pfx; } lastline = p; } else if( *l == '\r' ) { l++; } else if( nskip < nindent && *l == lineindent[nskip] ) { l++; nskip++; } else { nskip = nindent+1; *p++ = *l++; if( p - lastline >= LINE ) { fwrite( buffer, 1, p - buffer, stdout ); p = lastline = buffer; } } if( l == end ) fillb(); } if( p == lastline ) p = p0; else *p++ = '\n'; if( p - buffer ) fwrite( buffer, 1, p - buffer, stdout ); delete[] buffer; } /***********************************************************************************/ void SourceGenerator::printout() { const char *p, *l = templatedata ? templatedata : langs[language].templ_gen; int action[16], deep = 0; const char *loop[16]; int can_write = 1, denied_at = -1, line = 1; char var[128]; char indent[MAXINDENT]={0}; int nindent = 0; iteration_counter = -2; while( *l ) { for( p = l; *l && *l != '@' && *l != '$'; l++ ) { if( *l == '\n' ) { indent[0] = 0; nindent=0; line++; } else if( nindent < MAXINDENT-1 && (*l==' ' || *l=='\t') ) { indent[nindent] = *l; nindent++; indent[nindent] = 0; } else { nindent = MAXINDENT+1; } } if( l - p && can_write ) fwrite( p, 1, l - p, stdout ); if( *l == '@' ) { bool bracket = false; l++; if( *l == '(' ) { bracket = true; l++; } for( p = l; *l >= '0' && *l <= '9' || *l >= 'a' && *l <= 'z' || *l >= 'A' && *l <= 'Z' || *l == '_'; l++ ); if( l - p > 120 || l == p || bracket && *l != ')') { error( 0, "output_script(%i): @ variable name is wrong\n", line ); return; } strncpy( var, p, l - p ); var[l-p] = 0; if(bracket) l++; if( print_variable( var, indent, can_write ) ) { for( ;*l && *l != '\n'; l++ ); if( *l == '\n' ) l++, line++; } } else if( *l == '$' ) { l++; if( *l == '}' ) { l++; if( !deep ) { error( 0, "output_script(%i): unexpected $}\n", line ); return; } if( action[deep-1] >= 2 ) if( update_vars( action[deep-1]-2 ) ) { l = loop[deep-1]; continue; } else iteration_counter = -2; for( ;*l && *l != '\n'; l++ ); if( *l == '\n' ) l++, line++; deep--; if( deep == denied_at ) { can_write = 1; denied_at = -1; } } else if( *l == '{' ) { if( deep == 16 ) { error( 0, "output_script(%i): too deep\n", line ); return; } for( p = ++l; *l >= '0' && *l <= '9' || *l >= 'a' && *l <= 'z' || *l >= 'A' && *l <= 'Z' || *l == '_'; l++ ); if( l - p > 120 || l == p ) { error( 0, "output_script(%i): ${ variable name is wrong\n", line ); return; } strncpy( var, p, l - p ); var[l-p] = 0; action[deep] = check_variable(var); if( action[deep] == 0 && can_write ) { can_write = 0; denied_at = deep; } for( ;*l && *l != '\n'; l++ ); if( *l == '\n' ) l++, line++; loop[deep] = l; deep++; } else if( *l == '#' ) { for( p = ++l; *l >= '0' && *l <= '9' || *l >= 'a' && *l <= 'z' || *l >= 'A' && *l <= 'Z' || *l == '_'; l++ ); if( l - p > 120 || l == p ) { error( 0, "output_script(%i): $# variable name is wrong\n", line ); return; } strncpy( var, p, l - p ); var[l-p] = 0; int i = check_variable(var); if( i>=2 ) { error( 0, "output_script(%i): $# variable cannot be used in loop\n", line ); return; } if( !i ) { for( ;*l && *l != '\n'; l++ ); if( *l == '\n' ) l++, line++; } } else printf( "$" ); } } if( deep ) error( 0, "output_script(%i): unclosing $} is absent\n", line ); } static const char *at_varlist[] = { "target", /* 0 */ "lstates", "lchars", /* 2 */ "nstates", "next", "nactions", /* 5 */ "nsyms", "gotosize", /* 7 */ "rules", "classname", "errprefix", /* 10 */ "error", "maxtoken", /* 12 */ "maxstack", "char2no", "lexem", /* 15 */ "action", "lalr", /* 17 */ "sym_goto", "sym_from", "sym_to", /* 20 */ "rlen", "rlex", /* 22 */ "syms", "lexemnum", "lexemactioncpp",/* 25 */ "lexemaction", "rulenum", /* 27 */ "ruleactioncpp", "ruleaction", "nativecode", /* 30 */ "nativecodeall", "namespace", /* 32 */ "tokenenum", "parsefunc", "parseargs", "errorfunc", "sourcename", "runtime", "lapgversion", NULL }; static const char *sym_to_string( const char *s, int number ) { static char buffer[4096]; *buffer = 0; if( s[0] == '\'' ) { const char *p = s+1; char *dest = buffer; while( *p && *(p+1) ) { if( *p >= 'a' && *p <= 'z' || *p >= 'A' && *p <= 'Z' || *p == '_' ) *dest++ = *p++; else { char *name = NULL; switch( *p ) { case '{': name = "LBRACE"; break; case '}': name = "RBRACE"; break; case '[': name = "LBRACKET"; break; case ']': name = "RBRACKET"; break; case '(': name = "LROUNDBRACKET"; break; case ')': name = "RROUNDBRACKET"; break; case '.': name = "DOT"; break; case ',': name = "COMMA"; break; case ':': name = "COLON"; break; case ';': name = "SEMICOLON"; break; case '+': name = "PLUS"; break; case '-': name = "MINUS"; break; case '*': name = "MULT"; break; case '/': name = "DIV"; break; case '%': name = "PERC"; break; case '&': name = "AMP"; break; case '|': name = "OR"; break; case '^': name = "XOR"; break; case '!': name = "EXCL"; break; case '~': name = "TILDE"; break; case '=': name = "EQ"; break; case '<': name = "LESS"; break; case '>': name = "GREATER"; break; case '?': name = "QUESTMARK"; break; } if( name ) while( *name ) *dest++ = *name++; else { sprintf( dest, "N%02X", *p ); while( *dest ) dest++; } p++; } } *dest = 0; return buffer; } else if( s[0] == '{' && s[1] == '}' ) { sprintf(buffer,"_sym%i",number); return buffer; } else { return s; } } int SourceGenerator::print_variable( char *var, char *indent, int can_write ) { int i, e; for( i = 0; at_varlist[i]; i++ ) if( !strcmp( var, at_varlist[i] ) ) break; if( !at_varlist[i] ) { error( 0, "output_script: unknown @ variable: %s\n", var ); return 0; } if( !can_write ) return 0; switch( i ) { case 0: /* target */ printf( "%s", targetname ); break; case 1: /* lstates */ printf( "%i", lr.nstates ); break; case 2: /* lchars */ printf( "%i", lr.nchars ); break; case 3: /* nstates */ printf( "%i", gr.nstates ); break; case 4: /* next */ printf( "%s", (getsym)?getsym:"chr=next()" ); break; case 5: /* nactions */ printf( "%i", gr.nactions ); break; case 6: /* nsyms */ printf( "%i", gr.nsyms ); break; case 7: /* gotosize */ printf( "%i", gr.sym_goto[gr.nsyms] ); break; case 8: /* rules */ printf( "%i", gr.rules ); break; case 9: /* classname */ printf( "%s", (classn)?classn:"parser" );break; case 10: /* errprefix */ if( errprefix ) printf( "%s", errprefix ); break; case 11: /* error */ printf( "%i", gr.errorn ); break; case 12: /* maxtoken */ printf( "%i", maxtoken ); break; case 13: /* maxstack */ printf( "%i", maxstack ); break; case 14: /* char2no */ for( i = 0; i < 256; ) { printf( " %3i,", lr.char2no[i] ); if( ++i % 16 == 0 && i < 256 ) printf( "\n%s", indent ); } printf( "\n" ); return 1; case 15: /* lexem */ for( i = 0; i < lr.nstates; i++ ) { if( i ) printf( "%s%s", indent, langs[language].lexem_start); else printf(langs[language].lexem_start ); for( e = 0; e < lr.nchars; e++ ) printf( "%4i,", lr.dta[i]->change[e] ); printf( " %s,\n", langs[language].lexem_end ); } return 1; case 16: /* action */ for( i = 0; i < gr.nstates; i++ ) { if( i && !(i%16) ) printf( "\n%s", indent ); printf( "%4i,", gr.action_index[i] ); } printf( "\n" ); return 1; case 17: /* lalr */ for( i = 0; i < gr.nactions; i++ ) { if( i && !(i%16) ) printf( "\n%s", indent ); printf( "%4i,", gr.action_table[i] ); } printf( "\n" ); return 1; case 18: /* sym_goto */ for( i = 0; i <= gr.nsyms; i++ ) { if( i && !(i%16) ) printf( "\n%s", indent ); printf( "%4i,", gr.sym_goto[i] ); } printf( "\n" ); return 1; case 19: /* sym_from */ for( i = 0; i < gr.sym_goto[gr.nsyms]; i++ ) { if( i && !(i%16) ) printf( "\n%s", indent ); printf( "%4i,", gr.sym_from[i] ); } printf( "\n" ); return 1; case 20: /* sym_to */ for( i = 0; i < gr.sym_goto[gr.nsyms]; i++ ) { if( i && !(i%16) ) printf( "\n%s", indent ); printf( "%4i,", gr.sym_to[i] ); } printf( "\n" ); return 1; case 21: /* rlen */ for( i = 0; i < gr.rules; i++ ) { if( i && !(i%16) ) printf( "\n%s", indent ); for( e = 0; gr.rright[ gr.rindex[i]+e ] >= 0; e++ ); printf( "%4i,", e ); } printf( "\n" ); return 1; case 22: /* rlex */ for( i = 0; i < gr.rules; i++ ) { if( i && !(i%16) ) printf( "\n%s", indent ); printf( "%4i,", gr.rleft[i] ); } printf( "\n" ); return 1; case 23: /* syms */ for( i = 0; i < gr.nsyms; i++ ) printf( "%s\"%s\",\n", i?indent:"", gr.sym[i].name ); return 1; case 24: /* lexemnum */ if( iteration_counter >= 0 && iteration_counter < lr.nterms ) printf( "%i", lr.lnum[iteration_counter] ); else error( 0, "internal: using @%s in wrong loop\n", var ); break; case 25: /* lexemactioncpp */ if( iteration_counter >= 0 && iteration_counter < lr.nterms ) print_lexem_action( lr.lact[iteration_counter], gr.sym[lr.lnum[iteration_counter]].type, 1, indent ); else error( 0, "internal: using @%s in wrong loop\n", var ); break; case 26: /* lexemaction */ if( iteration_counter >= 0 && iteration_counter < lr.nterms ) print_lexem_action( lr.lact[iteration_counter], gr.sym[lr.lnum[iteration_counter]].type, 0, indent ); else error( 0, "internal: using @%s in wrong loop\n", var ); break; case 27: /* rulenum */ if( iteration_counter >= 0 && iteration_counter < gr.rules ) printf( "%i", iteration_counter ); else error( 0, "internal: using @%s in wrong loop\n", var ); break; case 28: /* ruleactioncpp */ if( iteration_counter >= 0 && iteration_counter < gr.rules ) print_action( gr.raction[iteration_counter], iteration_counter, 1, indent ); else error( 0, "internal: using @%s in wrong loop\n", var ); break; case 29: /* ruleaction */ if( iteration_counter >= 0 && iteration_counter < gr.rules ) print_action( gr.raction[iteration_counter], iteration_counter, 0, indent ); else error( 0, "internal: using @%s in wrong loop\n", var ); break; case 30: /* nativecode */ print_code( false, indent ); return 1; case 31: /* nativecodeall */ print_code( true, indent ); return 1; case 32: /* namespace */ printf( "%s", (ns)?ns:"lapg" ); break; case 33: /* tokenenum */ for( i = 0; i < gr.nsyms; i++ ) printf( "%s%s,\n", i?indent:"", sym_to_string(gr.sym[i].name, i) ); return 1; break; case 34: /* parsefunc */ printf( "%s", (parsefunc)?parsefunc:"parse" );break; case 35: /* parseargs */ if( parseargs ) printf( "%s", parseargs );break; case 36: /* errorfunc */ printf( "%s", (errorfunc)?errorfunc:"error" );break; case 37: /* sourcename */ printf( "%s", (sourcename)?sourcename:"<unspecified source>" );break; case 38: /* runtime */ { time_t now; time(&now); struct tm *lt = localtime(&now); printf("%04d-%02d-%02d %02d:%02d:%02d", lt->tm_year+1900,lt->tm_mon+1,lt->tm_mday, lt->tm_hour,lt->tm_min,lt->tm_sec ); } break; case 39: /* lapgversion */ if( lapgversion ) printf( "%s", lapgversion );break; } return 0; } static const char *dollar_varlist[] = { "pos", /* 0 */ "pos0", "pos1", /* 2 */ "pos2", "noterror", "error", /* 5 */ "nactions", "lexemactions", /* 7 */ "ruleactions", "eachlexem", "eachaction", /* 10 */ "lexemend", "pos3", /* 12 */ "breaks", NULL }; // returns: 0:deny, 1:grant, 2...:loop int SourceGenerator::check_variable( char *var ) { int i; for( i = 0; dollar_varlist[i]; i++ ) if( !strcmp( var, dollar_varlist[i] ) ) break; if( !dollar_varlist[i] ) { error( 0, "internal: unknown $ variable: %s\n", var ); return 0; } switch( i ) { case 0: /* pos */ return positioning!=0; case 1: /* pos0 */ return positioning==0; case 2: /* pos1 */ return positioning==1; case 3: /* pos2 */ return positioning==2; case 4: /* noterror */ return gr.errorn==-1; case 5: /* error */ return gr.errorn!=-1; case 6: /* nactions */ return gr.nactions!=0; case 7: /* lexemactions */ for( i = 0; i < lr.nterms; i++ ) if( lr.lact[i] ) return 1; return 0; case 8: /* ruleactions */ for( i = 0; i < gr.rules; i++ ) if( gr.raction[i] ) return 1; return 0; case 9: /* eachlexem */ if( iteration_counter != -2 ) { error( 0, "output_script: using nested loops\n" ); return 0; } iteration_counter = -1; update_vars( 0 ); return 2; case 10: /* eachaction */ if( iteration_counter != -2 ) { error( 0, "output_script: using nested loops\n" ); return 0; } iteration_counter = -1; update_vars( 1 ); return 3; case 11: /* lexemend */ return (lexemend && positioning) ? 1 : 0; case 12: /* pos3 */ return positioning==3; case 13: /* breaks */ return genbreaks ? 1 : 0; } return 0; } int SourceGenerator::update_vars( int type ) { if( iteration_counter == -2 ) { error( 0, "output_script: update vars failed\n" ); return 0; } iteration_counter++; switch( type ) { case 0: for( ; iteration_counter < lr.nterms && !lr.lact[iteration_counter]; iteration_counter++ ); return iteration_counter < lr.nterms; case 1: for( ; iteration_counter < gr.rules && !gr.raction[iteration_counter]; iteration_counter++ ); return iteration_counter < gr.rules; } return 0; } // Templates void SourceGenerator::TemplateFromString() { const char *s = langs[language==-1?0:language].templ_string; if( s ) fwrite( s, 1, strlen(s), stdout ); else fprintf( stderr, "template-from-string absent for %s language\n", langs[language==-1?0:language].lang ); } void SourceGenerator::TemplateFromFile() { const char *s = langs[language==-1?0:language].templ_file; if( s ) fwrite( s, 1, strlen(s), stdout ); else fprintf( stderr, "template-from-file absent for %s language\n", langs[language==-1?0:language].lang ); } void SourceGenerator::printScript() { const char *s = templatedata ? templatedata : langs[language==-1?0:language].templ_gen; fwrite( s, 1, strlen(s), stdout ); }
27.449756
147
0.496446
linz
9048b3c47c2404e45e27a60d05c37ac3f5509ac1
8,181
hxx
C++
OCC/inc/Units_Token.hxx
cy15196/FastCAE
0870752ec2e590f3ea6479e909ebf6c345ac2523
[ "BSD-3-Clause" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/Units_Token.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
33
2019-11-13T18:09:51.000Z
2021-11-26T17:24:12.000Z
opencascade/Units_Token.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1992-06-22 // Created by: Gilles DEBARBOUILLE // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Units_Token_HeaderFile #define _Units_Token_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TCollection_AsciiString.hxx> #include <Standard_Real.hxx> #include <Standard_Transient.hxx> #include <Standard_CString.hxx> #include <Standard_Integer.hxx> #include <Standard_Boolean.hxx> class Units_Dimensions; class Units_Token; DEFINE_STANDARD_HANDLE(Units_Token, Standard_Transient) //! This class defines an elementary word contained in //! a Sentence object. class Units_Token : public Standard_Transient { public: //! Creates and returns a empty token. Standard_EXPORT Units_Token(); //! Creates and returns a token. <aword> is a string //! containing the available word. Standard_EXPORT Units_Token(const Standard_CString aword); //! Creates and returns a token. <atoken> is copied in //! the returned token. Standard_EXPORT Units_Token(const Handle(Units_Token)& atoken); //! Creates and returns a token. <aword> is a string //! containing the available word and <amean> gives the //! signification of the token. Standard_EXPORT Units_Token(const Standard_CString aword, const Standard_CString amean); //! Creates and returns a token. <aword> is a string //! containing the available word, <amean> gives the //! signification of the token and <avalue> is the numeric //! value of the dimension. Standard_EXPORT Units_Token(const Standard_CString aword, const Standard_CString amean, const Standard_Real avalue); //! Creates and returns a token. <aword> is a string //! containing the available word, <amean> gives the //! signification of the token, <avalue> is the numeric //! value of the dimension, and <adimensions> is the //! dimension of the given word <aword>. Standard_EXPORT Units_Token(const Standard_CString aword, const Standard_CString amean, const Standard_Real avalue, const Handle(Units_Dimensions)& adimension); //! Creates and returns a token, which is a ShiftedToken. Standard_EXPORT virtual Handle(Units_Token) Creates() const; //! Returns the length of the word. Standard_EXPORT Standard_Integer Length() const; //! Returns the string <theword> TCollection_AsciiString Word() const; //! Sets the field <theword> to <aword>. void Word (const Standard_CString aword); //! Returns the significance of the word <theword>, which //! is in the field <themean>. TCollection_AsciiString Mean() const; //! Sets the field <themean> to <amean>. void Mean (const Standard_CString amean); //! Returns the value stored in the field <thevalue>. Standard_Real Value() const; //! Sets the field <thevalue> to <avalue>. void Value (const Standard_Real avalue); //! Returns the dimensions of the token <thedimensions>. Handle(Units_Dimensions) Dimensions() const; //! Sets the field <thedimensions> to <adimensions>. Standard_EXPORT void Dimensions (const Handle(Units_Dimensions)& adimensions); //! Updates the token <me> with the additional //! signification <amean> by concatenation of the two //! strings <themean> and <amean>. If the two //! significations are the same , an information message //! is written in the output device. Standard_EXPORT void Update (const Standard_CString amean); Standard_EXPORT Handle(Units_Token) Add (const Standard_Integer aninteger) const; //! Returns a token which is the addition of <me> and //! another token <atoken>. The addition is possible if //! and only if the dimensions are the same. Standard_EXPORT Handle(Units_Token) Add (const Handle(Units_Token)& atoken) const; //! Returns a token which is the subtraction of <me> and //! another token <atoken>. The subtraction is possible if //! and only if the dimensions are the same. Standard_EXPORT Handle(Units_Token) Subtract (const Handle(Units_Token)& atoken) const; //! Returns a token which is the product of <me> and //! another token <atoken>. Standard_EXPORT Handle(Units_Token) Multiply (const Handle(Units_Token)& atoken) const; //! This virtual method is called by the Measurement //! methods, to compute the measurement during a //! conversion. Standard_EXPORT Standard_NODISCARD virtual Standard_Real Multiplied (const Standard_Real avalue) const; //! Returns a token which is the division of <me> by another //! token <atoken>. Standard_EXPORT Handle(Units_Token) Divide (const Handle(Units_Token)& atoken) const; //! This virtual method is called by the Measurement //! methods, to compute the measurement during a //! conversion. Standard_EXPORT Standard_NODISCARD virtual Standard_Real Divided (const Standard_Real avalue) const; //! Returns a token which is <me> to the power of another //! token <atoken>. The computation is possible only if //! <atoken> is a dimensionless constant. Standard_EXPORT Handle(Units_Token) Power (const Handle(Units_Token)& atoken) const; //! Returns a token which is <me> to the power of <anexponent>. Standard_EXPORT Handle(Units_Token) Power (const Standard_Real anexponent) const; //! Returns true if the field <theword> and the string //! <astring> are the same, false otherwise. Standard_EXPORT Standard_Boolean IsEqual (const Standard_CString astring) const; //! Returns true if the field <theword> and the string //! <theword> contained in the token <atoken> are the //! same, false otherwise. Standard_EXPORT Standard_Boolean IsEqual (const Handle(Units_Token)& atoken) const; //! Returns false if the field <theword> and the string //! <astring> are the same, true otherwise. Standard_Boolean IsNotEqual (const Standard_CString astring) const; //! Returns false if the field <theword> and the string //! <theword> contained in the token <atoken> are the //! same, true otherwise. Standard_Boolean IsNotEqual (const Handle(Units_Token)& atoken) const; //! Returns true if the field <theword> is strictly //! contained at the beginning of the string <astring>, //! false otherwise. Standard_Boolean IsLessOrEqual (const Standard_CString astring) const; //! Returns false if the field <theword> is strictly //! contained at the beginning of the string <astring>, //! true otherwise. Standard_Boolean IsGreater (const Standard_CString astring) const; //! Returns false if the field <theword> is strictly //! contained at the beginning of the string <astring>, //! true otherwise. Standard_Boolean IsGreater (const Handle(Units_Token)& atoken) const; //! Returns true if the string <astring> is strictly //! contained at the beginning of the field <theword> //! false otherwise. Standard_Boolean IsGreaterOrEqual (const Handle(Units_Token)& atoken) const; //! Useful for debugging Standard_EXPORT virtual void Dump (const Standard_Integer ashift, const Standard_Integer alevel) const; DEFINE_STANDARD_RTTIEXT(Units_Token,Standard_Transient) protected: private: TCollection_AsciiString theword; TCollection_AsciiString themean; Standard_Real thevalue; Handle(Units_Dimensions) thedimensions; }; #include <Units_Token.lxx> #endif // _Units_Token_HeaderFile
37.700461
162
0.722406
cy15196
90499cec06459321763dd15cb1cd75b010965b2b
752
cpp
C++
performance_tests.cpp
miguelrodriguesdossantos/CellularAutomata
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
[ "MIT" ]
null
null
null
performance_tests.cpp
miguelrodriguesdossantos/CellularAutomata
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
[ "MIT" ]
null
null
null
performance_tests.cpp
miguelrodriguesdossantos/CellularAutomata
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
[ "MIT" ]
null
null
null
#include <iostream> #include <ctime> #include <unistd.h> #include <string> #include "board.hpp" #include "command_line_options.h" using namespace std; using namespace RuleStrings; /* This file exists to aid quick comparison between performances of two branches. */ int main(int argc, char** argv){ srand(time(NULL)); const unsigned int num_iterations = 1E3; // Default values unsigned int vertSize = 800; unsigned int horiSize = 400; double prob = 0.25; std::string ruleString = ConwaysLife_rulestring; Board B( Board::SizeV{vertSize}, Board::SizeH{horiSize}, ruleString); B.setRandom(prob*vertSize*horiSize); for( unsigned int i = 0; i < num_iterations && !B.isStable(); i++){ B.setNext(); } std::cout << B; return 0; }
19.789474
70
0.704787
miguelrodriguesdossantos
904d030a8f72976697d2666c0a1d7e09d800b8c7
3,028
cpp
C++
contracts/test_api/test_api.cpp
NunoEdgarGFlowHub/eos
38c6554f30ea8e755d23b7382bb7511795b1e857
[ "MIT" ]
null
null
null
contracts/test_api/test_api.cpp
NunoEdgarGFlowHub/eos
38c6554f30ea8e755d23b7382bb7511795b1e857
[ "MIT" ]
null
null
null
contracts/test_api/test_api.cpp
NunoEdgarGFlowHub/eos
38c6554f30ea8e755d23b7382bb7511795b1e857
[ "MIT" ]
null
null
null
#include <eoslib/eos.hpp> #include "test_api.hpp" extern "C" { void init() { } void apply( unsigned long long code, unsigned long long action ) { //eos::print("==> CONTRACT: ", code, " ", action, "\n"); //test_types WASM_TEST_HANDLER(test_types, types_size); WASM_TEST_HANDLER(test_types, char_to_symbol); WASM_TEST_HANDLER(test_types, string_to_name); WASM_TEST_HANDLER(test_types, name_class); //test_message WASM_TEST_HANDLER(test_message, read_message); WASM_TEST_HANDLER(test_message, read_message_to_0); WASM_TEST_HANDLER(test_message, read_message_to_64k); WASM_TEST_HANDLER(test_message, require_notice); WASM_TEST_HANDLER(test_message, require_auth); WASM_TEST_HANDLER(test_message, assert_false); WASM_TEST_HANDLER(test_message, assert_true); WASM_TEST_HANDLER(test_message, now); //test_print WASM_TEST_HANDLER(test_print, test_prints); WASM_TEST_HANDLER(test_print, test_printi); WASM_TEST_HANDLER(test_print, test_printi128); WASM_TEST_HANDLER(test_print, test_printn); //test_math WASM_TEST_HANDLER(test_math, test_multeq_i128); WASM_TEST_HANDLER(test_math, test_diveq_i128); WASM_TEST_HANDLER(test_math, test_diveq_i128_by_0); WASM_TEST_HANDLER(test_math, test_double_api); WASM_TEST_HANDLER(test_math, test_double_api_div_0); //test db WASM_TEST_HANDLER(test_db, key_i64_general); WASM_TEST_HANDLER(test_db, key_i64_remove_all); WASM_TEST_HANDLER(test_db, key_i64_small_load); WASM_TEST_HANDLER(test_db, key_i64_small_store); WASM_TEST_HANDLER(test_db, key_i64_store_scope); WASM_TEST_HANDLER(test_db, key_i64_remove_scope); WASM_TEST_HANDLER(test_db, key_i64_not_found); WASM_TEST_HANDLER(test_db, key_i64_front_back); WASM_TEST_HANDLER(test_db, key_i64i64i64_general); WASM_TEST_HANDLER(test_db, key_i128i128_general); //test crypto WASM_TEST_HANDLER(test_crypto, test_sha256); WASM_TEST_HANDLER(test_crypto, sha256_no_data); WASM_TEST_HANDLER(test_crypto, asert_sha256_false); WASM_TEST_HANDLER(test_crypto, asert_sha256_true); WASM_TEST_HANDLER(test_crypto, asert_no_data); //test transaction WASM_TEST_HANDLER(test_transaction, send_message); WASM_TEST_HANDLER(test_transaction, send_message_empty); WASM_TEST_HANDLER(test_transaction, send_message_max); WASM_TEST_HANDLER(test_transaction, send_message_large); WASM_TEST_HANDLER(test_transaction, send_message_recurse); WASM_TEST_HANDLER(test_transaction, send_message_inline_fail); WASM_TEST_HANDLER(test_transaction, send_transaction); WASM_TEST_HANDLER(test_transaction, send_transaction_empty); WASM_TEST_HANDLER(test_transaction, send_transaction_max); WASM_TEST_HANDLER(test_transaction, send_transaction_large); //unhandled test call WASM_TEST_ERROR_CODE = WASM_TEST_FAIL; } }
37.85
69
0.749339
NunoEdgarGFlowHub
904d96d7037f2c9f627651a8ec09f6f645fdf18c
2,055
cc
C++
cplusplus/MemoryEvolve/Tadpole/TestLexer.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
22
2015-05-18T07:04:36.000Z
2021-08-02T03:01:43.000Z
cplusplus/MemoryEvolve/Tadpole/TestLexer.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
1
2017-08-31T22:13:57.000Z
2017-09-05T15:00:25.000Z
cplusplus/MemoryEvolve/Tadpole/TestLexer.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
6
2015-06-06T07:16:12.000Z
2021-07-06T13:45:56.000Z
// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <Core/MEvolve.hh> #include <Tadpole/Lexer.hh> _MEVO_TEST(TadpoleLexer, _mevo::FakeTester) { auto token_repr = [](const _mevo::tadpole::Token& tok) { std::fprintf(stdout, "%-16s|%4d|%s\n", _mevo::tadpole::get_token_name(tok.kind()), tok.lineno(), tok.literal().c_str()); }; _mevo::str_t source_bytes = "// test case for Lexer\n" "var a = 34;\n" "var b = 56.43;\n" "var c = (a + b) * a / b;\n" "print(\"calculate value is: \", c);\n" ; _mevo::tadpole::Lexer lex(source_bytes); for (;;) { auto tok = lex.next_token(); token_repr(tok); if (tok.kind() == _mevo::tadpole::TokenKind::TK_EOF) break; } }
38.055556
71
0.701703
ASMlover
904de316d86f53af738469b6c0987d5d272883a0
246
hpp
C++
src/LibCraft/renderEngine/include/vbo.hpp
Kenny38GH/Test
24c0277de8f98a3b0b3b8a90a300a321a485684c
[ "MIT" ]
null
null
null
src/LibCraft/renderEngine/include/vbo.hpp
Kenny38GH/Test
24c0277de8f98a3b0b3b8a90a300a321a485684c
[ "MIT" ]
null
null
null
src/LibCraft/renderEngine/include/vbo.hpp
Kenny38GH/Test
24c0277de8f98a3b0b3b8a90a300a321a485684c
[ "MIT" ]
null
null
null
// // Created by leodlplq on 18/11/2021. // #pragma once #include "Vertex.hpp" #include "glad/glad.h" class vbo { public: GLuint _id; vbo(Vertex* vertices, GLsizeiptr size); void bind(); void unbind(); void deleteVbo(); };
13.666667
43
0.626016
Kenny38GH
9050ea50a92900b5722b9fe58d727d08f672df64
7,537
hpp
C++
Computer_Vision/Revision_DIP_Linear_and_Softmax_Regression/spatial_filtering/blob_detection_using_LoG.hpp
AlazzR/Computer-Vision-Cpp-ML
725ad6830341a2ed2ff088d50cb99b7f9117783b
[ "CC0-1.0" ]
null
null
null
Computer_Vision/Revision_DIP_Linear_and_Softmax_Regression/spatial_filtering/blob_detection_using_LoG.hpp
AlazzR/Computer-Vision-Cpp-ML
725ad6830341a2ed2ff088d50cb99b7f9117783b
[ "CC0-1.0" ]
null
null
null
Computer_Vision/Revision_DIP_Linear_and_Softmax_Regression/spatial_filtering/blob_detection_using_LoG.hpp
AlazzR/Computer-Vision-Cpp-ML
725ad6830341a2ed2ff088d50cb99b7f9117783b
[ "CC0-1.0" ]
null
null
null
#ifndef __BLOB_DETECTION__ #define __BLOB_DETECTION__ #include<iostream> #include<opencv4/opencv2/opencv.hpp> #include<opencv4/opencv2/imgproc.hpp> #include<cmath> #include<vector> #include<utility> #include<array> cv::Mat creating_LoF(const float sigma) { int kernel_size = std::ceil( 6 * sigma ); if(kernel_size%2 == 0) kernel_size -= 1; if(kernel_size == 0) kernel_size = 3; cv::Mat kernel = cv::Mat::zeros(cv::Size(kernel_size, kernel_size), CV_32FC1); std::cout << "Kernel size " << kernel.size() << std::endl; //equation from http://fourier.eng.hmc.edu/e161/lectures/gradient/node8.html float* ptrRow; float sum = 0.0f; for(int row=0; row < kernel.rows; row++) { ptrRow = kernel.ptr<float>(row); for(int col=0; col < kernel.cols; col++) { float c = ( std::pow(row - kernel_size/2,2) + std::pow(col - kernel_size/2,2) - 2 * sigma * sigma)/ ( std::sqrt(2* M_PI * sigma * sigma ) * std::pow(sigma, 4)); float exponent = -1.0f * ((std::pow(row - kernel_size/2,2) + std::pow(col - kernel_size/2,2))/ (2 * sigma * sigma)); ptrRow[col] = std::pow(sigma, 2) * c * std::exp(exponent);//normalized sigma sum += ptrRow[col]; } } // std::cout << kernel << std::endl; // std::cout << sum << std::endl; return kernel; } cv::Mat convolution(const cv::Mat& img, const cv::Mat& kernel, const float sigma) { //I will assume that the kernel is the LoG kernel //i.e no need to rotate the matrix 180 because LoG is already symmetric int k = (kernel.rows - 1)/2; int square_img = img.rows >= img.cols? img.rows: img.cols; cv::Mat padded_img = cv::Mat(cv::Size(square_img + 2 * k, square_img + 2 * k), CV_32FC1); img.copyTo(padded_img(cv::Rect(k, k, img.cols, img.rows)));//notice flip in size const uchar* ptrImg; float* ptrPaddedImg; for(int row=k; row < padded_img.rows - k; row++) { ptrImg = img.ptr<uchar>(row - k); ptrPaddedImg = padded_img.ptr<float>(row); for(int col=k; col < padded_img.cols - k; col++) { float sum=0.0f; for(int i=-k; i <=k; i++) { for(int j=-k; j <=k; j++) { sum += ptrImg[col - k + j] * kernel.at<float>(i + k, j + k); } } ptrPaddedImg[col] = sum; } } padded_img = padded_img(cv::Rect(k, k, img.cols, img.rows)); cv::Mat unnormalized = padded_img.clone(); cv::normalize(padded_img, padded_img, 0, 255, cv::NORM_MINMAX, CV_8UC1); cv::imwrite("../spatial_filtering/results/blob_detection_" + std::to_string(sigma) + "_" + std::to_string(kernel.rows) + "x" + std::to_string(kernel.cols) + ".jpg", padded_img); //cv::imshow("filtered image", padded_img); //cv::waitKey(0); return unnormalized; } std::vector<cv::Mat> pyramid(const cv::Mat& img, const float initial_sigma, const float scale_factor, const int pyramid_depth) { std::vector<cv::Mat> levels; float sigma = initial_sigma; for(int i=1; i<= pyramid_depth; i++) { std::cout << "level " << i << std::endl; cv::Mat kernel = creating_LoF(sigma); cv::Mat result = convolution(img, kernel, sigma); sigma = scale_factor * sigma; levels.push_back(result); } return levels; } std::vector<std::array<float, 3>> non_maximum_suppression(std::vector<cv::Mat>& levels, const float threshold, int window_size, const float initial_sigma, const float scale_factor) { std::vector<std::array<float, 3>> interest_points; if(window_size%2 == 0) window_size = window_size - 1; if(window_size == 0) window_size = 3; cv::Mat window = cv::Mat::zeros(window_size, window_size, CV_32FC1); int k = (window_size - 1)/2; std::cout << levels[0].size() << std::endl; //pad images in pyramid for(auto& level: levels) cv::copyMakeBorder(level, level, 2 * k, 2 * k, 2 * k, 2 * k, cv::BORDER_CONSTANT, 0); std::cout << levels[0].size() << std::endl; //non-overlapping windows for(int row=k; row < levels[0].rows - 2 * k; row+=window_size) { for(int col=k; col < levels[0].cols - 2 * k; col+=window_size) { int counter = 1; float putative_match[3] = {0, 0, 0}; double max = 0.0f; for(auto& img: levels) { window = img(cv::Rect(col, row, window_size, window_size));//notice the flip double max_v; cv::Point maxP; cv::minMaxLoc(window, (double*)0, &max_v, (cv::Point*) 0, &maxP); if(max <= max_v) { max = max_v; if(max_v >= threshold) { putative_match[0] = maxP.y + row;//row putative_match[1] = maxP.x + col;//notice the flip // col putative_match[2] = std::pow(scale_factor, counter) * initial_sigma * std::sqrt(2);//radius //std::cout << "x: " << putative_match[1] << " y: " << putative_match[0] << " r: " << putative_match[2] << std::endl; } } counter++; } std::array<float, 3> tmp = { putative_match[0], putative_match[1], putative_match[2] } ; if(putative_match[0] != 0 && putative_match[1] != 0 && putative_match[2] != 0) interest_points.push_back(tmp); } } return interest_points; } void blob_detector(const cv::Mat& img, const float initial_sigma, const float scale_factor=1.3f, const int pyramid_depth=5, const float threshold=0.0f, int window_size = 3) { int square = img.rows >= img.cols? img.rows: img.cols; cv::Mat grayscale = cv::Mat::zeros(cv::Size(square, square), CV_8UC1); img.copyTo(grayscale(cv::Rect(0, 0, img.cols, img.rows)));//notice the flip std::vector<cv::Mat> levels = pyramid(grayscale, initial_sigma, scale_factor, pyramid_depth); std::vector<std::array<float, 3>> interest_points = non_maximum_suppression(levels, threshold, window_size, initial_sigma, scale_factor); // cv::Mat imageWithColor = cv::Mat::zeros(cv::Size(square, square), CV_8UC3); // std::vector<cv::Mat> channels(3); // cv::split(imageWithColor, channels); // channels[0] = grayscale; channels[1] = grayscale; channels[2] = grayscale; std::cout << grayscale.channels() << std::endl; cv::cvtColor(grayscale, grayscale, cv::COLOR_GRAY2BGR); //opencv use BGR order for channels, I don't want to cvtColor for(auto& point: interest_points) { //std::cout << "x: " << point[1] << " y: " << point[0] << " r: " << point[2] << std::endl; cv::circle(grayscale, cv::Point(point[1], point[0]), point[2], cv::Scalar(0, 0, 255)); } // cv::resize(channels[0], channels[0], cv::Size(img.cols, img.rows)); // cv::resize(channels[1], channels[1], cv::Size(img.cols, img.rows)); // cv::resize(channels[2], channels[2], cv::Size(img.cols, img.rows)); // cv::merge(channels, grayscale); grayscale = grayscale(cv::Rect(0, 0, img.cols, img.rows));//notice the flip std::cout << grayscale.channels() << std::endl; cv::imshow("image with blob", grayscale); cv::waitKey(0); cv::imwrite("../spatial_filtering/results/blob_detection_with_blobs.jpg", grayscale); } #endif /*__BLOB_DETECTION__*/
40.304813
181
0.578081
AlazzR
90526583d33f42e4cb48d68d13bddcf18ace9937
4,058
cpp
C++
src/engine.cpp
dendisuhubdy/crypto_derivative_exchange
cb250062898b7f984ff708ad76ad7d8c9853e824
[ "FSFAP" ]
null
null
null
src/engine.cpp
dendisuhubdy/crypto_derivative_exchange
cb250062898b7f984ff708ad76ad7d8c9853e824
[ "FSFAP" ]
null
null
null
src/engine.cpp
dendisuhubdy/crypto_derivative_exchange
cb250062898b7f984ff708ad76ad7d8c9853e824
[ "FSFAP" ]
null
null
null
/***************************************************************************** * QuantCup 1: Price-Time Matching Engine * * Submitted by: voyager * * Design Overview: * In this implementation, the limit order book is represented using * a flat linear array (pricePoints), indexed by the numeric price value. * Each entry in this array corresponds to a specific price point and holds * an instance of struct pricePoint. This data structure maintains a list * of outstanding buy/sell orders at the respective price. Each outstanding * limit order is represented by an instance of struct orderBookEntry. * * askMin and bidMax are global variables that maintain starting points, * at which the matching algorithm initiates its search. * askMin holds the lowest price that contains at least one outstanding * sell order. Analogously, bidMax represents the maximum price point that * contains at least one outstanding buy order. * * When a Buy order arrives, we search the book for outstanding Sell orders * that cross with the incoming order. We start the search at askMin and * proceed upwards, incrementing askMin until: * a) The incoming Buy order is filled. * b) We reach a price point that no longer crosses with the incoming * limit price (askMin > BuyOrder.price) * In case b), we create a new orderBookEntry to record the * remainder of the incoming Buy order and add it to the global order * book by appending it to the list at pricePoints[BuyOrder.price]. * * Incoming Sell orders are handled analogously, except that we start at * bidMax and proceed downwards. * * Although this matching algorithm runs in linear time and may, in * degenerate cases, require scanning a large number of array slots, * it appears to work reasonably well in practice, at least on the * simulated data feed (score_feed.h). The vast majority of incoming * limit orders can be handled by examining no more than two distinct * price points and no order requires examining more than five price points. * * To avoid incurring the costs of dynamic heap-based memory allocation, * this implementation maintains the full set of orderBookEntry instances * in a statically-allocated contiguous memory arena (arenaBookEntries). * Allocating a new entry is simply a matter of bumping up the orderID * counter (curOrderID) and returning a pointer to *arenaBookEntries[curOrderID]. * * To cancel an order, we simply set its size to zero. Notably, we avoid * unhooking its orderBookEntry from the list of active orders in order to * avoid incurring the costs of pointer manipulation and conditional branches. * This allows us to handle order cancellation requests very efficiently; the * current implementation requires only one memory store instruction on * x86_64. During order matching, when we walk the list of outstanding orders, * we simply skip these zero-sized entries. * * The current implementation uses a custom version of strcpy() to copy the *string * fields ("symbol" and "trader") between data structures. This custom version * has been optimized for the case STRINGLEN=5 and implements loop unrolling * to eliminate the use of induction variables and conditional branching. * * The memory layout of struct orderBookEntry has been optimized for * efficient cache access. *****************************************************************************/ #include <stdio.h> #include <strings.h> #include <stdlib.h> #include <vector> #include <iostream> #include "engine.h" #include "order_book.h" #include <boost/intrusive/slist.hpp> #include <boost/intrusive/list.hpp> #include "util.h" void init() { OB::OrderBook::get().initialize(); } void destroy() { OB::OrderBook::get().shutdown(); } /* Process an incoming limit order */ t_orderid limit(t_order order) { return OB::OrderBook::get().limit(order); } /* Cancel an outstanding order */ void cancel(t_orderid orderid) { OB::OrderBook::get().cancel(orderid); }
47.741176
79
0.71587
dendisuhubdy
9058c32c9e0687f92a2d7900dfca1577e17609aa
549
cpp
C++
src/bindings/python/src/pyopenvino/graph/ops/util/binary_elementwise_logical.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
runtime/bindings/python/src/pyopenvino/graph/ops/util/binary_elementwise_logical.cpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
runtime/bindings/python/src/pyopenvino/graph/ops/util/binary_elementwise_logical.cpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "openvino/op/util/binary_elementwise_logical.hpp" #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pyopenvino/graph/ops/util/binary_elementwise_logical.hpp" namespace py = pybind11; void regclass_graph_op_util_BinaryElementwiseLogical(py::module m) { py::class_<ov::op::util::BinaryElementwiseLogical, std::shared_ptr<ov::op::util::BinaryElementwiseLogical>> binaryElementwiseLogical(m, "BinaryElementwiseLogical"); }
30.5
111
0.777778
pazamelin
905ccef4d64f7a9377cfdea51c4fdf8b71306e51
4,052
cpp
C++
src/libstringintern/string_page_nursery.cpp
RipcordSoftware/libstringintern
565ec0ca40f40fbe63fbeb2a9ed9ea03038218a0
[ "MIT" ]
13
2017-05-31T05:32:49.000Z
2021-12-07T19:05:47.000Z
src/libstringintern/string_page_nursery.cpp
RipcordSoftware/libstringintern
565ec0ca40f40fbe63fbeb2a9ed9ea03038218a0
[ "MIT" ]
11
2016-05-30T16:48:28.000Z
2017-08-25T21:04:13.000Z
src/libstringintern/string_page_nursery.cpp
RipcordSoftware/libstringintern
565ec0ca40f40fbe63fbeb2a9ed9ea03038218a0
[ "MIT" ]
2
2021-07-27T08:45:11.000Z
2021-12-07T19:09:54.000Z
/** * The MIT License (MIT) * * Copyright (c) 2016 Ripcord Software Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "string_page_nursery.h" #include "string_page_sizes.h" #include <algorithm> rs::stringintern::StringPageNursery::StringPageNursery(colcount_t cols, rowcount_t rows, pagesize_t pageSize, NewPageFunc newPageFunc) : rows_(rows), cols_(cols), pageSize_(pageSize), counters_(rows), data_(rows * cols), newPageFunc_(newPageFunc) { std::for_each(counters_.begin(), counters_.end(), [&](decltype(counters_[0])& c) { c.store(0, std::memory_order_relaxed); }); } rs::stringintern::StringPagePtr rs::stringintern::StringPageNursery::New(rowcount_t row) { auto entrySize = StringPageSizes::GetEntrySize(row); auto entryCount = pageSize_ / entrySize; auto newPage = newPageFunc_(row, entryCount, entrySize); auto col = counters_[row].fetch_add(1, std::memory_order_relaxed); auto dataIndex = (cols_ * row) + (col % cols_); data_[dataIndex].exchange(newPage, std::memory_order_relaxed); return newPage; } rs::stringintern::StringPagePtr rs::stringintern::StringPageNursery::Get(colcount_t col, rowcount_t row) { auto dataIndex = (cols_ * row) + (col % cols_); auto page = data_[dataIndex]; if (!page) { page = New(row); } return page; } rs::stringintern::StringPagePtr rs::stringintern::StringPageNursery::Get(colcount_t col, rowcount_t row) const { auto dataIndex = (cols_ * row) + (col % cols_); auto page = data_[dataIndex]; return page; } rs::stringintern::StringPageNursery::Iterator rs::stringintern::StringPageNursery::Iter(rowcount_t row) const noexcept { Iterator iter; if (row < rows_) { auto start = counters_[row].load(std::memory_order_relaxed); start = start > cols_ ? (start % cols_) : 0; iter = Iterator{cols_, row, start}; } return iter; } rs::stringintern::StringPagePtr rs::stringintern::StringPageNursery::Next(Iterator& iter) { if (!!iter) { auto col = iter++; return Get(col, iter.row_); } else { return StringPagePtr{}; } } std::vector<rs::stringintern::StringPagePtr> rs::stringintern::StringPageNursery::GetPages(rowcount_t row) const { std::vector<StringPagePtr> pages; auto cols = counters_[row].load(std::memory_order_relaxed); cols = cols > cols_ ? cols_ : cols; for (decltype(cols) i = 0; i < cols; ++i) { auto page = Get(i, row); if (!!page) { pages.emplace_back(std::move(page)); } } return pages; } std::vector<rs::stringintern::StringPage::entrycount_t> rs::stringintern::StringPageNursery::GetPageEntryCounts(rowcount_t row) const { std::vector<StringPage::entrycount_t> entries; auto pages = GetPages(row); for (auto page : pages) { if (!!page) { auto count = page->GetEntryCount(); entries.push_back(count); } } return entries; }
35.858407
136
0.6846
RipcordSoftware
905cf4a1e2bc0950d4d88f65fe0459084531c95d
1,578
cpp
C++
HW5/BoardArray1D.cpp
melihcanclk/CSE-241-Homeworks
270ad02749086bf830d8d6c51fc8f0729321996b
[ "MIT" ]
null
null
null
HW5/BoardArray1D.cpp
melihcanclk/CSE-241-Homeworks
270ad02749086bf830d8d6c51fc8f0729321996b
[ "MIT" ]
null
null
null
HW5/BoardArray1D.cpp
melihcanclk/CSE-241-Homeworks
270ad02749086bf830d8d6c51fc8f0729321996b
[ "MIT" ]
1
2021-12-30T20:11:05.000Z
2021-12-30T20:11:05.000Z
#include <iostream> #include <fstream> #include "BoardArray1D.h" using namespace std; void BoardArray1D::setSize(int coordinates[2]){ int index=1; AbstractClass::setSize(coordinates); (this->arr) = new int[size[1] * size[0]]; for(int i = 0; i < size[1]; ++i){ for(int j = 0; j < size[0]; ++j){ (*this)(j,i) = index; index++; } } arr[(size[0] * size[1]) -1] = -1; } void BoardArray1D::readFromFile(char *argv){ if(size[0] >0 || size[1]){ delete [] arr; } int coordinates[2],k=0; ifstream infile(argv); if(!infile.is_open()){ cout << "File couldn't be open." << "\n"; } string pString; calculateXandY(argv,coordinates); setSize(coordinates); for (int i = 0; i < coordinates[1] * coordinates[0]; i++) { infile >> pString; arr[i] = convertStringToInt(pString); } infile.close(); } const int &BoardArray1D::operator()(int x,int y)const { /*rvalue*/ if(x>=0 && x< size[0] && y>=0 && y< size[1]){ return arr[size[0] * y + x]; }else{ cout << "This coordinate is not valid." << endl; } } int &BoardArray1D::operator()(int x,int y) { /*lvalue*/ if(x>=0 && x<size[0] && y>=0 && y< size[1]){ return arr[size[0] * y + x]; }else{ cout << "This coordinate is not valid." << endl; } } void BoardArray1D::reset(){ AbstractClass::reset(); arr[(size[0] * size[1]) -1] = -1; } BoardArray1D::~BoardArray1D() { delete [] arr; } BoardArray1D::BoardArray1D()= default;
24.276923
68
0.536755
melihcanclk
905d99eda51c401b3210f38cc77d711274747bcd
53,452
cpp
C++
examples_tests/11.LoDSystem/main.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
examples_tests/11.LoDSystem/main.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
examples_tests/11.LoDSystem/main.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h #define _NBL_STATIC_LIB_ #include <nabla.h> #include "../common/Camera.hpp" #include "../common/CommonAPI.h" #include "nbl/ext/ScreenShot/ScreenShot.h" using namespace nbl; using namespace core; using namespace system; using namespace asset; using namespace ui; using lod_library_t = scene::CLevelOfDetailLibrary<>; using culling_system_t = scene::ICullingLoDSelectionSystem; struct LoDLibraryData { core::vector<uint32_t> drawCallOffsetsIn20ByteStrides; core::vector<uint32_t> drawCountOffsets; core::vector<asset::DrawElementsIndirectCommand_t> drawCallData; core::vector<uint32_t> drawCountData; core::vector<uint32_t> lodInfoDstUvec2s; core::vector<uint32_t> lodTableDstUvec4s; scene::ILevelOfDetailLibrary::InfoContainerAdaptor<lod_library_t::LoDInfo> lodInfoData; scene::ILevelOfDetailLibrary::InfoContainerAdaptor<scene::ILevelOfDetailLibrary::LoDTableInfo> lodTableData; }; enum E_GEOM_TYPE { EGT_CUBE, EGT_SPHERE, EGT_CYLINDER, EGT_COUNT }; template<E_GEOM_TYPE geom, uint32_t LoDLevels> void addLoDTable( IAssetManager* assetManager, const core::smart_refctd_ptr<ICPUDescriptorSetLayout>& cpuTransformTreeDSLayout, const core::smart_refctd_ptr<ICPUDescriptorSetLayout>& cpuPerViewDSLayout, const core::smart_refctd_ptr<ICPUSpecializedShader>* shaders, nbl::video::IGPUObjectFromAssetConverter::SParams& cpu2gpuParams, LoDLibraryData& lodLibraryData, video::CDrawIndirectAllocator<>* drawIndirectAllocator, lod_library_t* lodLibrary, core::vector<video::CSubpassKiln::DrawcallInfo>& drawcallInfos, const SBufferRange<video::IGPUBuffer>& perInstanceRedirectAttribs, const core::smart_refctd_ptr<video::IGPURenderpass>& renderpass, const video::IGPUDescriptorSet* transformTreeDS, const core::smart_refctd_ptr<video::IGPUDescriptorSet>& perViewDS ) { constexpr auto perInstanceRedirectAttrID = 15u; auto* const geometryCreator = assetManager->getGeometryCreator(); auto* const meshManipulator = assetManager->getMeshManipulator(); core::smart_refctd_ptr<ICPURenderpassIndependentPipeline> cpupipeline; core::smart_refctd_ptr<ICPUMeshBuffer> cpumeshes[LoDLevels]; for (uint32_t poly = 4u, lod = 0u; lod < LoDLevels; lod++) { IGeometryCreator::return_type geomData; switch (geom) { case EGT_CUBE: geomData = geometryCreator->createCubeMesh(core::vector3df(2.f)); break; case EGT_SPHERE: geomData = geometryCreator->createSphereMesh(2.f, poly, poly, meshManipulator); break; case EGT_CYLINDER: geomData = geometryCreator->createCylinderMesh(1.f, 4.f, poly, 0x0u, meshManipulator); break; default: assert(false); break; } // we'll stick instance data refs in the last attribute binding assert((geomData.inputParams.enabledBindingFlags >> perInstanceRedirectAttrID) == 0u); geomData.inputParams.enabledAttribFlags |= 0x1u << perInstanceRedirectAttrID; geomData.inputParams.enabledBindingFlags |= 0x1u << perInstanceRedirectAttrID; geomData.inputParams.attributes[perInstanceRedirectAttrID].binding = perInstanceRedirectAttrID; geomData.inputParams.attributes[perInstanceRedirectAttrID].relativeOffset = 0u; geomData.inputParams.attributes[perInstanceRedirectAttrID].format = asset::EF_R32G32_UINT; geomData.inputParams.bindings[perInstanceRedirectAttrID].inputRate = asset::EVIR_PER_INSTANCE; geomData.inputParams.bindings[perInstanceRedirectAttrID].stride = asset::getTexelOrBlockBytesize(asset::EF_R32G32_UINT); if (!cpupipeline) { auto pipelinelayout = core::make_smart_refctd_ptr<ICPUPipelineLayout>( nullptr, nullptr, core::smart_refctd_ptr(cpuTransformTreeDSLayout), core::smart_refctd_ptr(cpuPerViewDSLayout) ); SRasterizationParams rasterParams = {}; if (geom == EGT_CYLINDER) rasterParams.faceCullingMode = asset::EFCM_NONE; cpupipeline = core::make_smart_refctd_ptr<ICPURenderpassIndependentPipeline>( std::move(pipelinelayout), &shaders->get(), &shaders->get() + 2u, geomData.inputParams, SBlendParams{}, geomData.assemblyParams, rasterParams ); } cpumeshes[lod] = core::make_smart_refctd_ptr<ICPUMeshBuffer>(); cpumeshes[lod]->setPipeline(core::smart_refctd_ptr(cpupipeline)); cpumeshes[lod]->setIndexType(geomData.indexType); cpumeshes[lod]->setIndexCount(geomData.indexCount); cpumeshes[lod]->setIndexBufferBinding(std::move(geomData.indexBuffer)); for (auto j = 0u; j < ICPUMeshBuffer::MAX_ATTR_BUF_BINDING_COUNT; j++) cpumeshes[lod]->setVertexBufferBinding(asset::SBufferBinding(geomData.bindings[j]), j); poly <<= 1u; } auto gpumeshes = video::CAssetPreservingGPUObjectFromAssetConverter().getGPUObjectsFromAssets(cpumeshes, cpumeshes + LoDLevels, cpu2gpuParams); core::smart_refctd_ptr<video::IGPUGraphicsPipeline> pipeline; { video::IGPUGraphicsPipeline::SCreationParams params; params.renderpass = renderpass; params.renderpassIndependent = core::smart_refctd_ptr_dynamic_cast<video::IGPURenderpassIndependentPipeline>(assetManager->findGPUObject(cpupipeline.get())); params.subpassIx = 0u; pipeline = cpu2gpuParams.device->createGPUGraphicsPipeline(nullptr, std::move(params)); } auto drawcallInfosOutIx = drawcallInfos.size(); drawcallInfos.resize(drawcallInfos.size() + gpumeshes->size()); core::aabbox3df aabb(FLT_MAX, FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX); lod_library_t::LoDInfo prevInfo; for (auto lod = 0u; lod < gpumeshes->size(); lod++) { auto gpumb = gpumeshes->operator[](lod); auto& di = drawcallInfos[drawcallInfosOutIx++]; memcpy(di.pushConstantData, gpumb->getPushConstantsDataPtr(), video::IGPUMeshBuffer::MAX_PUSH_CONSTANT_BYTESIZE); di.pipeline = pipeline; std::fill_n(di.descriptorSets, video::IGPUPipelineLayout::DESCRIPTOR_SET_COUNT, nullptr); di.descriptorSets[0] = core::smart_refctd_ptr<const video::IGPUDescriptorSet>(transformTreeDS); di.descriptorSets[1] = perViewDS; di.indexType = gpumb->getIndexType(); std::copy_n(gpumb->getVertexBufferBindings(), perInstanceRedirectAttrID, di.vertexBufferBindings); di.vertexBufferBindings[perInstanceRedirectAttrID] = { perInstanceRedirectAttribs.offset,perInstanceRedirectAttribs.buffer }; di.indexBufferBinding = gpumb->getIndexBufferBinding().buffer; di.drawCommandStride = sizeof(asset::DrawElementsIndirectCommand_t); di.drawCountOffset = video::IDrawIndirectAllocator::invalid_draw_count_ix; di.drawCallOffset = video::IDrawIndirectAllocator::invalid_draw_range_begin; di.drawMaxCount = 0u; video::IDrawIndirectAllocator::Allocation mdiAlloc; mdiAlloc.count = 1u; mdiAlloc.multiDrawCommandRangeByteOffsets = &di.drawCallOffset; mdiAlloc.multiDrawCommandMaxCounts = &di.drawMaxCount; mdiAlloc.multiDrawCommandCountOffsets = &di.drawCountOffset; mdiAlloc.setAllCommandStructSizesConstant(di.drawCommandStride); // small enough batches that they could use 16-bit indices // the dispatcher gains above 4k triangles per batch are asymptotic // we could probably use smaller batches if we implemented drawcall compaction // (we wouldn't pay for the extra drawcalls generated by batches that have no instances) // if the culling system was to be used together with occlusion culling, we could use smaller batch sizes constexpr auto indicesPerBatch = 3u << 12u; const auto indexCount = gpumb->getIndexCount(); const auto batchCount = di.drawMaxCount = (indexCount - 1u) / indicesPerBatch + 1u; lodLibraryData.drawCountData.emplace_back(di.drawMaxCount); const bool success = drawIndirectAllocator->allocateMultiDraws(mdiAlloc); assert(success); lodLibraryData.drawCountOffsets.emplace_back(di.drawCountOffset); di.drawCountOffset *= sizeof(uint32_t); // auto& lodInfo = lodLibraryData.lodInfoData.emplace_back(batchCount); if (lod) { lodInfo = lod_library_t::LoDInfo(batchCount, { 129600.f / exp2f(lod << 1) }); if (!lodInfo.isValid(prevInfo)) { assert(false && "THE LEVEL OF DETAIL CHOICE PARAMS NEED TO BE MONOTONICALLY DECREASING"); exit(0x45u); } } else lodInfo = lod_library_t::LoDInfo(batchCount, { 2250000.f }); prevInfo = lodInfo; // size_t indexSize; switch (gpumb->getIndexType()) { case EIT_16BIT: indexSize = sizeof(uint16_t); break; case EIT_32BIT: indexSize = sizeof(uint32_t); break; default: assert(false); break; } auto batchID = 0u; for (auto i = 0u; i < indexCount; i += indicesPerBatch, batchID++) { auto& drawCallData = lodLibraryData.drawCallData.emplace_back(); drawCallData.count = core::min(indexCount-i,indicesPerBatch); drawCallData.instanceCount = 0u; drawCallData.firstIndex = gpumb->getIndexBufferBinding().offset/indexSize+i; drawCallData.baseVertex = 0u; drawCallData.baseInstance = 0xdeadbeefu; // set to garbage to test the prefix sum lodLibraryData.drawCallOffsetsIn20ByteStrides.emplace_back(di.drawCallOffset / di.drawCommandStride + batchID); core::aabbox3df batchAABB; { // temporarily change the base vertex and index count to make AABB computation easier auto mb = cpumeshes[lod].get(); auto oldBinding = mb->getIndexBufferBinding(); const auto oldIndexCount = mb->getIndexCount(); mb->setIndexBufferBinding({ oldBinding.offset + i * indexSize,oldBinding.buffer }); mb->setIndexCount(drawCallData.count); batchAABB = IMeshManipulator::calculateBoundingBox(mb); mb->setIndexCount(oldIndexCount); mb->setIndexBufferBinding(std::move(oldBinding)); } aabb.addInternalBox(batchAABB); const uint32_t drawCallDWORDOffset = (di.drawCallOffset + batchID * di.drawCommandStride) / sizeof(uint32_t); lodInfo.drawcallInfos[batchID] = scene::ILevelOfDetailLibrary::DrawcallInfo( drawCallDWORDOffset, batchAABB ); } } auto& lodTable = lodLibraryData.lodTableData.emplace_back(LoDLevels); lodTable = scene::ILevelOfDetailLibrary::LoDTableInfo(LoDLevels, aabb); std::fill_n(lodTable.leveInfoUvec2Offsets, LoDLevels, scene::ILevelOfDetailLibrary::invalid); { lod_library_t::Allocation::LevelInfoAllocation lodLevelAllocations[1] = { lodTable.leveInfoUvec2Offsets, lodLibraryData.drawCountData.data() + lodLibraryData.drawCountData.size() - LoDLevels }; uint32_t lodTableOffsets[1u] = { scene::ILevelOfDetailLibrary::invalid }; const uint32_t lodLevelCounts[1u] = { LoDLevels }; // lod_library_t::Allocation alloc = {}; { alloc.count = 1u; alloc.tableUvec4Offsets = lodTableOffsets; alloc.levelCounts = lodLevelCounts; alloc.levelAllocations = lodLevelAllocations; } const bool success = lodLibrary->allocateLoDs(alloc); assert(success); for (auto i = 0u; i < scene::ILevelOfDetailLibrary::LoDTableInfo::getSizeInAlignmentUnits(LoDLevels); i++) lodLibraryData.lodTableDstUvec4s.push_back(lodTableOffsets[0] + i); for (auto lod = 0u; lod < LoDLevels; lod++) { const auto drawcallCount = lodLevelAllocations[0].drawcallCounts[lod]; const auto offset = lodLevelAllocations[0].levelUvec2Offsets[lod]; for (auto i = 0u; i < lod_library_t::LoDInfo::getSizeInAlignmentUnits(drawcallCount); i++) lodLibraryData.lodInfoDstUvec2s.push_back(offset + i); } } cpu2gpuParams.waitForCreationToComplete(); } #include <random> #include "assets/common.glsl" class LoDSystemApp : public ApplicationBase { _NBL_STATIC_INLINE_CONSTEXPR uint32_t WIN_W = 1600; _NBL_STATIC_INLINE_CONSTEXPR uint32_t WIN_H = 900; _NBL_STATIC_INLINE_CONSTEXPR uint32_t FBO_COUNT = 1u; _NBL_STATIC_INLINE_CONSTEXPR uint32_t FRAMES_IN_FLIGHT = 5u; static_assert(FRAMES_IN_FLIGHT > FBO_COUNT); // lod table entries _NBL_STATIC_INLINE_CONSTEXPR auto MaxDrawables = EGT_COUNT; // all the lod infos from all lod entries _NBL_STATIC_INLINE_CONSTEXPR auto MaxTotalLoDs = 8u * MaxDrawables; // how many contiguous ranges of drawcalls with explicit draw counts _NBL_STATIC_INLINE_CONSTEXPR auto MaxMDIs = 16u; // how many drawcalls (meshlets) _NBL_STATIC_INLINE_CONSTEXPR auto MaxDrawCalls = 256u; // how many instances _NBL_STATIC_INLINE_CONSTEXPR auto MaxInstanceCount = 1677721u; // absolute max for Intel HD Graphics on Windows (to keep within 128MB SSBO limit) // maximum visible instances of a drawcall (should be a sum of MaxLoDDrawcalls[t]*MaxInstances[t] where t iterates over all LoD Tables) _NBL_STATIC_INLINE_CONSTEXPR auto MaxTotalVisibleDrawcallInstances = MaxInstanceCount + (MaxInstanceCount >> 8u); // This is literally my worst case guess of how many batch-draw-instances there will be on screen at the same time public: void setWindow(core::smart_refctd_ptr<nbl::ui::IWindow>&& wnd) override { window = std::move(wnd); } void setSystem(core::smart_refctd_ptr<nbl::system::ISystem>&& s) override { system = std::move(s); } nbl::ui::IWindow* getWindow() override { return window.get(); } video::IAPIConnection* getAPIConnection() override { return gl.get(); } video::ILogicalDevice* getLogicalDevice() override { return logicalDevice.get(); } video::IGPURenderpass* getRenderpass() override { return renderpass.get(); } void setSurface(core::smart_refctd_ptr<video::ISurface>&& s) override { surface = std::move(s); } void setFBOs(std::vector<core::smart_refctd_ptr<video::IGPUFramebuffer>>& f) override { for (int i = 0; i < f.size(); i++) { fbos[i] = core::smart_refctd_ptr(f[i]); } } void setSwapchain(core::smart_refctd_ptr<video::ISwapchain>&& s) override { swapchain = std::move(s); } uint32_t getSwapchainImageCount() override { return FBO_COUNT; } virtual nbl::asset::E_FORMAT getDepthFormat() override { return nbl::asset::EF_D32_SFLOAT; } APP_CONSTRUCTOR(LoDSystemApp) void onAppInitialized_impl() override { initOutput.window = core::smart_refctd_ptr(window); initOutput.system = core::smart_refctd_ptr(system); const auto swapchainImageUsage = static_cast<asset::IImage::E_USAGE_FLAGS>(asset::IImage::EUF_COLOR_ATTACHMENT_BIT | asset::IImage::EUF_TRANSFER_DST_BIT); const video::ISurface::SFormat surfaceFormat(asset::EF_B8G8R8A8_SRGB, asset::ECP_COUNT, asset::EOTF_UNKNOWN); CommonAPI::InitWithDefaultExt(initOutput, video::EAT_OPENGL_ES, "Level of Detail System", WIN_W, WIN_H, FBO_COUNT, swapchainImageUsage, surfaceFormat, asset::EF_D32_SFLOAT); window = std::move(initOutput.window); gl = std::move(initOutput.apiConnection); surface = std::move(initOutput.surface); gpuPhysicalDevice = std::move(initOutput.physicalDevice); logicalDevice = std::move(initOutput.logicalDevice); queues = std::move(initOutput.queues); swapchain = std::move(initOutput.swapchain); renderpass = std::move(initOutput.renderpass); fbos = std::move(initOutput.fbo); commandPools = std::move(initOutput.commandPools); assetManager = std::move(initOutput.assetManager); logger = std::move(initOutput.logger); inputSystem = std::move(initOutput.inputSystem); system = std::move(initOutput.system); windowCallback = std::move(initOutput.windowCb); cpu2gpuParams = std::move(initOutput.cpu2gpuParams); utilities = std::move(initOutput.utilities); transferUpQueue = queues[CommonAPI::InitOutput::EQT_TRANSFER_UP]; ttm = scene::ITransformTreeManager::create(utilities.get(),transferUpQueue); tt = scene::ITransformTreeWithNormalMatrices::create(logicalDevice.get(),MaxInstanceCount); const auto* ctt = tt.get(); // fight compiler, hard const video::IPropertyPool* nodePP = ctt->getNodePropertyPool(); asset::SBufferRange<video::IGPUBuffer> nodeList; // Drawcall Allocator { video::IDrawIndirectAllocator::ImplicitBufferCreationParameters drawAllocatorParams; drawAllocatorParams.device = logicalDevice.get(); drawAllocatorParams.maxDrawCommandStride = sizeof(asset::DrawElementsIndirectCommand_t); drawAllocatorParams.drawCommandCapacity = MaxDrawCalls; drawAllocatorParams.drawCountCapacity = MaxMDIs; drawIndirectAllocator = video::CDrawIndirectAllocator<>::create(std::move(drawAllocatorParams)); } // LoD Library lodLibrary = lod_library_t::create({ logicalDevice.get(),MaxDrawables,MaxTotalLoDs,MaxDrawCalls }); // Culling System core::smart_refctd_ptr<video::IDescriptorPool> cullingDSPool; cullPushConstants.instanceCount = 0u; { constexpr auto LayoutCount = 4u; core::smart_refctd_ptr<video::IGPUDescriptorSetLayout> layouts[LayoutCount] = { scene::ILevelOfDetailLibrary::createDescriptorSetLayout(logicalDevice.get()), culling_system_t::createInputDescriptorSetLayout(logicalDevice.get()), culling_system_t::createOutputDescriptorSetLayout(logicalDevice.get()), [&]() -> core::smart_refctd_ptr<video::IGPUDescriptorSetLayout> { // TODO: figure out what should be here constexpr auto BindingCount = 1u; video::IGPUDescriptorSetLayout::SBinding bindings[BindingCount]; for (auto i = 0u; i < BindingCount; i++) { bindings[i].binding = i; bindings[i].type = asset::EDT_STORAGE_BUFFER; bindings[i].count = 1u; bindings[i].stageFlags = asset::IShader::ESS_COMPUTE; bindings[i].samplers = nullptr; } return logicalDevice->createGPUDescriptorSetLayout(bindings,bindings + BindingCount); }() }; cullingDSPool = logicalDevice->createDescriptorPoolForDSLayouts(video::IDescriptorPool::ECF_NONE, &layouts->get(), &layouts->get() + LayoutCount); const asset::SPushConstantRange range = { asset::IShader::ESS_COMPUTE,0u,sizeof(CullPushConstants_t) }; cullingSystem = culling_system_t::create( core::smart_refctd_ptr<video::CScanner>(utilities->getDefaultScanner()), &range, &range + 1u, core::smart_refctd_ptr(layouts[3]), localInputCWD, "\n#include \"common.glsl\"\n", "\n#include \"cull_overrides.glsl\"\n" ); cullingParams.indirectDispatchParams = { 0ull,culling_system_t::createDispatchIndirectBuffer(utilities.get(),transferUpQueue) }; { video::IGPUBuffer::SCreationParams params; params.usage = asset::IBuffer::EUF_STORAGE_BUFFER_BIT; nodeList = {0ull,~0ull,logicalDevice->createDeviceLocalGPUBufferOnDedMem(params,sizeof(uint32_t)+sizeof(scene::ITransformTree::node_t)*MaxInstanceCount)}; nodeList.buffer->setObjectDebugName("transformTreeNodeList"); cullingParams.instanceList = {0ull,~0ull,logicalDevice->createDeviceLocalGPUBufferOnDedMem(params,sizeof(culling_system_t::InstanceToCull)*MaxInstanceCount)}; } cullingParams.scratchBufferRanges = culling_system_t::createScratchBuffer(utilities->getDefaultScanner(), MaxInstanceCount, MaxTotalVisibleDrawcallInstances); cullingParams.drawCalls = drawIndirectAllocator->getDrawCommandMemoryBlock(); cullingParams.perViewPerInstance = { 0ull,~0ull,culling_system_t::createPerViewPerInstanceDataBuffer<PerViewPerInstance_t>(logicalDevice.get(),MaxInstanceCount) }; cullingParams.perInstanceRedirectAttribs = { 0ul,~0ull,culling_system_t::createInstanceRedirectBuffer(logicalDevice.get(),MaxTotalVisibleDrawcallInstances) }; const auto drawCountsBlock = drawIndirectAllocator->getDrawCountMemoryBlock(); if (drawCountsBlock) cullingParams.drawCounts = *drawCountsBlock; cullingParams.lodLibraryDS = core::smart_refctd_ptr<video::IGPUDescriptorSet>(lodLibrary->getDescriptorSet()); cullingParams.transientOutputDS = culling_system_t::createOutputDescriptorSet( logicalDevice.get(), cullingDSPool.get(), std::move(layouts[2]), cullingParams.drawCalls, cullingParams.perViewPerInstance, cullingParams.perInstanceRedirectAttribs, cullingParams.drawCounts ); cullingParams.customDS = logicalDevice->createGPUDescriptorSet(cullingDSPool.get(), std::move(layouts[3])); { video::IGPUDescriptorSet::SWriteDescriptorSet write; video::IGPUDescriptorSet::SDescriptorInfo info(nodePP->getPropertyMemoryBlock(scene::ITransformTree::global_transform_prop_ix)); write.dstSet = cullingParams.customDS.get(); write.binding = 0u; write.arrayElement = 0u; write.count = 1u; write.descriptorType = EDT_STORAGE_BUFFER; write.info = &info; logicalDevice->updateDescriptorSets(1u, &write, 0u, nullptr); } cullingParams.indirectDispatchParams.buffer->setObjectDebugName("CullingIndirect"); cullingParams.drawCalls.buffer->setObjectDebugName("DrawCallPool"); cullingParams.perInstanceRedirectAttribs.buffer->setObjectDebugName("PerInstanceInputAttribs"); if (cullingParams.drawCounts.buffer) cullingParams.drawCounts.buffer->setObjectDebugName("DrawCountPool"); cullingParams.perViewPerInstance.buffer->setObjectDebugName("DrawcallInstanceRedirects"); cullingParams.indirectInstanceCull = false; } core::smart_refctd_ptr<ICPUSpecializedShader> shaders[2]; { IAssetLoader::SAssetLoadParams lp; lp.workingDirectory = localInputCWD; lp.logger = logger.get(); auto vertexShaderBundle = assetManager->getAsset("mesh.vert", lp); auto fragShaderBundle = assetManager->getAsset("mesh.frag", lp); shaders[0] = IAsset::castDown<ICPUSpecializedShader>(*vertexShaderBundle.getContents().begin()); shaders[1] = IAsset::castDown<ICPUSpecializedShader>(*fragShaderBundle.getContents().begin()); } core::smart_refctd_ptr<video::IGPUDescriptorSet> perViewDS; core::smart_refctd_ptr<ICPUDescriptorSetLayout> cpuPerViewDSLayout; { constexpr auto BindingCount = 1; ICPUDescriptorSetLayout::SBinding cpuBindings[BindingCount]; for (auto i = 0; i < BindingCount; i++) { cpuBindings[i].binding = i; cpuBindings[i].count = 1u; cpuBindings[i].stageFlags = IShader::ESS_VERTEX; cpuBindings[i].samplers = nullptr; } cpuBindings[0].type = EDT_STORAGE_BUFFER; cpuPerViewDSLayout = core::make_smart_refctd_ptr<ICPUDescriptorSetLayout>(cpuBindings, cpuBindings + BindingCount); auto bindings = reinterpret_cast<video::IGPUDescriptorSetLayout::SBinding*>(cpuBindings); auto perViewDSLayout = logicalDevice->createGPUDescriptorSetLayout(bindings, bindings + BindingCount); auto dsPool = logicalDevice->createDescriptorPoolForDSLayouts(video::IDescriptorPool::ECF_NONE, &perViewDSLayout.get(), &perViewDSLayout.get() + 1u); perViewDS = logicalDevice->createGPUDescriptorSet(dsPool.get(), std::move(perViewDSLayout)); { video::IGPUDescriptorSet::SWriteDescriptorSet writes[BindingCount]; video::IGPUDescriptorSet::SDescriptorInfo infos[BindingCount]; for (auto i = 0; i < BindingCount; i++) { writes[i].dstSet = perViewDS.get(); writes[i].binding = i; writes[i].arrayElement = 0u; writes[i].count = 1u; writes[i].info = infos + i; } writes[0].descriptorType = EDT_STORAGE_BUFFER; infos[0].desc = cullingParams.perViewPerInstance.buffer; infos[0].buffer = { 0u,video::IGPUDescriptorSet::SDescriptorInfo::SBufferInfo::WholeBuffer }; logicalDevice->updateDescriptorSets(BindingCount, writes, 0u, nullptr); } } // descset for global tform updates { auto layout = ttm->createRecomputeGlobalTransformsDescriptorSetLayout(logicalDevice.get()); auto pool = logicalDevice->createDescriptorPoolForDSLayouts(video::IDescriptorPool::ECF_NONE,&layout.get(),&layout.get()+1u); recomputeGlobalTransformsDS = logicalDevice->createGPUDescriptorSet(pool.get(),std::move(layout)); ttm->updateRecomputeGlobalTransformsDescriptorSet(logicalDevice.get(),recomputeGlobalTransformsDS.get(),{0ull,nodeList.buffer}); } std::mt19937 mt(0x45454545u); std::uniform_int_distribution<uint32_t> typeDist(0, EGT_COUNT - 1u); std::uniform_real_distribution<float> rotationDist(0, 2.f * core::PI<float>()); std::uniform_real_distribution<float> posDist(-1200.f, 1200.f); { video::CSubpassKiln kiln; { LoDLibraryData lodLibraryData; uint32_t lodTables[EGT_COUNT]; // create all the LoDs of drawables { auto* qnc = assetManager->getMeshManipulator()->getQuantNormalCache(); //loading cache from file const system::path cachePath = sharedOutputCWD / "normalCache101010.sse"; if (!qnc->loadCacheFromFile<asset::EF_A2B10G10R10_SNORM_PACK32>(system.get(), cachePath)) int a = 0;// logger->log("%s", ILogger::ELL_ERROR, "Couldn't load cache."); // core::smart_refctd_ptr<asset::ICPUDescriptorSetLayout> cpuTransformTreeDSLayout = scene::ITransformTreeWithNormalMatrices::createRenderDescriptorSetLayout(); // populating `lodTables` is a bit messy, I know size_t lodTableIx = lodLibraryData.lodTableDstUvec4s.size(); addLoDTable<EGT_CUBE, 1>( assetManager.get(), cpuTransformTreeDSLayout, cpuPerViewDSLayout, shaders, cpu2gpuParams, lodLibraryData, drawIndirectAllocator.get(), lodLibrary.get(), kiln.getDrawcallMetadataVector(), cullingParams.perInstanceRedirectAttribs, renderpass, ctt->getRenderDescriptorSet(), perViewDS ); lodTables[EGT_CUBE] = lodLibraryData.lodTableDstUvec4s[lodTableIx]; lodTableIx = lodLibraryData.lodTableDstUvec4s.size(); addLoDTable<EGT_SPHERE, 7>( assetManager.get(), cpuTransformTreeDSLayout, cpuPerViewDSLayout, shaders, cpu2gpuParams, lodLibraryData, drawIndirectAllocator.get(), lodLibrary.get(), kiln.getDrawcallMetadataVector(), cullingParams.perInstanceRedirectAttribs, renderpass, ctt->getRenderDescriptorSet(), perViewDS ); lodTables[EGT_SPHERE] = lodLibraryData.lodTableDstUvec4s[lodTableIx]; lodTableIx = lodLibraryData.lodTableDstUvec4s.size(); addLoDTable<EGT_CYLINDER, 6>( assetManager.get(), cpuTransformTreeDSLayout, cpuPerViewDSLayout, shaders, cpu2gpuParams, lodLibraryData, drawIndirectAllocator.get(), lodLibrary.get(), kiln.getDrawcallMetadataVector(), cullingParams.perInstanceRedirectAttribs, renderpass, ctt->getRenderDescriptorSet(), perViewDS ); lodTables[EGT_CYLINDER] = lodLibraryData.lodTableDstUvec4s[lodTableIx]; //! cache results -- speeds up mesh generation on second run qnc->saveCacheToFile<asset::EF_A2B10G10R10_SNORM_PACK32>(system.get(), cachePath); } constexpr auto MaxTransfers = 8u; video::CPropertyPoolHandler::UpStreamingRequest upstreamRequests[MaxTransfers]; // set up the instance list core::vector<scene::ITransformTree::node_t> instanceGUIDs( std::uniform_int_distribution<uint32_t>(MaxInstanceCount >> 1u, MaxInstanceCount)(mt), // Instance Count scene::ITransformTree::invalid_node ); const uint32_t objectCount = instanceGUIDs.size(); core::vector<core::matrix3x4SIMD> instanceTransforms(objectCount); for (auto& tform : instanceTransforms) { tform.setRotation(core::quaternion(rotationDist(mt), rotationDist(mt), rotationDist(mt))); tform.setTranslation(core::vectorSIMDf(posDist(mt), posDist(mt), posDist(mt))); } { tt->allocateNodes({instanceGUIDs.data(),instanceGUIDs.data()+objectCount}); utilities->updateBufferRangeViaStagingBuffer(transferUpQueue,{0u,sizeof(uint32_t),nodeList.buffer},&objectCount); utilities->updateBufferRangeViaStagingBuffer(transferUpQueue,{sizeof(uint32_t),objectCount*sizeof(scene::ITransformTree::node_t),nodeList.buffer},instanceGUIDs.data()); scene::ITransformTreeManager::UpstreamRequest request; request.tree = tt.get(); request.parents = {}; // no parents request.relativeTransforms.device2device = false; request.relativeTransforms.data = instanceTransforms.data(); // TODO: make an `UpstreamRequest` which allows for sourcing the node list from GPUBuffer request.nodes = {instanceGUIDs.data(),instanceGUIDs.data()+objectCount}; ttm->setupTransfers(request,upstreamRequests); core::vector<culling_system_t::InstanceToCull> instanceList; instanceList.reserve(objectCount); for (auto instanceGUID : instanceGUIDs) { auto& instance = instanceList.emplace_back(); instance.instanceGUID = instanceGUID; instance.lodTableUvec4Offset = lodTables[typeDist(mt)]; } utilities->updateBufferRangeViaStagingBuffer(transferUpQueue, { 0u,instanceList.size()*sizeof(culling_system_t::InstanceToCull),cullingParams.instanceList.buffer }, instanceList.data()); cullPushConstants.instanceCount += instanceList.size(); } cullingParams.drawcallCount = lodLibraryData.drawCallData.size(); // do the transfer of drawcall and LoD data { constexpr auto TTMTransfers = scene::ITransformTreeManager::TransferCount; for (auto i=TTMTransfers; i<MaxTransfers; i++) { upstreamRequests[i].fill = false; upstreamRequests[i].source.device2device = false; upstreamRequests[i].srcAddresses = nullptr; // iota 0,1,2,3,4,etc. } upstreamRequests[TTMTransfers + 0].destination = drawIndirectAllocator->getDrawCommandMemoryBlock(); upstreamRequests[TTMTransfers + 0].elementSize = sizeof(asset::DrawElementsIndirectCommand_t); upstreamRequests[TTMTransfers + 0].elementCount = cullingParams.drawcallCount; upstreamRequests[TTMTransfers + 0].source.data = lodLibraryData.drawCallData.data(); upstreamRequests[TTMTransfers + 0].dstAddresses = lodLibraryData.drawCallOffsetsIn20ByteStrides.data(); upstreamRequests[TTMTransfers + 1].destination = lodLibrary->getLoDInfoBinding(); upstreamRequests[TTMTransfers + 1].elementSize = alignof(lod_library_t::LoDInfo); upstreamRequests[TTMTransfers + 1].elementCount = lodLibraryData.lodInfoDstUvec2s.size(); upstreamRequests[TTMTransfers + 1].source.data = lodLibraryData.lodInfoData.data(); upstreamRequests[TTMTransfers + 1].dstAddresses = lodLibraryData.lodInfoDstUvec2s.data(); upstreamRequests[TTMTransfers + 2].destination = lodLibrary->getLodTableInfoBinding(); upstreamRequests[TTMTransfers + 2].elementSize = alignof(scene::ILevelOfDetailLibrary::LoDTableInfo); upstreamRequests[TTMTransfers + 2].elementCount = lodLibraryData.lodTableDstUvec4s.size(); upstreamRequests[TTMTransfers + 2].source.data = lodLibraryData.lodTableData.data(); upstreamRequests[TTMTransfers + 2].dstAddresses = lodLibraryData.lodTableDstUvec4s.data(); auto requestCount = TTMTransfers + 3u; if (drawIndirectAllocator->getDrawCountMemoryBlock()) { upstreamRequests[requestCount].destination = *drawIndirectAllocator->getDrawCountMemoryBlock(); upstreamRequests[requestCount].elementSize = sizeof(uint32_t); upstreamRequests[requestCount].elementCount = lodLibraryData.drawCountOffsets.size(); upstreamRequests[requestCount].source.data = lodLibraryData.drawCountData.data(); upstreamRequests[requestCount].dstAddresses = lodLibraryData.drawCountOffsets.data(); requestCount++; } core::smart_refctd_ptr<video::IGPUCommandBuffer> tferCmdBuf; logicalDevice->createCommandBuffers(commandPools[CommonAPI::InitOutput::EQT_TRANSFER_UP].get(), video::IGPUCommandBuffer::EL_PRIMARY, 1u, &tferCmdBuf); auto fence = logicalDevice->createFence(video::IGPUFence::ECF_UNSIGNALED); tferCmdBuf->begin(0u); // TODO some one time submit bit or something { auto ppHandler = utilities->getDefaultPropertyPoolHandler(); asset::SBufferBinding<video::IGPUBuffer> scratch; { video::IGPUBuffer::SCreationParams scratchParams = {}; scratchParams.canUpdateSubRange = true; scratchParams.usage = core::bitflag(video::IGPUBuffer::EUF_TRANSFER_DST_BIT) | video::IGPUBuffer::EUF_STORAGE_BUFFER_BIT; scratch = { 0ull,logicalDevice->createDeviceLocalGPUBufferOnDedMem(scratchParams,ppHandler->getMaxScratchSize()) }; scratch.buffer->setObjectDebugName("Scratch Buffer"); } auto* pRequests = upstreamRequests; uint32_t waitSemaphoreCount = 0u; video::IGPUSemaphore* const* waitSemaphores = nullptr; const asset::E_PIPELINE_STAGE_FLAGS* waitStages = nullptr; ppHandler->transferProperties( utilities->getDefaultUpStreamingBuffer(), tferCmdBuf.get(), fence.get(), transferUpQueue, scratch, pRequests, requestCount, waitSemaphoreCount, waitSemaphores, waitStages, logger.get(), std::chrono::high_resolution_clock::time_point::max() // must finish ); } // also clear the scratch cullingSystem->clearScratch(tferCmdBuf.get(),cullingParams.scratchBufferRanges.lodDrawCallCounts,cullingParams.scratchBufferRanges.prefixSumScratch); tferCmdBuf->end(); { video::IGPUQueue::SSubmitInfo submit = {}; // intializes all semaphore stuff to 0 and nullptr submit.commandBufferCount = 1u; submit.commandBuffers = &tferCmdBuf.get(); transferUpQueue->submit(1u, &submit, fence.get()); } logicalDevice->blockForFences(1u, &fence.get()); } // set up the remaining descriptor sets of the culling system { auto& drawCallOffsetsInDWORDs = lodLibraryData.drawCallOffsetsIn20ByteStrides; for (auto i = 0u; i < cullingParams.drawcallCount; i++) drawCallOffsetsInDWORDs[i] = lodLibraryData.drawCallOffsetsIn20ByteStrides[i] * sizeof(asset::DrawElementsIndirectCommand_t) / sizeof(uint32_t); cullingParams.transientInputDS = culling_system_t::createInputDescriptorSet( logicalDevice.get(), cullingDSPool.get(), culling_system_t::createInputDescriptorSetLayout(logicalDevice.get()), cullingParams.indirectDispatchParams, cullingParams.instanceList, cullingParams.scratchBufferRanges, { 0ull,~0ull,utilities->createFilledDeviceLocalGPUBufferOnDedMem(transferUpQueue,cullingParams.drawcallCount * sizeof(uint32_t),drawCallOffsetsInDWORDs.data()) }, { 0ull,~0ull,utilities->createFilledDeviceLocalGPUBufferOnDedMem(transferUpQueue,lodLibraryData.drawCountOffsets.size() * sizeof(uint32_t),lodLibraryData.drawCountOffsets.data()) } ); } } // prerecord the secondary cmdbuffer { logicalDevice->createCommandBuffers(commandPools[CommonAPI::InitOutput::EQT_GRAPHICS].get(), video::IGPUCommandBuffer::EL_SECONDARY, 1u, &bakedCommandBuffer); bakedCommandBuffer->begin(video::IGPUCommandBuffer::EU_RENDER_PASS_CONTINUE_BIT | video::IGPUCommandBuffer::EU_SIMULTANEOUS_USE_BIT); // TODO: handle teh offsets auto drawCountBlock = drawIndirectAllocator->getDrawCountMemoryBlock(); kiln.bake(bakedCommandBuffer.get(), renderpass.get(), 0u, drawIndirectAllocator->getDrawCommandMemoryBlock().buffer.get(), drawIndirectAllocator->supportsMultiDrawIndirectCount() ? drawCountBlock->buffer.get():nullptr); bakedCommandBuffer->end(); } } core::vectorSIMDf cameraPosition(0, 5, -10); matrix4SIMD projectionMatrix = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(60.0f), float(WIN_W) / WIN_H, 2.f, 4000.f); { cullPushConstants.fovDilationFactor = decltype(lod_library_t::LoDInfo::choiceParams)::getFoVDilationFactor(projectionMatrix); // dilate by resolution as well, because the LoD distances were tweaked @ 720p cullPushConstants.fovDilationFactor *= float(window->getWidth() * window->getHeight()) / float(1280u * 720u); } camera = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), projectionMatrix, 2.f, 1.f); oracle.reportBeginFrameRecord(); logicalDevice->createCommandBuffers(commandPools[CommonAPI::InitOutput::EQT_GRAPHICS].get(), video::IGPUCommandBuffer::EL_PRIMARY, FRAMES_IN_FLIGHT, commandBuffers); for (uint32_t i = 0u; i < FRAMES_IN_FLIGHT; i++) { imageAcquire[i] = logicalDevice->createSemaphore(); renderFinished[i] = logicalDevice->createSemaphore(); } } void onAppTerminated_impl() override { lodLibrary->clear(); drawIndirectAllocator->clear(); const auto& fboCreationParams = fbos[acquiredNextFBO]->getCreationParameters(); auto gpuSourceImageView = fboCreationParams.attachments[0]; bool status = ext::ScreenShot::createScreenShot( logicalDevice.get(), queues[CommonAPI::InitOutput::EQT_TRANSFER_DOWN], renderFinished[resourceIx].get(), gpuSourceImageView.get(), assetManager.get(), "ScreenShot.png", asset::EIL_PRESENT_SRC, static_cast<asset::E_ACCESS_FLAGS>(0u)); assert(status); } void workLoopBody() override { ++resourceIx; if (resourceIx >= FRAMES_IN_FLIGHT) resourceIx = 0; auto& commandBuffer = commandBuffers[resourceIx]; auto& fence = frameComplete[resourceIx]; if (fence) logicalDevice->blockForFences(1u, &fence.get()); else fence = logicalDevice->createFence(static_cast<video::IGPUFence::E_CREATE_FLAGS>(0)); // commandBuffer->reset(nbl::video::IGPUCommandBuffer::ERF_RELEASE_RESOURCES_BIT); commandBuffer->begin(0); // late latch input const auto nextPresentationTimestamp = oracle.acquireNextImage(swapchain.get(), imageAcquire[resourceIx].get(), nullptr, &acquiredNextFBO); // input { inputSystem->getDefaultMouse(&mouse); inputSystem->getDefaultKeyboard(&keyboard); camera.beginInputProcessing(nextPresentationTimestamp); mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); }, logger.get()); keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { camera.keyboardProcess(events); }, logger.get()); camera.endInputProcessing(nextPresentationTimestamp); } // update transforms { // buffers to barrier video::IGPUCommandBuffer::SBufferMemoryBarrier barriers[scene::ITransformTreeManager::SBarrierSuggestion::MaxBufferCount]; auto setBufferBarrier = [&barriers,commandBuffer](const uint32_t ix, const asset::SBufferRange<video::IGPUBuffer>& range, const asset::SMemoryBarrier& barrier) { barriers[ix].barrier = barrier; barriers[ix].dstQueueFamilyIndex = barriers[ix].srcQueueFamilyIndex = commandBuffer->getQueueFamilyIndex(); barriers[ix].buffer = range.buffer; barriers[ix].offset = range.offset; barriers[ix].size = range.size; }; // not going to barrier between last frame culling and rendering and TTM recompute, because its not in the same submit scene::ITransformTreeManager::BaseParams baseParams; baseParams.cmdbuf = commandBuffer.get(); baseParams.tree = tt.get(); baseParams.logger = logger.get(); scene::ITransformTreeManager::DispatchParams dispatchParams; dispatchParams.indirect.buffer = nullptr; dispatchParams.direct.nodeCount = cullPushConstants.instanceCount; ttm->recomputeGlobalTransforms(baseParams,dispatchParams,recomputeGlobalTransformsDS.get()); // barrier between TTM recompute and TTM recompute+culling system { const auto* ctt = tt.get(); auto node_pp = ctt->getNodePropertyPool(); auto sugg = scene::ITransformTreeManager::barrierHelper(scene::ITransformTreeManager::SBarrierSuggestion::EF_POST_GLOBAL_TFORM_RECOMPUTE); sugg.dstStageMask |= asset::EPSF_VERTEX_SHADER_BIT; // also rendering shader (to read the normal matrix transforms) uint32_t barrierCount = 0u; setBufferBarrier(barrierCount++,node_pp->getPropertyMemoryBlock(scene::ITransformTree::global_transform_prop_ix),sugg.globalTransforms); setBufferBarrier(barrierCount++,node_pp->getPropertyMemoryBlock(scene::ITransformTree::recomputed_stamp_prop_ix),sugg.recomputedTimestamps); setBufferBarrier(barrierCount++,node_pp->getPropertyMemoryBlock(scene::ITransformTreeWithNormalMatrices::normal_matrix_prop_ix),sugg.normalMatrices); commandBuffer->pipelineBarrier(sugg.srcStageMask,sugg.dstStageMask,asset::EDF_NONE,0u,nullptr,barrierCount,barriers,0u,nullptr); } } // cull, choose LoDs, and fill our draw indirects { const auto* layout = cullingSystem->getInstanceCullAndLoDSelectLayout(); cullPushConstants.viewProjMat = camera.getConcatenatedMatrix(); std::copy_n(camera.getPosition().pointer, 3u, cullPushConstants.camPos.comp); commandBuffer->pushConstants(layout, asset::IShader::ESS_COMPUTE, 0u, sizeof(cullPushConstants), &cullPushConstants); cullingParams.cmdbuf = commandBuffer.get(); cullingSystem->processInstancesAndFillIndirectDraws(cullingParams,cullPushConstants.instanceCount); } // renderpass { asset::SViewport viewport; viewport.minDepth = 1.f; viewport.maxDepth = 0.f; viewport.x = 0u; viewport.y = 0u; viewport.width = WIN_W; viewport.height = WIN_H; commandBuffer->setViewport(0u, 1u, &viewport); nbl::video::IGPUCommandBuffer::SRenderpassBeginInfo beginInfo; { VkRect2D area; area.offset = { 0,0 }; area.extent = { WIN_W, WIN_H }; asset::SClearValue clear[2] = {}; clear[0].color.float32[0] = 1.f; clear[0].color.float32[1] = 1.f; clear[0].color.float32[2] = 1.f; clear[0].color.float32[3] = 1.f; clear[1].depthStencil.depth = 0.f; beginInfo.clearValueCount = 2u; beginInfo.framebuffer = fbos[acquiredNextFBO]; beginInfo.renderpass = renderpass; beginInfo.renderArea = area; beginInfo.clearValues = clear; } commandBuffer->beginRenderPass(&beginInfo, nbl::asset::ESC_INLINE); commandBuffer->executeCommands(1u, &bakedCommandBuffer.get()); commandBuffer->endRenderPass(); commandBuffer->end(); } CommonAPI::Submit(logicalDevice.get(), swapchain.get(), commandBuffer.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], imageAcquire[resourceIx].get(), renderFinished[resourceIx].get(), fence.get()); CommonAPI::Present(logicalDevice.get(), swapchain.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], renderFinished[resourceIx].get(), acquiredNextFBO); } bool keepRunning() override { return windowCallback->isWindowOpen(); } private: CommonAPI::InitOutput initOutput; nbl::core::smart_refctd_ptr<nbl::ui::IWindow> window; nbl::core::smart_refctd_ptr<nbl::video::IAPIConnection> gl; nbl::core::smart_refctd_ptr<nbl::video::ISurface> surface; nbl::video::IPhysicalDevice* gpuPhysicalDevice; nbl::core::smart_refctd_ptr<nbl::video::ILogicalDevice> logicalDevice; std::array<video::IGPUQueue*, CommonAPI::InitOutput::MaxQueuesCount> queues; nbl::core::smart_refctd_ptr<nbl::video::ISwapchain> swapchain; nbl::core::smart_refctd_ptr<nbl::video::IGPURenderpass> renderpass; std::array<nbl::core::smart_refctd_ptr<nbl::video::IGPUFramebuffer>, CommonAPI::InitOutput::MaxSwapChainImageCount> fbos; std::array<nbl::core::smart_refctd_ptr<nbl::video::IGPUCommandPool>, CommonAPI::InitOutput::MaxQueuesCount> commandPools; nbl::core::smart_refctd_ptr<nbl::asset::IAssetManager> assetManager; nbl::core::smart_refctd_ptr<nbl::system::ILogger> logger; nbl::core::smart_refctd_ptr<CommonAPI::InputSystem> inputSystem; nbl::core::smart_refctd_ptr<nbl::system::ISystem> system; nbl::core::smart_refctd_ptr<CommonAPI::CommonAPIEventCallback> windowCallback; nbl::video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams; nbl::core::smart_refctd_ptr<nbl::video::IUtilities> utilities; nbl::video::IGPUQueue* transferUpQueue = nullptr; nbl::core::smart_refctd_ptr<nbl::scene::ITransformTreeManager> ttm; nbl::core::smart_refctd_ptr<nbl::scene::ITransformTree> tt; nbl::core::smart_refctd_ptr<nbl::video::IGPUDescriptorSet> recomputeGlobalTransformsDS; Camera camera = Camera(vectorSIMDf(0, 0, 0), vectorSIMDf(0, 0, 0), matrix4SIMD()); CommonAPI::InputSystem::ChannelReader<IMouseEventChannel> mouse; CommonAPI::InputSystem::ChannelReader<IKeyboardEventChannel> keyboard; core::smart_refctd_ptr<lod_library_t> lodLibrary; core::smart_refctd_ptr<culling_system_t> cullingSystem; CullPushConstants_t cullPushConstants; culling_system_t::Params cullingParams; core::smart_refctd_ptr<video::CDrawIndirectAllocator<>> drawIndirectAllocator; core::smart_refctd_ptr<video::IGPUCommandBuffer> commandBuffers[FRAMES_IN_FLIGHT]; core::smart_refctd_ptr<video::IGPUCommandBuffer> bakedCommandBuffer; core::smart_refctd_ptr<video::IGPUFence> frameComplete[FRAMES_IN_FLIGHT] = { nullptr }; core::smart_refctd_ptr<video::IGPUSemaphore> imageAcquire[FRAMES_IN_FLIGHT] = { nullptr }; core::smart_refctd_ptr<video::IGPUSemaphore> renderFinished[FRAMES_IN_FLIGHT] = { nullptr }; video::CDumbPresentationOracle oracle; uint32_t acquiredNextFBO = {}; int32_t resourceIx = -1; }; NBL_COMMON_API_MAIN(LoDSystemApp)
57.97397
239
0.627479
deprilula28
9062ce2842494425e6a4ea1295d791f91160075f
7,557
cpp
C++
server/Server/Packets/CGStallRemoveItemHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
3
2018-06-19T21:37:38.000Z
2021-07-31T21:51:40.000Z
server/Server/Packets/CGStallRemoveItemHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
null
null
null
server/Server/Packets/CGStallRemoveItemHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
13
2015-01-30T17:45:06.000Z
2022-01-06T02:29:34.000Z
#include "stdafx.h" /* 客户端通知服务器从摊位中拿走此物品 */ #include "CGStallRemoveItem.h" #include "GCStallRemoveItem.h" #include "GamePlayer.h" #include "Obj_Human.h" #include "Scene.h" #include "Log.h" #include "ItemOperator.h" #include "HumanItemLogic.h" UINT CGStallRemoveItemHandler::Execute( CGStallRemoveItem* pPacket, Player* pPlayer ) { __ENTER_FUNCTION GamePlayer* pGamePlayer = (GamePlayer*)pPlayer ; Assert( pGamePlayer ) ; Obj_Human* pHuman = pGamePlayer->GetHuman() ; Assert( pHuman ) ; Scene* pScene = pHuman->getScene() ; if( pScene==NULL ) { Assert(FALSE) ; return PACKET_EXE_ERROR ; } //检查线程执行资源是否正确 Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ; _ITEM_GUID ItemGuid = pPacket->GetObjGUID(); PET_GUID_t PetGuid = pPacket->GetPetGUID(); BYTE ToType = pPacket->GetToType(); UINT Serial = pPacket->GetSerial(); if(pHuman->m_StallBox.GetStallStatus() != ServerStallBox::STALL_OPEN) { GCStallError Msg; Msg.SetID(STALL_MSG::ERR_ILLEGAL); pGamePlayer->SendPacket(&Msg); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: != ServerStallBox::STALL_OPEN" ,pHuman->GetName()) ; return PACKET_EXE_CONTINUE; } ItemContainer* pStallContainer = pHuman->m_StallBox.GetContainer(); ItemContainer* pStallPetContainer = pHuman->m_StallBox.GetPetContainer(); GCStallError MsgError; GCStallRemoveItem MsgRemoveItem; switch(ToType) { case STALL_MSG::POS_BAG: { INT IndexInStall = pStallContainer->GetIndexByGUID(&ItemGuid); if(IndexInStall<0) { MsgError.SetID(STALL_MSG::ERR_NEED_NEW_COPY); pGamePlayer->SendPacket(&MsgError); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_NEED_NEW_COPY: IndexInStall = %d" ,pHuman->GetName(), IndexInStall) ; return PACKET_EXE_CONTINUE; } if( pHuman->m_StallBox.GetSerialByIndex(IndexInStall) > Serial) { MsgError.SetID(STALL_MSG::ERR_NEED_NEW_COPY); pGamePlayer->SendPacket(&MsgError); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_NEED_NEW_COPY: Serial = %d, BoxSerial = %d" ,pHuman->GetName(), Serial, pHuman->m_StallBox.GetSerialByIndex(IndexInStall)) ; return PACKET_EXE_CONTINUE; } Item* pItem = pStallContainer->GetItem(IndexInStall); ItemContainer* pBagContainer = HumanItemLogic::GetItemContain(pHuman, pItem->GetItemTableIndex()); INT IndexInBag = pBagContainer->GetIndexByGUID(&ItemGuid); if(IndexInBag<0) { MsgError.SetID(STALL_MSG::ERR_ILLEGAL); pHuman->m_StallBox.CleanUp(); pGamePlayer->SendPacket(&MsgError); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: IndexInBag = %d" ,pHuman->GetName(), IndexInBag) ; return PACKET_EXE_CONTINUE; } //解锁原背包中的物品 g_ItemOperator.UnlockItem( pBagContainer, IndexInBag ); //干掉物品 if(g_ItemOperator.EraseItem(pStallContainer, IndexInStall)>0) { pHuman->m_StallBox.IncSerialByIndex(IndexInStall); pHuman->m_StallBox.SetPriceByIndex(IndexInStall, 0); } else { MsgError.SetID(STALL_MSG::ERR_ILLEGAL); pHuman->m_StallBox.CleanUp(); pGamePlayer->SendPacket(&MsgError); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: IndexInStall = %d" ,pHuman->GetName(), IndexInStall) ; return PACKET_EXE_CONTINUE; } //通知客户端 MsgRemoveItem.SetObjGUID( ItemGuid ); MsgRemoveItem.SetSerial( pHuman->m_StallBox.GetSerialByIndex(IndexInStall) ); MsgRemoveItem.SetToType( STALL_MSG::POS_BAG ); pGamePlayer->SendPacket(&MsgRemoveItem); } break; case STALL_MSG::POS_EQUIP: { } break; case STALL_MSG::POS_PET: { INT IndexInStall = pStallPetContainer->GetIndexByGUID(&PetGuid); if(IndexInStall<0) { MsgError.SetID(STALL_MSG::ERR_NEED_NEW_COPY); pGamePlayer->SendPacket(&MsgError); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_NEED_NEW_COPY: IndexInStall = %d" ,pHuman->GetName(), IndexInStall) ; return PACKET_EXE_CONTINUE; } if( pHuman->m_StallBox.GetPetSerialByIndex(IndexInStall) > Serial) { MsgError.SetID(STALL_MSG::ERR_NEED_NEW_COPY); pGamePlayer->SendPacket(&MsgError); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_NEED_NEW_COPY: Serial = %d, BoxSerial = %d" ,pHuman->GetName(), Serial, pHuman->m_StallBox.GetPetSerialByIndex(IndexInStall)) ; return PACKET_EXE_CONTINUE; } ItemContainer* pPetContainer = pHuman->GetPetContain(); INT IndexInBag = pPetContainer->GetIndexByGUID(&PetGuid); if(IndexInBag<0) { MsgError.SetID(STALL_MSG::ERR_ILLEGAL); pHuman->m_StallBox.CleanUp(); pGamePlayer->SendPacket(&MsgError); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: IndexInBag = %d" ,pHuman->GetName(), IndexInBag) ; return PACKET_EXE_CONTINUE; } //解锁原背包中的物品 g_ItemOperator.UnlockItem( pPetContainer, IndexInBag ); //干掉物品 if(g_ItemOperator.EraseItem(pStallPetContainer, IndexInStall)>0) { pHuman->m_StallBox.IncPetSerialByIndex(IndexInStall); pHuman->m_StallBox.SetPetPriceByIndex(IndexInStall, 0); } else { MsgError.SetID(STALL_MSG::ERR_ILLEGAL); pHuman->m_StallBox.CleanUp(); pGamePlayer->SendPacket(&MsgError); g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: IndexInStall = %d" ,pHuman->GetName(), IndexInStall) ; return PACKET_EXE_CONTINUE; } //通知客户端 MsgRemoveItem.SetPetGUID( PetGuid ); MsgRemoveItem.SetSerial( pHuman->m_StallBox.GetPetSerialByIndex(IndexInStall) ); MsgRemoveItem.SetToType( STALL_MSG::POS_PET ); pGamePlayer->SendPacket(&MsgRemoveItem); } break; default: break; } g_pLog->FastSaveLog( LOG_FILE_1, "CGStallRemoveItemHandler::ObjName=%s, m_World = %d, m_Server = %d, m_Serial = %d" ,pHuman->GetName(), ItemGuid.m_World, ItemGuid.m_Server, ItemGuid.m_Serial) ; return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
37.974874
142
0.592166
viticm
9066b4d3be7d6c2b62013e62ccef5441636185da
1,112
cpp
C++
benchmark_dgemm.cpp
seriouslyhypersonic/benchmark_eigen_mkl
c2dde3a3ce9c51dd428746400de8e8d2802dc6c0
[ "BSL-1.0" ]
null
null
null
benchmark_dgemm.cpp
seriouslyhypersonic/benchmark_eigen_mkl
c2dde3a3ce9c51dd428746400de8e8d2802dc6c0
[ "BSL-1.0" ]
null
null
null
benchmark_dgemm.cpp
seriouslyhypersonic/benchmark_eigen_mkl
c2dde3a3ce9c51dd428746400de8e8d2802dc6c0
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) Nuno Alves de Sousa 2019 * * Use, modification and distribution is subject to the Boost Software License, * Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #include <celero/Celero.h> #include <fixture.hpp> #include <mkl.h> CELERO_MAIN //const int numLinearSamples = 3; //const int numLinearIterations = 75; // //BASELINE_F(Gemm, Baseline, MKLFixture<>, numLinearSamples, numLinearIterations) //{ // squareDgemm(mA, mA, mC, matrixDim, 1, 1); //} // //BENCHMARK_F(Gemm, Eigen, EigenFixture<>, numLinearSamples, numLinearIterations) //{ // celero::DoNotOptimizeAway((eA * eA).eval()); //} const int numSemilogSamples = 5; const int numSemilogIterations = 0; BASELINE_F(SemilogGemm, Baseline, MKLFixture<ProgressionPolicy::semilogGemm> ,numSemilogSamples, numSemilogIterations) { squareDgemm(mA, mA, mC, matrixDim, 1, 1); } BENCHMARK_F(SemilogGemm, Eigen, EigenFixture<ProgressionPolicy::semilogGemm> ,numSemilogSamples, numSemilogIterations) { celero::DoNotOptimizeAway((eA * eA).eval()); }
26.47619
81
0.720324
seriouslyhypersonic
90687b5190c80a3c7c005f5fe2d40921b351cff6
11,297
cpp
C++
nvmain/Prefetchers/STeMS/STeMS.cpp
code-lamem/lamem
c28f72c13a81fbb105c7c83d1b2720a720f3a47f
[ "BSD-3-Clause" ]
1
2019-08-27T14:36:00.000Z
2019-08-27T14:36:00.000Z
nvmain/Prefetchers/STeMS/STeMS.cpp
code-lamem/lamem
c28f72c13a81fbb105c7c83d1b2720a720f3a47f
[ "BSD-3-Clause" ]
null
null
null
nvmain/Prefetchers/STeMS/STeMS.cpp
code-lamem/lamem
c28f72c13a81fbb105c7c83d1b2720a720f3a47f
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (c) 2012-2014, The Microsystems Design Labratory (MDL) * Department of Computer Science and Engineering, The Pennsylvania State University * All rights reserved. * * This source code is part of NVMain - A cycle accurate timing, bit accurate * energy simulator for both volatile (e.g., DRAM) and non-volatile memory * (e.g., PCRAM). The source code is free and you can redistribute and/or * modify it by providing that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Author list: * Matt Poremba ( Email: mrp5060 at psu dot edu * Website: http://www.cse.psu.edu/~poremba/ ) *******************************************************************************/ #include "Prefetchers/STeMS/STeMS.h" #include <iostream> using namespace NVM; void STeMS::FetchNextUnused( PatternSequence *rps, int count, std::vector<NVMAddress>& prefetchList ) { uint64_t *lastUnused = new uint64_t[count]; bool *foundUnused = new bool[count]; for( int i = 0; i < count; i++ ) { lastUnused[i] = 0; foundUnused[i] = false; } /* Find the LAST requests marked as unused. */ for( int i = static_cast<int>(rps->size - 1); i >= 0; i-- ) { if( !rps->fetched[i] ) { for( int j = 0; j < count - 1; j++ ) { lastUnused[j] = lastUnused[j+1]; foundUnused[j] = foundUnused[j+1]; } lastUnused[count-1] = rps->offset[i]; foundUnused[count-1] = true; } else { break; } } for( int i = 0; i < count; i++ ) { if( foundUnused[i] ) { rps->startedPrefetch = true; #ifdef DBGPF std::cout << "Prefetching 0x" << std::hex << rps->address + lastUnused[i] << std::dec << std::endl; #endif NVMAddress pfAddr; pfAddr.SetPhysicalAddress( rps->address + lastUnused[i] ); prefetchList.push_back( pfAddr ); /* Mark offset as fetched. */ for( uint64_t j = 0; j < rps->size; j++ ) { if( rps->offset[j] == lastUnused[i] ) rps->fetched[j] = true; } } } } bool STeMS::NotifyAccess( NVMainRequest *accessOp, std::vector<NVMAddress>& prefetchList ) { bool rv = false; /* * If this access came from a PC that has an allocated reconstruction * buffer, but it is not the first unused address in the reconstruction * buffer, deallocate the buffer. */ if( ReconBuf.count( accessOp->programCounter ) ) { PatternSequence *rps = ReconBuf[accessOp->programCounter]; uint64_t address = accessOp->address.GetPhysicalAddress( ); /* Can't evaluate prefetch effectiveness until we've issued some. */ if( !rps->startedPrefetch ) return false; /* * If the access was a prefetch we did that was successful, prefetch * more else if the access is something that was not fetched, * deallocate the reconstruct buffer. */ bool successful = false; for( uint64_t i = 0; i < rps->size; i++ ) { if( address == ( rps->address + rps->offset[i] ) ) { if( rps->fetched[i] && !rps->used[i] ) { /* Successful prefetch, get more */ successful = true; #ifdef DBGPF std::cout << "Successful prefetch ! 0x" << std::hex << address << std::dec << std::endl; #endif FetchNextUnused( rps, 4, prefetchList ); rv = true; rps->used[i] = true; } } } if( !successful ) { /* Check if the address failed because it's not in the PST. If most * of the fetches were used, extend the PST. */ uint64_t numSuccess = 0; for( uint64_t i = 0; i < rps->size; i++ ) { if( rps->used[i] ) numSuccess++; } if( ((double)(numSuccess) / (double)(rps->size)) >= 0.6f ) { PatternSequence *ps = NULL; std::map<uint64_t, PatternSequence*>::iterator it; it = PST.find( accessOp->programCounter ); if( it != PST.end( ) ) { ps = it->second; if( ps->size < 16 ) { ps->offset[ps->size] = address - rps->address; ps->delta[ps->size] = 0; ps->size++; } } } std::map<uint64_t, PatternSequence*>::iterator it; it = ReconBuf.find( accessOp->programCounter ); ReconBuf.erase( it ); } } return rv; } bool STeMS::DoPrefetch( NVMainRequest *triggerOp, std::vector<NVMAddress>& prefetchList ) { NVMAddress pfAddr; /* If there is an entry in the PST for this PC, build a recon buffer */ if( PST.count( triggerOp->programCounter ) ) { PatternSequence *ps = PST[triggerOp->programCounter]; uint64_t address = triggerOp->address.GetPhysicalAddress( ); uint64_t pc = triggerOp->programCounter; /* Check for an RB that is actively being built */ if( ReconBuf.count( pc ) ) { PatternSequence *rps = ReconBuf[pc]; uint64_t numUsed, numFetched; numUsed = numFetched = 0; /* Mark this address as used. */ for( uint64_t i = 0; i < rps->size; i++ ) { if( ( rps->address + rps->offset[i] ) == address ) { rps->used[i] = rps->fetched[i] = true; } if( rps->used[i] ) numUsed++; if( rps->fetched[i] ) numFetched++; } /* * If there are enough used out of the fetched values, * get some more. */ if( numUsed >= 2 ) { FetchNextUnused( rps, 4, prefetchList ); } } /* Create new recon buffer by copying the PST entry */ else { PatternSequence *rps = new PatternSequence; uint64_t pc = triggerOp->programCounter; rps->size = ps->size; rps->address = triggerOp->address.GetPhysicalAddress( ); for( uint64_t i = 0; i < ps->size; i++ ) { rps->offset[i] = ps->offset[i]; rps->delta[i] = ps->delta[i]; rps->used[i] = false; rps->fetched[i] = false; } rps->useCount = 1; rps->startedPrefetch = false; /* * Mark the address that triggered reconstruction as * fetched and used */ rps->used[0] = rps->fetched[0] = true; ReconBuf.insert( std::pair<uint64_t, PatternSequence*>( pc, rps ) ); } #ifdef DBGPF std::cout << "Found a PST entry for PC 0x" << std::hex << triggerOp->programCounter << std::dec << std::endl; std::cout << "Triggered by 0x" << std::hex << triggerOp->address.GetPhysicalAddress( ) << std::dec << std::endl; std::cout << "Start address 0x" << std::hex << ps->address << ": " << std::dec; for( uint64_t i = 0; i < ps->size; i++ ) { std::cout << "[" << ps->offset[i] << "," << ps->delta[i] << "], "; } std::cout << std::endl; #endif } else { /* * If there is no entry in the PST for this PC, start building an * AGT entry. */ /* Check one of the AGT buffers for misses at this PC */ if( AGT.count( triggerOp->programCounter ) ) { uint64_t address = triggerOp->address.GetPhysicalAddress( ); uint64_t pc = triggerOp->programCounter; PatternSequence *ps = AGT[pc]; /* * If a buffer for this PC exists, append to it. If the buffer size * exceeds some threshold (say 4) and matches something in the pattern * table, issue a prefetch for the remaining items in the pattern (up to * say 8). */ uint64_t addressDiff; addressDiff = ((address > ps->address) ? (address - ps->address) : (ps->address - address)); if( ( addressDiff / 64 ) < 256 ) { ps->offset[ps->size] = address - ps->address; ps->delta[ps->size] = 0; ps->size++; /* * If a buffer exists and the size exceeds some threshold, * but does not match anything in the pattern table, add this * buffer to the pattern table */ if( ps->size >= 8 ) { PST.insert( std::pair<uint64_t, PatternSequence*>( pc, ps ) ); std::map<uint64_t, PatternSequence*>::iterator it; it = AGT.find( pc ); AGT.erase( it ); } } } /* If a buffer does not exist, create one. */ else { PatternSequence *ps = new PatternSequence; uint64_t pc = triggerOp->programCounter; ps->address = triggerOp->address.GetPhysicalAddress( ); ps->size = 1; ps->offset[0] = 0; ps->delta[0] = 0; AGT.insert( std::pair<uint64_t, PatternSequence*>( pc, ps ) ); } } return false; }
33.226471
84
0.500929
code-lamem
9068cd65b2531f63fc4eca84dc2e99af5531e3c6
4,685
cc
C++
core/Framebuffer.cc
pstiasny/derpengine
854f6896a6888724cb273c126bf92cc110f3da72
[ "MIT" ]
null
null
null
core/Framebuffer.cc
pstiasny/derpengine
854f6896a6888724cb273c126bf92cc110f3da72
[ "MIT" ]
null
null
null
core/Framebuffer.cc
pstiasny/derpengine
854f6896a6888724cb273c126bf92cc110f3da72
[ "MIT" ]
1
2019-12-02T22:31:08.000Z
2019-12-02T22:31:08.000Z
#include "Framebuffer.h" #include "FramebufferTexture.h" #include "DepthFramebufferTexture.h" #include "GraphNode.h" #include "RenderingContext.h" GLuint Framebuffer::active_framebuffer_id = 0; Framebuffer::Framebuffer(unsigned int w, unsigned int h) : width(w), height(h) { color_tex = NULL; depth_tex = NULL; color_renderbuffer_id = 0; depth_renderbuffer_id = 0; glGenFramebuffers(1, &framebuffer_id); } Framebuffer::~Framebuffer() { glDeleteFramebuffers(1, &framebuffer_id); // Delete renderbuffers if any were created if (color_renderbuffer_id) glDeleteRenderbuffers(1, &color_renderbuffer_id); if (depth_renderbuffer_id) glDeleteRenderbuffers(1, &depth_renderbuffer_id); } void Framebuffer::createColorRenderbuffer() { if (color_renderbuffer_id) return; color_renderbuffer_id = 0; glGenRenderbuffers(1, &color_renderbuffer_id); glBindRenderbuffer(GL_RENDERBUFFER, color_renderbuffer_id); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, color_renderbuffer_id); } void Framebuffer::createDepthRenderbuffer() { if (depth_renderbuffer_id) return; depth_renderbuffer_id = 0; glGenRenderbuffers(1, &depth_renderbuffer_id); glBindRenderbuffer(GL_RENDERBUFFER, depth_renderbuffer_id); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_renderbuffer_id); } void Framebuffer::setColorTexture(FramebufferTexture *tex) { glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id); color_tex = tex; if (tex) { if (color_renderbuffer_id) { glDeleteRenderbuffers(1, &color_renderbuffer_id); color_renderbuffer_id = 0; } tex->resize(width, height); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex->getId(), 0); } else { if (!color_renderbuffer_id) createColorRenderbuffer(); } glBindFramebuffer(GL_FRAMEBUFFER, active_framebuffer_id); } void Framebuffer::setDepthTexture(DepthFramebufferTexture *tex) { glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id); depth_tex = tex; if (tex) { if (depth_renderbuffer_id) { glDeleteRenderbuffers(1, &depth_renderbuffer_id); depth_renderbuffer_id = 0; } tex->resize(width, height); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tex->getId(), 0); } else { if (!depth_renderbuffer_id) createDepthRenderbuffer(); } glBindFramebuffer(GL_FRAMEBUFFER, active_framebuffer_id); } void Framebuffer::resize(unsigned int w, unsigned int h) { glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id); width = w; height = h; if (color_tex) color_tex->resize(w, h); else if (color_renderbuffer_id) { glBindRenderbuffer(GL_RENDERBUFFER, color_renderbuffer_id); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height); } if (depth_tex) depth_tex->resize(w, h); else if (depth_renderbuffer_id) { glBindRenderbuffer(GL_RENDERBUFFER, depth_renderbuffer_id); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, width, height); } glBindFramebuffer(GL_FRAMEBUFFER, active_framebuffer_id); } bool Framebuffer::isComplete() { glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id); switch(glCheckFramebufferStatus(GL_FRAMEBUFFER)) { case GL_FRAMEBUFFER_COMPLETE: return true; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: puts("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); break; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: puts("GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: puts("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); break; case GL_FRAMEBUFFER_UNSUPPORTED: puts("GL_FRAMEBUFFER_UNSUPPORTED"); break; default: puts("Unknown framebuffer status"); } return false; glBindFramebuffer(GL_FRAMEBUFFER, active_framebuffer_id); } void Framebuffer::bindFramebuffer() { assert(active_framebuffer_id == 0); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id); active_framebuffer_id = framebuffer_id; if (!color_tex && !color_renderbuffer_id) createColorRenderbuffer(); if (!depth_tex && !depth_renderbuffer_id) createDepthRenderbuffer(); } void Framebuffer::unbindFramebuffer() { assert(active_framebuffer_id == framebuffer_id); glBindFramebuffer(GL_FRAMEBUFFER, 0); active_framebuffer_id = 0; } void Framebuffer::renderTo(RenderingContext *rc, GraphNode *scene) { GLint prev_draw_buffer; glGetIntegerv(GL_DRAW_BUFFER, &prev_draw_buffer); glDrawBuffer(GL_NONE); bindFramebuffer(); //rc->reshape(w, h); rc->clear(); scene->render(rc); unbindFramebuffer(); glDrawBuffer(prev_draw_buffer); }
24.657895
78
0.785912
pstiasny
9068d3c52f143f3b942d07898fa909fd130de336
582
cpp
C++
Online Judges/Neps Academy/Copa do Mundo (OBI2010)/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/Neps Academy/Copa do Mundo (OBI2010)/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/Neps Academy/Copa do Mundo (OBI2010)/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include <queue> using namespace std; int main() { queue<char> q; int a, b; char ta = 'A', tb = 'B'; for (int i = 1; i <= 8; i++) { cin >> a >> b; if(a > b) { q.push(ta); } else { q.push(tb); } ta+=2; tb+=2; } while(q.size() > 1) { ta = q.front(); q.pop(); tb = q.front(); q.pop(); cin >> a >> b; if(a > b) { q.push(ta); } else { q.push(tb); } } cout << q.front() << endl; return 0; }
16.628571
34
0.348797
AnneLivia
90694f119ea87a46434d16d7c24cf05caf4648df
2,075
cpp
C++
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_ordered_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_ordered_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_ordered_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/prim/mat.hpp> #include <gtest/gtest.h> using stan::math::check_ordered; TEST(ErrorHandlingMatrix, checkOrdered) { Eigen::Matrix<double, Eigen::Dynamic, 1> y; y.resize(3); y << 0, 1, 2; EXPECT_NO_THROW(check_ordered("check_ordered", "y", y)); y << 0, 10, std::numeric_limits<double>::infinity(); EXPECT_NO_THROW(check_ordered("check_ordered", "y", y)); y << -10, 10, std::numeric_limits<double>::infinity(); EXPECT_NO_THROW(check_ordered("check_ordered", "y", y)); y << -std::numeric_limits<double>::infinity(), 10, std::numeric_limits<double>::infinity(); EXPECT_NO_THROW(check_ordered("check_ordered", "y", y)); y << 0, 0, 0; EXPECT_THROW(check_ordered("check_ordered", "y", y), std::domain_error); y << 0, std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(); EXPECT_THROW(check_ordered("check_ordered", "y", y), std::domain_error); y << -1, 3, 2; EXPECT_THROW(check_ordered("check_ordered", "y", y), std::domain_error); } TEST(ErrorHandlingMatrix, checkOrdered_one_indexed_message) { std::string message; Eigen::Matrix<double, Eigen::Dynamic, 1> y; y.resize(3); y << 0, 5, 1; try { check_ordered("check_ordered", "y", y); FAIL() << "should have thrown"; } catch (std::domain_error& e) { message = e.what(); } catch (...) { FAIL() << "threw the wrong error"; } EXPECT_NE(std::string::npos, message.find("element at 3")) << message; } TEST(ErrorHandlingMatrix, checkOrdered_nan) { Eigen::Matrix<double, Eigen::Dynamic, 1> y; double nan = std::numeric_limits<double>::quiet_NaN(); y.resize(3); y << 0, 1, 2; for (int i = 0; i < y.size(); i++) { y[i] = nan; EXPECT_THROW(check_ordered("check_ordered", "y", y), std::domain_error); y[i] = i; } for (int i = 0; i < y.size(); i++) { y << 0, 10, std::numeric_limits<double>::infinity(); y[i] = nan; EXPECT_THROW(check_ordered("check_ordered", "y", y), std::domain_error); } }
28.040541
93
0.615904
yizhang-cae
90697a7ef59d604af8973025d25ab85d61ef43ef
7,504
cpp
C++
android/android_9/hardware/qcom/display/msm8960/liboverlay/pipes/overlayGenPipe.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
1
2017-09-22T01:41:30.000Z
2017-09-22T01:41:30.000Z
qcom/display/msm8960/liboverlay/pipes/overlayGenPipe.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
null
null
null
qcom/display/msm8960/liboverlay/pipes/overlayGenPipe.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
1
2018-02-24T19:09:04.000Z
2018-02-24T19:09:04.000Z
/* * Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "overlayGenPipe.h" #include "overlay.h" #include "mdp_version.h" namespace overlay { GenericPipe::GenericPipe(int dpy) : mFbNum(dpy), mRot(0), mRotUsed(false), mRotDownscaleOpt(false), mPreRotated(false), pipeState(CLOSED) { init(); } GenericPipe::~GenericPipe() { close(); } bool GenericPipe::init() { ALOGE_IF(DEBUG_OVERLAY, "GenericPipe init"); mRotUsed = false; mRotDownscaleOpt = false; mPreRotated = false; if(mFbNum) mFbNum = Overlay::getInstance()->getExtFbNum(); ALOGD_IF(DEBUG_OVERLAY,"%s: mFbNum:%d",__FUNCTION__, mFbNum); if(!mCtrlData.ctrl.init(mFbNum)) { ALOGE("GenericPipe failed to init ctrl"); return false; } if(!mCtrlData.data.init(mFbNum)) { ALOGE("GenericPipe failed to init data"); return false; } //get a new rotator object, take ownership mRot = Rotator::getRotator(); return true; } bool GenericPipe::close() { bool ret = true; if(!mCtrlData.ctrl.close()) { ALOGE("GenericPipe failed to close ctrl"); ret = false; } if (!mCtrlData.data.close()) { ALOGE("GenericPipe failed to close data"); ret = false; } delete mRot; mRot = 0; setClosed(); return ret; } void GenericPipe::setSource(const utils::PipeArgs& args) { //Cache if user wants 0-rotation mRotUsed = args.rotFlags & utils::ROT_0_ENABLED; mRotDownscaleOpt = args.rotFlags & utils::ROT_DOWNSCALE_ENABLED; mPreRotated = args.rotFlags & utils::ROT_PREROTATED; if(mPreRotated) mRotUsed = false; mRot->setSource(args.whf); mRot->setFlags(args.mdpFlags); mCtrlData.ctrl.setSource(args); } void GenericPipe::setCrop(const overlay::utils::Dim& d) { mCtrlData.ctrl.setCrop(d); } void GenericPipe::setTransform(const utils::eTransform& orient) { //Rotation could be enabled by user for zero-rot or the layer could have //some transform. Mark rotation enabled in either case. mRotUsed |= ((orient & utils::OVERLAY_TRANSFORM_ROT_90) && !mPreRotated); mRot->setTransform(orient); mCtrlData.ctrl.setTransform(orient); } void GenericPipe::setPosition(const utils::Dim& d) { mCtrlData.ctrl.setPosition(d); } bool GenericPipe::setVisualParams(const MetaData_t &metadata) { return mCtrlData.ctrl.setVisualParams(metadata); } bool GenericPipe::commit() { bool ret = false; int downscale_factor = utils::ROT_DS_NONE; if(mRotDownscaleOpt) { ovutils::Dim src(mCtrlData.ctrl.getCrop()); ovutils::Dim dst(mCtrlData.ctrl.getPosition()); downscale_factor = ovutils::getDownscaleFactor( src.w, src.h, dst.w, dst.h); mRotUsed |= (downscale_factor && !mPreRotated); } if(mRotUsed) { mRot->setDownscale(downscale_factor); //If wanting to use rotator, start it. if(!mRot->commit()) { ALOGE("GenPipe Rotator commit failed"); //If rot commit fails, flush rotator session, memory, fd and create //a hollow rotator object delete mRot; mRot = Rotator::getRotator(); pipeState = CLOSED; return false; } /* Set the mdp src format to the output format of the rotator. * The output format of the rotator might be different depending on * whether fastyuv mode is enabled in the rotator. */ mCtrlData.ctrl.updateSrcFormat(mRot->getDstFormat()); } mCtrlData.ctrl.setDownscale(downscale_factor); ret = mCtrlData.ctrl.commit(); //If mdp commit fails, flush rotator session, memory, fd and create a hollow //rotator object if(ret == false) { delete mRot; mRot = Rotator::getRotator(); } pipeState = ret ? OPEN : CLOSED; return ret; } bool GenericPipe::queueBuffer(int fd, uint32_t offset) { //TODO Move pipe-id transfer to CtrlData class. Make ctrl and data private. OVASSERT(isOpen(), "State is closed, cannot queueBuffer"); int pipeId = mCtrlData.ctrl.getPipeId(); OVASSERT(-1 != pipeId, "Ctrl ID should not be -1"); // set pipe id from ctrl to data mCtrlData.data.setPipeId(pipeId); int finalFd = fd; uint32_t finalOffset = offset; //If rotator is to be used, queue to it, so it can ROTATE. if(mRotUsed) { if(!mRot->queueBuffer(fd, offset)) { ALOGE("GenPipe Rotator play failed"); return false; } //Configure MDP's source buffer as the current output buffer of rotator if(mRot->getDstMemId() != -1) { finalFd = mRot->getDstMemId(); finalOffset = mRot->getDstOffset(); } else { //Could be -1 for NullRotator, if queue above succeeds. //Need an actual rotator. Modify overlay State Traits. //Not fatal, keep queuing to MDP without rotation. ALOGE("Null rotator in use, where an actual is required"); } } return mCtrlData.data.queueBuffer(finalFd, finalOffset); } int GenericPipe::getCtrlFd() const { return mCtrlData.ctrl.getFd(); } utils::Dim GenericPipe::getCrop() const { return mCtrlData.ctrl.getCrop(); } void GenericPipe::dump() const { ALOGE("== Dump Generic pipe start =="); ALOGE("pipe state = %d", (int)pipeState); OVASSERT(mRot, "GenericPipe should have a valid Rot"); mCtrlData.ctrl.dump(); mCtrlData.data.dump(); mRot->dump(); ALOGE("== Dump Generic pipe end =="); } void GenericPipe::getDump(char *buf, size_t len) { mCtrlData.ctrl.getDump(buf, len); mCtrlData.data.getDump(buf, len); if(mRotUsed && mRot) mRot->getDump(buf, len); } bool GenericPipe::isClosed() const { return (pipeState == CLOSED); } bool GenericPipe::isOpen() const { return (pipeState == OPEN); } bool GenericPipe::setClosed() { pipeState = CLOSED; return true; } } //namespace overlay
31.136929
80
0.664845
yakuizhao
906a2524fe426138f4e1108f215ef70d6b50fbb4
36,024
cpp
C++
src/main.cpp
hdachev/Nimble
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
[ "MIT" ]
null
null
null
src/main.cpp
hdachev/Nimble
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
[ "MIT" ]
null
null
null
src/main.cpp
hdachev/Nimble
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
[ "MIT" ]
1
2021-05-10T02:07:12.000Z
2021-05-10T02:07:12.000Z
#include <iostream> #include <fstream> #include <gtc/matrix_transform.hpp> #include <gtc/type_ptr.hpp> #include <memory> #include "application.h" #include "camera.h" #include "utility.h" #include "material.h" #include "macros.h" #include "render_graph.h" #include "nodes/forward_node.h" #include "nodes/cubemap_skybox_node.h" #include "nodes/pcf_point_light_depth_node.h" #include "nodes/pcf_directional_light_depth_node.h" #include "nodes/pcss_directional_light_depth_node.h" #include "nodes/copy_node.h" #include "nodes/g_buffer_node.h" #include "nodes/deferred_node.h" #include "nodes/tone_map_node.h" #include "nodes/bloom_node.h" #include "nodes/ssao_node.h" #include "nodes/hiz_node.h" #include "nodes/adaptive_exposure_node.h" #include "nodes/motion_blur_node.h" #include "nodes/volumetric_light_node.h" #include "nodes/screen_space_reflection_node.h" #include "nodes/reflection_node.h" #include "nodes/fxaa_node.h" #include "nodes/depth_of_field_node.h" #include "nodes/vignette_node.h" #include "nodes/film_grain_node.h" #include "nodes/chromatic_aberration_node.h" #include "nodes/color_grade_node.h" #include "nodes/stop_nans_node.h" #include "nodes/taa_node.h" #include "nodes/tiled_forward_node.h" #include "nodes/tiled_deferred_node.h" #include "nodes/clustered_forward_node.h" #include "nodes/clustered_deferred_node.h" #include "nodes/tiled_light_culling_node.h" #include "nodes/clustered_light_culling_node.h" #include "nodes/depth_prepass_node.h" #include "debug_draw.h" #include "imgui_helpers.h" #include "external/nfd/nfd.h" #include "profiler.h" #include "probe_renderer/bruneton_probe_renderer.h" #include "ImGuizmo.h" #include <random> #define NIMBLE_EDITOR namespace nimble { #define CAMERA_DEFAULT_FOV 60.0f #define CAMERA_DEFAULT_NEAR_PLANE 1.0f #define CAMERA_DEFAULT_FAR_PLANE 3000.0f class Nimble : public Application { protected: // ----------------------------------------------------------------------------------------------------------------------------------- bool init(int argc, const char* argv[]) override { // Attempt to load startup scene. std::shared_ptr<Scene> scene = m_resource_manager.load_scene("scene/startup.json"); if (scene) m_scene = scene; else { // If failed, prompt user to select scene to be loaded. if (!scene && !load_scene_from_dialog()) return false; } //create_random_point_lights(); //create_random_spot_lights(); // Create camera. create_camera(); create_render_graphs(); return true; } // ----------------------------------------------------------------------------------------------------------------------------------- void update(double delta) override { // Update camera. update_camera(); if (m_debug_gui) gui(); #ifdef NIMBLE_EDITOR if (!m_edit_mode) { #endif if (m_scene) m_scene->update(); #ifdef NIMBLE_EDITOR } #endif m_renderer.render(delta, &m_viewport_manager); if (m_scene) m_debug_draw.render(nullptr, m_width, m_height, m_scene->camera()->m_view_projection); } // ----------------------------------------------------------------------------------------------------------------------------------- void shutdown() override { m_forward_graph.reset(); m_scene.reset(); } // ----------------------------------------------------------------------------------------------------------------------------------- AppSettings intial_app_settings() override { AppSettings settings; settings.resizable = true; settings.width = 1920; settings.height = 1080; settings.title = "Nimble - Dihara Wijetunga (c) 2020"; return settings; } // ----------------------------------------------------------------------------------------------------------------------------------- void window_resized(int width, int height) override { if (m_scene) { m_scene->camera()->m_width = m_width; m_scene->camera()->m_height = m_height; // Override window resized method to update camera projection. m_scene->camera()->update_projection(m_scene->camera()->m_fov, m_scene->camera()->m_near, m_scene->camera()->m_far, float(m_width) / float(m_height)); } m_viewport_manager.on_window_resized(width, height); m_renderer.on_window_resized(width, height); } // ----------------------------------------------------------------------------------------------------------------------------------- void key_pressed(int code) override { // Handle forward movement. if (code == GLFW_KEY_W) m_heading_speed = m_camera_speed; else if (code == GLFW_KEY_S) m_heading_speed = -m_camera_speed; // Handle sideways movement. if (code == GLFW_KEY_A) m_sideways_speed = -m_camera_speed; else if (code == GLFW_KEY_D) m_sideways_speed = m_camera_speed; if (code == GLFW_KEY_G) m_debug_gui = !m_debug_gui; } // ----------------------------------------------------------------------------------------------------------------------------------- void key_released(int code) override { // Handle forward movement. if (code == GLFW_KEY_W || code == GLFW_KEY_S) m_heading_speed = 0.0f; // Handle sideways movement. if (code == GLFW_KEY_A || code == GLFW_KEY_D) m_sideways_speed = 0.0f; } // ----------------------------------------------------------------------------------------------------------------------------------- void mouse_pressed(int code) override { // Enable mouse look. if (code == GLFW_MOUSE_BUTTON_RIGHT) m_mouse_look = true; } // ----------------------------------------------------------------------------------------------------------------------------------- void mouse_released(int code) override { // Disable mouse look. if (code == GLFW_MOUSE_BUTTON_RIGHT) m_mouse_look = false; } // ----------------------------------------------------------------------------------------------------------------------------------- private: // ----------------------------------------------------------------------------------------------------------------------------------- void create_camera() { m_scene->camera()->m_width = m_width; m_scene->camera()->m_height = m_height; m_scene->camera()->m_half_pixel_jitter = false; m_scene->camera()->update_projection(CAMERA_DEFAULT_FOV, CAMERA_DEFAULT_NEAR_PLANE, CAMERA_DEFAULT_FAR_PLANE, float(m_width) / float(m_height)); m_viewport = m_viewport_manager.create_viewport("Main", 0.0f, 0.0f, 1.0f, 1.0f, 0); m_scene->camera()->m_viewport = m_viewport; } // ----------------------------------------------------------------------------------------------------------------------------------- void create_render_graphs() { REGISTER_RENDER_NODE(ForwardNode, m_resource_manager); REGISTER_RENDER_NODE(CubemapSkyboxNode, m_resource_manager); REGISTER_RENDER_NODE(PCFPointLightDepthNode, m_resource_manager); REGISTER_RENDER_NODE(PCFDirectionalLightDepthNode, m_resource_manager); REGISTER_RENDER_NODE(PCFSpotLightDepthNode, m_resource_manager); REGISTER_RENDER_NODE(PCSSDirectionalLightDepthNode, m_resource_manager); REGISTER_RENDER_NODE(CopyNode, m_resource_manager); REGISTER_RENDER_NODE(GBufferNode, m_resource_manager); REGISTER_RENDER_NODE(DeferredNode, m_resource_manager); REGISTER_RENDER_NODE(ToneMapNode, m_resource_manager); REGISTER_RENDER_NODE(BloomNode, m_resource_manager); REGISTER_RENDER_NODE(SSAONode, m_resource_manager); REGISTER_RENDER_NODE(HiZNode, m_resource_manager); REGISTER_RENDER_NODE(AdaptiveExposureNode, m_resource_manager); REGISTER_RENDER_NODE(MotionBlurNode, m_resource_manager); REGISTER_RENDER_NODE(VolumetricLightNode, m_resource_manager); REGISTER_RENDER_NODE(ScreenSpaceReflectionNode, m_resource_manager); REGISTER_RENDER_NODE(ReflectionNode, m_resource_manager); REGISTER_RENDER_NODE(FXAANode, m_resource_manager); REGISTER_RENDER_NODE(DepthOfFieldNode, m_resource_manager); REGISTER_RENDER_NODE(FilmGrainNode, m_resource_manager); REGISTER_RENDER_NODE(ChromaticAberrationNode, m_resource_manager); REGISTER_RENDER_NODE(VignetteNode, m_resource_manager); REGISTER_RENDER_NODE(ColorGradeNode, m_resource_manager); REGISTER_RENDER_NODE(StopNaNsNode, m_resource_manager); REGISTER_RENDER_NODE(TAANode, m_resource_manager); REGISTER_RENDER_NODE(TiledForwardNode, m_resource_manager); REGISTER_RENDER_NODE(TiledDeferredNode, m_resource_manager); REGISTER_RENDER_NODE(ClusteredForwardNode, m_resource_manager); REGISTER_RENDER_NODE(ClusteredDeferredNode, m_resource_manager); REGISTER_RENDER_NODE(TiledLightCullingNode, m_resource_manager); REGISTER_RENDER_NODE(ClusteredLightCullingNode, m_resource_manager); REGISTER_RENDER_NODE(DepthPrepassNode, m_resource_manager); // Create Forward render graph m_forward_graph = m_resource_manager.load_render_graph("graph/clustered_deferred_graph.json", &m_renderer); // Create Point Light render graph m_pcf_point_light_graph = m_resource_manager.load_shadow_render_graph("PCFPointLightDepthNode", &m_renderer); // Create Spot Light render graph m_pcf_spot_light_graph = m_resource_manager.load_shadow_render_graph("PCFSpotLightDepthNode", &m_renderer); // Create Directional Light render graph m_pcf_directional_light_graph = m_resource_manager.load_shadow_render_graph("PCSSDirectionalLightDepthNode", &m_renderer); m_bruneton_probe_renderer = std::make_shared<BrunetonProbeRenderer>(); // Set the graphs as the active graphs m_renderer.set_scene(m_scene); m_renderer.set_point_light_render_graph(m_pcf_point_light_graph); m_renderer.set_spot_light_render_graph(m_pcf_spot_light_graph); m_renderer.set_directional_light_render_graph(m_pcf_directional_light_graph); m_renderer.set_global_probe_renderer(m_bruneton_probe_renderer); m_renderer.set_scene_render_graph(m_forward_graph); //create_random_point_lights(4096); } // ----------------------------------------------------------------------------------------------------------------------------------- void create_random_spot_lights(uint32_t num_lights) { AABB aabb = m_scene->aabb(); const float range = 300.0f; const float intensity = 10.0f; const float aabb_scale = 0.6f; std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<float> dis(0.0f, 1.0f); std::uniform_real_distribution<float> dis_x(aabb.min.x * aabb_scale, aabb.max.x * aabb_scale); std::uniform_real_distribution<float> dis_y(aabb.min.y * aabb_scale, aabb.max.y * aabb_scale); std::uniform_real_distribution<float> dis_z(aabb.min.z * aabb_scale, aabb.max.z * aabb_scale); std::uniform_real_distribution<float> dis_pitch(0.0f, 180.0f); std::uniform_real_distribution<float> dis_yaw(0.0f, 360.0f); for (int n = 0; n < num_lights; n++) m_scene->create_spot_light(glm::vec3(dis_x(rd), dis_y(rd), dis_z(rd)), glm::vec3(dis_pitch(rd), dis_yaw(rd), 0.0f), glm::vec3(dis(rd), dis(rd), dis(rd)), 35.0f, 45.0f, 1000.0f, 10.0f); } // ----------------------------------------------------------------------------------------------------------------------------------- void create_random_point_lights(uint32_t num_lights) { AABB aabb = m_scene->aabb(); const float range = 100.0f; const float intensity = 10.0f; const float aabb_scale = 0.6f; std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<float> dis(0.0f, 1.0f); std::uniform_real_distribution<float> dis_x(aabb.min.x * aabb_scale, aabb.max.x * aabb_scale); std::uniform_real_distribution<float> dis_y(aabb.min.y * aabb_scale, aabb.max.y * aabb_scale); std::uniform_real_distribution<float> dis_z(aabb.min.z * aabb_scale, aabb.max.z * aabb_scale); for (int n = 0; n < num_lights; n++) m_scene->create_point_light(glm::vec3(dis_x(rd), dis_y(rd), dis_z(rd)), glm::vec3(dis(rd), dis(rd), dis(rd)), range, intensity, false); } // ----------------------------------------------------------------------------------------------------------------------------------- void gui() { ImGui::ShowDemoWindow(); ImGuizmo::BeginFrame(); ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f)); ImGui::SetNextWindowSize(ImVec2(m_width, m_height)); int flags = ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse; ImGui::SetNextWindowPos(ImVec2(0, 0)); ImGui::SetNextWindowSize(ImVec2(m_width, m_height)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); if (ImGui::Begin("Gizmo", (bool*)0, flags)) ImGuizmo::SetDrawlist(); ImGui::End(); ImGui::PopStyleVar(); if (m_edit_mode) { if (ImGui::Begin("Inspector")) { Transform* t = nullptr; if (m_selected_entity != UINT32_MAX) { t = &m_scene->lookup_entity(m_selected_entity).transform; edit_transform((float*)&m_scene->camera()->m_view, (float*)&m_scene->camera()->m_projection, t); } else if (m_selected_dir_light != UINT32_MAX) { DirectionalLight& light = m_scene->lookup_directional_light(m_selected_dir_light); t = &light.transform; edit_transform((float*)&m_scene->camera()->m_view, (float*)&m_scene->camera()->m_projection, t, false, true, false); ImGui::Separator(); ImGui::Checkbox("Casts Shadows", &light.casts_shadow); ImGui::InputFloat("Shadow Map Bias", &light.shadow_map_bias); ImGui::InputFloat("Intensity", &light.intensity); ImGui::ColorPicker3("Color", &light.color.x); } else if (m_selected_point_light != UINT32_MAX) { PointLight& light = m_scene->lookup_point_light(m_selected_point_light); t = &light.transform; edit_transform((float*)&m_scene->camera()->m_view, (float*)&m_scene->camera()->m_projection, t, true, false, false); ImGui::Separator(); ImGui::Checkbox("Casts Shadows", &light.casts_shadow); ImGui::InputFloat("Shadow Map Bias", &light.shadow_map_bias); ImGui::InputFloat("Intensity", &light.intensity); ImGui::InputFloat("Range", &light.range); ImGui::ColorPicker3("Color", &light.color.x); m_debug_draw.sphere(light.range, light.transform.position, light.color); } else if (m_selected_spot_light != UINT32_MAX) { SpotLight& light = m_scene->lookup_spot_light(m_selected_spot_light); t = &light.transform; edit_transform((float*)&m_scene->camera()->m_view, (float*)&m_scene->camera()->m_projection, t, true, true, false); ImGui::Separator(); ImGui::Checkbox("Casts Shadows", &light.casts_shadow); ImGui::InputFloat("Shadow Map Bias", &light.shadow_map_bias); ImGui::InputFloat("Intensity", &light.intensity); ImGui::InputFloat("Range", &light.range); ImGui::InputFloat("Inner Cone Angle", &light.inner_cone_angle); ImGui::InputFloat("Outer Cone Angle", &light.outer_cone_angle); ImGui::ColorPicker3("Color", &light.color.x); } } ImGui::End(); } if (ImGui::Begin("Editor")) { ImGui::Checkbox("Edit Mode", &m_edit_mode); ImGui::Separator(); if (ImGui::CollapsingHeader("Scene")) { if (m_scene) ImGui::Text("Current Scene: %s", m_scene->name().c_str()); else ImGui::Text("Current Scene: -"); if (ImGui::Button("Load")) { if (load_scene_from_dialog()) { create_camera(); m_renderer.set_scene(m_scene); } } if (m_scene) { if (ImGui::Button("Unload")) { m_scene = nullptr; m_resource_manager.shutdown(); } } } if (ImGui::CollapsingHeader("Profiler")) profiler::ui(); if (ImGui::CollapsingHeader("Render Graph")) render_node_params(); if (ImGui::CollapsingHeader("Render Target Inspector")) render_target_inspector(); if (m_renderer.global_probe_renderer()) { if (ImGui::CollapsingHeader("Global Probe Renderer")) paramerizable_ui(m_renderer.global_probe_renderer()); } if (ImGui::CollapsingHeader("Entities")) { if (m_scene) { Entity* entities = m_scene->entities(); for (uint32_t i = 0; i < m_scene->entity_count(); i++) { if (ImGui::Selectable(entities[i].name.c_str(), m_selected_entity == entities[i].id)) { m_selected_entity = entities[i].id; m_selected_dir_light = UINT32_MAX; m_selected_point_light = UINT32_MAX; m_selected_spot_light = UINT32_MAX; } } } } if (ImGui::CollapsingHeader("Camera")) { std::shared_ptr<Camera> camera = m_scene->camera(); float near_plane = camera->m_near; float far_plane = camera->m_far; float fov = camera->m_fov; ImGui::InputFloat("Near Plane", &near_plane); ImGui::InputFloat("Far Plane", &far_plane); ImGui::SliderFloat("FOV", &fov, 1.0f, 90.0f); if (near_plane != camera->m_near || far_plane != camera->m_far || fov != camera->m_fov) camera->update_projection(fov, near_plane, far_plane, float(m_width) / float(m_height)); ImGui::SliderFloat("Near Field Begin", &camera->m_near_begin, camera->m_near, camera->m_far); ImGui::SliderFloat("Near Field End", &camera->m_near_end, camera->m_near, camera->m_far); ImGui::SliderFloat("Far Field Begin", &camera->m_far_begin, camera->m_near, camera->m_far); ImGui::SliderFloat("Far Field End", &camera->m_far_end, camera->m_near, camera->m_far); } if (ImGui::CollapsingHeader("Point Lights")) { if (m_scene) { PointLight* lights = m_scene->point_lights(); for (uint32_t i = 0; i < m_scene->point_light_count(); i++) { std::string name = std::to_string(lights[i].id); if (ImGui::Selectable(name.c_str(), m_selected_point_light == lights[i].id)) { m_selected_entity = UINT32_MAX; m_selected_dir_light = UINT32_MAX; m_selected_point_light = lights[i].id; m_selected_spot_light = UINT32_MAX; } } ImGui::Separator(); ImGui::PushID(1); if (ImGui::Button("Create")) m_scene->create_point_light(glm::vec3(0.0f), glm::vec3(1.0f), 100.0f, 1.0f); if (m_selected_point_light != UINT32_MAX) { ImGui::SameLine(); if (ImGui::Button("Remove")) { m_scene->destroy_point_light(m_selected_point_light); m_selected_point_light = UINT32_MAX; } } ImGui::PopID(); } } if (ImGui::CollapsingHeader("Spot Lights")) { if (m_scene) { SpotLight* lights = m_scene->spot_lights(); for (uint32_t i = 0; i < m_scene->spot_light_count(); i++) { std::string name = std::to_string(lights[i].id); if (ImGui::Selectable(name.c_str(), m_selected_spot_light == lights[i].id)) { m_selected_entity = UINT32_MAX; m_selected_dir_light = UINT32_MAX; m_selected_point_light = UINT32_MAX; m_selected_spot_light = lights[i].id; } } ImGui::Separator(); ImGui::PushID(2); if (ImGui::Button("Create")) m_scene->create_spot_light(glm::vec3(0.0f), glm::vec3(0.0f), glm::vec3(1.0f), 35.0f, 45.0f, 100.0f, 1.0f); if (m_selected_spot_light != UINT32_MAX) { ImGui::SameLine(); if (ImGui::Button("Remove")) { m_scene->destroy_spot_light(m_selected_spot_light); m_selected_spot_light = UINT32_MAX; } } ImGui::PopID(); } } if (ImGui::CollapsingHeader("Directional Lights")) { if (m_scene) { DirectionalLight* lights = m_scene->directional_lights(); for (uint32_t i = 0; i < m_scene->directional_light_count(); i++) { std::string name = std::to_string(lights[i].id); if (ImGui::Selectable(name.c_str(), m_selected_dir_light == lights[i].id)) { m_selected_entity = UINT32_MAX; m_selected_dir_light = lights[i].id; m_selected_point_light = UINT32_MAX; m_selected_spot_light = UINT32_MAX; } } ImGui::Separator(); ImGui::PushID(3); if (ImGui::Button("Create")) m_scene->create_directional_light(glm::vec3(0.0f), glm::vec3(1.0f), 10.0f); if (m_selected_dir_light != UINT32_MAX) { ImGui::SameLine(); if (ImGui::Button("Remove")) { m_scene->destroy_directional_light(m_selected_dir_light); m_selected_dir_light = UINT32_MAX; } } ImGui::PopID(); } } } ImGui::End(); } // ----------------------------------------------------------------------------------------------------------------------------------- void paramerizable_ui(std::shared_ptr<Parameterizable> paramterizable) { int32_t num_bool_params = 0; int32_t num_int_params = 0; int32_t num_float_params = 0; BoolParameter* bool_params = paramterizable->bool_parameters(num_bool_params); IntParameter* int_params = paramterizable->int_parameters(num_int_params); FloatParameter* float_params = paramterizable->float_parameters(num_float_params); for (uint32_t i = 0; i < num_bool_params; i++) ImGui::Checkbox(bool_params[i].name.c_str(), bool_params[i].ptr); for (uint32_t i = 0; i < num_int_params; i++) { if (int_params[i].min == int_params[i].max) ImGui::InputInt(int_params[i].name.c_str(), int_params[i].ptr); else ImGui::SliderInt(int_params[i].name.c_str(), int_params[i].ptr, int_params[i].min, int_params[i].max); } for (uint32_t i = 0; i < num_float_params; i++) { if (float_params[i].min == float_params[i].max) ImGui::InputFloat(float_params[i].name.c_str(), float_params[i].ptr); else ImGui::SliderFloat(float_params[i].name.c_str(), float_params[i].ptr, float_params[i].min, float_params[i].max); } } // ----------------------------------------------------------------------------------------------------------------------------------- void render_node_params() { for (uint32_t i = 0; i < m_forward_graph->node_count(); i++) { auto node = m_forward_graph->node(i); if (ImGui::TreeNode(node->name().c_str())) { paramerizable_ui(node); ImGui::TreePop(); } } } // ----------------------------------------------------------------------------------------------------------------------------------- void render_target_inspector() { bool scaled = m_renderer.scaled_debug_output(); ImGui::Checkbox("Scaled Debug Output", &scaled); m_renderer.set_scaled_debug_output(scaled); bool mask_bool[4]; glm::vec4 mask = m_renderer.debug_color_mask(); mask_bool[0] = (bool)mask.x; mask_bool[1] = (bool)mask.y; mask_bool[2] = (bool)mask.z; mask_bool[3] = (bool)mask.w; ImGui::Checkbox("Red", &mask_bool[0]); ImGui::Checkbox("Green", &mask_bool[1]); ImGui::Checkbox("Blue", &mask_bool[2]); ImGui::Checkbox("Alpha", &mask_bool[3]); mask.x = (float)mask_bool[0]; mask.y = (float)mask_bool[1]; mask.z = (float)mask_bool[2]; mask.w = (float)mask_bool[3]; m_renderer.set_debug_color_mask(mask); for (uint32_t i = 0; i < m_forward_graph->node_count(); i++) { auto node = m_forward_graph->node(i); if (ImGui::TreeNode(node->name().c_str())) { auto& rts = node->output_render_targets(); for (auto& output : rts) { if (ImGui::Selectable(output.slot_name.c_str(), m_renderer.debug_render_target() == output.render_target)) { if (m_renderer.debug_render_target() == output.render_target) m_renderer.set_debug_render_target(nullptr); else m_renderer.set_debug_render_target(output.render_target); } } for (int j = 0; j < node->intermediate_render_target_count(); j++) { std::string name = node->name() + "_intermediate_" + std::to_string(j); if (ImGui::Selectable(name.c_str(), m_renderer.debug_render_target() == node->intermediate_render_target(j))) { if (m_renderer.debug_render_target() == node->intermediate_render_target(j)) m_renderer.set_debug_render_target(nullptr); else m_renderer.set_debug_render_target(node->intermediate_render_target(j)); } } ImGui::TreePop(); } } } // ----------------------------------------------------------------------------------------------------------------------------------- void edit_transform(const float* cameraView, float* cameraProjection, Transform* t, bool show_translate = true, bool show_rotate = true, bool show_scale = true) { static ImGuizmo::OPERATION mCurrentGizmoOperation(ImGuizmo::TRANSLATE); static ImGuizmo::MODE mCurrentGizmoMode(ImGuizmo::WORLD); static bool useSnap = false; static float snap[3] = { 1.f, 1.f, 1.f }; if (show_translate) { if (ImGui::RadioButton("Translate", mCurrentGizmoOperation == ImGuizmo::TRANSLATE)) mCurrentGizmoOperation = ImGuizmo::TRANSLATE; } if (show_rotate) { ImGui::SameLine(); if (ImGui::RadioButton("Rotate", mCurrentGizmoOperation == ImGuizmo::ROTATE)) mCurrentGizmoOperation = ImGuizmo::ROTATE; } if (show_scale) { ImGui::SameLine(); if (ImGui::RadioButton("Scale", mCurrentGizmoOperation == ImGuizmo::SCALE)) mCurrentGizmoOperation = ImGuizmo::SCALE; } glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; ImGuizmo::DecomposeMatrixToComponents(&t->model[0][0], &position.x, &rotation.x, &scale.x); if (show_translate) ImGui::InputFloat3("Tr", &position.x, 3); if (show_rotate) ImGui::InputFloat3("Rt", &rotation.x, 3); if (show_scale) ImGui::InputFloat3("Sc", &scale.x, 3); ImGuizmo::RecomposeMatrixFromComponents(&position.x, &rotation.x, &scale.x, (float*)&t->model); if (mCurrentGizmoOperation != ImGuizmo::SCALE) { if (ImGui::RadioButton("Local", mCurrentGizmoMode == ImGuizmo::LOCAL)) mCurrentGizmoMode = ImGuizmo::LOCAL; ImGui::SameLine(); if (ImGui::RadioButton("World", mCurrentGizmoMode == ImGuizmo::WORLD)) mCurrentGizmoMode = ImGuizmo::WORLD; } ImGui::Checkbox("", &useSnap); ImGui::SameLine(); switch (mCurrentGizmoOperation) { case ImGuizmo::TRANSLATE: ImGui::InputFloat3("Snap", &snap[0]); break; case ImGuizmo::ROTATE: ImGui::InputFloat("Angle Snap", &snap[0]); break; case ImGuizmo::SCALE: ImGui::InputFloat("Scale Snap", &snap[0]); break; } ImGuiIO& io = ImGui::GetIO(); ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y); ImGuizmo::Manipulate(cameraView, cameraProjection, mCurrentGizmoOperation, mCurrentGizmoMode, (float*)&t->model, NULL, useSnap ? &snap[0] : NULL); glm::vec3 temp; ImGuizmo::DecomposeMatrixToComponents((float*)&t->model, &t->position.x, &temp.x, &t->scale.x); t->prev_model = t->model; t->orientation = glm::quat(glm::radians(temp)); } // ----------------------------------------------------------------------------------------------------------------------------------- bool load_scene_from_dialog() { std::shared_ptr<Scene> scene = nullptr; nfdchar_t* scene_path = nullptr; nfdresult_t result = NFD_OpenDialog("json", nullptr, &scene_path); if (result == NFD_OKAY) { scene = m_resource_manager.load_scene(scene_path, true); free(scene_path); if (!scene) { NIMBLE_LOG_ERROR("Failed to load scene!"); return false; } else { if (m_scene) m_renderer.shader_cache().clear_generated_cache(); m_scene = scene; } return true; } else if (result == NFD_CANCEL) return false; else { std::string error = "Scene file read error: "; error += NFD_GetError(); NIMBLE_LOG_ERROR(error); return false; } } // ----------------------------------------------------------------------------------------------------------------------------------- void update_camera() { if (m_scene) { auto current = m_scene->camera(); float forward_delta = m_heading_speed * m_delta; float right_delta = m_sideways_speed * m_delta; current->set_translation_delta(current->m_forward, forward_delta); current->set_translation_delta(current->m_right, right_delta); if (m_mouse_look) { // Activate Mouse Look current->set_rotatation_delta(glm::vec3((float)(m_mouse_delta_y * m_camera_sensitivity), (float)(m_mouse_delta_x * m_camera_sensitivity), (float)(0.0f))); } else { current->set_rotatation_delta(glm::vec3((float)(0), (float)(0), (float)(0))); } current->update(); } } // ----------------------------------------------------------------------------------------------------------------------------------- private: // Camera controls. bool m_mouse_look = false; bool m_edit_mode = true; bool m_debug_mode = false; bool m_debug_gui = false; bool m_move_entities = false; float m_heading_speed = 0.0f; float m_sideways_speed = 0.0f; float m_camera_sensitivity = 0.05f; float m_camera_speed = 0.1f; std::shared_ptr<Scene> m_scene; std::shared_ptr<Viewport> m_viewport; std::shared_ptr<RenderGraph> m_forward_graph; std::shared_ptr<RenderGraph> m_pcf_point_light_graph; std::shared_ptr<RenderGraph> m_pcf_spot_light_graph; std::shared_ptr<RenderGraph> m_pcf_directional_light_graph; std::shared_ptr<BrunetonProbeRenderer> m_bruneton_probe_renderer; Entity::ID m_selected_entity = UINT32_MAX; PointLight::ID m_selected_point_light = UINT32_MAX; SpotLight::ID m_selected_spot_light = UINT32_MAX; DirectionalLight::ID m_selected_dir_light = UINT32_MAX; }; } // namespace nimble NIMBLE_DECLARE_MAIN(nimble::Nimble)
39.24183
273
0.515018
hdachev
906b7416fccae8b3af91851f3b4dcd5301c0c104
483
cpp
C++
client/include/game/CTaskSimpleFacial.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
client/include/game/CTaskSimpleFacial.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
92
2019-01-23T23:02:31.000Z
2022-03-23T19:59:40.000Z
client/include/game/CTaskSimpleFacial.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto San Andreas) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CTaskSimpleFacial.h" CTaskSimpleFacial::CTaskSimpleFacial(eFacialExpression nFacialExpress, int nDuration) : CTaskSimple(plugin::dummy) , m_Timer(plugin::dummy) { plugin::CallMethod<0x690C70, CTaskSimpleFacial*, eFacialExpression, int>(this, nFacialExpress, nDuration); }
37.153846
110
0.780538
MayconFelipeA
906b770be0557513b38aa2e86e6953ee76de6f45
45,893
cpp
C++
aws-cpp-sdk-globalaccelerator/source/GlobalAcceleratorClient.cpp
orinem/aws-sdk-cpp
f38413cc1f278689ef14e9ebdd74a489a48776be
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-globalaccelerator/source/GlobalAcceleratorClient.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-globalaccelerator/source/GlobalAcceleratorClient.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/globalaccelerator/GlobalAcceleratorClient.h> #include <aws/globalaccelerator/GlobalAcceleratorEndpoint.h> #include <aws/globalaccelerator/GlobalAcceleratorErrorMarshaller.h> #include <aws/globalaccelerator/model/AdvertiseByoipCidrRequest.h> #include <aws/globalaccelerator/model/CreateAcceleratorRequest.h> #include <aws/globalaccelerator/model/CreateEndpointGroupRequest.h> #include <aws/globalaccelerator/model/CreateListenerRequest.h> #include <aws/globalaccelerator/model/DeleteAcceleratorRequest.h> #include <aws/globalaccelerator/model/DeleteEndpointGroupRequest.h> #include <aws/globalaccelerator/model/DeleteListenerRequest.h> #include <aws/globalaccelerator/model/DeprovisionByoipCidrRequest.h> #include <aws/globalaccelerator/model/DescribeAcceleratorRequest.h> #include <aws/globalaccelerator/model/DescribeAcceleratorAttributesRequest.h> #include <aws/globalaccelerator/model/DescribeEndpointGroupRequest.h> #include <aws/globalaccelerator/model/DescribeListenerRequest.h> #include <aws/globalaccelerator/model/ListAcceleratorsRequest.h> #include <aws/globalaccelerator/model/ListByoipCidrsRequest.h> #include <aws/globalaccelerator/model/ListEndpointGroupsRequest.h> #include <aws/globalaccelerator/model/ListListenersRequest.h> #include <aws/globalaccelerator/model/ListTagsForResourceRequest.h> #include <aws/globalaccelerator/model/ProvisionByoipCidrRequest.h> #include <aws/globalaccelerator/model/TagResourceRequest.h> #include <aws/globalaccelerator/model/UntagResourceRequest.h> #include <aws/globalaccelerator/model/UpdateAcceleratorRequest.h> #include <aws/globalaccelerator/model/UpdateAcceleratorAttributesRequest.h> #include <aws/globalaccelerator/model/UpdateEndpointGroupRequest.h> #include <aws/globalaccelerator/model/UpdateListenerRequest.h> #include <aws/globalaccelerator/model/WithdrawByoipCidrRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::GlobalAccelerator; using namespace Aws::GlobalAccelerator::Model; using namespace Aws::Http; using namespace Aws::Utils::Json; static const char* SERVICE_NAME = "globalaccelerator"; static const char* ALLOCATION_TAG = "GlobalAcceleratorClient"; GlobalAcceleratorClient::GlobalAcceleratorClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<GlobalAcceleratorErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } GlobalAcceleratorClient::GlobalAcceleratorClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<GlobalAcceleratorErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } GlobalAcceleratorClient::GlobalAcceleratorClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<GlobalAcceleratorErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } GlobalAcceleratorClient::~GlobalAcceleratorClient() { } void GlobalAcceleratorClient::init(const ClientConfiguration& config) { m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + GlobalAcceleratorEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } } void GlobalAcceleratorClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } } AdvertiseByoipCidrOutcome GlobalAcceleratorClient::AdvertiseByoipCidr(const AdvertiseByoipCidrRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return AdvertiseByoipCidrOutcome(AdvertiseByoipCidrResult(outcome.GetResult())); } else { return AdvertiseByoipCidrOutcome(outcome.GetError()); } } AdvertiseByoipCidrOutcomeCallable GlobalAcceleratorClient::AdvertiseByoipCidrCallable(const AdvertiseByoipCidrRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< AdvertiseByoipCidrOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->AdvertiseByoipCidr(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::AdvertiseByoipCidrAsync(const AdvertiseByoipCidrRequest& request, const AdvertiseByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->AdvertiseByoipCidrAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::AdvertiseByoipCidrAsyncHelper(const AdvertiseByoipCidrRequest& request, const AdvertiseByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, AdvertiseByoipCidr(request), context); } CreateAcceleratorOutcome GlobalAcceleratorClient::CreateAccelerator(const CreateAcceleratorRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return CreateAcceleratorOutcome(CreateAcceleratorResult(outcome.GetResult())); } else { return CreateAcceleratorOutcome(outcome.GetError()); } } CreateAcceleratorOutcomeCallable GlobalAcceleratorClient::CreateAcceleratorCallable(const CreateAcceleratorRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateAcceleratorOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateAccelerator(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::CreateAcceleratorAsync(const CreateAcceleratorRequest& request, const CreateAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateAcceleratorAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::CreateAcceleratorAsyncHelper(const CreateAcceleratorRequest& request, const CreateAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateAccelerator(request), context); } CreateEndpointGroupOutcome GlobalAcceleratorClient::CreateEndpointGroup(const CreateEndpointGroupRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return CreateEndpointGroupOutcome(CreateEndpointGroupResult(outcome.GetResult())); } else { return CreateEndpointGroupOutcome(outcome.GetError()); } } CreateEndpointGroupOutcomeCallable GlobalAcceleratorClient::CreateEndpointGroupCallable(const CreateEndpointGroupRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateEndpointGroupOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateEndpointGroup(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::CreateEndpointGroupAsync(const CreateEndpointGroupRequest& request, const CreateEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateEndpointGroupAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::CreateEndpointGroupAsyncHelper(const CreateEndpointGroupRequest& request, const CreateEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateEndpointGroup(request), context); } CreateListenerOutcome GlobalAcceleratorClient::CreateListener(const CreateListenerRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return CreateListenerOutcome(CreateListenerResult(outcome.GetResult())); } else { return CreateListenerOutcome(outcome.GetError()); } } CreateListenerOutcomeCallable GlobalAcceleratorClient::CreateListenerCallable(const CreateListenerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateListenerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateListener(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::CreateListenerAsync(const CreateListenerRequest& request, const CreateListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateListenerAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::CreateListenerAsyncHelper(const CreateListenerRequest& request, const CreateListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateListener(request), context); } DeleteAcceleratorOutcome GlobalAcceleratorClient::DeleteAccelerator(const DeleteAcceleratorRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DeleteAcceleratorOutcome(NoResult()); } else { return DeleteAcceleratorOutcome(outcome.GetError()); } } DeleteAcceleratorOutcomeCallable GlobalAcceleratorClient::DeleteAcceleratorCallable(const DeleteAcceleratorRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteAcceleratorOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteAccelerator(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::DeleteAcceleratorAsync(const DeleteAcceleratorRequest& request, const DeleteAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteAcceleratorAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::DeleteAcceleratorAsyncHelper(const DeleteAcceleratorRequest& request, const DeleteAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteAccelerator(request), context); } DeleteEndpointGroupOutcome GlobalAcceleratorClient::DeleteEndpointGroup(const DeleteEndpointGroupRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DeleteEndpointGroupOutcome(NoResult()); } else { return DeleteEndpointGroupOutcome(outcome.GetError()); } } DeleteEndpointGroupOutcomeCallable GlobalAcceleratorClient::DeleteEndpointGroupCallable(const DeleteEndpointGroupRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteEndpointGroupOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteEndpointGroup(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::DeleteEndpointGroupAsync(const DeleteEndpointGroupRequest& request, const DeleteEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteEndpointGroupAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::DeleteEndpointGroupAsyncHelper(const DeleteEndpointGroupRequest& request, const DeleteEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteEndpointGroup(request), context); } DeleteListenerOutcome GlobalAcceleratorClient::DeleteListener(const DeleteListenerRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DeleteListenerOutcome(NoResult()); } else { return DeleteListenerOutcome(outcome.GetError()); } } DeleteListenerOutcomeCallable GlobalAcceleratorClient::DeleteListenerCallable(const DeleteListenerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteListenerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteListener(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::DeleteListenerAsync(const DeleteListenerRequest& request, const DeleteListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteListenerAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::DeleteListenerAsyncHelper(const DeleteListenerRequest& request, const DeleteListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteListener(request), context); } DeprovisionByoipCidrOutcome GlobalAcceleratorClient::DeprovisionByoipCidr(const DeprovisionByoipCidrRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DeprovisionByoipCidrOutcome(DeprovisionByoipCidrResult(outcome.GetResult())); } else { return DeprovisionByoipCidrOutcome(outcome.GetError()); } } DeprovisionByoipCidrOutcomeCallable GlobalAcceleratorClient::DeprovisionByoipCidrCallable(const DeprovisionByoipCidrRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeprovisionByoipCidrOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeprovisionByoipCidr(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::DeprovisionByoipCidrAsync(const DeprovisionByoipCidrRequest& request, const DeprovisionByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeprovisionByoipCidrAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::DeprovisionByoipCidrAsyncHelper(const DeprovisionByoipCidrRequest& request, const DeprovisionByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeprovisionByoipCidr(request), context); } DescribeAcceleratorOutcome GlobalAcceleratorClient::DescribeAccelerator(const DescribeAcceleratorRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DescribeAcceleratorOutcome(DescribeAcceleratorResult(outcome.GetResult())); } else { return DescribeAcceleratorOutcome(outcome.GetError()); } } DescribeAcceleratorOutcomeCallable GlobalAcceleratorClient::DescribeAcceleratorCallable(const DescribeAcceleratorRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeAcceleratorOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeAccelerator(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::DescribeAcceleratorAsync(const DescribeAcceleratorRequest& request, const DescribeAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeAcceleratorAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::DescribeAcceleratorAsyncHelper(const DescribeAcceleratorRequest& request, const DescribeAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeAccelerator(request), context); } DescribeAcceleratorAttributesOutcome GlobalAcceleratorClient::DescribeAcceleratorAttributes(const DescribeAcceleratorAttributesRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DescribeAcceleratorAttributesOutcome(DescribeAcceleratorAttributesResult(outcome.GetResult())); } else { return DescribeAcceleratorAttributesOutcome(outcome.GetError()); } } DescribeAcceleratorAttributesOutcomeCallable GlobalAcceleratorClient::DescribeAcceleratorAttributesCallable(const DescribeAcceleratorAttributesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeAcceleratorAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeAcceleratorAttributes(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::DescribeAcceleratorAttributesAsync(const DescribeAcceleratorAttributesRequest& request, const DescribeAcceleratorAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeAcceleratorAttributesAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::DescribeAcceleratorAttributesAsyncHelper(const DescribeAcceleratorAttributesRequest& request, const DescribeAcceleratorAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeAcceleratorAttributes(request), context); } DescribeEndpointGroupOutcome GlobalAcceleratorClient::DescribeEndpointGroup(const DescribeEndpointGroupRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DescribeEndpointGroupOutcome(DescribeEndpointGroupResult(outcome.GetResult())); } else { return DescribeEndpointGroupOutcome(outcome.GetError()); } } DescribeEndpointGroupOutcomeCallable GlobalAcceleratorClient::DescribeEndpointGroupCallable(const DescribeEndpointGroupRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeEndpointGroupOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeEndpointGroup(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::DescribeEndpointGroupAsync(const DescribeEndpointGroupRequest& request, const DescribeEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeEndpointGroupAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::DescribeEndpointGroupAsyncHelper(const DescribeEndpointGroupRequest& request, const DescribeEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeEndpointGroup(request), context); } DescribeListenerOutcome GlobalAcceleratorClient::DescribeListener(const DescribeListenerRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DescribeListenerOutcome(DescribeListenerResult(outcome.GetResult())); } else { return DescribeListenerOutcome(outcome.GetError()); } } DescribeListenerOutcomeCallable GlobalAcceleratorClient::DescribeListenerCallable(const DescribeListenerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeListenerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeListener(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::DescribeListenerAsync(const DescribeListenerRequest& request, const DescribeListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeListenerAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::DescribeListenerAsyncHelper(const DescribeListenerRequest& request, const DescribeListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeListener(request), context); } ListAcceleratorsOutcome GlobalAcceleratorClient::ListAccelerators(const ListAcceleratorsRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListAcceleratorsOutcome(ListAcceleratorsResult(outcome.GetResult())); } else { return ListAcceleratorsOutcome(outcome.GetError()); } } ListAcceleratorsOutcomeCallable GlobalAcceleratorClient::ListAcceleratorsCallable(const ListAcceleratorsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListAcceleratorsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListAccelerators(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::ListAcceleratorsAsync(const ListAcceleratorsRequest& request, const ListAcceleratorsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListAcceleratorsAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::ListAcceleratorsAsyncHelper(const ListAcceleratorsRequest& request, const ListAcceleratorsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListAccelerators(request), context); } ListByoipCidrsOutcome GlobalAcceleratorClient::ListByoipCidrs(const ListByoipCidrsRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListByoipCidrsOutcome(ListByoipCidrsResult(outcome.GetResult())); } else { return ListByoipCidrsOutcome(outcome.GetError()); } } ListByoipCidrsOutcomeCallable GlobalAcceleratorClient::ListByoipCidrsCallable(const ListByoipCidrsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListByoipCidrsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListByoipCidrs(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::ListByoipCidrsAsync(const ListByoipCidrsRequest& request, const ListByoipCidrsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListByoipCidrsAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::ListByoipCidrsAsyncHelper(const ListByoipCidrsRequest& request, const ListByoipCidrsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListByoipCidrs(request), context); } ListEndpointGroupsOutcome GlobalAcceleratorClient::ListEndpointGroups(const ListEndpointGroupsRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListEndpointGroupsOutcome(ListEndpointGroupsResult(outcome.GetResult())); } else { return ListEndpointGroupsOutcome(outcome.GetError()); } } ListEndpointGroupsOutcomeCallable GlobalAcceleratorClient::ListEndpointGroupsCallable(const ListEndpointGroupsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListEndpointGroupsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListEndpointGroups(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::ListEndpointGroupsAsync(const ListEndpointGroupsRequest& request, const ListEndpointGroupsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListEndpointGroupsAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::ListEndpointGroupsAsyncHelper(const ListEndpointGroupsRequest& request, const ListEndpointGroupsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListEndpointGroups(request), context); } ListListenersOutcome GlobalAcceleratorClient::ListListeners(const ListListenersRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListListenersOutcome(ListListenersResult(outcome.GetResult())); } else { return ListListenersOutcome(outcome.GetError()); } } ListListenersOutcomeCallable GlobalAcceleratorClient::ListListenersCallable(const ListListenersRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListListenersOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListListeners(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::ListListenersAsync(const ListListenersRequest& request, const ListListenersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListListenersAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::ListListenersAsyncHelper(const ListListenersRequest& request, const ListListenersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListListeners(request), context); } ListTagsForResourceOutcome GlobalAcceleratorClient::ListTagsForResource(const ListTagsForResourceRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListTagsForResourceOutcome(ListTagsForResourceResult(outcome.GetResult())); } else { return ListTagsForResourceOutcome(outcome.GetError()); } } ListTagsForResourceOutcomeCallable GlobalAcceleratorClient::ListTagsForResourceCallable(const ListTagsForResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListTagsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTagsForResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::ListTagsForResourceAsync(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListTagsForResourceAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::ListTagsForResourceAsyncHelper(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListTagsForResource(request), context); } ProvisionByoipCidrOutcome GlobalAcceleratorClient::ProvisionByoipCidr(const ProvisionByoipCidrRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ProvisionByoipCidrOutcome(ProvisionByoipCidrResult(outcome.GetResult())); } else { return ProvisionByoipCidrOutcome(outcome.GetError()); } } ProvisionByoipCidrOutcomeCallable GlobalAcceleratorClient::ProvisionByoipCidrCallable(const ProvisionByoipCidrRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ProvisionByoipCidrOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ProvisionByoipCidr(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::ProvisionByoipCidrAsync(const ProvisionByoipCidrRequest& request, const ProvisionByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ProvisionByoipCidrAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::ProvisionByoipCidrAsyncHelper(const ProvisionByoipCidrRequest& request, const ProvisionByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ProvisionByoipCidr(request), context); } TagResourceOutcome GlobalAcceleratorClient::TagResource(const TagResourceRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return TagResourceOutcome(TagResourceResult(outcome.GetResult())); } else { return TagResourceOutcome(outcome.GetError()); } } TagResourceOutcomeCallable GlobalAcceleratorClient::TagResourceCallable(const TagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, TagResource(request), context); } UntagResourceOutcome GlobalAcceleratorClient::UntagResource(const UntagResourceRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UntagResourceOutcome(UntagResourceResult(outcome.GetResult())); } else { return UntagResourceOutcome(outcome.GetError()); } } UntagResourceOutcomeCallable GlobalAcceleratorClient::UntagResourceCallable(const UntagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UntagResource(request), context); } UpdateAcceleratorOutcome GlobalAcceleratorClient::UpdateAccelerator(const UpdateAcceleratorRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateAcceleratorOutcome(UpdateAcceleratorResult(outcome.GetResult())); } else { return UpdateAcceleratorOutcome(outcome.GetError()); } } UpdateAcceleratorOutcomeCallable GlobalAcceleratorClient::UpdateAcceleratorCallable(const UpdateAcceleratorRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateAcceleratorOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateAccelerator(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::UpdateAcceleratorAsync(const UpdateAcceleratorRequest& request, const UpdateAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateAcceleratorAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::UpdateAcceleratorAsyncHelper(const UpdateAcceleratorRequest& request, const UpdateAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateAccelerator(request), context); } UpdateAcceleratorAttributesOutcome GlobalAcceleratorClient::UpdateAcceleratorAttributes(const UpdateAcceleratorAttributesRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateAcceleratorAttributesOutcome(UpdateAcceleratorAttributesResult(outcome.GetResult())); } else { return UpdateAcceleratorAttributesOutcome(outcome.GetError()); } } UpdateAcceleratorAttributesOutcomeCallable GlobalAcceleratorClient::UpdateAcceleratorAttributesCallable(const UpdateAcceleratorAttributesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateAcceleratorAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateAcceleratorAttributes(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::UpdateAcceleratorAttributesAsync(const UpdateAcceleratorAttributesRequest& request, const UpdateAcceleratorAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateAcceleratorAttributesAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::UpdateAcceleratorAttributesAsyncHelper(const UpdateAcceleratorAttributesRequest& request, const UpdateAcceleratorAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateAcceleratorAttributes(request), context); } UpdateEndpointGroupOutcome GlobalAcceleratorClient::UpdateEndpointGroup(const UpdateEndpointGroupRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateEndpointGroupOutcome(UpdateEndpointGroupResult(outcome.GetResult())); } else { return UpdateEndpointGroupOutcome(outcome.GetError()); } } UpdateEndpointGroupOutcomeCallable GlobalAcceleratorClient::UpdateEndpointGroupCallable(const UpdateEndpointGroupRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateEndpointGroupOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateEndpointGroup(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::UpdateEndpointGroupAsync(const UpdateEndpointGroupRequest& request, const UpdateEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateEndpointGroupAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::UpdateEndpointGroupAsyncHelper(const UpdateEndpointGroupRequest& request, const UpdateEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateEndpointGroup(request), context); } UpdateListenerOutcome GlobalAcceleratorClient::UpdateListener(const UpdateListenerRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateListenerOutcome(UpdateListenerResult(outcome.GetResult())); } else { return UpdateListenerOutcome(outcome.GetError()); } } UpdateListenerOutcomeCallable GlobalAcceleratorClient::UpdateListenerCallable(const UpdateListenerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateListenerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateListener(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::UpdateListenerAsync(const UpdateListenerRequest& request, const UpdateListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateListenerAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::UpdateListenerAsyncHelper(const UpdateListenerRequest& request, const UpdateListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateListener(request), context); } WithdrawByoipCidrOutcome GlobalAcceleratorClient::WithdrawByoipCidr(const WithdrawByoipCidrRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return WithdrawByoipCidrOutcome(WithdrawByoipCidrResult(outcome.GetResult())); } else { return WithdrawByoipCidrOutcome(outcome.GetError()); } } WithdrawByoipCidrOutcomeCallable GlobalAcceleratorClient::WithdrawByoipCidrCallable(const WithdrawByoipCidrRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< WithdrawByoipCidrOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->WithdrawByoipCidr(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void GlobalAcceleratorClient::WithdrawByoipCidrAsync(const WithdrawByoipCidrRequest& request, const WithdrawByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->WithdrawByoipCidrAsyncHelper( request, handler, context ); } ); } void GlobalAcceleratorClient::WithdrawByoipCidrAsyncHelper(const WithdrawByoipCidrRequest& request, const WithdrawByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, WithdrawByoipCidr(request), context); }
45.619284
269
0.783627
orinem
906c27d56bc24a4ac2a48fa53fdd7821d5e5f405
3,313
cpp
C++
modules/cpplocate/source/cpplocate/source/cpplocate.cpp
helmesjo/minesweeper-sweeper
06e269e8a7342d343c6f145af9ac43a52dfc2239
[ "MIT" ]
null
null
null
modules/cpplocate/source/cpplocate/source/cpplocate.cpp
helmesjo/minesweeper-sweeper
06e269e8a7342d343c6f145af9ac43a52dfc2239
[ "MIT" ]
null
null
null
modules/cpplocate/source/cpplocate/source/cpplocate.cpp
helmesjo/minesweeper-sweeper
06e269e8a7342d343c6f145af9ac43a52dfc2239
[ "MIT" ]
null
null
null
#include <cpplocate/cpplocate.h> #if defined SYSTEM_LINUX #include <unistd.h> #include <limits.h> #elif defined SYSTEM_WINDOWS #include <stdlib.h> #elif defined SYSTEM_SOLARIS #include <stdlib.h> #include <limits.h> #elif defined SYSTEM_DARWIN #include <mach-o/dyld.h> #elif defined SYSTEM_FREEBSD #include <sys/types.h> #include <sys/sysctl.h> #endif #include <cstdlib> #include <vector> #include <string> #include <cpplocate/utils.h> namespace { #ifdef SYSTEM_WINDOWS const char pathDelim = '\\'; #else const char pathDelim = '/'; #endif } // namespace namespace cpplocate { std::string getExecutablePath() { #if defined SYSTEM_LINUX char exePath[PATH_MAX]; ssize_t len = ::readlink("/proc/self/exe", exePath, sizeof(exePath)); if (len == -1 || len == sizeof(exePath)) { len = 0; } exePath[len] = '\0'; #elif defined SYSTEM_WINDOWS char * exePath; if (_get_pgmptr(&exePath) != 0) { exePath = ""; } #elif defined SYSTEM_SOLARIS char exePath[PATH_MAX]; if (realpath(getexecname(), exePath) == nullptr) { exePath[0] = '\0'; } #elif defined SYSTEM_DARWIN char exePath[PATH_MAX]; uint32_t len = sizeof(exePath); if (_NSGetExecutablePath(exePath, &len) == 0) { char * realPath = realpath(exePath, nullptr); if (realPath) { strncpy(exePath, realPath, len); free(realPath); } } else { exePath[0] = '\0'; } #elif defined SYSTEM_FREEBSD char exePath[2048]; size_t len = sizeof(exePath); int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; if (sysctl(mib, 4, exePath, &len, nullptr, 0) != 0) { exePath[0] = '\0'; } #else char * exePath = ""; #endif return std::string(exePath); } std::string getModulePath() { return utils::getDirectoryPath(getExecutablePath()); } ModuleInfo findModule(const std::string & name) { ModuleInfo info; // Search at current module location if (utils::loadModule(getModulePath(), name, info)) { return info; } // Search all paths in CPPLOCATE_PATH std::vector<std::string> paths; std::string cppLocatePath = utils::getEnv("CPPLOCATE_PATH"); utils::getPaths(cppLocatePath, paths); for (std::string path : paths) { if (utils::loadModule(path, name, info)) { return info; } if (utils::loadModule(utils::trimPath(path) + pathDelim + name, name, info)) { return info; } } // Search in standard locations #if defined SYSTEM_WINDOWS std::string programFiles64 = utils::getEnv("programfiles"); std::string programFiles32 = utils::getEnv("programfiles(x86)"); if (utils::loadModule(programFiles64 + "\\" + name, name, info)) { return info; } if (utils::loadModule(programFiles32 + "\\" + name, name, info)) { return info; } #else if (utils::loadModule("/usr/share/" + name, name, info)) { return info; } if (utils::loadModule("/usr/local/share/" + name, name, info)) { return info; } #endif // Not found return ModuleInfo(); } } // namespace cpplocate
18.931429
84
0.598853
helmesjo
906cf38280a216b2fac548bef4a0f9d47b36abbc
1,394
cc
C++
src/rocksdb2/util/hash.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
5
2019-01-23T04:36:03.000Z
2020-02-04T07:10:39.000Z
src/rocksdb2/util/hash.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
null
null
null
src/rocksdb2/util/hash.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
2
2019-05-14T07:26:59.000Z
2020-06-15T07:25:01.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2011至今,Facebook,Inc.保留所有权利。 //此源代码在两个gplv2下都获得了许可(在 //复制根目录中的文件)和Apache2.0许可证 //(在根目录的license.apache文件中找到)。 // //版权所有(c)2011 LevelDB作者。版权所有。 //此源代码的使用受可以 //在许可证文件中找到。有关参与者的名称,请参阅作者文件。 #include <string.h> #include "util/coding.h" #include "util/hash.h" namespace rocksdb { uint32_t Hash(const char* data, size_t n, uint32_t seed) { //类似于杂音杂音杂音 const uint32_t m = 0xc6a4a793; const uint32_t r = 24; const char* limit = data + n; uint32_t h = static_cast<uint32_t>(seed ^ (n * m)); //一次接收四个字节 while (data + 4 <= limit) { uint32_t w = DecodeFixed32(data); data += 4; h += w; h *= m; h ^= (h >> 16); } //提取剩余字节 switch (limit - data) { //注意:最初的哈希实现使用了数据[i]<<shift,其中 //将char提升为int,然后执行移位。如果字符是 //否定,移位是C++中未定义的行为。哈希算法是 //格式定义的一部分,因此我们不能更改它;以获取相同的 //在法律上的行为,我们只是投给uint32,这会 //延长签名。确保与chars架构的兼容性 //是无符号的,我们首先将字符转换为int8_t。 case 3: h += static_cast<uint32_t>(static_cast<int8_t>(data[2])) << 16; //跌倒 case 2: h += static_cast<uint32_t>(static_cast<int8_t>(data[1])) << 8; //跌倒 case 1: h += static_cast<uint32_t>(static_cast<int8_t>(data[0])); h *= m; h ^= (h >> r); break; } return h; } } //命名空间rocksdb
21.446154
69
0.662123
yinchengtsinghua
906d57444875fde21714cb5e41b17f06969ab1d2
97
cpp
C++
elements/behavior/movebehavior.cpp
zenitaeglos/AsteroidsGame
7456d29f5edee3089fd15d51e2247c8b4f351cdf
[ "CC-BY-3.0" ]
null
null
null
elements/behavior/movebehavior.cpp
zenitaeglos/AsteroidsGame
7456d29f5edee3089fd15d51e2247c8b4f351cdf
[ "CC-BY-3.0" ]
null
null
null
elements/behavior/movebehavior.cpp
zenitaeglos/AsteroidsGame
7456d29f5edee3089fd15d51e2247c8b4f351cdf
[ "CC-BY-3.0" ]
null
null
null
#include "movebehavior.h" MoveBehavior::MoveBehavior() { } MoveBehavior::~MoveBehavior() { }
8.083333
29
0.701031
zenitaeglos
9070c486a2eccf11ce71491643e47edb3543c1e2
806
cpp
C++
codeforces/914E.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
codeforces/914E.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
codeforces/914E.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define pb push_back #define mp make_pair #define pii pair <int, int> #define all(v) (v).begin() (v).end() #define fi first #define se second #define ll long long #define ull long long #define ld long double #define MOD 1000000007 #define MAXN 200005 using namespace std; map <int, int> DP[MAXN]; vector <int> G[MAXN]; int n; char label[MAXN]; void dfs1(int nd, int parent) { for (int i = 0, h; i < G[nd].size(); i++) { h = G[nd][i]; if (h == parent) continue; dfs1(h, nd); } DP[nd][1<<(label[nd-1] - 'a')] = 1; } int main(int nargs, char **args) { scanf("%d", &n); for (int i = 1, u, v; i < n; i++) { scanf("%d%d", &u, &v); G[u].pb(v); G[v].pb(u); } scanf("%s", label); return 0; }
17.521739
47
0.532258
Victoralin10
907319f2232ab9f64e20be32d130956246853a4c
4,607
cpp
C++
source/tests/external/gotcha_tests_lib.cpp
dalg24/timemory
8cbbf89a25d8d460382664baeec0b13d5d4e2d38
[ "MIT" ]
null
null
null
source/tests/external/gotcha_tests_lib.cpp
dalg24/timemory
8cbbf89a25d8d460382664baeec0b13d5d4e2d38
[ "MIT" ]
null
null
null
source/tests/external/gotcha_tests_lib.cpp
dalg24/timemory
8cbbf89a25d8d460382664baeec0b13d5d4e2d38
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2019, The Regents of the University of California, // through Lawrence Berkeley National Laboratory (subject to receipt of any // required approvals from the U.S. Dept. of Energy). All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "gotcha_tests_lib.hpp" #include <chrono> #include <cmath> #include <cstdint> #include <cstdio> #include <string> #include <thread> extern "C" { double test_exp(double val) { return exp(val); } } // namespace ext { //--------------------------------------------------------------------------------------// void do_puts(const char* msg) { puts(msg); } //--------------------------------------------------------------------------------------// template <typename _Tp, typename _Func, typename _Incr> _Tp work(int64_t nitr, _Func&& func, _Incr&& incr) { _Tp val = 2.0; _Tp sum = 0.0; for(int64_t i = 0; i < nitr; ++i) { sum += func(val); val = incr(val, i + 1); } return sum; } //--------------------------------------------------------------------------------------// std::tuple<float, double> do_work(int64_t nitr, const std::pair<float, double>& p) { auto fsum = work<float>(nitr, [](float val) -> float { return cosf(val); }, [&](float val, int64_t i) -> float { return val + p.first * i; }); auto dsum = work<double>(nitr, [](double val) -> double { return cos(val); }, [&](double val, int64_t i) -> double { return val + p.second * i; }); return std::tuple<float, double>(fsum, dsum); } //--------------------------------------------------------------------------------------// } // namespace ext //--------------------------------------------------------------------------------------// DoWork::DoWork(const std::pair<float, double>& pair) : m_pair(pair) , m_tuple{ 0.0f, 0.0 } {} //--------------------------------------------------------------------------------------// void DoWork::execute_fp4(int64_t nitr) { std::get<0>(m_tuple) = ext::work<float>( nitr, [](float val) -> float { return cosf(val); }, [&](float val, int64_t i) -> float { return val + m_pair.first * i; }); } //--------------------------------------------------------------------------------------// void DoWork::execute_fp8(int64_t nitr) { std::get<1>(m_tuple) = ext::work<double>( nitr, [](double val) -> double { return cos(val); }, [&](double val, int64_t i) -> double { return val + m_pair.second * i; }); } //--------------------------------------------------------------------------------------// void DoWork::execute_fp(int64_t nitr, std::vector<float> fvals, const std::deque<double>& dvals) { float fret = 0.0; for(const auto& itr : fvals) { fret += ext::work<float>( nitr, [](float val) -> float { return cosf(val); }, [&](float val, int64_t i) -> float { return val + itr * i; }); } std::get<0>(m_tuple) = fret; double dret = 0.0; for(const auto& itr : dvals) { dret += ext::work<double>( nitr, [](double val) -> double { return cos(val); }, [&](double val, int64_t i) -> double { return val + itr * i; }); } std::get<1>(m_tuple) = dret; } //--------------------------------------------------------------------------------------// std::tuple<float, double> DoWork::get() const { return m_tuple; } //--------------------------------------------------------------------------------------//
31.128378
90
0.504884
dalg24
9074dc8635d8b3d0bfec8f90a2099edfec85ab3a
1,713
cpp
C++
timus/1002.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
timus/1002.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
timus/1002.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
#include<cstdio> #include<cstring> struct node { node *ne,*ch; char d; int x; }*root; char num[]={2,2,2,3,3,3,4,4,1,1,5,5,6,6,0,7,0,7,7,8,8,8,9,9,9,0}; void clear(node *ptr=root) { if(!ptr)return; clear(ptr->ne),clear(ptr->ch); delete ptr; } char ins(int i,char s[],node *&ptr=root) { if(!ptr) { ptr=new node; ptr->d=num[s[0]-'a']; ptr->x=-1; ptr->ne=ptr->ch=NULL; } if(ptr->d!=num[s[0]-'a']) return ins(i,s,ptr->ne); if(!s[1]) { if(ptr->x!=-1)return 0; ptr->x=i; return 1; } return ins(i,s+1,ptr->ch); } char word[50000][51]; int p[101],s[101]; void print(int i) { if(i-strlen(word[p[i]])>0) print(i-strlen(word[p[i]])),putchar(' '); printf(word[p[i]]); } main() { int i,j,k; char tmp[101],tmp0[51]; node *ptr; while(scanf("%s",tmp) && tmp[0]!='-') { clear(),root=NULL; scanf("%d",&j); for(i=0;j--;) { scanf("%s",word[i]); for(k=0;word[i][k];k++) tmp0[k]=word[i][k]; tmp0[k]=0; if(ins(i,tmp0))i++; } for(i=0;tmp[i];i++)s[i+1]=200000000; for(i=0;tmp[i];i++) { if(s[i]>=200000000)continue; for(j=0,ptr=root;ptr && tmp[i+j];j++,ptr=ptr->ch) { while(ptr && ptr->d!=tmp[i+j]-'0')ptr=ptr->ne; if(ptr && ptr->x>=0 && s[i]+1<s[i+j+1]) s[i+j+1]=s[i]+1,p[i+j+1]=ptr->x; if(!ptr)break; } } if(s[i]<200000000) print(i); else printf("No solution."); puts(""); } }
21.683544
65
0.414478
dk00
90765230c369d628ba14bbe060f929bf2968ff97
1,609
cpp
C++
src/solar/windows/layout/window_layout_margins.cpp
jseward/solar
a0b76e3c945679a8fcb4cc94160298788b96e4a5
[ "MIT" ]
4
2017-04-02T07:56:14.000Z
2021-10-01T18:23:33.000Z
src/solar/windows/layout/window_layout_margins.cpp
jseward/solar
a0b76e3c945679a8fcb4cc94160298788b96e4a5
[ "MIT" ]
null
null
null
src/solar/windows/layout/window_layout_margins.cpp
jseward/solar
a0b76e3c945679a8fcb4cc94160298788b96e4a5
[ "MIT" ]
1
2021-10-01T18:23:38.000Z
2021-10-01T18:23:38.000Z
#include "window_layout_margins.h" #include "solar/archiving/archiving_helpers.h" #include "solar/utility/type_convert.h" namespace solar { window_layout_margins::window_layout_margins() : _left(0) , _right(0) , _top(0) , _bottom(0) { } window_layout_margins::window_layout_margins(int left, int right, int top, int bottom) : _left(left) , _right(right) , _top(top) , _bottom(bottom) { } int window_layout_margins::get_left() const { return _left; } int window_layout_margins::get_right() const { return _right; } int window_layout_margins::get_top() const { return _top; } int window_layout_margins::get_bottom() const { return _bottom; } window_layout_margins window_layout_margins::operator*(float rhs) const { return window_layout_margins( static_cast<int>(_left * rhs), static_cast<int>(_right * rhs), static_cast<int>(_top * rhs), static_cast<int>(_bottom * rhs)); } rect window_layout_margins::transform_area(const rect& in_area, float in_area_scale) const { return rect( in_area.get_left() + float_to_int(_left * in_area_scale), in_area.get_top() + float_to_int(_top * in_area_scale), in_area.get_right() - float_to_int(_right * in_area_scale), in_area.get_bottom() - float_to_int(_bottom * in_area_scale)); } void window_layout_margins::read_from_archive(archive_reader& reader, const char* name) { read_ints(reader, name, _left, _top, _right, _bottom); } void window_layout_margins::write_to_archive(archive_writer& writer, const char* name) const { write_ints(writer, name, _left, _top, _right, _bottom); } }
25.539683
95
0.732753
jseward
90797082a0f4ca7439543035bd08f5a61b201d42
2,236
cpp
C++
Light.cpp
catinapoke/opengl-1-intermediate-mode
9562f258024408625688c52d349738ba9dfb83e4
[ "Unlicense" ]
4
2019-10-19T18:30:26.000Z
2019-12-15T17:54:27.000Z
Light.cpp
catinapoke/opengl-1-intermediate-mode
9562f258024408625688c52d349738ba9dfb83e4
[ "Unlicense" ]
null
null
null
Light.cpp
catinapoke/opengl-1-intermediate-mode
9562f258024408625688c52d349738ba9dfb83e4
[ "Unlicense" ]
null
null
null
#include "Light.h" Light::Light() :Light(vec3(0, 0, 0)) { } Light::Light(vec3 position) { setPosition(vec4(position.x, position.y, position.z, 1.0)); setAmbient(vec4(1.0, 1.0, 1.0, 1.0)); setDiffuse(vec4(0.0, 0.0, 0.0, 1.0)); setSpecular(vec4(0.0, 0.0, 0.0, 1.0)); } Light::Light(float x, float y, float z) :Light(vec3(x, y, z)) { } Light::Light(const char* filename) { load(filename); } void Light::setAmbient(vec4 color) { ambient = color; } void Light::setDiffuse(vec4 color) { diffuse = color; } void Light::setSpecular(vec4 color) { ambient = color; } void Light::setPosition(vec4 pos) { position = pos; } void Light::setPosition(glm::vec3 pos) { position.x = pos.x; position.y = pos.y; position.z = pos.z; position.w = 1; } void Light::load(const char* jsonfile) { std::ifstream ifs(jsonfile); if (!ifs.is_open()) { std::cerr << "Couldn't open file " << jsonfile << "for reading \n"; return; } //Read from file rapidjson::IStreamWrapper isw(ifs); rapidjson::Document doc; doc.ParseStream(isw); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); if (doc.HasParseError()) { std::cerr << "Parse error: " << doc.GetParseError() << "\n Offset: " << doc.GetErrorOffset() << "\n"; return; } ambient = vec4( doc["ambient"][0].GetDouble(), doc["ambient"][1].GetDouble(), doc["ambient"][2].GetDouble(), doc["ambient"][3].GetDouble() ); diffuse = vec4( doc["diffuse"][0].GetDouble(), doc["diffuse"][1].GetDouble(), doc["diffuse"][2].GetDouble(), doc["diffuse"][3].GetDouble() ); specular = vec4( doc["specular"][0].GetDouble(), doc["specular"][1].GetDouble(), doc["specular"][2].GetDouble(), doc["specular"][3].GetDouble() ); position = vec4( doc["position"][0].GetDouble(), doc["position"][1].GetDouble(), doc["position"][2].GetDouble(), doc["position"][3].GetDouble() ); //Close the file ifs.close(); } void Light::apply(GLenum light) { glEnable(light); glLightfv(light, GL_AMBIENT, glm::value_ptr(ambient)); glLightfv(light, GL_DIFFUSE, glm::value_ptr(diffuse)); glLightfv(light, GL_SPECULAR, glm::value_ptr(specular)); glLightfv(light, GL_POSITION, glm::value_ptr(position)); }
19.614035
103
0.650268
catinapoke
907a031332650c8d30a5de25fe9a8499f0c9f866
4,251
hpp
C++
include/data_types/candidates.hpp
kernsuite-debian/peasoup
d542e0b707d797883d7dacbfce8234d2465068de
[ "Apache-2.0" ]
10
2015-10-03T00:17:03.000Z
2021-05-09T11:29:24.000Z
include/data_types/candidates.hpp
kernsuite-debian/peasoup
d542e0b707d797883d7dacbfce8234d2465068de
[ "Apache-2.0" ]
1
2018-03-20T08:37:41.000Z
2018-03-20T08:50:01.000Z
include/data_types/candidates.hpp
kernsuite-debian/peasoup
d542e0b707d797883d7dacbfce8234d2465068de
[ "Apache-2.0" ]
8
2015-10-28T16:01:58.000Z
2021-11-03T05:53:41.000Z
#pragma once #include <iostream> #include <vector> #include <sstream> #include "stdio.h" //Lightweight plain old data struct //used to combine multiple writes into //one big write struct CandidatePOD { float dm; int dm_idx; float acc; int nh; float snr; float freq; }; struct Candidate { public: float dm; int dm_idx; float acc; int nh; float snr; float freq; float folded_snr; double opt_period; bool is_adjacent; bool is_physical; float ddm_count_ratio; float ddm_snr_ratio; std::vector<Candidate> assoc; std::vector<float> fold; int nbins; int nints; void append(Candidate& other){ assoc.push_back(other); } int count_assoc(void){ int count = 0; for (int ii=0;ii<assoc.size();ii++){ count ++; count += assoc[ii].count_assoc(); } return count; } Candidate(float dm, int dm_idx, float acc, int nh, float snr, float freq) :dm(dm),dm_idx(dm_idx),acc(acc),nh(nh), snr(snr),folded_snr(0.0),freq(freq), opt_period(0.0),is_adjacent(false),is_physical(false), ddm_count_ratio(0.0),ddm_snr_ratio(0.0),nints(0),nbins(0){} Candidate(float dm, int dm_idx, float acc, int nh, float snr, float folded_snr, float freq) :dm(dm),dm_idx(dm_idx),acc(acc),nh(nh),snr(snr), folded_snr(folded_snr),freq(freq),opt_period(0.0), is_adjacent(false),is_physical(false), ddm_count_ratio(0.0),ddm_snr_ratio(0.0),nints(0),nbins(0){} Candidate() :dm(0.0),dm_idx(0.0),acc(0.0),nh(0.0),snr(0.0), folded_snr(0.0),freq(0.0),opt_period(0.0), is_adjacent(false),is_physical(false), ddm_count_ratio(0.0),ddm_snr_ratio(0.0),nints(0),nbins(0){} void set_fold(float* ar, int nbins, int nints){ int size = nbins*nints; this->nints = nints; this->nbins = nbins; fold.resize(size); for (int ii=0;ii<size;ii++) fold[ii] = ar[ii]; } void collect_candidates(std::vector<CandidatePOD>& cands_lite){ CandidatePOD cand_stats = {dm,dm_idx,acc,nh,snr,freq}; cands_lite.push_back(cand_stats); for (int ii=0;ii<assoc.size();ii++){ assoc[ii].collect_candidates(cands_lite); } } void print(FILE* fo=stdout){ fprintf(fo,"%.15f\t%.15f\t%.15f\t%.2f\t%.2f\t%d\t%.1f\t%.1f\t%d\t%d\t%.4f\t%.4f\t%d\n", 1.0/freq,opt_period,freq,dm,acc, nh,snr,folded_snr,is_adjacent, is_physical,ddm_count_ratio, ddm_snr_ratio,assoc.size()); for (int ii=0;ii<assoc.size();ii++){ assoc[ii].print(fo); } } }; class CandidateCollection { public: std::vector<Candidate> cands; CandidateCollection(){} void append(CandidateCollection& other){ cands.insert(cands.end(),other.cands.begin(),other.cands.end()); } void append(std::vector<Candidate> other){ cands.insert(cands.end(),other.begin(),other.end()); } void reset(void){ cands.clear(); } void print(FILE* fo=stdout){ for (int ii=0;ii<cands.size();ii++) cands[ii].print(fo); } void generate_candidate_binaries(std::string output_directory="./") { char filename[80]; std::stringstream filepath; for (int ii=0;ii<cands.size();ii++){ filepath.str(""); sprintf(filename,"cand_%04d_%.5f_%.1f_%.1f.peasoup", ii,1.0/cands[ii].freq,cands[ii].dm,cands[ii].acc); filepath << output_directory << "/" << filename; FILE* fo = fopen(filepath.str().c_str(),"w"); cands[ii].print(fo); fclose(fo); } } void write_candidate_file(std::string filepath="./candidates.txt") { FILE* fo = fopen(filepath.c_str(),"w"); fprintf(fo,"#Period...Optimal period...Frequency...DM...Acceleration...Harmonic number...S/N...Folded S/N\n"); for (int ii=0;ii<cands.size();ii++){ fprintf(fo,"#Candidate %d\n",ii); cands[ii].print(fo); } fclose(fo); } }; class SpectrumCandidates: public CandidateCollection { public: float dm; int dm_idx; float acc; SpectrumCandidates(float dm, int dm_idx, float acc) :dm(dm),dm_idx(dm_idx),acc(acc){} void append(float* snrs, float* freqs, int nh, int size){ cands.reserve(size+cands.size()); for (int ii=0;ii<size;ii++) cands.push_back(Candidate(dm,dm_idx,acc,nh,snrs[ii],freqs[ii])); } };
25.303571
114
0.633263
kernsuite-debian
907ce120fbae988d50cb97e27cbcc255829e5da4
9,901
cpp
C++
libs/cocos2dx/platform/emscripten/CCEGLView.cpp
qq2588258/floweers
c7f117f29dee21473821b89ff9b18058f7ebdadf
[ "MIT" ]
17
2015-01-09T07:34:32.000Z
2021-06-25T02:50:03.000Z
libs/cocos2dx/platform/emscripten/CCEGLView.cpp
qq2588258/floweers
c7f117f29dee21473821b89ff9b18058f7ebdadf
[ "MIT" ]
null
null
null
libs/cocos2dx/platform/emscripten/CCEGLView.cpp
qq2588258/floweers
c7f117f29dee21473821b89ff9b18058f7ebdadf
[ "MIT" ]
4
2015-01-24T02:48:46.000Z
2020-07-02T06:29:06.000Z
/**************************************************************************** Copyright (c) 2010 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCEGLView.h" #include "cocoa/CCSet.h" #include "CCDirector.h" #include "ccMacros.h" #include "touch_dispatcher/CCTouch.h" #include "touch_dispatcher/CCTouchDispatcher.h" #include "text_input_node/CCIMEDispatcher.h" #include "keypad_dispatcher/CCKeypadDispatcher.h" #include "CCGL.h" #include "CCAccelerometer.h" #include "CCApplication.h" #include <emscripten/emscripten.h> #include <SDL/SDL.h> #include <SDL/SDL_ttf.h> #include <SDL/SDL_mixer.h> #include <ctype.h> #include <stdlib.h> extern "C" { void glutInit(int *argcp, char **argv); void glutMouseFunc(void (*func)(int button, int state, int x, int y)); void glutMotionFunc(void (*func)(int x, int y)); void glutPassiveMotionFunc(void (*func)(int x, int y)); } // Constants for mouse events (inferred from experiment) static const int glutLeftButton = 0; static const int glutMouseDown = 0; static const int glutMouseUp = 1; NS_CC_BEGIN bool EGLView::_initializedFunctions = false; const GLubyte *EGLView::_extensions = 0; enum Orientation { PORTRAIT, LANDSCAPE, AUTO }; static Orientation orientation = LANDSCAPE; #define MAX_TOUCHES 4 static EGLView* s_pInstance = NULL; static bool buttonDepressed = false; extern "C" void mouseCB(int button, int state, int x, int y) { float fx = x; float fy = y; EGLView* pEGLView = EGLView::getInstance(); int id = 0; if(button != glutLeftButton) return; if(state == glutMouseDown) { pEGLView->handleTouchesBegin(1, &id, &fx, &fy); buttonDepressed = true; } else if(state == glutMouseUp) { pEGLView->handleTouchesEnd(1, &id, &fx, &fy); buttonDepressed = false; } } extern "C" void motionCB(int x, int y) { float fx = x; float fy = y; EGLView* pEGLView = EGLView::getInstance(); int id = 0; if(buttonDepressed) { pEGLView->handleTouchesMove(1, &id, &fx, &fy); } } EGLView::EGLView() { _eglDisplay = EGL_NO_DISPLAY; _eglContext = EGL_NO_CONTEXT; _eglSurface = EGL_NO_SURFACE; strcpy(_windowGroupID, ""); snprintf(_windowGroupID, sizeof(_windowGroupID), "%d", 1); _isGLInitialized = initGL(); if (_isGLInitialized) initEGLFunctions(); // Initialize SDL: used for font rendering, sprite loading and audio // playing. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); // Emscripten ignores all these values. Mix_OpenAudio(0, 0, 0, 0); TTF_Init(); char *arg1 = (char*)malloc(1); char **dummyArgv = (char**)malloc(sizeof(char*)); dummyArgv[0] = arg1; glutInit(0, dummyArgv); free(dummyArgv[0]); free(dummyArgv); glutMouseFunc(&mouseCB); glutMotionFunc(&motionCB); glutPassiveMotionFunc(&motionCB); } EGLView::~EGLView() { } const char* EGLView::getWindowGroupId() const { return _windowGroupID; } void EGLView::release() { if (_eglDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } if (_eglSurface != EGL_NO_SURFACE) { eglDestroySurface(_eglDisplay, _eglSurface); _eglSurface = EGL_NO_SURFACE; } if (_eglContext != EGL_NO_CONTEXT) { eglDestroyContext(_eglDisplay, _eglContext); _eglContext = EGL_NO_CONTEXT; } if (_eglDisplay != EGL_NO_DISPLAY) { eglTerminate(_eglDisplay); _eglDisplay = EGL_NO_DISPLAY; } _isGLInitialized = false; exit(0); } void EGLView::initEGLFunctions() { _extensions = glGetString(GL_EXTENSIONS); _initializedFunctions = true; } bool EGLView::isOpenGLReady() { return (_isGLInitialized && _screenSize.height != 0 && _screenSize.width != 0); } void EGLView::end() { release(); } void EGLView::swapBuffers() { eglSwapBuffers(_eglDisplay, _eglSurface); } EGLView* EGLView::getInstance() { if (!s_pInstance) { s_pInstance = new EGLView(); } CCAssert(s_pInstance != NULL, "CCEGLView wasn't constructed yet"); return s_pInstance; } // XXX: deprecated EGLView* EGLView::sharedOpenGLView() { return EGLView::getInstance(); } void EGLView::showKeyboard() { } void EGLView::hideKeyboard() { } void EGLView::setIMEKeyboardState(bool bOpen) { } bool EGLView::isGLExtension(const char *searchName) const { const GLubyte *start; GLubyte *where, *terminator; /* It takes a bit of care to be fool-proof about parsing the OpenGL extensions string. Don't be fooled by sub-strings, etc. */ start = _extensions; for (;;) { where = (GLubyte *) strstr((const char *) start, searchName); if (!where) break; terminator = where + strlen(searchName); if (where == start || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return true; start = terminator; } return false; } static EGLenum checkErrorEGL(const char* msg) { assert(msg); static const char* errmsg[] = { "EGL function succeeded", "EGL is not initialized, or could not be initialized, for the specified display", "EGL cannot access a requested resource", "EGL failed to allocate resources for the requested operation", "EGL fail to access an unrecognized attribute or attribute value was passed in an attribute list", "EGLConfig argument does not name a valid EGLConfig", "EGLContext argument does not name a valid EGLContext", "EGL current surface of the calling thread is no longer valid", "EGLDisplay argument does not name a valid EGLDisplay", "EGL arguments are inconsistent", "EGLNativePixmapType argument does not refer to a valid native pixmap", "EGLNativeWindowType argument does not refer to a valid native window", "EGL one or more argument values are invalid", "EGLSurface argument does not name a valid surface configured for rendering", "EGL power management event has occurred", }; EGLenum error = eglGetError(); fprintf(stderr, "%s: %s\n", msg, errmsg[error - EGL_SUCCESS]); return error; } bool EGLView::initGL() { EGLint eglConfigCount; EGLConfig config; // Hard-coded to 32-bit/OpenGL ES 2.0. const EGLint eglConfigAttrs[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE }; const EGLint eglContextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; const EGLint eglSurfaceAttrs[] = { EGL_RENDER_BUFFER, EGL_BACK_BUFFER, EGL_NONE }; // Get the EGL display and initialize. _eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (_eglDisplay == EGL_NO_DISPLAY) { perror("eglGetDisplay"); return false; } if (eglInitialize(_eglDisplay, NULL, NULL) != EGL_TRUE) { perror("eglInitialize"); return false; } if (eglChooseConfig(_eglDisplay, eglConfigAttrs, &config, 1, &eglConfigCount) != EGL_TRUE || eglConfigCount == 0) { checkErrorEGL("eglChooseConfig"); return false; } _eglContext = eglCreateContext(_eglDisplay, config, EGL_NO_CONTEXT, eglContextAttrs); if (_eglContext == EGL_NO_CONTEXT) { checkErrorEGL("eglCreateContext"); return false; } _eglSurface = eglCreateWindowSurface(_eglDisplay, config, NULL, eglSurfaceAttrs); if (_eglSurface == EGL_NO_SURFACE) { checkErrorEGL("eglCreateWindowSurface"); return false; } if (eglMakeCurrent(_eglDisplay, _eglSurface, _eglSurface, _eglContext) != EGL_TRUE) { checkErrorEGL("eglMakeCurrent"); return false; } // FIXME: Get the actual canvas size somehow. EGLint width; EGLint height; if ((_eglDisplay == EGL_NO_DISPLAY) || (_eglSurface == EGL_NO_SURFACE) ) return EXIT_FAILURE; eglQuerySurface(_eglDisplay, _eglSurface, EGL_WIDTH, &width); eglQuerySurface(_eglDisplay, _eglSurface, EGL_HEIGHT, &height); _screenSize.width = width; _screenSize.height = height; glViewport(0, 0, width, height); // Default the frame size to be the whole canvas. In general we want to be // setting the size of the viewport by adjusting the canvas size (so // there's no weird letterboxing). setFrameSize(width, height); return true; } static long time2millis(struct timespec *times) { return times->tv_sec*1000 + times->tv_nsec/1000000; } bool EGLView::handleEvents() { return true; } NS_CC_END
25.322251
117
0.668619
qq2588258
908026e9f741b99671f70fd49c30840c0c3ad925
170
cpp
C++
src/Hooks.cpp
Exit-9B/Enemy-Health-HUD
e209582a0430673dafce5a550be85eb8b80b4222
[ "MIT" ]
1
2021-03-19T14:32:16.000Z
2021-03-19T14:32:16.000Z
src/Hooks.cpp
Exit-9B/Enemy-Health-HUD
e209582a0430673dafce5a550be85eb8b80b4222
[ "MIT" ]
null
null
null
src/Hooks.cpp
Exit-9B/Enemy-Health-HUD
e209582a0430673dafce5a550be85eb8b80b4222
[ "MIT" ]
1
2021-03-19T14:32:18.000Z
2021-03-19T14:32:18.000Z
#include "Hooks.h" #include "EnemyHealthManager.h" namespace Hooks { void Install() { EnemyHealthManager::InstallHooks(); logger::info("Installed all hooks"); } }
15.454545
38
0.711765
Exit-9B
9083c828bb3a94f8f3618f072dff28ba8df65ea1
2,952
cc
C++
src/externalized/content/Dialogs.cc
oldlaptop/ja2-stracciatella
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
[ "BSD-Source-Code" ]
null
null
null
src/externalized/content/Dialogs.cc
oldlaptop/ja2-stracciatella
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
[ "BSD-Source-Code" ]
null
null
null
src/externalized/content/Dialogs.cc
oldlaptop/ja2-stracciatella
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
[ "BSD-Source-Code" ]
null
null
null
#include "Dialogs.h" #include <stdio.h> #include "game/Directories.h" #include "game/Tactical/Soldier_Profile.h" #include "game/Tactical/Soldier_Profile_Type.h" #include "MercProfile.h" const char* Content::GetDialogueTextFilename(const MercProfile &profile, bool useAlternateDialogueFile, bool isCurrentlyTalking) { static char zFileName[164]; uint8_t ubFileNumID; // Are we an NPC OR an RPC that has not been recruited? // ATE: Did the || clause here to allow ANY RPC that talks while the talking menu is up to use an npc quote file if ( useAlternateDialogueFile ) { { // assume EDT files are in EDT directory on HARD DRIVE sprintf(zFileName, NPCDATADIR "/d_%03d.edt", profile.getNum()); } } else if ( profile.getNum() >= FIRST_RPC && ( !profile.isRecruited() || isCurrentlyTalking || profile.isForcedNPCQuote())) { ubFileNumID = profile.getNum(); // ATE: If we are merc profile ID #151-154, all use 151's data.... if (profile.getNum() >= HERVE && profile.getNum() <= CARLO) { ubFileNumID = HERVE; } { // assume EDT files are in EDT directory on HARD DRIVE sprintf(zFileName, NPCDATADIR "/%03d.edt", ubFileNumID); } } else { { // assume EDT files are in EDT directory on HARD DRIVE sprintf(zFileName, MERCEDTDIR "/%03d.edt", profile.getNum()); } } return( zFileName ); } const char* Content::GetDialogueVoiceFilename(const MercProfile &profile, uint16_t usQuoteNum, bool useAlternateDialogueFile, bool isCurrentlyTalking, bool isRussianVersion) { static char zFileName[164]; uint8_t ubFileNumID; // Are we an NPC OR an RPC that has not been recruited? // ATE: Did the || clause here to allow ANY RPC that talks while the talking menu is up to use an npc quote file if ( useAlternateDialogueFile ) { { // build name of wav file (characternum + quotenum) sprintf(zFileName, NPC_SPEECHDIR "/d_%03d_%03d.wav", profile.getNum(), usQuoteNum); } } else if ( profile.getNum() >= FIRST_RPC && ( !profile.isRecruited() || isCurrentlyTalking || profile.isForcedNPCQuote())) { ubFileNumID = profile.getNum(); // ATE: If we are merc profile ID #151-154, all use 151's data.... if (profile.getNum() >= HERVE && profile.getNum() <= CARLO) { ubFileNumID = HERVE; } { sprintf(zFileName, NPC_SPEECHDIR "/%03d_%03d.wav", ubFileNumID, usQuoteNum); } } else { { if(isRussianVersion) { if (profile.getNum() >= FIRST_RPC && profile.isRecruited()) { sprintf(zFileName, SPEECHDIR "/r_%03d_%03d.wav", profile.getNum(), usQuoteNum); } else { // build name of wav file (characternum + quotenum) sprintf(zFileName, SPEECHDIR "/%03d_%03d.wav", profile.getNum(), usQuoteNum); } } else { // build name of wav file (characternum + quotenum) sprintf(zFileName, SPEECHDIR "/%03d_%03d.wav", profile.getNum(), usQuoteNum); } } } return( zFileName ); }
25.894737
113
0.671748
oldlaptop
90846bb77f329996dc9479a922ccfff66d831ae4
3,703
cpp
C++
samples/ScenegraphTestApp.cpp
calebjohnston/Cinder-scenegraph
590b9e12966c5ca25fbccaf69b3199dfeebfb777
[ "BSD-2-Clause" ]
null
null
null
samples/ScenegraphTestApp.cpp
calebjohnston/Cinder-scenegraph
590b9e12966c5ca25fbccaf69b3199dfeebfb777
[ "BSD-2-Clause" ]
null
null
null
samples/ScenegraphTestApp.cpp
calebjohnston/Cinder-scenegraph
590b9e12966c5ca25fbccaf69b3199dfeebfb777
[ "BSD-2-Clause" ]
null
null
null
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "NodeBase.h" #include "Node2d.h" #include "Node3d.h" using namespace ci; using namespace ci::app; using namespace std; class ScenegraphTestApp : public App { public: void mouseMove( MouseEvent event ); void mouseDown( MouseEvent event ); void mouseDrag( MouseEvent event ); void mouseUp( MouseEvent event ); void keyDown( KeyEvent event ); void keyUp( KeyEvent event ); void resize(); void setup(); void update(); void draw(); protected: //! Keeps track of current game time, used to calculate elapsed time in seconds. double mTime; scene::Node2dRef mRoot; }; void ScenegraphTestApp::setup() { // Initialize game time mTime = getElapsedSeconds(); // create the root node: a large rectangle mRoot = scene::Node2d::create(); // specify the position of the anchor point on our canvas mRoot->setPosition(320, 240); // set the size of the node mRoot->setSize(600, 450); // we can easily set the anchor point to its center: mRoot->setPivotPercentage(0.5f, 0.5f); // add smaller rectangles to the root node Node2dRef child1 = scene::Node2d::create(); child1->setPosition(0, 0); child1->setSize(240, 200); mRoot->addChild(child1); Node2dRef child2 = scene::Node2d::create(); child2->setPosition(260, 0); child2->setSize(240, 200); mRoot->addChild(child2); // add even smaller rectangles to the child rectangles Node2dRef child = scene::Node2d::create(); child->setPosition(5, 5); child->setSize(100, 100); child1->addChild(child); //child.reset( new NodeRectangle() ); child->setPosition(5, 5); child->setSize(100, 100); child2->addChild(child); } void ScenegraphTestApp::mouseMove( MouseEvent event ) { // pass the mouseMove event to all nodes. Important: this can easily bring your // frame rate down if you have a lot of nodes and none of them does anything with // this event. Only use it if you must! Needs optimization. // mRoot->deepMouseMove(event); } void ScenegraphTestApp::mouseDown( MouseEvent event ) { // pass the mouseDown event to all nodes. This is usually very quick because // it starts at the top nodes and they often catch the event. // mRoot->deepMouseDown(event); } void ScenegraphTestApp::mouseDrag( MouseEvent event ) { // pass the mouseDrag event to all nodes. This is usually very quick. // mRoot->deepMouseDrag(event); } void ScenegraphTestApp::mouseUp( MouseEvent event ) { // pass the mouseUp event to all nodes. This is usually very quick. // mRoot->deepMouseUp(event); } void ScenegraphTestApp::keyDown( KeyEvent event ) { // let nodes handle keys first /* if (!mRoot->deepKeyDown(event)) { switch(event.getCode()) { case KeyEvent::KEY_ESCAPE: quit(); break; case KeyEvent::KEY_f: setFullScreen(!isFullScreen()); break; } } */ } void ScenegraphTestApp::keyUp( KeyEvent event ) { // mRoot->deepKeyUp(event); } void ScenegraphTestApp::update() { // calculate elapsed time since last frame double elapsed = getElapsedSeconds() - mTime; mTime = getElapsedSeconds(); // rotate the root node around its anchor point mRoot->setRotation( 0.1 * mTime ); // update all nodes mRoot->deepUpdate( elapsed ); // important and easy to forget: calculate transformations of all nodes // after they have been updated, so the transformation matrices reflect // any animation done on the nodes mRoot->deepTransform( gl::getModelView() ); } void ScenegraphTestApp::draw() { // clear out the window with black gl::clear( Color( 0, 0, 0 ) ); // draw all nodes, starting with the root node mRoot->deepDraw(); } CINDER_APP_BASIC( ScenegraphTestApp, RendererGl )
24.361842
82
0.712935
calebjohnston
90849e310a69a084de74906cbf8f6c09f67e143d
61,373
inl
C++
ijk/include/ijk/ijk-math/ijk-real/_util/_inl/ijkVectorSwizzle.inl
dbuckstein/ijk
959f7292d6465e9d2c888ea94bc724c8ee03597e
[ "Apache-2.0" ]
1
2020-05-31T21:14:49.000Z
2020-05-31T21:14:49.000Z
ijk/include/ijk/ijk-math/ijk-real/_util/_inl/ijkVectorSwizzle.inl
dbuckstein/ijk
959f7292d6465e9d2c888ea94bc724c8ee03597e
[ "Apache-2.0" ]
null
null
null
ijk/include/ijk/ijk-math/ijk-real/_util/_inl/ijkVectorSwizzle.inl
dbuckstein/ijk
959f7292d6465e9d2c888ea94bc724c8ee03597e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020-2021 Daniel S. Buckstein 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. */ /* ijk: an open-source, cross-platform, light-weight, c-based rendering framework By Daniel S. Buckstein ijkVectorSwizzle.inl Inline definitions for vector swizzling types (C++). */ #ifdef _IJK_VECTORSWIZZLE_H_ #ifndef _IJK_VECTORSWIZZLE_INL_ #define _IJK_VECTORSWIZZLE_INL_ #ifdef __cplusplus //----------------------------------------------------------------------------- /* ttvec1 const operator +() const; ttvec1 const operator -() const; ttvec1 const operator ~() const; ttvec1 const operator +(ttvec1 const& v_rh) const; ttvec1 const operator -(ttvec1 const& v_rh) const; ttvec1 const operator *(ttvec1 const& v_rh) const; ttvec1 const operator /(ttvec1 const& v_rh) const; ttvec1 const operator %(ttvec1 const& v_rh) const; ttvec1 const operator &(ttvec1 const& v_rh) const; ttvec1 const operator |(ttvec1 const& v_rh) const; ttvec1 const operator ^(ttvec1 const& v_rh) const; ttvec1 const operator <<(ttvec1 const& v_rh) const; ttvec1 const operator >>(ttvec1 const& v_rh) const; ttvec1 const operator +(type const& s_rh) const; ttvec1 const operator -(type const& s_rh) const; ttvec1 const operator *(type const& s_rh) const; ttvec1 const operator /(type const& s_rh) const; ttvec1 const operator %(type const& s_rh) const; ttvec1 const operator &(type const& s_rh) const; ttvec1 const operator |(type const& s_rh) const; ttvec1 const operator ^(type const& s_rh) const; ttvec1 const operator <<(type const& s_rh) const; ttvec1 const operator >>(type const& s_rh) const; ttvec1<bool> const operator !() const; ttvec1<bool> const operator ==(ttvec1 const& v_rh) const; ttvec1<bool> const operator !=(ttvec1 const& v_rh) const; ttvec1<bool> const operator <=(ttvec1 const& v_rh) const; ttvec1<bool> const operator >=(ttvec1 const& v_rh) const; ttvec1<bool> const operator <(ttvec1 const& v_rh) const; ttvec1<bool> const operator >(ttvec1 const& v_rh) const; ttvec1<bool> const operator ==(type const& s_rh) const; ttvec1<bool> const operator !=(type const& s_rh) const; ttvec1<bool> const operator <=(type const& s_rh) const; ttvec1<bool> const operator >=(type const& s_rh) const; ttvec1<bool> const operator <(type const& s_rh) const; ttvec1<bool> const operator >(type const& s_rh) const; ttvec1& operator +=(ttvec1 const& v_rh); ttvec1& operator -=(ttvec1 const& v_rh); ttvec1& operator *=(ttvec1 const& v_rh); ttvec1& operator /=(ttvec1 const& v_rh); ttvec1& operator %=(ttvec1 const& v_rh); ttvec1& operator &=(ttvec1 const& v_rh); ttvec1& operator |=(ttvec1 const& v_rh); ttvec1& operator ^=(ttvec1 const& v_rh); ttvec1& operator <<=(ttvec1 const& v_rh); ttvec1& operator >>=(ttvec1 const& v_rh); ttvec1& operator +=(type const& s_rh); ttvec1& operator -=(type const& s_rh); ttvec1& operator *=(type const& s_rh); ttvec1& operator /=(type const& s_rh); ttvec1& operator %=(type const& s_rh); ttvec1& operator &=(type const& s_rh); ttvec1& operator |=(type const& s_rh); ttvec1& operator ^=(type const& s_rh); ttvec1& operator <<=(type const& s_rh); ttvec1& operator >>=(type const& s_rh); */ /* template<typename type> inline ttvec1<type> const ttvec1<type>::operator +() const { return *this; } template<typename type> inline ttvec1<type> const ttvec1<type>::operator -() const { return ttvec1<type>(-x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator ~() const { return ttvec1<type>(~x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator +(ttvec1 const& v_rh) const { return ttvec1<type>(x + v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator -(ttvec1 const& v_rh) const { return ttvec1<type>(x - v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator *(ttvec1 const& v_rh) const { return ttvec1<type>(x * v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator /(ttvec1 const& v_rh) const { return ttvec1<type>(x / v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator %(ttvec1 const& v_rh) const { return ttvec1<type>(x % v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator &(ttvec1 const& v_rh) const { return ttvec1<type>(x & v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator |(ttvec1 const& v_rh) const { return ttvec1<type>(x | v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator ^(ttvec1 const& v_rh) const { return ttvec1<type>(x ^ v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator <<(ttvec1 const& v_rh) const { return ttvec1<type>(x << v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator >>(ttvec1 const& v_rh) const { return ttvec1<type>(x >> v_rh.x); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator +(type const& s_rh) const { return ttvec1<type>(x + s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator -(type const& s_rh) const { return ttvec1<type>(x - s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator *(type const& s_rh) const { return ttvec1<type>(x * s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator /(type const& s_rh) const { return ttvec1<type>(x / s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator %(type const& s_rh) const { return ttvec1<type>(x % s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator &(type const& s_rh) const { return ttvec1<type>(x & s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator |(type const& s_rh) const { return ttvec1<type>(x | s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator ^(type const& s_rh) const { return ttvec1<type>(x ^ s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator <<(type const& s_rh) const { return ttvec1<type>(x << s_rh); } template<typename type> inline ttvec1<type> const ttvec1<type>::operator >>(type const& s_rh) const { return ttvec1<type>(x >> s_rh); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator !() const { return ttvec1<bool>(!x); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator ==(ttvec1 const& v_rh) const { return ttvec1<bool>(x == v_rh.x); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator !=(ttvec1 const& v_rh) const { return ttvec1<bool>(x != v_rh.x); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator <=(ttvec1 const& v_rh) const { return ttvec1<bool>(x <= v_rh.x); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator >=(ttvec1 const& v_rh) const { return ttvec1<bool>(x >= v_rh.x); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator <(ttvec1 const& v_rh) const { return ttvec1<bool>(x < v_rh.x); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator >(ttvec1 const& v_rh) const { return ttvec1<bool>(x > v_rh.x); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator ==(type const& s_rh) const { return ttvec1<bool>(x == s_rh); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator !=(type const& s_rh) const { return ttvec1<bool>(x != s_rh); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator <=(type const& s_rh) const { return ttvec1<bool>(x <= s_rh); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator >=(type const& s_rh) const { return ttvec1<bool>(x >= s_rh); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator <(type const& s_rh) const { return ttvec1<bool>(x < s_rh); } template<typename type> inline ttvec1<bool> const ttvec1<type>::operator >(type const& s_rh) const { return ttvec1<bool>(x > s_rh); } template<typename type> inline ttvec1<type>& ttvec1<type>::operator +=(ttvec1 const& v_rh) { x += v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator -=(ttvec1 const& v_rh) { x -= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator *=(ttvec1 const& v_rh) { x *= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator /=(ttvec1 const& v_rh) { x /= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator %=(ttvec1 const& v_rh) { x %= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator &=(ttvec1 const& v_rh) { x &= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator |=(ttvec1 const& v_rh) { x |= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator ^=(ttvec1 const& v_rh) { x ^= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator <<=(ttvec1 const& v_rh) { x <<= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator >>=(ttvec1 const& v_rh) { x >>= v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator +=(type const& s_rh) { x += s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator -=(type const& s_rh) { x -= s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator *=(type const& s_rh) { x *= s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator /=(type const& s_rh) { x /= s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator %=(type const& s_rh) { x %= s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator &=(type const& s_rh) { x &= s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator |=(type const& s_rh) { x |= s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator ^=(type const& s_rh) { x ^= s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator <<=(type const& s_rh) { x <<= s_rh; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator >>=(type const& s_rh) { x >>= s_rh; return *this; } */ //----------------------------------------------------------------------------- template<typename type> inline ttvec1<type>::ttvec1(type const& xc) : x(xc) { } template<typename type> inline ttvec1<type>::ttvec1(ttvec1 const& xc) : x(xc.x) { } template<typename type> inline ttvec1<type>::ttvec1(stvec1<type> const& xc) : x(xc.x) { } template<typename type> inline ttvec1<type>& ttvec1<type>::operator =(ttvec1 const& v_rh) { x = v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator =(stvec1<type> const& v_rh) { x = v_rh.x; return *this; } template<typename type> inline ttvec1<type>& ttvec1<type>::operator =(type const& s_rh) { x = s_rh; return *this; } template<typename type> inline ttvec1<type>::operator type const () const { return x; } template<typename type> inline ttvec1<type>::operator type& () { return x; } //----------------------------------------------------------------------------- template <typename type> inline ttvec2<type>::ttvec2(type const& xy) : x(xy), y(xy) { } template <typename type> inline ttvec2<type>::ttvec2(type const& xc, type const& yc) : x(xc), y(yc) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec2 const& xy) : x(xy.x), y(xy.y) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec3<type> const& xy) : x(xy.x), y(xy.y) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec4<type> const& xy) : x(xy.x), y(xy.y) { } template <typename type> inline ttvec2<type>::ttvec2(stvec2<type> const& xy) : x(xy.x), y(xy.y) { } template <typename type> inline ttvec2<type>::ttvec2(stvec3<type> const& xy) : x(xy.x), y(xy.y) { } template <typename type> inline ttvec2<type>::ttvec2(stvec4<type> const& xy) : x(xy.x), y(xy.y) { } template <typename type> inline ttvec2<type>::ttvec2(bool2 const xy) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(int2 const xy) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(intl2 const xy) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(uint2 const xy) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(uintl2 const xy) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(float2 const xy) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(double2 const xy) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec1<bool> const xy[2]) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec1<i32> const xy[2]) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec1<i64> const xy[2]) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec1<ui32> const xy[2]) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec1<ui64> const xy[2]) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec1<f32> const xy[2]) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type>::ttvec2(ttvec1<f64> const xy[2]) : x((type)xy[0]), y((type)xy[1]) { } template <typename type> inline ttvec2<type> const ttvec2<type>::operator +() const { return *this; } template <typename type> inline ttvec2<type> const ttvec2<type>::operator -() const { return ttvec2(-x, -y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator ~() const { return ttvec2(~x, ~y); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator !() const { return ttvec2<bool>(!x, !y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator +(ttvec2 const& v_rh) const { return ttvec2(x + v_rh.x, y + v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator -(ttvec2 const& v_rh) const { return ttvec2(x - v_rh.x, y - v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator *(ttvec2 const& v_rh) const { return ttvec2(x * v_rh.x, y * v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator /(ttvec2 const& v_rh) const { return ttvec2(x / v_rh.x, y / v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator %(ttvec2 const& v_rh) const { return ttvec2(x % v_rh.x, y % v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator &(ttvec2 const& v_rh) const { return ttvec2(x & v_rh.x, y & v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator |(ttvec2 const& v_rh) const { return ttvec2(x | v_rh.x, y | v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator ^(ttvec2 const& v_rh) const { return ttvec2(x ^ v_rh.x, y ^ v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator <<(ttvec2 const& v_rh) const { return ttvec2(x << v_rh.x, y << v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator >>(ttvec2 const& v_rh) const { return ttvec2(x >> v_rh.x, y >> v_rh.y); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator ==(ttvec2 const& v_rh) const { return ttvec2<bool>(x == v_rh.x, y == v_rh.y); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator !=(ttvec2 const& v_rh) const { return ttvec2<bool>(x != v_rh.x, y != v_rh.y); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator <=(ttvec2 const& v_rh) const { return ttvec2<bool>(x <= v_rh.x, y <= v_rh.y); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator >=(ttvec2 const& v_rh) const { return ttvec2<bool>(x >= v_rh.x, y >= v_rh.y); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator <(ttvec2 const& v_rh) const { return ttvec2<bool>(x < v_rh.x, y < v_rh.y); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator >(ttvec2 const& v_rh) const { return ttvec2<bool>(x > v_rh.x, y > v_rh.y); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator +(type const& s_rh) const { return ttvec2(x + s_rh, y + s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator -(type const& s_rh) const { return ttvec2(x - s_rh, y - s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator *(type const& s_rh) const { return ttvec2(x * s_rh, y * s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator /(type const& s_rh) const { return ttvec2(x / s_rh, y / s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator %(type const& s_rh) const { return ttvec2(x % s_rh, y % s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator &(type const& s_rh) const { return ttvec2(x & s_rh, y & s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator |(type const& s_rh) const { return ttvec2(x | s_rh, y | s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator ^(type const& s_rh) const { return ttvec2(x ^ s_rh, y ^ s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator <<(type const& s_rh) const { return ttvec2(x << s_rh, y << s_rh); } template <typename type> inline ttvec2<type> const ttvec2<type>::operator >>(type const& s_rh) const { return ttvec2(x >> s_rh, y >> s_rh); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator ==(type const& s_rh) const { return ttvec2<bool>(x == s_rh, y == s_rh); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator !=(type const& s_rh) const { return ttvec2<bool>(x != s_rh, y != s_rh); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator <=(type const& s_rh) const { return ttvec2<bool>(x <= s_rh, y <= s_rh); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator >=(type const& s_rh) const { return ttvec2<bool>(x >= s_rh, y >= s_rh); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator <(type const& s_rh) const { return ttvec2<bool>(x < s_rh, y < s_rh); } template <typename type> inline ttvec2<bool> const ttvec2<type>::operator >(type const& s_rh) const { return ttvec2<bool>(x > s_rh, y > s_rh); } template <typename type> inline type const ttvec2<type>::operator [](index const i) const { return xy[i]; } template <typename type> inline ttvec2<type>::operator type const* () const { return xy; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator =(ttvec2 const& v_rh) { x = v_rh.x; y = v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator =(stvec2<type> const& v_rh) { x = v_rh.x; y = v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator +=(ttvec2 const& v_rh) { x += v_rh.x; y += v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator -=(ttvec2 const& v_rh) { x -= v_rh.x; y -= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator *=(ttvec2 const& v_rh) { x *= v_rh.x; y *= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator /=(ttvec2 const& v_rh) { x /= v_rh.x; y /= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator %=(ttvec2 const& v_rh) { x %= v_rh.x; y %= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator &=(ttvec2 const& v_rh) { x &= v_rh.x; y &= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator |=(ttvec2 const& v_rh) { x |= v_rh.x; y |= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator ^=(ttvec2 const& v_rh) { x ^= v_rh.x; y ^= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator <<=(ttvec2 const& v_rh) { x <<= v_rh.x; y <<= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator >>=(ttvec2 const& v_rh) { x >>= v_rh.x; y >>= v_rh.y; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator =(type const& s_rh) { x = y = s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator +=(type const& s_rh) { x += s_rh; y += s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator -=(type const& s_rh) { x -= s_rh; y -= s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator *=(type const& s_rh) { x *= s_rh; y *= s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator /=(type const& s_rh) { x /= s_rh; y /= s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator %=(type const& s_rh) { x %= s_rh; y %= s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator &=(type const& s_rh) { x &= s_rh; y &= s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator |=(type const& s_rh) { x |= s_rh; y |= s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator ^=(type const& s_rh) { x ^= s_rh; y ^= s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator <<=(type const& s_rh) { x <<= s_rh; y <<= s_rh; return *this; } template <typename type> inline ttvec2<type>& ttvec2<type>::operator >>=(type const& s_rh) { x >>= s_rh; y >>= s_rh; return *this; } template <typename type> inline type& ttvec2<type>::operator [](index const i) { return xy[i]; } template <typename type> inline ttvec2<type>::operator type* () { return xy; } template<typename type> inline ttvec2<type> const operator +(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh + s_lh); } template<typename type> inline ttvec2<type> const operator -(type const& s_lh, ttvec2<type> const& v_rh) { return ttvec2<type>(s_lh - v_rh.x, s_lh - v_rh.y); } template<typename type> inline ttvec2<type> const operator *(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh * s_lh); } template<typename type> inline ttvec2<type> const operator /(type const& s_lh, ttvec2<type> const& v_rh) { return ttvec2<type>(s_lh / v_rh.x, s_lh / v_rh.y); } template<typename type> inline ttvec2<type> const operator %(type const& s_lh, ttvec2<type> const& v_rh) { return ttvec2<type>(s_lh % v_rh.x, s_lh % v_rh.y); } template<typename type> inline ttvec2<type> const operator &(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh & s_lh); } template<typename type> inline ttvec2<type> const operator |(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh | s_lh); } template<typename type> inline ttvec2<type> const operator ^(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh ^ s_lh); } template<typename type> inline ttvec2<type> const operator <<(type const& s_lh, ttvec2<type> const& v_rh) { return ttvec2<type>(s_lh << v_rh.x, s_lh << v_rh.y); } template<typename type> inline ttvec2<type> const operator >>(type const& s_lh, ttvec2<type> const& v_rh) { return ttvec2<type>(s_lh >> v_rh.x, s_lh >> v_rh.y); } template<typename type> inline ttvec2<bool> const operator ==(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh == s_lh); } template<typename type> inline ttvec2<bool> const operator !=(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh != s_lh); } template<typename type> inline ttvec2<bool> const operator <=(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh <= s_lh); } template<typename type> inline ttvec2<bool> const operator >=(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh >= s_lh); } template<typename type> inline ttvec2<bool> const operator <(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh < s_lh); } template<typename type> inline ttvec2<bool> const operator >(type const& s_lh, ttvec2<type> const& v_rh) { return (v_rh > s_lh); } //----------------------------------------------------------------------------- template <typename type> inline ttvec3<type>::ttvec3(type const& xyz) : x(xyz), y(xyz), z(xyz) { } template <typename type> inline ttvec3<type>::ttvec3(type const& xc, type const& yc, type const& zc) : x(xc), y(yc), z(zc) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec2<type> const& xy, type const& zc) : x(xy.x), y(xy.y), z(zc) { } template <typename type> inline ttvec3<type>::ttvec3(type const& xc, ttvec2<type> const& yz) : x(xc), y(yz.x), z(yz.y) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec3 const& xyz) : x(xyz.x), y(xyz.y), z(xyz.z) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec4<type> const& xyz) : x(xyz.x), y(xyz.y), z(xyz.z) { } template <typename type> inline ttvec3<type>::ttvec3(stvec2<type> const& xy, type const& zc) : x(xy.x), y(xy.y), z(zc) { } template <typename type> inline ttvec3<type>::ttvec3(type const& xc, stvec2<type> const& yz) : x(xc), y(yz.x), z(yz.y) { } template <typename type> inline ttvec3<type>::ttvec3(stvec3<type> const& xyz) : x(xyz.x), y(xyz.y), z(xyz.z) { } template <typename type> inline ttvec3<type>::ttvec3(stvec4<type> const& xyz) : x(xyz.x), y(xyz.y), z(xyz.z) { } template <typename type> inline ttvec3<type>::ttvec3(bool3 const xyz) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(int3 const xyz) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(intl3 const xyz) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(uint3 const xyz) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(uintl3 const xyz) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(float3 const xyz) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(double3 const xyz) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec1<bool> const xyz[3]) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec1<i32> const xyz[3]) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec1<i64> const xyz[3]) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec1<ui32> const xyz[3]) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec1<ui64> const xyz[3]) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec1<f32> const xyz[3]) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type>::ttvec3(ttvec1<f64> const xyz[3]) : x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2]) { } template <typename type> inline ttvec3<type> const ttvec3<type>::operator +() const { return *this; } template <typename type> inline ttvec3<type> const ttvec3<type>::operator -() const { return ttvec3(-x, -y, -z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator ~() const { return ttvec3(~x, ~y, ~z); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator !() const { return ttvec3<bool>(!x, !y, !z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator +(ttvec3 const& v_rh) const { return ttvec3(x + v_rh.x, y + v_rh.y, z + v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator -(ttvec3 const& v_rh) const { return ttvec3(x - v_rh.x, y - v_rh.y, z - v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator *(ttvec3 const& v_rh) const { return ttvec3(x * v_rh.x, y * v_rh.y, z * v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator /(ttvec3 const& v_rh) const { return ttvec3(x / v_rh.x, y / v_rh.y, z / v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator %(ttvec3 const& v_rh) const { return ttvec3(x % v_rh.x, y % v_rh.y, z % v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator &(ttvec3 const& v_rh) const { return ttvec3(x & v_rh.x, y & v_rh.y, z & v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator |(ttvec3 const& v_rh) const { return ttvec3(x | v_rh.x, y | v_rh.y, z | v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator ^(ttvec3 const& v_rh) const { return ttvec3(x ^ v_rh.x, y ^ v_rh.y, z ^ v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator <<(ttvec3 const& v_rh) const { return ttvec3(x << v_rh.x, y << v_rh.y, z << v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator >>(ttvec3 const& v_rh) const { return ttvec3(x >> v_rh.x, y >> v_rh.y, z >> v_rh.z); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator ==(ttvec3 const& v_rh) const { return ttvec3<bool>(x == v_rh.x, y == v_rh.y, z == v_rh.z); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator !=(ttvec3 const& v_rh) const { return ttvec3<bool>(x != v_rh.x, y != v_rh.y, z != v_rh.z); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator <=(ttvec3 const& v_rh) const { return ttvec3<bool>(x <= v_rh.x, y <= v_rh.y, z <= v_rh.z); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator >=(ttvec3 const& v_rh) const { return ttvec3<bool>(x >= v_rh.x, y >= v_rh.y, z >= v_rh.z); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator <(ttvec3 const& v_rh) const { return ttvec3<bool>(x < v_rh.x, y < v_rh.y, z < v_rh.z); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator >(ttvec3 const& v_rh) const { return ttvec3<bool>(x > v_rh.x, y > v_rh.y, z > v_rh.z); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator +(type const& s_rh) const { return ttvec3(x + s_rh, y + s_rh, z + s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator -(type const& s_rh) const { return ttvec3(x - s_rh, y - s_rh, z - s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator *(type const& s_rh) const { return ttvec3(x * s_rh, y * s_rh, z * s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator /(type const& s_rh) const { return ttvec3(x / s_rh, y / s_rh, z / s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator %(type const& s_rh) const { return ttvec3(x % s_rh, y % s_rh, z % s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator &(type const& s_rh) const { return ttvec3(x & s_rh, y & s_rh, z & s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator |(type const& s_rh) const { return ttvec3(x | s_rh, y | s_rh, z | s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator ^(type const& s_rh) const { return ttvec3(x ^ s_rh, y ^ s_rh, z ^ s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator <<(type const& s_rh) const { return ttvec3(x << s_rh, y << s_rh, z << s_rh); } template <typename type> inline ttvec3<type> const ttvec3<type>::operator >>(type const& s_rh) const { return ttvec3(x >> s_rh, y >> s_rh, z >> s_rh); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator ==(type const& s_rh) const { return ttvec3<bool>(x == s_rh, y == s_rh, z == s_rh); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator !=(type const& s_rh) const { return ttvec3<bool>(x != s_rh, y != s_rh, z != s_rh); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator <=(type const& s_rh) const { return ttvec3<bool>(x <= s_rh, y <= s_rh, z <= s_rh); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator >=(type const& s_rh) const { return ttvec3<bool>(x >= s_rh, y >= s_rh, z >= s_rh); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator <(type const& s_rh) const { return ttvec3<bool>(x < s_rh, y < s_rh, z < s_rh); } template <typename type> inline ttvec3<bool> const ttvec3<type>::operator >(type const& s_rh) const { return ttvec3<bool>(x > s_rh, y > s_rh, z > s_rh); } template <typename type> inline type const ttvec3<type>::operator [](index const i) const { return xyz[i]; } template <typename type> inline ttvec3<type>::operator type const* () const { return xyz; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator =(ttvec3 const& v_rh) { x = v_rh.x; y = v_rh.y; z = v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator =(stvec3<type> const& v_rh) { x = v_rh.x; y = v_rh.y; z = v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator +=(ttvec3 const& v_rh) { x += v_rh.x; y += v_rh.y; z += v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator -=(ttvec3 const& v_rh) { x -= v_rh.x; y -= v_rh.y; z -= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator *=(ttvec3 const& v_rh) { x *= v_rh.x; y *= v_rh.y; z *= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator /=(ttvec3 const& v_rh) { x /= v_rh.x; y /= v_rh.y; z /= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator %=(ttvec3 const& v_rh) { x %= v_rh.x; y %= v_rh.y; z %= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator &=(ttvec3 const& v_rh) { x &= v_rh.x; y &= v_rh.y; z &= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator |=(ttvec3 const& v_rh) { x |= v_rh.x; y |= v_rh.y; z |= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator ^=(ttvec3 const& v_rh) { x ^= v_rh.x; y ^= v_rh.y; z ^= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator <<=(ttvec3 const& v_rh) { x <<= v_rh.x; y <<= v_rh.y; z <<= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator >>=(ttvec3 const& v_rh) { x >>= v_rh.x; y >>= v_rh.y; z >>= v_rh.z; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator =(type const& s_rh) { x = y = z = s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator +=(type const& s_rh) { x += s_rh; y += s_rh; z += s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator -=(type const& s_rh) { x -= s_rh; y -= s_rh; z -= s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator *=(type const& s_rh) { x *= s_rh; y *= s_rh; z *= s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator /=(type const& s_rh) { x /= s_rh; y /= s_rh; z /= s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator %=(type const& s_rh) { x %= s_rh; y %= s_rh; z %= s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator &=(type const& s_rh) { x &= s_rh; y &= s_rh; z &= s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator |=(type const& s_rh) { x |= s_rh; y |= s_rh; z |= s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator ^=(type const& s_rh) { x ^= s_rh; y ^= s_rh; z ^= s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator <<=(type const& s_rh) { x <<= s_rh; y <<= s_rh; z <<= s_rh; return *this; } template <typename type> inline ttvec3<type>& ttvec3<type>::operator >>=(type const& s_rh) { x >>= s_rh; y >>= s_rh; z >>= s_rh; return *this; } template <typename type> inline type& ttvec3<type>::operator [](index const i) { return xyz[i]; } template <typename type> inline ttvec3<type>::operator type* () { return xyz; } template<typename type> inline ttvec3<type> const operator +(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh + s_lh); } template<typename type> inline ttvec3<type> const operator -(type const& s_lh, ttvec3<type> const& v_rh) { return ttvec3<type>(s_lh - v_rh.x, s_lh - v_rh.y, s_lh - v_rh.z); } template<typename type> inline ttvec3<type> const operator *(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh * s_lh); } template<typename type> inline ttvec3<type> const operator /(type const& s_lh, ttvec3<type> const& v_rh) { return ttvec3<type>(s_lh / v_rh.x, s_lh / v_rh.y, s_lh / v_rh.z); } template<typename type> inline ttvec3<type> const operator %(type const& s_lh, ttvec3<type> const& v_rh) { return ttvec3<type>(s_lh % v_rh.x, s_lh % v_rh.y, s_lh % v_rh.z); } template<typename type> inline ttvec3<type> const operator &(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh & s_lh); } template<typename type> inline ttvec3<type> const operator |(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh | s_lh); } template<typename type> inline ttvec3<type> const operator ^(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh ^ s_lh); } template<typename type> inline ttvec3<type> const operator <<(type const& s_lh, ttvec3<type> const& v_rh) { return ttvec3<type>(s_lh << v_rh.x, s_lh << v_rh.y, s_lh << v_rh.z); } template<typename type> inline ttvec3<type> const operator >>(type const& s_lh, ttvec3<type> const& v_rh) { return ttvec3<type>(s_lh >> v_rh.x, s_lh >> v_rh.y, s_lh >> v_rh.z); } template<typename type> inline ttvec3<bool> const operator ==(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh == s_lh); } template<typename type> inline ttvec3<bool> const operator !=(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh != s_lh); } template<typename type> inline ttvec3<bool> const operator <=(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh <= s_lh); } template<typename type> inline ttvec3<bool> const operator >=(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh >= s_lh); } template<typename type> inline ttvec3<bool> const operator <(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh < s_lh); } template<typename type> inline ttvec3<bool> const operator >(type const& s_lh, ttvec3<type> const& v_rh) { return (v_rh > s_lh); } //----------------------------------------------------------------------------- template <typename type> inline ttvec4<type>::ttvec4(type const& xyzw) : x(xyzw), y(xyzw), z(xyzw), w(xyzw) { } template <typename type> inline ttvec4<type>::ttvec4(type const& xc, type const& yc, type const& zc, type const& wc) : x(xc), y(yc), z(zc), w(wc) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec2<type> const& xy, type const& zc, type const& wc) : x(xy.x), y(xy.y), z(zc), w(wc) { } template <typename type> inline ttvec4<type>::ttvec4(type const& xc, ttvec2<type> const& yz, type const& wc) : x(xc), y(yz.x), z(yz.y), w(wc) { } template <typename type> inline ttvec4<type>::ttvec4(type const& xc, type const& yc, ttvec2<type> const& zw) : x(xc), y(yc), z(zw.x), w(zw.y) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec2<type> const& xy, ttvec2<type> const& zw) : x(xy.x), y(xy.y), z(zw.x), w(zw.y) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec3<type> const& xyz, type const& wc) : x(xyz.x), y(xyz.y), z(xyz.z), w(wc) { } template <typename type> inline ttvec4<type>::ttvec4(type const& xc, ttvec3<type> const& yzw) : x(xc), y(yzw.x), z(yzw.y), w(yzw.z) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec4 const& xyzw) : x(xyzw.x), y(xyzw.y), z(xyzw.z), w(xyzw.w) { } template <typename type> inline ttvec4<type>::ttvec4(stvec2<type> const& xy, type const& zc, type const& wc) : x(xy.x), y(xy.y), z(zc), w(wc) { } template <typename type> inline ttvec4<type>::ttvec4(type const& xc, stvec2<type> const& yz, type const& wc) : x(xc), y(yz.x), z(yz.y), w(wc) { } template <typename type> inline ttvec4<type>::ttvec4(type const& xc, type const& yc, stvec2<type> const& zw) : x(xc), y(yc), z(zw.x), w(zw.y) { } template <typename type> inline ttvec4<type>::ttvec4(stvec2<type> const& xy, stvec2<type> const& zw) : x(xy.x), y(xy.y), z(zw.x), w(zw.y) { } template <typename type> inline ttvec4<type>::ttvec4(stvec3<type> const& xyz, type const& wc) : x(xyz.x), y(xyz.y), z(xyz.z), w(wc) { } template <typename type> inline ttvec4<type>::ttvec4(type const& xc, stvec3<type> const& yzw) : x(xc), y(yzw.x), z(yzw.y), w(yzw.z) { } template <typename type> inline ttvec4<type>::ttvec4(stvec4<type> const& xyzw) : x(xyzw.x), y(xyzw.y), z(xyzw.z), w(xyzw.w) { } template <typename type> inline ttvec4<type>::ttvec4(bool4 const xyzw) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(int4 const xyzw) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(intl4 const xyzw) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(uint4 const xyzw) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(uintl4 const xyzw) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(float4 const xyzw) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(double4 const xyzw) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec1<bool> const xyzw[4]) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec1<i32> const xyzw[4]) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec1<i64> const xyzw[4]) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec1<ui32> const xyzw[4]) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec1<ui64> const xyzw[4]) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec1<f32> const xyzw[4]) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type>::ttvec4(ttvec1<f64> const xyzw[4]) : x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3]) { } template <typename type> inline ttvec4<type> const ttvec4<type>::operator +() const { return *this; } template <typename type> inline ttvec4<type> const ttvec4<type>::operator -() const { return ttvec4(-x, -y, -z, -w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator ~() const { return ttvec4(~x, ~y, ~z, ~w); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator !() const { return ttvec4<bool>(!x, !y, !z, !w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator +(ttvec4 const& v_rh) const { return ttvec4(x + v_rh.x, y + v_rh.y, z + v_rh.z, w + v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator -(ttvec4 const& v_rh) const { return ttvec4(x - v_rh.x, y - v_rh.y, z - v_rh.z, w - v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator *(ttvec4 const& v_rh) const { return ttvec4(x * v_rh.x, y * v_rh.y, z * v_rh.z, w * v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator /(ttvec4 const& v_rh) const { return ttvec4(x / v_rh.x, y / v_rh.y, z / v_rh.z, w / v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator %(ttvec4 const& v_rh) const { return ttvec4(x % v_rh.x, y % v_rh.y, z % v_rh.z, w % v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator &(ttvec4 const& v_rh) const { return ttvec4(x & v_rh.x, y & v_rh.y, z & v_rh.z, w & v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator |(ttvec4 const& v_rh) const { return ttvec4(x | v_rh.x, y | v_rh.y, z | v_rh.z, w | v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator ^(ttvec4 const& v_rh) const { return ttvec4(x ^ v_rh.x, y ^ v_rh.y, z ^ v_rh.z, w ^ v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator <<(ttvec4 const& v_rh) const { return ttvec4(x << v_rh.x, y << v_rh.y, z << v_rh.z, w << v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator >>(ttvec4 const& v_rh) const { return ttvec4(x >> v_rh.x, y >> v_rh.y, z >> v_rh.z, w >> v_rh.w); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator ==(ttvec4 const& v_rh) const { return ttvec4<bool>(x == v_rh.x, y == v_rh.y, z == v_rh.z, w == v_rh.w); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator !=(ttvec4 const& v_rh) const { return ttvec4<bool>(x != v_rh.x, y != v_rh.y, z != v_rh.z, w != v_rh.w); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator <=(ttvec4 const& v_rh) const { return ttvec4<bool>(x <= v_rh.x, y <= v_rh.y, z <= v_rh.z, w <= v_rh.w); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator >=(ttvec4 const& v_rh) const { return ttvec4<bool>(x >= v_rh.x, y >= v_rh.y, z >= v_rh.z, w >= v_rh.w); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator <(ttvec4 const& v_rh) const { return ttvec4<bool>(x < v_rh.x, y < v_rh.y, z < v_rh.z, w < v_rh.w); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator >(ttvec4 const& v_rh) const { return ttvec4<bool>(x > v_rh.x, y > v_rh.y, z > v_rh.z, w > v_rh.w); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator +(type const& s_rh) const { return ttvec4(x + s_rh, y + s_rh, z + s_rh, w + s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator -(type const& s_rh) const { return ttvec4(x - s_rh, y - s_rh, z - s_rh, w - s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator *(type const& s_rh) const { return ttvec4(x * s_rh, y * s_rh, z * s_rh, w * s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator /(type const& s_rh) const { return ttvec4(x / s_rh, y / s_rh, z / s_rh, w / s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator %(type const& s_rh) const { return ttvec4(x % s_rh, y % s_rh, z % s_rh, w % s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator &(type const& s_rh) const { return ttvec4(x & s_rh, y & s_rh, z & s_rh, w & s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator |(type const& s_rh) const { return ttvec4(x | s_rh, y | s_rh, z | s_rh, w | s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator ^(type const& s_rh) const { return ttvec4(x ^ s_rh, y ^ s_rh, z ^ s_rh, w ^ s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator <<(type const& s_rh) const { return ttvec4(x << s_rh, y << s_rh, z << s_rh, w << s_rh); } template <typename type> inline ttvec4<type> const ttvec4<type>::operator >>(type const& s_rh) const { return ttvec4(x >> s_rh, y >> s_rh, z >> s_rh, w >> s_rh); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator ==(type const& s_rh) const { return ttvec4<bool>(x == s_rh, y == s_rh, z == s_rh, w == s_rh); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator !=(type const& s_rh) const { return ttvec4<bool>(x != s_rh, y != s_rh, z != s_rh, w != s_rh); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator <=(type const& s_rh) const { return ttvec4<bool>(x <= s_rh, y <= s_rh, z <= s_rh, w <= s_rh); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator >=(type const& s_rh) const { return ttvec4<bool>(x >= s_rh, y >= s_rh, z >= s_rh, w >= s_rh); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator <(type const& s_rh) const { return ttvec4<bool>(x < s_rh, y < s_rh, z < s_rh, w < s_rh); } template <typename type> inline ttvec4<bool> const ttvec4<type>::operator >(type const& s_rh) const { return ttvec4<bool>(x > s_rh, y > s_rh, z > s_rh, w > s_rh); } template <typename type> inline type const ttvec4<type>::operator [](index const i) const { return xyzw[i]; } template <typename type> inline ttvec4<type>::operator type const* () const { return xyzw; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator =(ttvec4 const& v_rh) { x = v_rh.x; y = v_rh.y; z = v_rh.z; w = v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator =(stvec4<type> const& v_rh) { x = v_rh.x; y = v_rh.y; z = v_rh.z; w = v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator +=(ttvec4 const& v_rh) { x += v_rh.x; y += v_rh.y; z += v_rh.z; w += v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator -=(ttvec4 const& v_rh) { x -= v_rh.x; y -= v_rh.y; z -= v_rh.z; w -= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator *=(ttvec4 const& v_rh) { x *= v_rh.x; y *= v_rh.y; z *= v_rh.z; w *= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator /=(ttvec4 const& v_rh) { x /= v_rh.x; y /= v_rh.y; z /= v_rh.z; w /= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator %=(ttvec4 const& v_rh) { x %= v_rh.x; y %= v_rh.y; z %= v_rh.z; w %= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator &=(ttvec4 const& v_rh) { x &= v_rh.x; y &= v_rh.y; z &= v_rh.z; w &= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator |=(ttvec4 const& v_rh) { x |= v_rh.x; y |= v_rh.y; z |= v_rh.z; w |= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator ^=(ttvec4 const& v_rh) { x ^= v_rh.x; y ^= v_rh.y; z ^= v_rh.z; w ^= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator <<=(ttvec4 const& v_rh) { x <<= v_rh.x; y <<= v_rh.y; z <<= v_rh.z; w <<= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator >>=(ttvec4 const& v_rh) { x >>= v_rh.x; y >>= v_rh.y; z >>= v_rh.z; w >>= v_rh.w; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator =(type const& s_rh) { x = y = z = w = s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator +=(type const& s_rh) { x += s_rh; y += s_rh; z += s_rh; w += s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator -=(type const& s_rh) { x -= s_rh; y -= s_rh; z -= s_rh; w -= s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator *=(type const& s_rh) { x *= s_rh; y *= s_rh; z *= s_rh; w *= s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator /=(type const& s_rh) { x /= s_rh; y /= s_rh; z /= s_rh; w /= s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator %=(type const& s_rh) { x %= s_rh; y %= s_rh; z %= s_rh; w %= s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator &=(type const& s_rh) { x &= s_rh; y &= s_rh; z &= s_rh; w &= s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator |=(type const& s_rh) { x |= s_rh; y |= s_rh; z |= s_rh; w |= s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator ^=(type const& s_rh) { x ^= s_rh; y ^= s_rh; z ^= s_rh; w ^= s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator <<=(type const& s_rh) { x <<= s_rh; y <<= s_rh; z <<= s_rh; w <<= s_rh; return *this; } template <typename type> inline ttvec4<type>& ttvec4<type>::operator >>=(type const& s_rh) { x >>= s_rh; y >>= s_rh; z >>= s_rh; w >>= s_rh; return *this; } template <typename type> inline type& ttvec4<type>::operator [](index const i) { return xyzw[i]; } template <typename type> inline ttvec4<type>::operator type* () { return xyzw; } template<typename type> inline ttvec4<type> const operator +(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh + s_lh); } template<typename type> inline ttvec4<type> const operator -(type const& s_lh, ttvec4<type> const& v_rh) { return ttvec4<type>(s_lh - v_rh.x, s_lh - v_rh.y, s_lh - v_rh.z, s_lh - v_rh.w); } template<typename type> inline ttvec4<type> const operator *(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh * s_lh); } template<typename type> inline ttvec4<type> const operator /(type const& s_lh, ttvec4<type> const& v_rh) { return ttvec4<type>(s_lh / v_rh.x, s_lh / v_rh.y, s_lh / v_rh.z, s_lh / v_rh.w); } template<typename type> inline ttvec4<type> const operator %(type const& s_lh, ttvec4<type> const& v_rh) { return ttvec4<type>(s_lh % v_rh.x, s_lh % v_rh.y, s_lh % v_rh.z, s_lh % v_rh.w); } template<typename type> inline ttvec4<type> const operator &(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh & s_lh); } template<typename type> inline ttvec4<type> const operator |(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh | s_lh); } template<typename type> inline ttvec4<type> const operator ^(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh ^ s_lh); } template<typename type> inline ttvec4<type> const operator <<(type const& s_lh, ttvec4<type> const& v_rh) { return ttvec4<type>(s_lh << v_rh.x, s_lh << v_rh.y, s_lh << v_rh.z, s_lh << v_rh.w); } template<typename type> inline ttvec4<type> const operator >>(type const& s_lh, ttvec4<type> const& v_rh) { return ttvec4<type>(s_lh >> v_rh.x, s_lh >> v_rh.y, s_lh >> v_rh.z, s_lh >> v_rh.w); } template<typename type> inline ttvec4<bool> const operator ==(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh == s_lh); } template<typename type> inline ttvec4<bool> const operator !=(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh != s_lh); } template<typename type> inline ttvec4<bool> const operator <=(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh <= s_lh); } template<typename type> inline ttvec4<bool> const operator >=(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh >= s_lh); } template<typename type> inline ttvec4<bool> const operator <(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh < s_lh); } template<typename type> inline ttvec4<bool> const operator >(type const& s_lh, ttvec4<type> const& v_rh) { return (v_rh > s_lh); } //----------------------------------------------------------------------------- template<typename type> inline ttvec1<type> const stvec1<type>::operator =(ttvec1<type> const v) { // pass-by-value is deliberate; need copy in case 'v' is the swizzle target this->x = v.x; return ttvec1<type>(*this); } template<typename type> inline ttvec1<type> const stvec1<type>::operator =(stvec1 const& v) { return (*this = ttvec1<type>(v)); } template<typename type> inline ttvec1<type> const stvec1<type>::operator =(type const& xc) { return (*this = ttvec1<type>(xc)); } template<typename type> inline stvec1<type>::stvec1(type& xr) : ttvec1<type>(xr), xr(xr) { } template<typename type> inline stvec1<type>::~stvec1() { // assign final state xr = this->x; } template<typename type> inline ttvec2<type> const stvec2<type>::operator =(ttvec2<type> const v) { // pass-by-value is deliberate; need copy in case 'v' is the swizzle target this->x = v.x; this->y = v.y; return ttvec2<type>(*this); } template<typename type> inline ttvec2<type> const stvec2<type>::operator =(stvec2 const& v) { return (*this = ttvec2<type>(v)); } template<typename type> inline ttvec2<type> const stvec2<type>::operator =(type const& xy) { return (*this = ttvec2<type>(xy)); } template<typename type> inline stvec2<type>::stvec2(type& xr, type& yr) : ttvec2<type>(xr, yr), xr(xr), yr(yr) { } template<typename type> inline stvec2<type>::~stvec2() { // assign final state xr = this->x; yr = this->y; } template<typename type> inline ttvec3<type> const stvec3<type>::operator =(ttvec3<type> const v) { // pass-by-value is deliberate; need copy in case 'v' is the swizzle target this->x = v.x; this->y = v.y; this->z = v.z; return ttvec3<type>(*this); } template<typename type> inline ttvec3<type> const stvec3<type>::operator =(stvec3 const& v) { return (*this = ttvec3<type>(v)); } template<typename type> inline ttvec3<type> const stvec3<type>::operator =(type const& xyz) { return (*this = ttvec3<type>(xyz)); } template<typename type> inline stvec3<type>::stvec3(type& xr, type& yr, type& zr) : ttvec3<type>(xr, yr, zr), xr(xr), yr(yr), zr(zr) { } template<typename type> inline stvec3<type>::~stvec3() { // assign final state xr = this->x; yr = this->y; zr = this->z; } template<typename type> inline ttvec4<type> const stvec4<type>::operator =(ttvec4<type> const v) { // pass-by-value is deliberate; need copy in case 'v' is the swizzle target this->x = v.x; this->y = v.y; this->z = v.z; this->w = v.w; return ttvec4<type>(*this); } template<typename type> inline ttvec4<type> const stvec4<type>::operator =(stvec4 const& v) { return (*this = ttvec4<type>(v)); } template<typename type> inline ttvec4<type> const stvec4<type>::operator =(type const& xyzw) { return (*this = ttvec4<type>(xyzw)); } template<typename type> inline stvec4<type>::stvec4(type& xr, type& yr, type& zr, type& wr) : ttvec4<type>(xr, yr, zr, wr), xr(xr), yr(yr), zr(zr), wr(wr) { } template<typename type> inline stvec4<type>::~stvec4() { // assign final state xr = this->x; yr = this->y; zr = this->z; wr = this->w; } //----------------------------------------------------------------------------- #ifdef IJK_VECTOR_SWIZZLE IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, ttvec, 1, inline); IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, ttvec, 2, inline); IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, ttvec, 3, inline); IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, ttvec, 4, inline); /* IJK_SWIZZLE_ALL(IJK_SWIZZLE_DECL_RTEMP, IJK_SWIZZLE_DECL_RTEMP, ttvec, stvec, stvec, 1); IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, stvec, 1, inline); IJK_SWIZZLE_ALL(IJK_SWIZZLE_DECL_RTEMP, IJK_SWIZZLE_DECL_RTEMP, ttvec, stvec, stvec, 2); IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, stvec, 2, inline); IJK_SWIZZLE_ALL(IJK_SWIZZLE_DECL_RTEMP, IJK_SWIZZLE_DECL_RTEMP, ttvec, stvec, stvec, 3); IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, stvec, 3, inline); IJK_SWIZZLE_ALL(IJK_SWIZZLE_DECL_RTEMP, IJK_SWIZZLE_DECL_RTEMP, ttvec, stvec, stvec, 4); IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, stvec, 4, inline); */ #endif // IJK_VECTOR_SWIZZLE //----------------------------------------------------------------------------- #endif // __cplusplus #endif // !_IJK_VECTORSWIZZLE_INL_ #endif // _IJK_VECTORSWIZZLE_H_
25.604088
96
0.675053
dbuckstein
908711a2194f5d82a80a46a8537ec2f653d75e7d
2,541
cpp
C++
LeetCode-Weekly-Contest/weekly-contest-224/1727.cpp
sptuan/PAT-Practice
68e1ca329190264fdeeef1a2a1d4c2a56caa27f6
[ "MIT" ]
null
null
null
LeetCode-Weekly-Contest/weekly-contest-224/1727.cpp
sptuan/PAT-Practice
68e1ca329190264fdeeef1a2a1d4c2a56caa27f6
[ "MIT" ]
null
null
null
LeetCode-Weekly-Contest/weekly-contest-224/1727.cpp
sptuan/PAT-Practice
68e1ca329190264fdeeef1a2a1d4c2a56caa27f6
[ "MIT" ]
null
null
null
class Solution { public: int largestSubmatrix(vector<vector<int>>& matrix) { vector<int> conti_seg_left,conti_seg_right; // speical for line int line_counter = 0; int total_counter = 0; if(matrix.size() == 1){ for(int i=0; i<matrix[0].size(); i++){ if(matrix[0][i] == 1){ line_counter++; } //cout<<line_counter<<endl; } return line_counter; } if(matrix[0].size() == 1){ for(int i=0; i<matrix.size(); i++){ if(matrix[i][0] == 1){ line_counter++; } //cout<<line_counter<<endl; } return line_counter; } // common else{ for(int i=0; i<matrix[0].size(); i++){ int temp_l = 0; int temp_r = 0; if(matrix[0][i] == 1){ conti_seg_left.push_back(0); //total total_counter++; } for(int j=1; j<matrix.size(); j++){ if(matrix[j][i] == 0 && matrix[j-1][i] == 1){ conti_seg_right.push_back(j-1); } if(matrix[j][i] == 1 && matrix[j-1][i] == 0){ conti_seg_left.push_back(j); } //total if(matrix[j][i] == 1){ total_counter++; } } if(matrix[matrix.size()-1][i] == 1){ conti_seg_right.push_back(matrix.size()-1); } } } int max_size = 0; if(total_counter == (matrix.size() * matrix[0].size())) return total_counter; for(int L=0; L<matrix.size(); L++){ for(int R=L; R<matrix.size(); R++){ int temp_counter = 0; for(int s=0; s<conti_seg_left.size(); s++){ if(conti_seg_left[s]<=L && conti_seg_right[s]>=R) temp_counter++; } int temp_size = (R-L+1) * temp_counter; if(temp_size > max_size){ max_size = temp_size; } } } return max_size; } };
33
70
0.358127
sptuan
9089238947f1e8711dae4a052cd900474a4e6e4f
770
cpp
C++
src/MainMenuGamestate.cpp
q4a/carnage3d
bbc1b88feccde68a1b547bbc5d8eb37d852136f1
[ "MIT" ]
null
null
null
src/MainMenuGamestate.cpp
q4a/carnage3d
bbc1b88feccde68a1b547bbc5d8eb37d852136f1
[ "MIT" ]
null
null
null
src/MainMenuGamestate.cpp
q4a/carnage3d
bbc1b88feccde68a1b547bbc5d8eb37d852136f1
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "MainMenuGamestate.h" void MainMenuGamestate::OnGamestateEnter() { } void MainMenuGamestate::OnGamestateLeave() { } void MainMenuGamestate::OnGamestateFrame() { } void MainMenuGamestate::OnGamestateInputEvent(KeyInputEvent& inputEvent) { } void MainMenuGamestate::OnGamestateInputEvent(MouseButtonInputEvent& inputEvent) { } void MainMenuGamestate::OnGamestateInputEvent(MouseMovedInputEvent& inputEvent) { } void MainMenuGamestate::OnGamestateInputEvent(MouseScrollInputEvent& inputEvent) { } void MainMenuGamestate::OnGamestateInputEvent(KeyCharEvent& inputEvent) { } void MainMenuGamestate::OnGamestateInputEvent(GamepadInputEvent& inputEvent) { } void MainMenuGamestate::OnGamestateInputEventLost() { }
18.333333
80
0.794805
q4a
90898fe488adab6971bf2aad38e6aedfc53a6181
5,692
cpp
C++
LeetCode/C++/1032. Stream of Characters.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/1032. Stream of Characters.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/1032. Stream of Characters.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//Runtime: 1760 ms, faster than 6.41% of C++ online submissions for Stream of Characters. //Memory Usage: 105.9 MB, less than 58.81% of C++ online submissions for Stream of Characters. class TrieNode{ public: vector<TrieNode*> children; bool isEnd; TrieNode(){ children = vector<TrieNode*>(26, nullptr); isEnd = false; } }; class StreamChecker { public: TrieNode* root; int max_word_len; vector<TrieNode*> nodes; void add(string& word){ TrieNode* cur = root; for(char& c : word){ if(cur->children[c-'a'] == nullptr){ cur->children[c-'a'] = new TrieNode(); } cur = cur->children[c-'a']; } cur->isEnd = true; } StreamChecker(vector<string>& words) { root = new TrieNode(); max_word_len = 0; for(string& word : words){ add(word); max_word_len = max(max_word_len, (int)word.size()); } } bool query(char letter) { bool found = false; nodes.push_back(root); // cout << "nodes: " << nodes.size() << endl; for(int i = nodes.size()-1; i >= 0; --i){ // cout << "i: " << i << " "; if(nodes[i]->children[letter-'a'] == nullptr){ nodes.erase(nodes.begin()+i); }else{ nodes[i] = nodes[i]->children[letter-'a']; if(nodes[i]->isEnd){ found = true; } } } return found; } }; /** * Your StreamChecker object will be instantiated and called as such: * StreamChecker* obj = new StreamChecker(words); * bool param_1 = obj->query(letter); */ //revised from above, add restriction of the level of pointers, but slower than above //Runtime: 1928 ms, faster than 5.12% of C++ online submissions for Stream of Characters. //Memory Usage: 105.7 MB, less than 66.34% of C++ online submissions for Stream of Characters. class TrieNode{ public: vector<TrieNode*> children; bool isEnd; int level; TrieNode(){ children = vector<TrieNode*>(26, nullptr); isEnd = false; level = 0; } }; class StreamChecker { public: TrieNode* root; int max_word_len; vector<TrieNode*> nodes; void add(string& word){ TrieNode* cur = root; for(char& c : word){ if(cur->children[c-'a'] == nullptr){ cur->children[c-'a'] = new TrieNode(); cur->children[c-'a']->level = cur->level+1; } cur = cur->children[c-'a']; } cur->isEnd = true; } StreamChecker(vector<string>& words) { root = new TrieNode(); max_word_len = 0; for(string& word : words){ add(word); max_word_len = max(max_word_len, (int)word.size()); } } bool query(char letter) { bool found = false; nodes.push_back(root); // cout << "nodes: " << nodes.size() << endl; for(int i = nodes.size()-1; i >= 0; --i){ // cout << "i: " << i << " "; if(nodes[i]->children[letter-'a'] == nullptr || nodes[i]->level > max_word_len){ nodes.erase(nodes.begin()+i); }else{ nodes[i] = nodes[i]->children[letter-'a']; if(nodes[i]->isEnd){ found = true; } } } return found; } }; /** * Your StreamChecker object will be instantiated and called as such: * StreamChecker* obj = new StreamChecker(words); * bool param_1 = obj->query(letter); */ //store words in reverse order, and find the query string in reverse order //also pruning when query string is too long //https://leetcode.com/problems/stream-of-characters/discuss/278769/Java-Trie-Solution //Runtime: 624 ms, faster than 59.45% of C++ online submissions for Stream of Characters. //Memory Usage: 265.8 MB, less than 13.61% of C++ online submissions for Stream of Characters. class TrieNode{ public: vector<TrieNode*> children; bool isEnd; TrieNode(){ children = vector<TrieNode*>(26, nullptr); isEnd = false; } }; class StreamChecker { public: TrieNode* root; int max_word_len; string past; void reverse_add(string& word){ TrieNode* cur = root; for(int i = word.size()-1; i >= 0; --i){ char c = word[i]; if(cur->children[c-'a'] == nullptr){ cur->children[c-'a'] = new TrieNode(); } cur = cur->children[c-'a']; } cur->isEnd = true; } StreamChecker(vector<string>& words) { root = new TrieNode(); max_word_len = 0; for(string& word : words){ reverse_add(word); max_word_len = max(max_word_len, (int)word.size()); } } bool query(char letter) { past = letter + past; //this avoids TLE!! if(past.size() > max_word_len){ past = past.substr(0, max_word_len); } TrieNode* cur = root; for(char& c : past){ cur = cur->children[c-'a']; if(!cur) break; if(cur->isEnd){ return true; } } return false; } }; /** * Your StreamChecker object will be instantiated and called as such: * StreamChecker* obj = new StreamChecker(words); * bool param_1 = obj->query(letter); */
26.474419
94
0.512474
shreejitverma
908ce98a98ca51186e12f3042435ce3af8a27cba
810
cpp
C++
src/HAL/InputPin.cpp
SqLemon/Robotics_HAL
3364ef3a41345b9551a19554015b9582b7258fc6
[ "MIT" ]
null
null
null
src/HAL/InputPin.cpp
SqLemon/Robotics_HAL
3364ef3a41345b9551a19554015b9582b7258fc6
[ "MIT" ]
null
null
null
src/HAL/InputPin.cpp
SqLemon/Robotics_HAL
3364ef3a41345b9551a19554015b9582b7258fc6
[ "MIT" ]
null
null
null
/* * Pin.h * * Created on: Jan 2, 2021 * Author: ianicknoejovich */ #include <HAL/InputPin.h> InputPin::InputPin(uint8_t port, uint8_t pin, Mode mode) : Pin(port, pin) { _mode = mode; } void InputPin::init(void){ GPIO_setDir(_port, _pin, INPUT); if(_mode == PULLDOWN) GPIO_setInputMode(_port, _pin, _mode-1); else GPIO_setInputMode(_port, _pin, _mode); if(_mode == PULLUP) GPIO_setPull(_port, _pin, HIGH); else GPIO_setPull(_port, _pin, LOW); } void InputPin::paramInit(uint8_t port, uint8_t pin, Mode mode){ GPIO_setDir(port, pin, INPUT); if(mode == PULLDOWN) GPIO_setInputMode(port, pin, PULLUP); //form input mode pullup and pullfown share "code" else GPIO_setInputMode(port, pin, mode); if(mode == PULLUP) GPIO_setPull(port, pin, HIGH); else GPIO_setPull(port, pin, LOW); }
25.3125
110
0.7
SqLemon
908f67e681541d578b4cd466bda4805f73cce902
1,765
cpp
C++
server/main.cpp
ReddyArunreddy/BeastLounge
ae848cb604d1cac785d6345252de5007377f2ee1
[ "BSL-1.0" ]
null
null
null
server/main.cpp
ReddyArunreddy/BeastLounge
ae848cb604d1cac785d6345252de5007377f2ee1
[ "BSL-1.0" ]
null
null
null
server/main.cpp
ReddyArunreddy/BeastLounge
ae848cb604d1cac785d6345252de5007377f2ee1
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2018-2019 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/vinniefalco/BeastLounge // #include "logger.hpp" #include "server.hpp" #include <boost/config.hpp> #include <boost/beast/src.hpp> #include <iostream> #ifdef BOOST_MSVC # ifndef WIN32_LEAN_AND_MEAN // VC_EXTRALEAN # define WIN32_LEAN_AND_MEAN # include <windows.h> # undef WIN32_LEAN_AND_MEAN # else # include <windows.h> # endif #endif //------------------------------------------------------------------------------ extern std::unique_ptr<logger> make_logger(); /** Create a server. The configuration file is loaded, and all child objects are created. */ extern std::unique_ptr<server> make_server( char const* config_path, std::unique_ptr<logger> log); //------------------------------------------------------------------------------ int main(int argc, char* argv[]) { #if BOOST_MSVC { int flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); flags |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(flags); } #endif // Create the logger auto log = make_logger(); if(! log) return EXIT_FAILURE; // Check command line arguments. if(argc != 2) { log->cerr() << "Usage: lounge-server <config-path>\n"; return EXIT_FAILURE; } auto const config_path = argv[1]; // Create the server beast::error_code ec; auto srv = make_server( config_path, std::move(log)); if(! srv) return EXIT_FAILURE; srv->run(); return EXIT_SUCCESS; }
21.52439
80
0.5983
ReddyArunreddy
9093b2b88c85bb24c49e59169ca9c1a7ccc7eb9d
4,475
cpp
C++
src/shared/tests/diagnostics/counter_set.cpp
snowmeltarcade/projectbirdracing
55cd479c81979de535b0cf496e91dd8d48b99fa8
[ "MIT" ]
null
null
null
src/shared/tests/diagnostics/counter_set.cpp
snowmeltarcade/projectbirdracing
55cd479c81979de535b0cf496e91dd8d48b99fa8
[ "MIT" ]
3
2021-11-13T02:18:59.000Z
2021-12-04T18:16:01.000Z
src/shared/tests/diagnostics/counter_set.cpp
snowmeltarcade/projectbirdracing
55cd479c81979de535b0cf496e91dd8d48b99fa8
[ "MIT" ]
null
null
null
#include <thread> #include "catch2/catch.hpp" #include "shared/diagnostics/counter_set.h" using namespace pbr::shared::diagnostics; ////////// /// increment ////////// TEST_CASE("increment - valid amount - increments counter", "[shared/diagnostics]") { counter_set c; auto key = "key"; auto value = 10; c.increment_counter(key, value); c.increment_counter(key, value); auto result = c.get_counter(key); REQUIRE(result == value * 2); } ////////// /// decrement ////////// TEST_CASE("decrement - valid amount - decrements counter", "[shared/diagnostics]") { counter_set c; auto key = "key"; auto value = 10; c.decrement_counter(key, value); c.decrement_counter(key, value); auto result = c.get_counter(key); REQUIRE(result == -value * 2); } ////////// /// add_value_to_list ////////// TEST_CASE("add_value_to_list - valid value - adds value to list", "[shared/diagnostics]") { counter_set c; auto key = "key"; auto value = 10; auto value2 = 20; c.add_value_to_list(key, value); c.add_value_to_list(key, value2); auto result = c.get_values_for_counter_list(key); REQUIRE(result.size() == 2); REQUIRE(result[0] == value); REQUIRE(result[1] == value2); } ////////// /// get_counter ////////// TEST_CASE("get_counter - returns counter", "[shared/diagnostics]") { counter_set c; auto key = "key"; auto value = 10; c.increment_counter(key, value); auto result = c.get_counter(key); REQUIRE(result == value); c.increment_counter(key, value); result = c.get_counter(key); REQUIRE(result == value * 2); } ////////// /// get_values_for_counter_list ////////// TEST_CASE("get_values_for_counter_list - returns values", "[shared/diagnostics]") { counter_set c; auto key = "key"; auto value = 10; auto value2 = 20; c.add_value_to_list(key, value); auto result = c.get_values_for_counter_list(key); REQUIRE(result.size() == 1); REQUIRE(result[0] == value); c.add_value_to_list(key, value2); result = c.get_values_for_counter_list(key); REQUIRE(result.size() == 2); REQUIRE(result[0] == value); REQUIRE(result[1] == value2); } ////////// /// get_counter_for_duration ////////// TEST_CASE("get_counter_for_duration - returns values", "[shared/diagnostics]") { counter_set c; auto key = "key"; auto value = 10; auto now = std::chrono::system_clock::now(); auto duration = std::chrono::milliseconds(500); auto expected {0}; auto result_on_duration {0}; // ensure the last update time is set up correctly c.get_counter_for_duration(key, duration, result_on_duration); result_on_duration = 0; while (std::chrono::system_clock::now() - now < duration) { expected += value; c.increment_counter(key, value); auto result = c.get_counter_for_duration(key, duration, result_on_duration); REQUIRE(result == expected); REQUIRE(result_on_duration == 0); } std::this_thread::sleep_for(duration / 2); // the duration has now passed auto passed_result = c.get_counter_for_duration(key, duration, result_on_duration); REQUIRE(passed_result >= 0); REQUIRE(passed_result < expected); REQUIRE(expected == result_on_duration); } ////////// /// get_average_for_duration ////////// TEST_CASE("get_average_for_duration - returns values", "[shared/diagnostics]") { counter_set c; auto key = "key"; auto value = 10; auto now = std::chrono::system_clock::now(); auto duration = std::chrono::milliseconds(500); auto number_of_additions {0}; auto total {0}; auto result_on_duration {0.0f}; // ensure the last update time is set up correctly c.get_average_for_duration(key, duration, result_on_duration); result_on_duration = 0.0f; while (std::chrono::system_clock::now() - now <= duration) { total += value; ++number_of_additions; c.add_value_to_list(key, value); c.get_average_for_duration(key, duration, result_on_duration); REQUIRE(result_on_duration == 0.0f); } std::this_thread::sleep_for(duration / 2); auto expected = static_cast<float>(total) / number_of_additions; // the duration has now passed auto result = c.get_average_for_duration(key, duration, result_on_duration); REQUIRE(result == expected); REQUIRE(result_on_duration == expected); }
23.677249
91
0.642458
snowmeltarcade
90959b3dd90afb9a9bb2734d16fef8bdfda59684
18,918
cc
C++
mediapipe/python/pybind/packet_creator.cc
Yuuraa/mediapipe-gesture-recognition
e2444cedbfcedf2b242ad025ceac39359c945db2
[ "Apache-2.0" ]
47
2019-12-29T02:52:48.000Z
2022-02-21T08:39:14.000Z
mediapipe/python/pybind/packet_creator.cc
Yuuraa/mediapipe-gesture-recognition
e2444cedbfcedf2b242ad025ceac39359c945db2
[ "Apache-2.0" ]
null
null
null
mediapipe/python/pybind/packet_creator.cc
Yuuraa/mediapipe-gesture-recognition
e2444cedbfcedf2b242ad025ceac39359c945db2
[ "Apache-2.0" ]
16
2020-07-21T06:28:25.000Z
2022-02-02T13:40:36.000Z
// Copyright 2020 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mediapipe/python/pybind/packet_creator.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "mediapipe/framework/formats/matrix.h" #include "mediapipe/framework/packet.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/framework/timestamp.h" #include "mediapipe/python/pybind/image_frame_util.h" #include "mediapipe/python/pybind/util.h" #include "pybind11/eigen.h" #include "pybind11/pybind11.h" #include "pybind11/stl.h" namespace mediapipe { namespace python { namespace { Packet CreateImageFramePacket(mediapipe::ImageFormat::Format format, const py::array& data) { if (format == mediapipe::ImageFormat::SRGB || format == mediapipe::ImageFormat::SRGBA || format == mediapipe::ImageFormat::GRAY8) { return Adopt(CreateImageFrame<uint8>(format, data).release()); } else if (format == mediapipe::ImageFormat::GRAY16 || format == mediapipe::ImageFormat::SRGB48 || format == mediapipe::ImageFormat::SRGBA64) { return Adopt(CreateImageFrame<uint16>(format, data).release()); } else if (format == mediapipe::ImageFormat::VEC32F1 || format == mediapipe::ImageFormat::VEC32F2) { return Adopt(CreateImageFrame<float>(format, data).release()); } throw RaisePyError(PyExc_RuntimeError, absl::StrCat("Unsupported ImageFormat: ", format).c_str()); return Packet(); } } // namespace namespace py = pybind11; void PublicPacketCreators(pybind11::module* m) { m->def( "create_string", [](const std::string& data) { return MakePacket<std::string>(data); }, R"doc(Create a MediaPipe std::string Packet from a str. Args: data: A str. Returns: A MediaPipe std::string Packet. Raises: TypeError: If the input is not a str. Examples: packet = mp.packet_creator.create_string('abc') data = mp.packet_getter.get_string(packet) )doc", py::return_value_policy::move); m->def( "create_string", [](const py::bytes& data) { return MakePacket<std::string>(data); }, R"doc(Create a MediaPipe std::string Packet from a bytes object. Args: data: A bytes object. Returns: A MediaPipe std::string Packet. Raises: TypeError: If the input is not a bytes object. Examples: packet = mp.packet_creator.create_string(b'\xd0\xd0\xd0') data = mp.packet_getter.get_bytes(packet) )doc", py::return_value_policy::move); m->def( "create_bool", [](bool data) { return MakePacket<bool>(data); }, R"doc(Create a MediaPipe bool Packet from a boolean object. Args: data: A boolean object. Returns: A MediaPipe bool Packet. Raises: TypeError: If the input is not a boolean object. Examples: packet = mp.packet_creator.create_bool(True) data = mp.packet_getter.get_bool(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_int", [](int64 data) { RaisePyErrorIfOverflow(data, INT_MIN, INT_MAX); return MakePacket<int>(data); }, R"doc(Create a MediaPipe int Packet from an integer. Args: data: An integer or a np.intc. Returns: A MediaPipe int Packet. Raises: OverflowError: If the input integer overflows. TypeError: If the input is not an integer. Examples: packet = mp.packet_creator.create_int(0) data = mp.packet_getter.get_int(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_int8", [](int64 data) { RaisePyErrorIfOverflow(data, INT8_MIN, INT8_MAX); return MakePacket<int8>(data); }, R"doc(Create a MediaPipe int8 Packet from an integer. Args: data: An integer or a np.int8. Returns: A MediaPipe int8 Packet. Raises: OverflowError: If the input integer overflows. TypeError: If the input is neither an integer nor a np.int8. Examples: packet = mp.packet_creator.create_int8(2**7 - 1) data = mp.packet_getter.get_int(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_int16", [](int64 data) { RaisePyErrorIfOverflow(data, INT16_MIN, INT16_MAX); return MakePacket<int16>(data); }, R"doc(Create a MediaPipe int16 Packet from an integer. Args: data: An integer or a np.int16. Returns: A MediaPipe int16 Packet. Raises: OverflowError: If the input integer overflows. TypeError: If the input is neither an integer nor a np.int16. Examples: packet = mp.packet_creator.create_int16(2**15 - 1) data = mp.packet_getter.get_int(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_int32", [](int64 data) { RaisePyErrorIfOverflow(data, INT32_MIN, INT32_MAX); return MakePacket<int32>(data); }, R"doc(Create a MediaPipe int32 Packet from an integer. Args: data: An integer or a np.int32. Returns: A MediaPipe int32 Packet. Raises: OverflowError: If the input integer overflows. TypeError: If the input is neither an integer nor a np.int32. Examples: packet = mp.packet_creator.create_int32(2**31 - 1) data = mp.packet_getter.get_int(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_int64", [](int64 data) { return MakePacket<int64>(data); }, R"doc(Create a MediaPipe int64 Packet from an integer. Args: data: An integer or a np.int64. Returns: A MediaPipe int64 Packet. Raises: TypeError: If the input is neither an integer nor a np.int64. Examples: packet = mp.packet_creator.create_int64(2**63 - 1) data = mp.packet_getter.get_int(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_uint8", [](int64 data) { RaisePyErrorIfOverflow(data, 0, UINT8_MAX); return MakePacket<uint8>(data); }, R"doc(Create a MediaPipe uint8 Packet from an integer. Args: data: An integer or a np.uint8. Returns: A MediaPipe uint8 Packet. Raises: OverflowError: If the input integer overflows. TypeError: If the input is neither an integer nor a np.uint8. Examples: packet = mp.packet_creator.create_uint8(2**8 - 1) data = mp.packet_getter.get_uint(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_uint16", [](int64 data) { RaisePyErrorIfOverflow(data, 0, UINT16_MAX); return MakePacket<uint16>(data); }, R"doc(Create a MediaPipe uint16 Packet from an integer. Args: data: An integer or a np.uint16. Returns: A MediaPipe uint16 Packet. Raises: OverflowError: If the input integer overflows. TypeError: If the input is neither an integer nor a np.uint16. Examples: packet = mp.packet_creator.create_uint16(2**16 - 1) data = mp.packet_getter.get_uint(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_uint32", [](int64 data) { RaisePyErrorIfOverflow(data, 0, UINT32_MAX); return MakePacket<uint32>(data); }, R"doc(Create a MediaPipe uint32 Packet from an integer. Args: data: An integer or a np.uint32. Returns: A MediaPipe uint32 Packet. Raises: OverflowError: If the input integer overflows. TypeError: If the input is neither an integer nor a np.uint32. Examples: packet = mp.packet_creator.create_uint32(2**32 - 1) data = mp.packet_getter.get_uint(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_uint64", [](uint64 data) { return MakePacket<uint64>(data); }, R"doc(Create a MediaPipe uint64 Packet from an integer. Args: data: An integer or a np.uint64. Returns: A MediaPipe uint64 Packet. Raises: TypeError: If the input is neither an integer nor a np.uint64. Examples: packet = mp.packet_creator.create_uint64(2**64 - 1) data = mp.packet_getter.get_uint(packet) )doc", // py::arg().noconvert() won't allow this to accept np.uint64 data type. py::arg(), py::return_value_policy::move); m->def( "create_float", [](float data) { return MakePacket<float>(data); }, R"doc(Create a MediaPipe float Packet from a float. Args: data: A float or a np.float. Returns: A MediaPipe float Packet. Raises: TypeError: If the input is neither a float nor a np.float. Examples: packet = mp.packet_creator.create_float(0.1) data = mp.packet_getter.get_float(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_double", [](double data) { return MakePacket<double>(data); }, R"doc(Create a MediaPipe double Packet from a float. Args: data: A float or a np.double. Returns: A MediaPipe double Packet. Raises: TypeError: If the input is neither a float nore a np.double. Examples: packet = mp.packet_creator.create_double(0.1) data = mp.packet_getter.get_float(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_int_array", [](const std::vector<int>& data) { int* ints = new int[data.size()]; std::copy(data.begin(), data.end(), ints); return Adopt(reinterpret_cast<int(*)[]>(ints)); }, R"doc(Create a MediaPipe int array Packet from a list of integers. Args: data: A list of integers. Returns: A MediaPipe int array Packet. Raises: TypeError: If the input is not a list of integers. Examples: packet = mp.packet_creator.create_int_array([1, 2, 3]) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_float_array", [](const std::vector<float>& data) { float* floats = new float[data.size()]; std::copy(data.begin(), data.end(), floats); return Adopt(reinterpret_cast<float(*)[]>(floats)); }, R"doc(Create a MediaPipe float array Packet from a list of floats. Args: data: A list of floats. Returns: A MediaPipe float array Packet. Raises: TypeError: If the input is not a list of floats. Examples: packet = mp.packet_creator.create_float_array([0.1, 0.2, 0.3]) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_int_vector", [](const std::vector<int>& data) { return MakePacket<std::vector<int>>(data); }, R"doc(Create a MediaPipe int vector Packet from a list of integers. Args: data: A list of integers. Returns: A MediaPipe int vector Packet. Raises: TypeError: If the input is not a list of integers. Examples: packet = mp.packet_creator.create_int_vector([1, 2, 3]) data = mp.packet_getter.get_int_vector(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_float_vector", [](const std::vector<float>& data) { return MakePacket<std::vector<float>>(data); }, R"doc(Create a MediaPipe float vector Packet from a list of floats. Args: data: A list of floats Returns: A MediaPipe float vector Packet. Raises: TypeError: If the input is not a list of floats. Examples: packet = mp.packet_creator.create_float_vector([0.1, 0.2, 0.3]) data = mp.packet_getter.get_float_list(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_string_vector", [](const std::vector<std::string>& data) { return MakePacket<std::vector<std::string>>(data); }, R"doc(Create a MediaPipe std::string vector Packet from a list of str. Args: data: A list of str. Returns: A MediaPipe std::string vector Packet. Raises: TypeError: If the input is not a list of str. Examples: packet = mp.packet_creator.create_string_vector(['a', 'b', 'c']) data = mp.packet_getter.get_str_list(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_packet_vector", [](const std::vector<Packet>& data) { return MakePacket<std::vector<Packet>>(data); }, R"doc(Create a MediaPipe Packet holds a vector of packets. Args: data: A list of packets. Returns: A MediaPipe Packet holds a vector of packets. Raises: TypeError: If the input is not a list of packets. Examples: packet = mp.packet_creator.create_packet_vector([ mp.packet_creator.create_float(0.1), mp.packet_creator.create_int(1), mp.packet_creator.create_string('1') ]) data = mp.packet_getter.get_packet_vector(packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_string_to_packet_map", [](const std::map<std::string, Packet>& data) { return MakePacket<std::map<std::string, Packet>>(data); }, R"doc(Create a MediaPipe std::string to packet map Packet from a dictionary. Args: data: A dictionary that has (str, Packet) pairs. Returns: A MediaPipe Packet holds std::map<std::string, Packet>. Raises: TypeError: If the input is not a dictionary from str to packet. Examples: dict_packet = mp.packet_creator.create_string_to_packet_map({ 'float': mp.packet_creator.create_float(0.1), 'int': mp.packet_creator.create_int(1), 'std::string': mp.packet_creator.create_string('1') data = mp.packet_getter.get_str_to_packet_dict(dict_packet) )doc", py::arg().noconvert(), py::return_value_policy::move); m->def( "create_matrix", // Eigen Map class // (https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html) is the // way to reuse the external memory as an Eigen type. However, when // creating an Eigen::MatrixXf from an Eigen Map object, the data copy // still happens. We can make a packet of an Eigen Map type for reusing // external memory. However,the packet data type is no longer // Eigen::MatrixXf. // TODO: Should take "const Eigen::Ref<const Eigen::MatrixXf>&" // as the input argument. Investigate why bazel non-optimized mode // triggers a memory allocation bug in Eigen::internal::aligned_free(). [](const Eigen::MatrixXf& matrix) { // MakePacket copies the data. return MakePacket<Matrix>(matrix); }, R"doc(Create a MediaPipe Matrix Packet from a 2d numpy float ndarray. The method copies data from the input MatrixXf and the returned packet owns a MatrixXf object. Args: matrix: A 2d numpy float ndarray. Returns: A MediaPipe Matrix Packet. Raises: TypeError: If the input is not a 2d numpy float ndarray. Examples: packet = mp.packet_creator.create_matrix( np.array([[.1, .2, .3], [.4, .5, .6]]) matrix = mp.packet_getter.get_matrix(packet) )doc", py::return_value_policy::move); } void InternalPacketCreators(pybind11::module* m) { m->def( "_create_image_frame_with_copy", [](mediapipe::ImageFormat::Format format, const py::array& data) { return CreateImageFramePacket(format, data); }, py::arg("format"), py::arg("data").noconvert(), py::return_value_policy::move); m->def( "_create_image_frame_with_reference", [](mediapipe::ImageFormat::Format format, const py::array& data) { throw RaisePyError( PyExc_NotImplementedError, "Creating image frame packet with reference is not supproted yet."); }, py::arg("format"), py::arg("data").noconvert(), py::return_value_policy::move); m->def( "_create_image_frame_with_copy", [](ImageFrame& image_frame) { auto image_frame_copy = absl::make_unique<ImageFrame>(); // Set alignment_boundary to kGlDefaultAlignmentBoundary so that // both GPU and CPU can process it. image_frame_copy->CopyFrom(image_frame, ImageFrame::kGlDefaultAlignmentBoundary); return Adopt(image_frame_copy.release()); }, py::arg("image_frame").noconvert(), py::return_value_policy::move); m->def( "_create_image_frame_with_reference", [](ImageFrame& image_frame) { throw RaisePyError( PyExc_NotImplementedError, "Creating image frame packet with reference is not supproted yet."); }, py::arg("image_frame").noconvert(), py::return_value_policy::move); m->def( "_create_proto", [](const std::string& type_name, const py::bytes& serialized_proto) { using packet_internal::HolderBase; mediapipe::StatusOr<std::unique_ptr<HolderBase>> maybe_holder = packet_internal::MessageHolderRegistry::CreateByName(type_name); if (!maybe_holder.ok()) { throw RaisePyError( PyExc_RuntimeError, absl::StrCat("Unregistered proto message type: ", type_name) .c_str()); } // Creates a Packet with the concrete C++ payload type. std::unique_ptr<HolderBase> message_holder = std::move(maybe_holder).ValueOrDie(); auto* copy = const_cast<proto_ns::MessageLite*>( message_holder->GetProtoMessageLite()); copy->ParseFromString(serialized_proto); return packet_internal::Create(message_holder.release()); }, py::return_value_policy::move); m->def( "_create_proto_vector", [](const std::string& type_name, const std::vector<py::bytes>& serialized_proto_vector) { // TODO: Implement this. throw RaisePyError(PyExc_NotImplementedError, "Creating a packet from a vector of proto messages " "is not supproted yet."); return Packet(); }, py::return_value_policy::move); } void PacketCreatorSubmodule(pybind11::module* module) { py::module m = module->def_submodule( "_packet_creator", "MediaPipe internal packet creator module."); PublicPacketCreators(&m); InternalPacketCreators(&m); } } // namespace python } // namespace mediapipe
29.28483
82
0.654773
Yuuraa
9095db0cb28841f876b7afc98e190e3bf83f740e
1,497
cc
C++
zircon/system/ulib/zbitl/checking.cc
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
[ "BSD-2-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
zircon/system/ulib/zbitl/checking.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
zircon/system/ulib/zbitl/checking.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/zbitl/checking.h> namespace zbitl { using namespace std::literals; template <> fitx::result<std::string_view> CheckHeader<Checking::kPermissive>(const zbi_header_t& header, size_t capacity) { // Permissive mode only checks things that break the structural navigation. if (header.length > capacity) { return fitx::error{"item doesn't fit, container truncated?"sv}; } return fitx::ok(); } template <> fitx::result<std::string_view> CheckHeader<Checking::kStrict>(const zbi_header_t& header, size_t capacity) { if (auto result = CheckHeader<Checking::kPermissive>(header, capacity); result.is_error()) { return result; } // Strict mode also checks policy requirements. Boot loaders do not always // bother with setting the fields correctly, but the kernel need not care. if (header.magic != ZBI_ITEM_MAGIC) { return fitx::error{"bad item magic number"sv}; } if (!(header.flags & ZBI_FLAG_VERSION)) { return fitx::error{"bad item header version"sv}; } if (!(header.flags & ZBI_FLAG_CRC32) && header.crc32 != ZBI_ITEM_NO_CRC32) { return fitx::error{"bad crc32 field in item without CRC"sv}; } return fitx::ok(); } } // namespace zbitl
33.266667
94
0.654643
EnderNightLord-ChromeBook
90983beec8f4579019604a4f5fe12d342d12cab7
11,829
cpp
C++
common/jpeg/ImgHWEncoder.cpp
rockchip-toybrick/hardware_rockchip_camera
18ff40c3b502c65b9cbb35902b3419ebae60726b
[ "Apache-2.0" ]
null
null
null
common/jpeg/ImgHWEncoder.cpp
rockchip-toybrick/hardware_rockchip_camera
18ff40c3b502c65b9cbb35902b3419ebae60726b
[ "Apache-2.0" ]
null
null
null
common/jpeg/ImgHWEncoder.cpp
rockchip-toybrick/hardware_rockchip_camera
18ff40c3b502c65b9cbb35902b3419ebae60726b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2014-2017 Intel Corporation * Copyright (c) 2017, Fuzhou Rockchip Electronics Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "ImgHWEncoder" #include "ImgHWEncoder.h" #include "LogHelper.h" #include "PerformanceTraces.h" #include "CameraMetadataHelper.h" #include "PlatformData.h" #include <cutils/properties.h> namespace android { namespace camera2 { #define ALIGN(value, x) ((value + (x-1)) & (~(x-1))) ImgHWEncoder::ImgHWEncoder(int cameraid) : mCameraId(cameraid), mPool(NULL) { memset(sMaker, 0, sizeof(sMaker)); memset(sModel, 0, sizeof(sModel)); LOGI("@%s enter", __FUNCTION__); } ImgHWEncoder::~ImgHWEncoder() { LOGI("@%s enter", __FUNCTION__); deInit(); } status_t ImgHWEncoder::init() { status_t status = NO_ERROR; LOGI("@%s enter", __FUNCTION__); memset(&mExifInfo, 0, sizeof(RkExifInfo)); memset(&mGpsInfo, 0, sizeof(RkGPSInfo)); if (create_vpu_memory_pool_allocator(&mPool, 1, 320*240*2) < 0) { LOGE("@%s %d: create vpu memory failed ", __FUNCTION__, __LINE__); return UNKNOWN_ERROR; } return status; } void ImgHWEncoder::deInit() { LOGI("@%s enter", __FUNCTION__); if (mPool) { release_vpu_memory_pool_allocator(mPool); mPool = NULL; } } void ImgHWEncoder::fillRkExifInfo(RkExifInfo &exifInfo, exif_attribute_t* exifAttrs) { char maker_value[PROPERTY_VALUE_MAX] = {0}; char model_value[PROPERTY_VALUE_MAX] = {0}; property_get("ro.product.manufacturer", maker_value, "rockchip"); property_get("ro.product.model", model_value, "rockchip_mid"); memcpy(sMaker, maker_value, strlen(maker_value)); memcpy(sModel, model_value, strlen(model_value)); exifInfo.maker = sMaker; exifInfo.makerchars = ALIGN(strlen(sMaker),4); //gallery can't get the maker if maker value longer than 4byte exifInfo.modelstr = sModel; exifInfo.modelchars = ALIGN(strlen(sModel),4); //gallery can't get the tag if the value longer than 4byte, need fix exifInfo.Orientation = exifAttrs->orientation; memcpy(exifInfo.DateTime, exifAttrs->date_time, 20); exifInfo.ExposureTime.num = exifAttrs->exposure_time.num; exifInfo.ExposureTime.denom = exifAttrs->exposure_time.den; exifInfo.ApertureFNumber.num = exifAttrs->fnumber.num; exifInfo.ApertureFNumber.denom = exifAttrs->fnumber.den; exifInfo.ISOSpeedRatings = exifAttrs->iso_speed_rating; exifInfo.CompressedBitsPerPixel.num = 0x4; exifInfo.CompressedBitsPerPixel.denom = 0x1; exifInfo.ShutterSpeedValue.num = exifAttrs->shutter_speed.num; exifInfo.ShutterSpeedValue.denom = exifAttrs->shutter_speed.den; exifInfo.ApertureValue.num = exifAttrs->aperture.num; exifInfo.ApertureValue.denom = exifAttrs->aperture.den; exifInfo.ExposureBiasValue.num = exifAttrs->exposure_bias.num; exifInfo.ExposureBiasValue.denom = exifAttrs->exposure_bias.den; exifInfo.MaxApertureValue.num = exifAttrs->max_aperture.num; exifInfo.MaxApertureValue.denom = exifAttrs->max_aperture.den; exifInfo.MeteringMode = exifAttrs->metering_mode; exifInfo.Flash = exifAttrs->flash; exifInfo.FocalLength.num = exifAttrs->focal_length.num; exifInfo.FocalLength.denom = exifAttrs->focal_length.den; exifInfo.FocalPlaneXResolution.num = exifAttrs->x_resolution.num; exifInfo.FocalPlaneXResolution.denom = exifAttrs->x_resolution.den; exifInfo.FocalPlaneYResolution.num = exifAttrs->y_resolution.num; exifInfo.FocalPlaneYResolution.denom = exifAttrs->y_resolution.den; exifInfo.SensingMethod = 2;//2 means 1 chip color area sensor exifInfo.FileSource = 3;//3 means the image source is digital still camera exifInfo.CustomRendered = exifAttrs->custom_rendered; exifInfo.ExposureMode = exifAttrs->exposure_mode; exifInfo.WhiteBalance = exifAttrs->white_balance; exifInfo.DigitalZoomRatio.num = exifAttrs->zoom_ratio.num; exifInfo.DigitalZoomRatio.denom = exifAttrs->zoom_ratio.den; exifInfo.SceneCaptureType = exifAttrs->scene_capture_type; exifInfo.makernote = NULL; exifInfo.makernotechars = 0; memcpy(exifInfo.subsectime, exifAttrs->subsec_time, 8); } void ImgHWEncoder::fillGpsInfo(RkGPSInfo &gpsInfo, exif_attribute_t* exifAttrs) { gpsInfo.GPSLatitudeRef[0] = exifAttrs->gps_latitude_ref[0]; gpsInfo.GPSLatitudeRef[1] = exifAttrs->gps_latitude_ref[1]; gpsInfo.GPSLatitude[0].num = exifAttrs->gps_latitude[0].num; gpsInfo.GPSLatitude[0].denom = exifAttrs->gps_latitude[0].den; gpsInfo.GPSLatitude[1].num = exifAttrs->gps_latitude[1].num; gpsInfo.GPSLatitude[1].denom = exifAttrs->gps_latitude[1].den; gpsInfo.GPSLatitude[2].num = exifAttrs->gps_latitude[2].num; gpsInfo.GPSLatitude[2].denom = exifAttrs->gps_latitude[2].den; gpsInfo.GPSLongitudeRef[0] = exifAttrs->gps_longitude_ref[0]; gpsInfo.GPSLongitudeRef[1] = exifAttrs->gps_longitude_ref[1]; gpsInfo.GPSLongitude[0].num = exifAttrs->gps_longitude[0].num; gpsInfo.GPSLongitude[0].denom = exifAttrs->gps_longitude[0].den; gpsInfo.GPSLongitude[1].num = exifAttrs->gps_longitude[1].num; gpsInfo.GPSLongitude[1].denom = exifAttrs->gps_longitude[1].den; gpsInfo.GPSLongitude[2].num = exifAttrs->gps_longitude[2].num; gpsInfo.GPSLongitude[2].denom = exifAttrs->gps_longitude[2].den; gpsInfo.GPSAltitudeRef = exifAttrs->gps_altitude_ref; gpsInfo.GPSAltitude.num = exifAttrs->gps_altitude.num; gpsInfo.GPSAltitude.denom = exifAttrs->gps_altitude.den; gpsInfo.GpsTimeStamp[0].num = exifAttrs->gps_timestamp[0].num; gpsInfo.GpsTimeStamp[0].denom = exifAttrs->gps_timestamp[0].den; gpsInfo.GpsTimeStamp[1].num = exifAttrs->gps_timestamp[1].num; gpsInfo.GpsTimeStamp[1].denom = exifAttrs->gps_timestamp[1].den; gpsInfo.GpsTimeStamp[2].num = exifAttrs->gps_timestamp[2].num; gpsInfo.GpsTimeStamp[2].denom = exifAttrs->gps_timestamp[2].den; memcpy(gpsInfo.GpsDateStamp, exifAttrs->gps_datestamp, 11);//"YYYY:MM:DD\0" gpsInfo.GPSProcessingMethod = (char *)exifAttrs->gps_processing_method; gpsInfo.GpsProcessingMethodchars = 100;//length of GpsProcessingMethod } bool ImgHWEncoder::checkInputBuffer(CameraBuffer* buf) { // just for YUV420 format buffer int Ysize = ALIGN(buf->width(), 16) * ALIGN(buf->height(), 16); int UVsize = ALIGN(buf->width(), 16) * ALIGN(buf->height() / 2, 16); if(buf->size() >= Ysize + UVsize) { return true; } else { LOGE("@%s : Input buffer (%dx%d) size(%d) can't meet the HwJpeg input condition", __FUNCTION__, buf->width(), buf->height(), buf->size()); return false; } } /** * encodeSync * */ status_t ImgHWEncoder::encodeSync(EncodePackage & package) { PERFORMANCE_ATRACE_CALL(); status_t status = NO_ERROR; JpegEncInInfo JpegInInfo; JpegEncOutInfo JpegOutInfo; std::shared_ptr<CameraBuffer> srcBuf = package.main; std::shared_ptr<CameraBuffer> destBuf = package.jpegOut; ExifMetaData *exifMeta = package.exifMeta; exif_attribute_t *exifAttrs = package.exifAttrs; int width = srcBuf->width(); int height = srcBuf->height(); int stride = srcBuf->stride(); void* srcY = srcBuf->data(); int jpegw = width; int jpegh = height; int outJPEGSize = destBuf->size(); int quality = exifMeta->mJpegSetting.jpegQuality; int thumbquality = exifMeta->mJpegSetting.jpegThumbnailQuality; LOGI("@%s %d: in buffer fd:%d, vir_addr:%p, out buffer fd:%d, vir_addr:%p", __FUNCTION__, __LINE__, srcBuf->dmaBufFd(), srcBuf->data(), destBuf->dmaBufFd(), destBuf->data()); // HwJpeg encode require buffer width and height align to 16 or large enough. if(!checkInputBuffer(srcBuf.get())) return UNKNOWN_ERROR; JpegInInfo.pool = mPool; JpegInInfo.frameHeader = 1; // TODO: we only support DEGREE_0 now JpegInInfo.rotateDegree = DEGREE_0; // After Android7.1, HW jpeg encoder just supports fd, and // no longer supports virtual address. JpegInInfo.y_rgb_addr = srcBuf->dmaBufFd(); // virtual address is just used for thumbnail JpegInInfo.y_vir_addr = (unsigned char*)srcBuf->data(); JpegInInfo.uv_vir_addr = ((unsigned char*)srcBuf->data() + jpegw*jpegh); JpegInInfo.inputW = jpegw; JpegInInfo.inputH = jpegh; if(srcBuf->v4l2Fmt() != V4L2_PIX_FMT_NV12) { LOGE("@%s %d: srcBuffer format(%s) is not NV12", __FUNCTION__, __LINE__, v4l2Fmt2Str(srcBuf->v4l2Fmt())); return UNKNOWN_ERROR; } JpegInInfo.type = JPEGENC_YUV420_SP;//HWJPEGENC_RGB888//HWJPEGENC_RGB565 JpegInInfo.qLvl = quality/10; if (JpegInInfo.qLvl < 5) JpegInInfo.qLvl = 5; if(JpegInInfo.qLvl > 10) JpegInInfo.qLvl = 9; //if not doThumb,please set doThumbNail,thumbW and thumbH to zero; if (exifMeta->mJpegSetting.thumbWidth && exifMeta->mJpegSetting.thumbHeight) JpegInInfo.doThumbNail = 1; else JpegInInfo.doThumbNail = 0; LOGD("@%s : exifAttrs->enableThumb = %d doThumbNail=%d", __FUNCTION__, exifAttrs->enableThumb, JpegInInfo.doThumbNail); JpegInInfo.thumbW = exifMeta->mJpegSetting.thumbWidth; JpegInInfo.thumbH = exifMeta->mJpegSetting.thumbHeight; //if thumbData is NULL, do scale, the type above can not be 420_P or 422_UYVY JpegInInfo.thumbData = NULL; JpegInInfo.thumbDataLen = 0; //don't care when thumbData is Null JpegInInfo.thumbqLvl = thumbquality /10; if (JpegInInfo.thumbqLvl < 5) JpegInInfo.thumbqLvl = 5; if(JpegInInfo.thumbqLvl > 10) JpegInInfo.thumbqLvl = 9; fillRkExifInfo(mExifInfo, exifAttrs); JpegInInfo.exifInfo = &mExifInfo; if (exifAttrs->enableGps) { fillGpsInfo(mGpsInfo, exifAttrs); JpegInInfo.gpsInfo = &mGpsInfo; } else { JpegInInfo.gpsInfo = NULL; } JpegOutInfo.outBufPhyAddr = destBuf->dmaBufFd(); JpegOutInfo.outBufVirAddr = (unsigned char*)destBuf->data(); JpegOutInfo.outBuflen = outJPEGSize; JpegOutInfo.jpegFileLen = 0; JpegOutInfo.cacheflush = NULL; LOGI("@%s %d: JpegInInfo thumbW:%d, thumbH:%d, thumbqLvl:%d, inputW:%d, inputH:%d, qLvl:%d", __FUNCTION__, __LINE__, JpegInInfo.thumbW, JpegInInfo.thumbH, JpegInInfo.thumbqLvl, JpegInInfo.inputW, JpegInInfo.inputH, JpegInInfo.qLvl); if(hw_jpeg_encode(&JpegInInfo, &JpegOutInfo) < 0 || JpegOutInfo.jpegFileLen <= 0){ LOGE("@%s %d: hw jpeg encode fail.", __FUNCTION__, __LINE__); return UNKNOWN_ERROR; } LOGI("@%s %d: actual jpeg offset: %d, size: %d, destBuf size: %d ", __FUNCTION__, __LINE__, JpegOutInfo.finalOffset, JpegOutInfo.jpegFileLen, destBuf->size()); // save jpeg size at the end of file, App will detect this header for the // jpeg actual size if (destBuf->size()) { char *pCur = (char*)(destBuf->data()) + destBuf->size() - sizeof(struct camera_jpeg_blob); struct camera_jpeg_blob *blob = new struct camera_jpeg_blob; blob->jpeg_blob_id = CAMERA_JPEG_BLOB_ID; blob->jpeg_size = JpegOutInfo.jpegFileLen; STDCOPY(pCur, (int8_t *)blob, sizeof(struct camera_jpeg_blob)); delete blob; } else { LOGE("ERROR: JPEG_MAX_SIZE is 0 !"); } return status; } } }
40.789655
163
0.704793
rockchip-toybrick
909ac26aac994415c2710c1450a8bdcf843db85d
1,539
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgAnimation/StackedMatrixElement.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgAnimation/StackedMatrixElement.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgAnimation/StackedMatrixElement.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/* -*-c++-*- * Copyright (C) 2009 Cedric Pinson <cedric.pinson@plopbyte.net> * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgAnimation/StackedMatrixElement> using namespace osgAnimation; StackedMatrixElement::StackedMatrixElement() {} StackedMatrixElement::StackedMatrixElement(const std::string& name, const osg::Matrix& matrix) : StackedTransformElement(), _matrix(matrix) { setName(name); } StackedMatrixElement::StackedMatrixElement(const osg::Matrix& matrix) : _matrix(matrix) { setName("matrix"); } StackedMatrixElement::StackedMatrixElement(const StackedMatrixElement& rhs, const osg::CopyOp& c) : StackedTransformElement(rhs, c), _matrix(rhs._matrix) { if (rhs._target.valid()) _target = new MatrixTarget(*rhs._target); } Target* StackedMatrixElement::getOrCreateTarget() { if (!_target.valid()) _target = new MatrixTarget(_matrix); return _target.get(); } void StackedMatrixElement::update() { if (_target.valid()) _matrix = _target->getValue(); }
37.536585
158
0.740091
UM-ARM-Lab
909bdb00928874bbdefcc83246d92c5f266ed5bb
5,414
cpp
C++
third_party/WebKit/Source/platform/LayoutLocale.cpp
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
third_party/WebKit/Source/platform/LayoutLocale.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
third_party/WebKit/Source/platform/LayoutLocale.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "platform/LayoutLocale.h" #include "platform/Language.h" #include "platform/fonts/AcceptLanguagesResolver.h" #include "platform/text/LocaleToScriptMapping.h" #include "wtf/HashMap.h" #include "wtf/text/AtomicStringHash.h" #include "wtf/text/StringHash.h" #include <hb.h> #include <unicode/locid.h> namespace blink { const LayoutLocale* LayoutLocale::s_default = nullptr; const LayoutLocale* LayoutLocale::s_system = nullptr; const LayoutLocale* LayoutLocale::s_defaultForHan = nullptr; bool LayoutLocale::s_defaultForHanComputed = false; static hb_language_t toHarfbuzLanguage(const AtomicString& locale) { CString localeAsLatin1 = locale.latin1(); return hb_language_from_string(localeAsLatin1.data(), localeAsLatin1.length()); } // SkFontMgr requires script-based locale names, like "zh-Hant" and "zh-Hans", // instead of "zh-CN" and "zh-TW". static const char* toSkFontMgrLocale(UScriptCode script) { switch (script) { case USCRIPT_KATAKANA_OR_HIRAGANA: return "ja-JP"; case USCRIPT_HANGUL: return "ko-KR"; case USCRIPT_SIMPLIFIED_HAN: return "zh-Hans"; case USCRIPT_TRADITIONAL_HAN: return "zh-Hant"; default: return nullptr; } } const char* LayoutLocale::localeForSkFontMgr() const { if (m_stringForSkFontMgr.isNull()) { m_stringForSkFontMgr = toSkFontMgrLocale(m_script); if (m_stringForSkFontMgr.isNull()) m_stringForSkFontMgr = m_string.ascii(); } return m_stringForSkFontMgr.data(); } void LayoutLocale::computeScriptForHan() const { if (isUnambiguousHanScript(m_script)) { m_scriptForHan = m_script; m_hasScriptForHan = true; return; } m_scriptForHan = scriptCodeForHanFromSubtags(m_string); if (m_scriptForHan == USCRIPT_COMMON) m_scriptForHan = USCRIPT_SIMPLIFIED_HAN; else m_hasScriptForHan = true; DCHECK(isUnambiguousHanScript(m_scriptForHan)); } UScriptCode LayoutLocale::scriptForHan() const { if (m_scriptForHan == USCRIPT_COMMON) computeScriptForHan(); return m_scriptForHan; } bool LayoutLocale::hasScriptForHan() const { if (m_scriptForHan == USCRIPT_COMMON) computeScriptForHan(); return m_hasScriptForHan; } const LayoutLocale* LayoutLocale::localeForHan( const LayoutLocale* contentLocale) { if (contentLocale && contentLocale->hasScriptForHan()) return contentLocale; if (!s_defaultForHanComputed) computeLocaleForHan(); return s_defaultForHan; } void LayoutLocale::computeLocaleForHan() { if (const LayoutLocale* locale = AcceptLanguagesResolver::localeForHan()) s_defaultForHan = locale; else if (getDefault().hasScriptForHan()) s_defaultForHan = &getDefault(); else if (getSystem().hasScriptForHan()) s_defaultForHan = &getSystem(); else s_defaultForHan = nullptr; s_defaultForHanComputed = true; } const char* LayoutLocale::localeForHanForSkFontMgr() const { const char* locale = toSkFontMgrLocale(scriptForHan()); DCHECK(locale); return locale; } LayoutLocale::LayoutLocale(const AtomicString& locale) : m_string(locale), m_harfbuzzLanguage(toHarfbuzLanguage(locale)), m_script(localeToScriptCodeForFontSelection(locale)), m_scriptForHan(USCRIPT_COMMON), m_hasScriptForHan(false), m_hyphenationComputed(false) {} using LayoutLocaleMap = HashMap<AtomicString, RefPtr<LayoutLocale>, CaseFoldingHash>; static LayoutLocaleMap& getLocaleMap() { DEFINE_STATIC_LOCAL(LayoutLocaleMap, localeMap, ()); return localeMap; } const LayoutLocale* LayoutLocale::get(const AtomicString& locale) { if (locale.isNull()) return nullptr; auto result = getLocaleMap().add(locale, nullptr); if (result.isNewEntry) result.storedValue->value = adoptRef(new LayoutLocale(locale)); return result.storedValue->value.get(); } const LayoutLocale& LayoutLocale::getDefault() { if (s_default) return *s_default; AtomicString locale = defaultLanguage(); s_default = get(!locale.isEmpty() ? locale : "en"); return *s_default; } const LayoutLocale& LayoutLocale::getSystem() { if (s_system) return *s_system; // Platforms such as Windows can give more information than the default // locale, such as "en-JP" for English speakers in Japan. String name = icu::Locale::getDefault().getName(); s_system = get(AtomicString(name.replace('_', '-'))); return *s_system; } PassRefPtr<LayoutLocale> LayoutLocale::createForTesting( const AtomicString& locale) { return adoptRef(new LayoutLocale(locale)); } void LayoutLocale::clearForTesting() { s_default = nullptr; s_system = nullptr; s_defaultForHan = nullptr; s_defaultForHanComputed = false; getLocaleMap().clear(); } Hyphenation* LayoutLocale::getHyphenation() const { if (m_hyphenationComputed) return m_hyphenation.get(); m_hyphenationComputed = true; m_hyphenation = Hyphenation::platformGetHyphenation(localeString()); return m_hyphenation.get(); } void LayoutLocale::setHyphenationForTesting( const AtomicString& localeString, PassRefPtr<Hyphenation> hyphenation) { const LayoutLocale& locale = valueOrDefault(get(localeString)); locale.m_hyphenationComputed = true; locale.m_hyphenation = hyphenation; } } // namespace blink
28.951872
78
0.740672
google-ar
909ce75922a92ddc79f97b2f910bbbf631708371
5,331
cpp
C++
llvm/tools/clang/test/Index/usrs.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
58
2016-08-27T03:19:14.000Z
2022-01-05T17:33:44.000Z
llvm/tools/clang/test/Index/usrs.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
14
2017-12-01T17:16:59.000Z
2020-12-21T12:16:35.000Z
llvm/tools/clang/test/Index/usrs.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
22
2016-11-27T09:53:31.000Z
2021-11-22T00:22:53.000Z
namespace foo { int x; void bar(int z); } namespace bar { typedef int QType; void bar(QType z); } class ClsA { public: int a, b; ClsA(int A, int B) : a(A), b(B) {} }; namespace foo { class ClsB : public ClsA { public: ClsB() : ClsA(1, 2) {} int result() const; }; } int foo::ClsB::result() const { return a + b; } namespace { class ClsC : public foo::ClsB {}; int w; } int z; namespace foo { namespace taz { int x; static inline int add(int a, int b) { return a + b; } void sub(int a, int b); } } namespace foo { namespace taz { class ClsD : public foo::ClsB { public: ClsD& operator=(int x) { a = x; return *this; } ClsD& operator=(double x) { a = (int) x; return *this; } ClsD& operator=(const ClsD &x) { a = x.a; return *this; } static int qux(); static int uz(int z, ...); bool operator==(const ClsD &x) const { return a == x.a; } }; }} extern "C" { void rez(int a, int b); } namespace foo_alias = foo; using namespace foo; namespace foo_alias2 = foo; using foo::ClsB; namespace foo_alias3 = foo; namespace { class RDar9371763_Foo { public: void bar(); }; } void RDar9371763_Foo::bar() {} void rdar9371763() { RDar9371763_Foo foo; foo.bar(); } // RUN: c-index-test -test-load-source-usrs all %s | FileCheck %s // CHECK: usrs.cpp c:@N@foo Extent=[1:1 - 4:2] // CHECK: usrs.cpp c:@N@foo@x Extent=[2:3 - 2:8] // CHECK: usrs.cpp c:@N@foo@F@bar#I# Extent=[3:3 - 3:18] // CHECK: usrs.cpp c:usrs.cpp@36@N@foo@F@bar#I#@z Extent=[3:12 - 3:17] // CHECK: usrs.cpp c:@N@bar Extent=[5:1 - 8:2] // CHECK: usrs.cpp c:usrs.cpp@N@bar@T@QType Extent=[6:3 - 6:20] // CHECK: usrs.cpp c:@N@bar@F@bar#I# Extent=[7:3 - 7:20] // CHECK: usrs.cpp c:usrs.cpp@94@N@bar@F@bar#I#@z Extent=[7:12 - 7:19] // CHECK: usrs.cpp c:@C@ClsA Extent=[10:1 - 14:2] // CHECK: usrs.cpp c: Extent=[11:1 - 11:8] // CHECK: usrs.cpp c:@C@ClsA@FI@a Extent=[12:3 - 12:8] // CHECK: usrs.cpp c:@C@ClsA@FI@b Extent=[12:3 - 12:11] // CHECK: usrs.cpp c:@C@ClsA@F@ClsA#I#I# Extent=[13:3 - 13:37] // CHECK: usrs.cpp c:usrs.cpp@147@C@ClsA@F@ClsA#I#I#@A Extent=[13:8 - 13:13] // CHECK: usrs.cpp c:usrs.cpp@154@C@ClsA@F@ClsA#I#I#@B Extent=[13:15 - 13:20] // CHECK: usrs.cpp c:@N@foo Extent=[16:1 - 22:2] // CHECK: usrs.cpp c:@N@foo@C@ClsB Extent=[17:3 - 21:4] // CHECK: usrs.cpp c: Extent=[18:3 - 18:10] // CHECK: usrs.cpp c:@N@foo@C@ClsB@F@ClsB# Extent=[19:5 - 19:27] // CHECK: usrs.cpp c:@N@foo@C@ClsB@F@result#1 Extent=[20:5 - 20:23] // CHECK: usrs.cpp c:@N@foo@C@ClsB@F@result#1 Extent=[24:1 - 26:2] // CHECK: usrs.cpp c:usrs.cpp@aN@C@ClsC Extent=[29:3 - 29:35] // CHECK: usrs.cpp c:usrs.cpp@aN@w Extent=[30:3 - 30:8] // CHECK: usrs.cpp c:@z Extent=[33:1 - 33:6] // CHECK: usrs.cpp c:@N@foo Extent=[35:1 - 40:2] // CHECK: usrs.cpp c:@N@foo@N@taz Extent=[35:17 - 39:2] // CHECK: usrs.cpp c:@N@foo@N@taz@x Extent=[36:3 - 36:8] // CHECK: usrs.cpp c:usrs.cpp@N@foo@N@taz@F@add#I#I# Extent=[37:3 - 37:56] // CHECK: usrs.cpp c:usrs.cpp@479@N@foo@N@taz@F@add#I#I#@a Extent=[37:25 - 37:30] // CHECK: usrs.cpp c:usrs.cpp@486@N@foo@N@taz@F@add#I#I#@b Extent=[37:32 - 37:37] // CHECK: usrs.cpp c:@N@foo@N@taz@F@sub#I#I# Extent=[38:3 - 38:25] // CHECK: usrs.cpp c:usrs.cpp@522@N@foo@N@taz@F@sub#I#I#@a Extent=[38:12 - 38:17] // CHECK: usrs.cpp c:usrs.cpp@529@N@foo@N@taz@F@sub#I#I#@b Extent=[38:19 - 38:24] // CHECK: usrs.cpp c:@N@foo Extent=[42:1 - 52:3] // CHECK: usrs.cpp c:@N@foo@N@taz Extent=[42:17 - 52:2] // CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD Extent=[43:3 - 51:4] // CHECK: usrs.cpp c: Extent=[44:3 - 44:10] // CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator=#I# Extent=[45:5 - 45:52] // CHECK: usrs.cpp c:usrs.cpp@638@N@foo@N@taz@C@ClsD@F@operator=#I#@x Extent=[45:21 - 45:26] // CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator=#d# Extent=[46:5 - 46:61] // CHECK: usrs.cpp c:usrs.cpp@690@N@foo@N@taz@C@ClsD@F@operator=#d#@x Extent=[46:21 - 46:29] // CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator=#&1$@N@foo@N@taz@C@ClsD# Extent=[47:5 - 47:62] // CHECK: usrs.cpp c:usrs.cpp@751@N@foo@N@taz@C@ClsD@F@operator=#&1$@N@foo@N@taz@C@ClsD#@x Extent=[47:21 - 47:34] // CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@qux#S Extent=[48:5 - 48:21] // CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@uz#I.#S Extent=[49:5 - 49:30] // CHECK: usrs.cpp c:usrs.cpp@833@N@foo@N@taz@C@ClsD@F@uz#I.#S@z Extent=[49:19 - 49:24] // CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator==#&1$@N@foo@N@taz@C@ClsD#1 Extent=[50:5 - 50:62] // CHECK: usrs.cpp c:usrs.cpp@866@N@foo@N@taz@C@ClsD@F@operator==#&1$@N@foo@N@taz@C@ClsD#1@x Extent=[50:21 - 50:34] // CHECK: usrs.cpp c:@F@rez Extent=[55:3 - 55:25] // CHECK: usrs.cpp c:usrs.cpp@941@F@rez@a Extent=[55:12 - 55:17] // CHECK: usrs.cpp c:usrs.cpp@948@F@rez@b Extent=[55:19 - 55:24] // CHECK: usrs.cpp c:@NA@foo_alias // CHECK-NOT: foo // CHECK: usrs.cpp c:@NA@foo_alias2 // CHECK-NOT: ClsB // CHECK: usrs.cpp c:@NA@foo_alias3 // CHECK: usrs.cpp c:@aN Extent=[68:1 - 73:2] // CHECK: usrs.cpp c:usrs.cpp@aN@C@RDar9371763_Foo Extent=[69:1 - 72:2] // CHECK: usrs.cpp c: Extent=[70:1 - 70:8] // CHECK: usrs.cpp c:usrs.cpp@aN@C@RDar9371763_Foo@F@bar# Extent=[71:3 - 71:13] // CHECK: usrs.cpp c:usrs.cpp@aN@C@RDar9371763_Foo@F@bar# Extent=[75:1 - 75:31] // CHECK: usrs.cpp c:@F@rdar9371763# Extent=[77:1 - 80:2] // CHECK: usrs.cpp c:usrs.cpp@1204@F@rdar9371763#@foo Extent=[78:3 - 78:22]
36.265306
115
0.619959
oslab-swrc
909e3d56baefe70e1e3c4fc6048bb0bcdcdd240a
393
cpp
C++
engine/runtime/ecs/constructs/scene.cpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
791
2016-11-04T14:13:41.000Z
2022-03-20T20:47:31.000Z
engine/runtime/ecs/constructs/scene.cpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
28
2016-12-01T05:59:30.000Z
2021-03-20T09:49:26.000Z
engine/runtime/ecs/constructs/scene.cpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
151
2016-12-21T09:44:43.000Z
2022-03-31T13:42:18.000Z
#include "scene.h" #include "utils.h" #include <core/system/subsystem.h> std::vector<runtime::entity> scene::instantiate(mode mod) { if(mod == mode::standard) { auto& ecs = core::get_subsystem<runtime::entity_component_system>(); ecs.dispose(); } std::vector<runtime::entity> out_vec; if(!data) return out_vec; ecs::utils::deserialize_data(*data, out_vec); return out_vec; }
17.863636
70
0.699746
ValtoForks
90a49f2a73d1ce757385c238c58fe933898cc5d2
8,061
cpp
C++
kernel/thor/generic/core.cpp
Apache-HB/managarm
df922a987167948369ea1d0e675925126bb5fdad
[ "MIT" ]
null
null
null
kernel/thor/generic/core.cpp
Apache-HB/managarm
df922a987167948369ea1d0e675925126bb5fdad
[ "MIT" ]
null
null
null
kernel/thor/generic/core.cpp
Apache-HB/managarm
df922a987167948369ea1d0e675925126bb5fdad
[ "MIT" ]
null
null
null
#include <thor-internal/core.hpp> #include <thor-internal/debug.hpp> #include <thor-internal/kasan.hpp> #include <thor-internal/physical.hpp> #include <thor-internal/ring-buffer.hpp> // This is required for virtual destructors. It should not be called though. void operator delete(void *, size_t) { thor::panicLogger() << "thor: operator delete() called" << frg::endlog; } namespace thor { size_t kernelVirtualUsage = 0; size_t kernelMemoryUsage = 0; namespace { constexpr bool logCleanup = false; } // -------------------------------------------------------- // Locking primitives // -------------------------------------------------------- void IrqSpinlock::lock() { irqMutex().lock(); _spinlock.lock(); } void IrqSpinlock::unlock() { _spinlock.unlock(); irqMutex().unlock(); } // -------------------------------------------------------- // Memory management // -------------------------------------------------------- KernelVirtualMemory::KernelVirtualMemory() { // The size is chosen arbitrarily here; 1 GiB of kernel heap is sufficient for now. uintptr_t vmBase = 0xFFFF'E000'0000'0000; size_t desiredSize = 0x4000'0000; // Setup a buddy allocator. auto tableOrder = BuddyAccessor::suitableOrder(desiredSize >> kPageShift); auto guessedRoots = desiredSize >> (kPageShift + tableOrder); auto overhead = BuddyAccessor::determineSize(guessedRoots, tableOrder); overhead = (overhead + (kPageSize - 1)) & ~(kPageSize - 1); size_t availableSize = desiredSize - overhead; auto availableRoots = availableSize >> (kPageShift + tableOrder); for(size_t pg = 0; pg < overhead; pg += kPageSize) { PhysicalAddr physical = physicalAllocator->allocate(0x1000); assert(physical != static_cast<PhysicalAddr>(-1) && "OOM"); KernelPageSpace::global().mapSingle4k(vmBase + availableSize + pg, physical, page_access::write, CachingMode::null); } auto tablePtr = reinterpret_cast<int8_t *>(vmBase + availableSize); unpoisonKasanShadow(tablePtr, overhead); BuddyAccessor::initialize(tablePtr, availableRoots, tableOrder); buddy_ = BuddyAccessor{vmBase, kPageShift, tablePtr, availableRoots, tableOrder}; } void *KernelVirtualMemory::allocate(size_t length) { auto irqLock = frg::guard(&irqMutex()); auto lock = frg::guard(&mutex_); // TODO: use a smarter implementation here. int order = 0; while(length > (size_t{1} << (kPageShift + order))) ++order; auto address = buddy_.allocate(order, 64); if(address == BuddyAccessor::illegalAddress) { infoLogger() << "thor: Failed to allocate 0x" << frg::hex_fmt(length) << " bytes of kernel virtual memory" << frg::endlog; infoLogger() << "thor:" " Physical usage: " << (physicalAllocator->numUsedPages() * 4) << " KiB," " kernel VM: " << (kernelVirtualUsage / 1024) << " KiB" " kernel RSS: " << (kernelMemoryUsage / 1024) << " KiB" << frg::endlog; panicLogger() << "\e[31m" "thor: Out of kernel virtual memory" "\e[39m" << frg::endlog; } kernelVirtualUsage += (size_t{1} << (kPageShift + order)); auto pointer = reinterpret_cast<void *>(address); unpoisonKasanShadow(pointer, size_t{1} << (kPageShift + order)); return pointer; } void KernelVirtualMemory::deallocate(void *pointer, size_t length) { auto irqLock = frg::guard(&irqMutex()); auto lock = frg::guard(&mutex_); // TODO: use a smarter implementation here. int order = 0; while(length > (size_t{1} << (kPageShift + order))) ++order; poisonKasanShadow(pointer, size_t{1} << (kPageShift + order)); buddy_.free(reinterpret_cast<uintptr_t>(pointer), order); assert(kernelVirtualUsage >= (size_t{1} << (kPageShift + order))); kernelVirtualUsage -= (size_t{1} << (kPageShift + order)); } frg::manual_box<KernelVirtualMemory> kernelVirtualMemory; KernelVirtualMemory &KernelVirtualMemory::global() { // TODO: This should be initialized at a well-defined stage in the // kernel's boot process. if(!kernelVirtualMemory) kernelVirtualMemory.initialize(); return *kernelVirtualMemory; } KernelVirtualAlloc::KernelVirtualAlloc() { } uintptr_t KernelVirtualAlloc::map(size_t length) { auto p = KernelVirtualMemory::global().allocate(length); // TODO: The slab_pool unpoisons memory before calling this. // It would be better not to unpoison in the kernel's VMM code. poisonKasanShadow(p, length); for(size_t offset = 0; offset < length; offset += kPageSize) { PhysicalAddr physical = physicalAllocator->allocate(kPageSize); assert(physical != static_cast<PhysicalAddr>(-1) && "OOM"); KernelPageSpace::global().mapSingle4k(VirtualAddr(p) + offset, physical, page_access::write, CachingMode::null); } kernelMemoryUsage += length; return uintptr_t(p); } void KernelVirtualAlloc::unmap(uintptr_t address, size_t length) { assert((address % kPageSize) == 0); assert((length % kPageSize) == 0); // TODO: The slab_pool poisons memory before calling this. // It would be better not to poison in the kernel's VMM code. unpoisonKasanShadow(reinterpret_cast<void *>(address), length); for(size_t offset = 0; offset < length; offset += kPageSize) { PhysicalAddr physical = KernelPageSpace::global().unmapSingle4k(address + offset); physicalAllocator->free(physical, kPageSize); } kernelMemoryUsage -= length; struct Closure : ShootNode { void complete() override { KernelVirtualMemory::global().deallocate(reinterpret_cast<void *>(address), size); auto physical = thisPage; Closure::~Closure(); asm volatile ("" : : : "memory"); physicalAllocator->free(physical, kPageSize); } PhysicalAddr thisPage; }; static_assert(sizeof(Closure) <= kPageSize); // We need some memory to store the closure that waits until shootdown completes. // For now, our stategy consists of allocating one page of *physical* memory // and accessing it through the global physical mapping. auto physical = physicalAllocator->allocate(kPageSize); PageAccessor accessor{physical}; auto p = new (accessor.get()) Closure; p->thisPage = physical; p->address = address; p->size = length; if(KernelPageSpace::global().submitShootdown(p)) p->complete(); } frg::manual_box<LogRingBuffer> allocLog; void KernelVirtualAlloc::unpoison(void *pointer, size_t size) { unpoisonKasanShadow(pointer, size); } void KernelVirtualAlloc::unpoison_expand(void *pointer, size_t size) { cleanKasanShadow(pointer, size); } void KernelVirtualAlloc::poison(void *pointer, size_t size) { poisonKasanShadow(pointer, size); } void KernelVirtualAlloc::output_trace(uint8_t val) { if (!allocLog) allocLog.initialize(0xFFFF'F000'0000'0000, 268435456); allocLog->enqueue(val); } frg::manual_box<PhysicalChunkAllocator> physicalAllocator; frg::manual_box<KernelVirtualAlloc> kernelVirtualAlloc; frg::manual_box< frg::slab_pool< KernelVirtualAlloc, IrqSpinlock > > kernelHeap; frg::manual_box<KernelAlloc> kernelAlloc; // -------------------------------------------------------- // CpuData // -------------------------------------------------------- IrqMutex &irqMutex() { return getCpuData()->irqMutex; } ExecutorContext::ExecutorContext() { } CpuData::CpuData() : scheduler{this}, activeFiber{nullptr}, heartbeat{0} { } // -------------------------------------------------------- // Threading related functions // -------------------------------------------------------- Universe::Universe() : _descriptorMap{frg::hash<Handle>{}, *kernelAlloc}, _nextHandle{1} { } Universe::~Universe() { if(logCleanup) infoLogger() << "\e[31mthor: Universe is deallocated\e[39m" << frg::endlog; } Handle Universe::attachDescriptor(Guard &guard, AnyDescriptor descriptor) { assert(guard.protects(&lock)); Handle handle = _nextHandle++; _descriptorMap.insert(handle, std::move(descriptor)); return handle; } AnyDescriptor *Universe::getDescriptor(Guard &guard, Handle handle) { assert(guard.protects(&lock)); return _descriptorMap.get(handle); } frg::optional<AnyDescriptor> Universe::detachDescriptor(Guard &guard, Handle handle) { assert(guard.protects(&lock)); return _descriptorMap.remove(handle); } } // namespace thor
30.885057
86
0.682546
Apache-HB
90a5bfac2a60f91735e7509413cb52df81968193
1,061
cpp
C++
src/engine/lua_bind/lua_env.cpp
LunarGameTeam/Lunar-GameEngine
b387d7008525681fe06db8811f4f7ee95aa7aaf1
[ "MIT" ]
4
2020-08-07T02:18:13.000Z
2021-07-08T09:46:11.000Z
src/engine/lua_bind/lua_env.cpp
LunarGameTeam/Lunar-GameEngine
b387d7008525681fe06db8811f4f7ee95aa7aaf1
[ "MIT" ]
null
null
null
src/engine/lua_bind/lua_env.cpp
LunarGameTeam/Lunar-GameEngine
b387d7008525681fe06db8811f4f7ee95aa7aaf1
[ "MIT" ]
null
null
null
#include "lua_env.h" #include "core/object/entity.h" #include "core/object/component.h" #include "world/scene.h" namespace luna { void luna::LuaEnv::Init() { // m_state = luaL_newstate(); // const luaL_Reg lualibs[] = { // { LUA_COLIBNAME, luaopen_base }, // { LUA_LOADLIBNAME, luaopen_package }, // { LUA_TABLIBNAME, luaopen_table }, // { LUA_IOLIBNAME, luaopen_io }, // { LUA_OSLIBNAME, luaopen_os }, // { LUA_STRLIBNAME, luaopen_string }, // { LUA_MATHLIBNAME, luaopen_math }, // { LUA_DBLIBNAME, luaopen_debug }, // { NULL, NULL } // }; // if (m_state != NULL) // { // const luaL_Reg* lib = lualibs; // for (; lib->func; lib++) { // lua_pushcfunction(m_state, lib->func); // lua_pushstring(m_state, lib->name); // lua_call(m_state, 1, 0); // } // } } void luna::LuaEnv::RunScript(const LString &str) { // // int err = luaL_loadbuffer(m_state, str.c_str(), str.Length(), "console"); // if (err == 0) // { // err = lua_pcall(m_state, 0, 0, 0); // } // if (err) // { // lua_pop(m_state, 1); // } } }
20.803922
77
0.598492
LunarGameTeam
90a98e4cd7a03185d19e2b699f3ce8272de4b9d7
3,761
hpp
C++
include/tiny/basic.hpp
yell0w4x/tiny-arduino-serial-port
af4318e1c210e80d31be3d4993c8124dd4e2c8c0
[ "MIT" ]
null
null
null
include/tiny/basic.hpp
yell0w4x/tiny-arduino-serial-port
af4318e1c210e80d31be3d4993c8124dd4e2c8c0
[ "MIT" ]
null
null
null
include/tiny/basic.hpp
yell0w4x/tiny-arduino-serial-port
af4318e1c210e80d31be3d4993c8124dd4e2c8c0
[ "MIT" ]
null
null
null
// Arduino async serial port library with nine data bits support. // // 2015, (c) Gk Ltd. // MIT License #ifndef TINY_BASIC_HPP_ #define TINY_BASIC_HPP_ #include <tiny/detail/auto_sense.hpp> #include <iterator> #include <bitset> #include <stdint.h> namespace tiny { #ifdef bit # undef bit #endif // bit #ifdef TINY_ARDUINO_MEGA //# include <avr/io.h> typedef uint8_t reg_type; #elif defined(TINY_ARDUINO_DUE) //# include <chip.h> typedef uint32_t reg_type; #endif // TINY_ARDUINO_MEGA /** Control and status register type. */ typedef volatile reg_type register_type; /** Pointer to control and status register type. */ typedef register_type* /*const*/ register_ptr; /** The size of the register in bits. */ enum { register_width = sizeof(register_type) * 8 }; /** The type representing register bits. */ typedef std::bitset<register_width> register_bits_type; /** Returns the mask for the given bit no. */ template <typename ResultT> inline ResultT mask(size_t pos) { return static_cast<ResultT>(1 << pos); } /** Returns the mask for the given bit no. */ inline register_type mask(size_t pos) { return mask<register_type>(pos); } #ifdef TINY_ARDUINO_MEGA /** Reads the register bit. * * @param r Register address. * @param pos Position of the bit where 0 is lsb. * @return r & (1 << bit_pos) */ inline size_t bit(register_ptr r, size_t pos) { return *r & (1 << pos); } /** Reads the register bit. * * @param r Register address. * @param pos Position of the bit where 0 is lsb. * @return r & (1 << bit_pos) */ inline size_t bit(register_type r, size_t pos) { return r & (1 << pos); } /** Tests whether bit is set or clear. * * @param r Register address. * @param pos Position of the bit where 0 is lsb. * @return True if set, false if clear. */ template <typename T> inline bool is_bit(T r, size_t pos) { return bit(r, pos) != 0; } /** Sets the register bit. */ inline void set_bit(register_ptr r, size_t pos) { *r |= mask(pos); } /** Sets the register bit. */ inline void set_bit(register_type& r, size_t pos) { r |= mask(pos); } /** Clears the register bit. */ inline void clear_bit(register_ptr r, size_t pos) { *r &= ~mask(pos); } /** Clears the register bit. */ inline void clear_bit(register_type& r, size_t pos) { r &= ~mask(pos); } /** Sets the register bit. */ template <typename T> inline void set_bit(T& r, size_t pos, bool value) { if (value) { set_bit(r, pos); } else { clear_bit(r, pos); } } /** Returns the value of bits specified. */ inline size_t bits_value(register_ptr r, const register_bits_type& mask) { register_type msk = static_cast<register_type>(mask.to_ulong()); size_t v = *r & msk; for (; msk && (msk & 1) == 0; msk >>= 1) { v >>= 1; } return v; } /** Returns the value of bits specified. */ inline size_t bits_value(register_type r, const register_bits_type& mask) { register_type msk = static_cast<register_type>(mask.to_ulong()); size_t v = r & msk; for (; msk && (msk & 1) == 0; msk >>= 1) { v >>= 1; } return v; } #elif defined(TINY_ARDUINO_DUE) /** Reads the register bit. * * @param r Register address. * @param pos Position of the bit where 0 is lsb. * @return r & (1 << bit_pos) */ inline size_t bit(register_type r, register_type mask) { return r & mask; } /** Tests whether bit is set or clear. * * @param r Register address. * @param pos Position of the bit where 0 is lsb. * @return True if set, false if clear. */ template <typename T> inline bool is_bit(T r, register_type mask) { return bit(r, mask) != 0; } /** Sets the register bit. */ inline void set_bit(register_type& r, register_type mask) { r |= mask; } #endif // TINY_ARDUINO_MEGA } // namespace tiny #endif // TINY_BASIC_HPP_
21.369318
74
0.670035
yell0w4x
90ab42f31a104a3e7ed5de92918fefab26330e23
214
cpp
C++
VertexBuffer.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
5
2020-03-06T10:01:28.000Z
2020-05-06T07:57:20.000Z
VertexBuffer.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
1
2020-03-06T02:51:50.000Z
2020-03-06T04:33:30.000Z
VertexBuffer.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
29
2020-03-05T15:15:24.000Z
2021-07-21T07:05:00.000Z
#include "VertexBuffer.hpp" VertexBuffer::VertexBuffer(const void *data, const unsigned int size) { glGenBuffers(1, &m_RendererID); Bind(); glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW); }
23.777778
69
0.733645
rabinadk1
90ab57fa83b576215082827427467f947a158eb3
675
cc
C++
modules/ugdk-core/src/time/manager.cc
uspgamedev/ugdk
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
[ "Zlib" ]
11
2015-03-06T13:14:32.000Z
2020-06-09T23:34:28.000Z
modules/ugdk-core/src/time/manager.cc
uspgamedev/ugdk
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
[ "Zlib" ]
62
2015-01-04T05:47:40.000Z
2018-06-15T17:00:25.000Z
modules/ugdk-core/src/time/manager.cc
uspgamedev/ugdk
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
[ "Zlib" ]
2
2017-04-05T20:35:49.000Z
2017-07-30T03:44:02.000Z
#include <ugdk/time/manager.h> #include "SDL_timer.h" namespace ugdk { namespace time { Manager::Manager() { last_update_ = current_time_ = initial_time_ = SDL_GetTicks(); } void Manager::Update() { last_update_ = current_time_; current_time_ = SDL_GetTicks(); } uint32 Manager::TimeElapsed() const { return current_time_ - initial_time_; } uint32 Manager::TimeElapsedInFrame() const{ return SDL_GetTicks() - current_time_; } uint32 Manager::TimeDifference() const { return current_time_ - last_update_; } uint32 Manager::TimeSince(uint32 t0) const { return current_time_ - t0 - initial_time_; } } // namespace time } // namespace ugdk
19.285714
66
0.715556
uspgamedev
90ace0723ffa28c84e0a5d311d3736cf148f0fa0
9,047
cpp
C++
deps/pooling.cpp
baajur/Mocha.jl
5e15b882d7dd615b0c5159bb6fde2cc040b2d8ee
[ "MIT" ]
1,397
2015-01-04T02:35:49.000Z
2022-03-15T19:26:14.000Z
deps/pooling.cpp
baajur/Mocha.jl
5e15b882d7dd615b0c5159bb6fde2cc040b2d8ee
[ "MIT" ]
197
2015-01-09T20:15:23.000Z
2021-05-06T17:46:39.000Z
deps/pooling.cpp
baajur/Mocha.jl
5e15b882d7dd615b0c5159bb6fde2cc040b2d8ee
[ "MIT" ]
357
2015-01-05T00:40:20.000Z
2022-03-23T15:01:20.000Z
#include <algorithm> #include <limits> #include <cstring> #include <cstdio> template <typename T> void max_pooling_fwd(const T* global_input, T *global_output, size_t *global_mask, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { int input_offset = width*height; int output_offset = pooled_width*pooled_height; #pragma omp parallel for for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { int offset = (n * channels + c); const T *input = global_input + input_offset * offset; T *output = global_output + output_offset * offset; size_t *mask = global_mask + output_offset * offset; for (int ph = 0; ph < pooled_height; ++ph) { for (int pw = 0; pw < pooled_width; ++pw) { int hstart = ph*stride_h - pad_h; int wstart = pw*stride_w - pad_w; int hend = std::min(hstart + kernel_h, height); int wend = std::min(wstart + kernel_w, width); hstart = std::max(hstart, 0); wstart = std::max(wstart, 0); int pool_index = ph * pooled_width + pw; T maxval = -std::numeric_limits<T>::max(); size_t maxidx = 0; for (int h = hstart; h < hend; ++h) { for (int w = wstart; w < wend; ++w) { int index = h * width + w; if (input[index] > maxval) { maxval = input[index]; maxidx = index; } } } output[pool_index] = maxval; mask[pool_index] = maxidx; } } } } } template <typename T> void max_pooling_bwd(T* global_input, const T *global_output, const size_t *global_mask, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { int input_offset = width*height; int output_offset = pooled_width*pooled_height; memset(global_input, 0, input_offset*channels*num*sizeof(T)); #pragma omp parallel for for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { int offset = (n * channels + c); T *input = global_input + input_offset * offset; const T *output = global_output + output_offset * offset; const size_t *mask = global_mask + output_offset * offset; for (int ph = 0; ph < pooled_height; ++ph) { for (int pw = 0; pw < pooled_width; ++pw) { int pool_index = ph * pooled_width + pw; input[mask[pool_index]] += output[pool_index]; } } } } } template <typename T> void mean_pooling_fwd(const T* global_input, T *global_output, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { int input_offset = width*height; int output_offset = pooled_width*pooled_height; int kernel_size = kernel_w * kernel_h; #pragma omp parallel for for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { int offset = (n * channels + c); const T *input = global_input + input_offset * offset; T *output = global_output + output_offset * offset; for (int ph = 0; ph < pooled_height; ++ph) { for (int pw = 0; pw < pooled_width; ++pw) { int hstart = ph*stride_h - pad_h; int wstart = pw*stride_w - pad_w; int hend = std::min(hstart + kernel_h, height); int wend = std::min(wstart + kernel_w, width); hstart = std::max(hstart, 0); wstart = std::max(wstart, 0); int pool_index = ph * pooled_width + pw; T meanval = 0; for (int h = hstart; h < hend; ++h) { for (int w = wstart; w < wend; ++w) { meanval += input[h * width + w]; } } output[pool_index] = meanval / kernel_size; } } } } } template <typename T> void mean_pooling_bwd(T* global_input, const T *global_output, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { int input_offset = width*height; int output_offset = pooled_width*pooled_height; int kernel_size = kernel_w * kernel_h; memset(global_input, 0, input_offset*channels*num*sizeof(T)); #pragma omp parallel for for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { int offset = (n * channels + c); T *input = global_input + input_offset * offset; const T *output = global_output + output_offset * offset; for (int ph = 0; ph < pooled_height; ++ph) { for (int pw = 0; pw < pooled_width; ++pw) { int hstart = ph*stride_h - pad_h; int wstart = pw*stride_w - pad_w; int hend = std::min(hstart + kernel_h, height); int wend = std::min(wstart + kernel_w, width); hstart = std::max(hstart, 0); wstart = std::max(wstart, 0); int pool_index = ph * pooled_width + pw; for (int h = hstart; h < hend; ++h) { for (int w = wstart; w < wend; ++w) { input[h * width + w] += output[pool_index] / kernel_size; } } } } } } } extern "C" { void max_pooling_fwd_float(const float* global_input, float *global_output, size_t *global_mask, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { max_pooling_fwd(global_input, global_output, global_mask, width, height, channels, num, pooled_width, pooled_height, kernel_w, kernel_h, pad_w, pad_h, stride_w, stride_h); } void max_pooling_fwd_double(const double* global_input, double *global_output, size_t *global_mask, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { max_pooling_fwd(global_input, global_output, global_mask, width, height, channels, num, pooled_width, pooled_height, kernel_w, kernel_h, pad_w, pad_h, stride_w, stride_h); } void max_pooling_bwd_float(float* global_input, const float *global_output, const size_t *global_mask, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { max_pooling_bwd(global_input, global_output, global_mask, width, height, channels, num, pooled_width, pooled_height, kernel_w, kernel_h, pad_w, pad_h, stride_w, stride_h); } void max_pooling_bwd_double(double* global_input, const double *global_output, const size_t *global_mask, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { max_pooling_bwd(global_input, global_output, global_mask, width, height, channels, num, pooled_width, pooled_height, kernel_w, kernel_h, pad_w, pad_h, stride_w, stride_h); } void mean_pooling_fwd_float(const float* global_input, float *global_output, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { mean_pooling_fwd(global_input, global_output, width, height, channels, num, pooled_width, pooled_height, kernel_w, kernel_h, pad_w, pad_h, stride_w, stride_h); } void mean_pooling_fwd_double(const double* global_input, double *global_output, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { mean_pooling_fwd(global_input, global_output, width, height, channels, num, pooled_width, pooled_height, kernel_w, kernel_h, pad_w, pad_h, stride_w, stride_h); } void mean_pooling_bwd_float(float* global_input, const float *global_output, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { mean_pooling_bwd(global_input, global_output, width, height, channels, num, pooled_width, pooled_height, kernel_w, kernel_h, pad_w, pad_h, stride_w, stride_h); } void mean_pooling_bwd_double(double* global_input, const double *global_output, int width, int height, int channels, int num, int pooled_width, int pooled_height, int kernel_w, int kernel_h, int pad_w, int pad_h, int stride_w, int stride_h) { mean_pooling_bwd(global_input, global_output, width, height, channels, num, pooled_width, pooled_height, kernel_w, kernel_h, pad_w, pad_h, stride_w, stride_h); } } // extern "C"
38.99569
105
0.647065
baajur
90aead07e280f730ea042b4a74cb137141dbcc46
5,421
hpp
C++
include/codegen/include/HMUI/ColorGradientSlider.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/HMUI/ColorGradientSlider.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/HMUI/ColorGradientSlider.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:21 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: HMUI.TextSlider #include "HMUI/TextSlider.hpp" // Including type: ColorChangeUIEventType #include "GlobalNamespace/ColorChangeUIEventType.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: HMUI namespace HMUI { // Forward declaring type: GradientImage class GradientImage; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`3<T1, T2, T3> template<typename T1, typename T2, typename T3> class Action_3; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: StringBuilder class StringBuilder; } // Forward declaring namespace: UnityEngine::EventSystems namespace UnityEngine::EventSystems { // Forward declaring type: PointerEventData class PointerEventData; } // Completed forward declares // Type namespace: HMUI namespace HMUI { // Autogenerated type: HMUI.ColorGradientSlider class ColorGradientSlider : public HMUI::TextSlider, public UnityEngine::EventSystems::IPointerUpHandler, public UnityEngine::EventSystems::IEventSystemHandler { public: // private System.String _textPrefix // Offset: 0x138 ::Il2CppString* textPrefix; // private UnityEngine.Color _color0 // Offset: 0x140 UnityEngine::Color color0; // private UnityEngine.Color _color1 // Offset: 0x150 UnityEngine::Color color1; // private HMUI.GradientImage[] _gradientImages // Offset: 0x160 ::Array<HMUI::GradientImage*>* gradientImages; // private UnityEngine.Color _darkColor // Offset: 0x168 UnityEngine::Color darkColor; // private UnityEngine.Color _lightColor // Offset: 0x178 UnityEngine::Color lightColor; // private System.Action`3<HMUI.ColorGradientSlider,UnityEngine.Color,ColorChangeUIEventType> colorDidChangeEvent // Offset: 0x188 System::Action_3<HMUI::ColorGradientSlider*, UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* colorDidChangeEvent; // private System.Text.StringBuilder _stringBuilder // Offset: 0x190 System::Text::StringBuilder* stringBuilder; // public System.Void add_colorDidChangeEvent(System.Action`3<HMUI.ColorGradientSlider,UnityEngine.Color,ColorChangeUIEventType> value) // Offset: 0xEC1524 void add_colorDidChangeEvent(System::Action_3<HMUI::ColorGradientSlider*, UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* value); // public System.Void remove_colorDidChangeEvent(System.Action`3<HMUI.ColorGradientSlider,UnityEngine.Color,ColorChangeUIEventType> value) // Offset: 0xEC15CC void remove_colorDidChangeEvent(System::Action_3<HMUI::ColorGradientSlider*, UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* value); // public System.Void SetColors(UnityEngine.Color color0, UnityEngine.Color color1) // Offset: 0xEC179C void SetColors(UnityEngine::Color color0, UnityEngine::Color color1); // private System.Void HandleNormalizedValueDidChange(HMUI.TextSlider slider, System.Single normalizedValue) // Offset: 0xEC1B18 void HandleNormalizedValueDidChange(HMUI::TextSlider* slider, float normalizedValue); // protected override System.Void Awake() // Offset: 0xEC1674 // Implemented from: UnityEngine.UI.Selectable // Base method: System.Void Selectable::Awake() void Awake(); // protected override System.Void OnDestroy() // Offset: 0xEC1710 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnDestroy() void OnDestroy(); // protected override System.Void UpdateVisuals() // Offset: 0xEC17CC // Implemented from: HMUI.TextSlider // Base method: System.Void TextSlider::UpdateVisuals() void UpdateVisuals(); // protected override System.String TextForNormalizedValue(System.Single normalizedValue) // Offset: 0xEC1A48 // Implemented from: HMUI.TextSlider // Base method: System.String TextSlider::TextForNormalizedValue(System.Single normalizedValue) ::Il2CppString* TextForNormalizedValue(float normalizedValue); // public override System.Void OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0xEC1BCC // Implemented from: UnityEngine.UI.Selectable // Base method: System.Void Selectable::OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData) void OnPointerUp(UnityEngine::EventSystems::PointerEventData* eventData); // public System.Void .ctor() // Offset: 0xEC1CEC // Implemented from: HMUI.TextSlider // Base method: System.Void TextSlider::.ctor() // Base method: System.Void Selectable::.ctor() // Base method: System.Void UIBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static ColorGradientSlider* New_ctor(); }; // HMUI.ColorGradientSlider } DEFINE_IL2CPP_ARG_TYPE(HMUI::ColorGradientSlider*, "HMUI", "ColorGradientSlider"); #pragma pack(pop)
45.554622
163
0.740638
Futuremappermydud
90af742b1238da924714fea6e215a543d2a078e1
454
cpp
C++
keccak/src/keccak/keccak_buffer.cpp
verified-network/Patricia-Merkle-Trie
fa1d375629dd97270efa2ec3b66136dda9fa2568
[ "MIT" ]
1
2021-01-20T07:50:24.000Z
2021-01-20T07:50:24.000Z
keccak/src/keccak/keccak_buffer.cpp
bulldex/verified-storage
cb8e687bc2026a4dd8502a15e54fc60b1759cb5b
[ "MIT" ]
8
2020-06-03T12:53:42.000Z
2020-08-28T15:57:25.000Z
keccak/src/keccak/keccak_buffer.cpp
bulldex/verified-storage
cb8e687bc2026a4dd8502a15e54fc60b1759cb5b
[ "MIT" ]
2
2021-07-10T18:41:29.000Z
2022-03-20T04:08:13.000Z
#include "keccak_buffer.hpp" #include <utils/hex.hpp> KeccakBuffer::KeccakBuffer() { keccak_ = Keccak(Keccak::Bits::Keccak256); } KeccakBuffer::KeccakBuffer(const Keccak::Bits bits) { keccak_ = Keccak(bits); } buffer_t KeccakBuffer::operator()(const buffer_t& input) { std::string byte_str_ = verified::utils::BytesToString(input); auto byte_hash_ = keccak_(byte_str_); return verified::utils::StringToBytes(byte_hash_); }
21.619048
66
0.713656
verified-network
90b0960d974ad6a84c89a3d7ea0498d656a6482c
566
cpp
C++
lowercase.cpp
AyushVerma-code/databinarytextfiles
f404bfb07d1854e9e4f8f6edbb32268d39aed908
[ "MIT" ]
1
2021-02-12T08:24:17.000Z
2021-02-12T08:24:17.000Z
lowercase.cpp
AyushVerma-code/databinarytextfiles
f404bfb07d1854e9e4f8f6edbb32268d39aed908
[ "MIT" ]
null
null
null
lowercase.cpp
AyushVerma-code/databinarytextfiles
f404bfb07d1854e9e4f8f6edbb32268d39aed908
[ "MIT" ]
null
null
null
#include<iostream.h> #include<conio.h> #include<fstream.h> #include<ctype.h> void alphacount() { fstream f; f.open("notes3.txt",ios::in|ios::out); char ch; int count=0; char ans='y'; while(ans=='y') { cout<<"\nEnter a character "; cin>>ch; f<<ch; cout<<"\nDo you want to continue "; cin>>ans; } f.seekg(0); while(!f.eof()) { f.get(ch); if(islower(ch)) { count++; } } cout<<"\nLowercase alphabets are "<<count; f.close(); } void main() { clrscr(); alphacount(); getch(); }
11.32
47
0.526502
AyushVerma-code
90b0d97bc0cdfd4edc927326e751bd0351824eb7
2,945
inl
C++
CraftEngine/src/Bezier2D.inl
jstine35/rpgcraft
0a2c1b0e9c6e5abb6fa1e5f001f1dfc49da4f5e0
[ "MIT" ]
9
2017-04-05T01:42:36.000Z
2021-11-14T20:37:58.000Z
CraftEngine/src/Bezier2D.inl
guibec/rpgcraft
a4fd84effaf334b1ed637d32b8853b0e6beadf1e
[ "MIT" ]
82
2017-04-05T00:26:54.000Z
2019-09-21T22:43:09.000Z
CraftEngine/src/Bezier2D.inl
jstine35/rpgcraft
0a2c1b0e9c6e5abb6fa1e5f001f1dfc49da4f5e0
[ "MIT" ]
3
2019-01-08T17:11:17.000Z
2021-08-11T23:59:23.000Z
#pragma once #include "Bezier2D.h" // -------------------------------------------------------------------------------------- // SubDiv_BezierFan () // -------------------------------------------------------------------------------------- // Thoughts: // - Steps per side should be a function of the length of a side. // - Visible length is also a function of the distance from the camera, in case there's some zoom or 3D effect happening. // - The length can vary according to the control points: // // chord = (p3-p0).Length; // cont_net = (p0 - p1).Length + (p2 - p1).Length + (p3 - p2).Length; // app_arc_length = (cont_net + chord) / 2; // // To calculate perpendicular angle along a curve, use standard tangent method: // ATAN2(DY, DX) +/- Math.Pi/2 // ATAN2((pn+1).y - (pn-1).y, (pn+1).x - (pn-1).x) +/- Math.Pi/2 // // Or calculate using Derivative (but tangent'ing is probably much faster): // 3 * (t^2) * (d + 3*(b - c) - a) + 6t*(a - 2*b + c) + 3*(b - a) // // To convert angle into a line: // x = start_x + len * cos(angle); // startx == pn.x // y = start_y + len * sin(angle); // starty == pn.y // // Long-tail TODO: Try implementing this as a geometry shader? // Pro: Can determine correct # of verticies based on length within actual scene orientation. // Con: Geometry shaders are still generally slower than just rough-guessing lengths based on // distance from player. // template<typename VertexType> void SubDiv_BezierFan(VertexBufferState<VertexType>& dest, int numSubdivs, const vFloat2& center, const vFloat2(&xy)[4]) { const auto& x1 = xy[0].x; const auto& x2 = xy[1].x; const auto& x3 = xy[2].x; const auto& x4 = xy[3].x; const auto& y1 = xy[0].y; const auto& y2 = xy[1].y; const auto& y3 = xy[2].y; const auto& y4 = xy[3].y; float stepIncr = 1.0f / numSubdivs; for (int idx = 0; idx < numSubdivs; ++idx) { float i = idx * stepIncr; float x = CalculateBezierPoint(i, x1, x2, x3, x4); float y = CalculateBezierPoint(i, y1, y2, y3, y4); dest.vertices[dest.m_vidx].Pos = vFloat3(x, y, 0.5f); dest.m_vidx += 1; } } // StripTool_FromLine // StripTool_FromPatch // // Converts a series of 2D xy coordinates into a triangle strip with a given 2D thickness. // FromLine assumes endpoints are independent. // (numXY-1)*2 triangles will be generated. // // FromPatch assumes endpoints are closed. // (numXY )*2 triangles will be generated. template<typename VertexType> void StripTool_FromLine(VertexBufferState<VertexType>& dest, const vFloat2 *xy, int numXY) { // ATAN2((pn+1).y - (pn-1).y, (pn+1).x - (pn-1).x) +/- Math.Pi/2 } template<typename VertexType> void StripTool_FromPatch(VertexBufferState<VertexType>& dest, const vFloat2 *xy, int numXY) { // ATAN2((pn+1).y - (pn-1).y, (pn+1).x - (pn-1).x) +/- Math.Pi/2 }
34.244186
122
0.585059
jstine35
90b32d3646f414cd94bd41b90a51ca6072a5bc3a
3,594
cpp
C++
src/BoundaryConditions/FixedCellBoundaryCondition.cpp
clairemiller/2018_MaintainingStemCellNiche
2999a37169ac0db78ebf9ac57b36153a0a149eb3
[ "BSD-4-Clause-UC" ]
null
null
null
src/BoundaryConditions/FixedCellBoundaryCondition.cpp
clairemiller/2018_MaintainingStemCellNiche
2999a37169ac0db78ebf9ac57b36153a0a149eb3
[ "BSD-4-Clause-UC" ]
null
null
null
src/BoundaryConditions/FixedCellBoundaryCondition.cpp
clairemiller/2018_MaintainingStemCellNiche
2999a37169ac0db78ebf9ac57b36153a0a149eb3
[ "BSD-4-Clause-UC" ]
null
null
null
/* Copyright (c) 2005-2016, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "FixedCellBoundaryCondition.hpp" #include "Debug.hpp" template<unsigned DIM> FixedCellBoundaryCondition<DIM>::FixedCellBoundaryCondition(AbstractCellPopulation<DIM>* pCellPopulation) : AbstractCellPopulationBoundaryCondition<DIM>(pCellPopulation) { } template<unsigned DIM> void FixedCellBoundaryCondition<DIM>::ImposeBoundaryCondition(const std::map<Node<DIM>*, c_vector<double, DIM> >& rOldLocations) { // Iterate over all nodes associated with real cells to update their positions for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = this->mpCellPopulation->Begin(); cell_iter != this->mpCellPopulation->End(); ++cell_iter) { if ( (*cell_iter)->GetCellProliferativeType()->template IsType<StemCellProliferativeType>() ) { // Get the node unsigned node_index = this->mpCellPopulation->GetLocationIndexUsingCell(*cell_iter); Node<DIM>* p_node = this->mpCellPopulation->GetNode(node_index); // Get old node location c_vector<double, DIM> old_node_location = rOldLocations.find(p_node)->second; // Return node to old location p_node->rGetModifiableLocation() = old_node_location; } } } template<unsigned DIM> void FixedCellBoundaryCondition<DIM>::OutputCellPopulationBoundaryConditionParameters(out_stream& rParamsFile) { // Call method on direct parent class AbstractCellPopulationBoundaryCondition<DIM>::OutputCellPopulationBoundaryConditionParameters(rParamsFile); } // Explicit instantiation template class FixedCellBoundaryCondition<1>; template class FixedCellBoundaryCondition<2>; template class FixedCellBoundaryCondition<3>; // Serialization for Boost >= 1.36 #include "SerializationExportWrapperForCpp.hpp" EXPORT_TEMPLATE_CLASS_SAME_DIMS(FixedCellBoundaryCondition)
43.829268
128
0.772955
clairemiller
ff968874b35bad61e310e991a29fce0b8b16d91f
524
cpp
C++
modules/asyn/testErrorsApp/src/myTimeStampSource.cpp
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
20
2015-01-07T09:02:42.000Z
2021-07-27T14:35:19.000Z
modules/asyn/testErrorsApp/src/myTimeStampSource.cpp
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
400
2015-01-06T14:44:30.000Z
2022-02-07T17:45:32.000Z
modules/asyn/testErrorsApp/src/myTimeStampSource.cpp
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
72
2015-01-23T23:23:02.000Z
2022-02-07T15:14:35.000Z
#include <epicsTime.h> #include <registryFunction.h> #include <epicsExport.h> // This function demonstrates using a user-define time stamp source // It simply returns the current time but with the nsec field set to 0, so that record timestamps // can be checked to see that the user-defined function is indeed being called. static void myTimeStampSource(void *userPvt, epicsTimeStamp *pTimeStamp) { epicsTimeGetCurrent(pTimeStamp); pTimeStamp->nsec = 0; } extern "C" { epicsRegisterFunction(myTimeStampSource); }
29.111111
97
0.770992
A2-Collaboration
ff9b1c0934cc08187bc8bd8b0e814679b27b59bc
4,247
cpp
C++
kernel/src/sound/sound-blaster16/sb16.cpp
pradosh-arduino/pradoshOS
b7c2a8b238261fc61460e609fd8352aa62b5f32e
[ "MIT" ]
9
2021-11-17T10:27:18.000Z
2022-03-16T09:43:24.000Z
kernel/src/sound/sound-blaster16/sb16.cpp
pradosh-arduino/pradoshOS
b7c2a8b238261fc61460e609fd8352aa62b5f32e
[ "MIT" ]
1
2022-03-17T08:31:05.000Z
2022-03-28T02:50:59.000Z
kernel/src/sound/sound-blaster16/sb16.cpp
pradosh-arduino/pradoshOS
b7c2a8b238261fc61460e609fd8352aa62b5f32e
[ "MIT" ]
1
2021-12-21T09:49:02.000Z
2021-12-21T09:49:02.000Z
#include "sb16.h" const uint32_t PCI_Enable_Bit = 0x80000000; const uint32_t PCI_Config_Address = 0xCF8; const uint32_t PCI_Config_Data = 0xCFC; unsigned char pci_bus_sb16 = 0; unsigned char pci_device_sb16 = 0; unsigned char pci_device_fn_sb16 = 0; SoundBlaster16* SB16; uint32_t sb16_ioaddr; DSP* dspPort; DSP_Write* dspPortw; MixerPort* Mixer; SoundBlaster16::SoundBlaster16(DSP* dspPort, DSP_Write* dspPortw){ ResetDSP(dspPort); TurnSpeakerOn(dspPortw); DMAChannel1(); Program(dspPort); SetIRQ(dspPort); GlobalRenderer->Print("Sound Blaster 16 - sound card Initialized!"); GlobalRenderer->Next(); } SoundBlaster16::~SoundBlaster16(){ GlobalRenderer->Print("Sound Blaster 16 - Exited"); } uint16_t getDeviceAddr; void SoundBlaster16::PCI(){ for (uint8_t bus = 0; bus != 0xff; bus++) { // per bus there can be at most 32 devices for (int device = 0; device < 32; device++) { // every device can be multi function device of up to 8 functions for (int func = 0; func < 8; func++) { // read the first dword (index 0) from the PCI configuration space // dword 0 contains the vendor and device values from the PCI configuration space int data = r_pci_32(pci_bus_sb16, pci_bus_sb16, func, 0); if (data != 0xffffffff) { // parse the values uint16_t device_value = (data >> 16); uint16_t vendor = data & 0xFFFF; pci_bus_sb16 = bus; pci_device_sb16 = device; pci_device_fn_sb16 = func; } } } } for(getDeviceAddr = getDeviceAddr; getDeviceAddr < 0xFFFF; getDeviceAddr++){ sb16_ioaddr = r_pci_32(pci_bus_sb16, getDeviceAddr, pci_device_fn_sb16, 4); GlobalRenderer->Print(" Device ID 0x"); GlobalRenderer->Print(to_hstring((uint16_t)getDeviceAddr)); GlobalRenderer->Next(); exit(); //if(r_pci_32(pci_bus_sb16, pci_device_sb16, pci_device_fn_sb16, 4) <= 0){ // //}else{ // //GlobalRenderer->Print("Found SB16! BUS: 0x"); // //GlobalRenderer->Print(to_hstring((uint16_t)pci_bus_sb16)); // //GlobalRenderer->Print(" Device: 0x"); // //GlobalRenderer->Print(to_hstring((uint16_t)pci_device_sb16)); // ////GlobalRenderer->Print(" Function: 0x"); // ////GlobalRenderer->Print(to_hstring((uint16_t)func)); // //GlobalRenderer->Print(" Device ID 0x"); // //GlobalRenderer->Print(to_hstring((uint16_t)getDeviceAddr)); // //GlobalRenderer->Next(); // exit(); //} } } void exit(){ for(int i=0;i<100;i++){ } GlobalRenderer->Clear(); GlobalRenderer->CursorPosition = {0, 0}; } void SoundBlaster16::ResetDSP(DSP* dspPort){ outb(dspPort->DSPReset, 0x01); outb(dspPort->DSPReset, 0x00); dspPort->DSPReadPort = 0xAA; } void SoundBlaster16::SetIRQ(DSP* dspPort){ outb(dspPort->DSPMixerPort, 0x80); uint16_t GetIRQ = inb(dspPort->DSPMixerPort); outb(dspPort->DSPMixerDataPort, GetIRQ); } void SoundBlaster16::TurnSpeakerOn(DSP_Write* dspPortw){ outb(dspPortw->SpeakerAddr, dspPortw->SpeakerOn); } void SoundBlaster16::TurnSpeakerOff(DSP_Write* dspPortw){ outb(dspPortw->SpeakerAddr, dspPortw->SpeakerOff); } void SoundBlaster16::DMAChannel1(){ outb(0x0A, 5); // disable channel 1 outb(0x0C, 1); // filp flop outb(0x0B, 0x49); // transfer mode outb(0x83, 0x01); // Page Transfer outb(0x02, 0x04); // Position Low Bit outb(0x02, 0x0F); // Position High Bit outb(0x03, 0xFF); // Count Low Bit outb(0x03, 0x0F); // Count High Bit outb(0x0A, 1); // enable channel 1 } void SoundBlaster16::Program(DSP* dspPort){ outb(dspPort->DSPWrite, 0x40); outb(dspPort->DSPWrite, 165); outb(dspPort->DSPWrite, 0xC0); outb(dspPort->DSPWrite, 0x00); outb(dspPort->DSPWrite, 0xFE); outb(dspPort->DSPWrite, 0x0F); } void SoundBlaster16::SetVolume(MixerPort* mixer, uint8_t volume){ outb(mixer->MasterVolume, volume); } uint32_t SoundBlaster16::r_pci_32(uint8_t bus, uint8_t device, uint8_t func, uint8_t pcireg) { uint32_t index = PCI_Enable_Bit | (bus << 16) | (device << 11) | (func << 8) | (pcireg << 2); outl(index, PCI_Config_Address); return inl(PCI_Config_Data); }
30.120567
95
0.662821
pradosh-arduino
ff9c0267390a4ec675aba10b3cb535abe4407a51
3,859
cpp
C++
src/3rdparty/khtml/src/imload/imagepainter.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
src/3rdparty/khtml/src/imload/imagepainter.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
src/3rdparty/khtml/src/imload/imagepainter.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
/* Progressive image displaying library. Copyright (C) 2004,2005 Maks Orlovich (maksim@kde.org) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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 "imagepainter.h" #include "image.h" #include "pixmapplane.h" #include "imagemanager.h" namespace khtmlImLoad { ImagePainter::ImagePainter(Image *_image): image(_image), sizeRefd(false) { //No need to ref, default size. size = image->size(); } ImagePainter::ImagePainter(Image *_image, QSize _size): image(_image), size(_size), sizeRefd(false) { if (!ImageManager::isAcceptableScaleSize(_size.width(), _size.height())) { setDefaultSize(); } } ImagePainter::~ImagePainter() { if (sizeRefd) { image->derefSize(size); } } ImagePainter::ImagePainter(const ImagePainter &src) { image = src.image; size = src.size; sizeRefd = false; } ImagePainter &ImagePainter::operator=(const ImagePainter &src) { if (sizeRefd) { image->derefSize(size); } image = src.image; size = src.size; sizeRefd = false; return *this; } void ImagePainter::setSize(QSize _size) { if (!ImageManager::isAcceptableScaleSize(_size.width(), _size.height())) { setDefaultSize(); return; } // Don't do anything if size didn't change, // to avoid dropping the image.. if (size == _size) { return; } if (sizeRefd) { image->derefSize(size); } size = _size; sizeRefd = false; } void ImagePainter::setDefaultSize() { if (sizeRefd) { image->derefSize(size); } size = image->size(); sizeRefd = false; } void ImagePainter::paint(int dx, int dy, QPainter *p, int sx, int sy, int width, int height) { if (!image->mayPaint()) // ### fallback painting in case bg? { return; } // Do our lazy ref if needed. Safe due to above if (!sizeRefd && size != image->size()) { image->refSize(size); sizeRefd = true; } PixmapPlane *plane = image->getSize(size); if (plane->animProvider) { // Clip the request ourselves when animating.. if (width == -1) { width = size.width(); } if (height == -1) { height = size.height(); } QRect clippedRect = QRect(0, 0, size.width(), size.height()) & QRect(sx, sy, width, height); //AFA plane->animProvider->paint(dx, dy, p, clippedRect.x(), clippedRect.y(), //AFA clippedRect.width(), clippedRect.height()); //AFA-modify plane->animProvider->paint(dx, dy, width, height, p, sx, sy, size.width(), size.height()); return; } // non-animated, go straight to PixmapPlane; it clips itself plane->paint(dx, dy, p, sx, sy, width, height); } }
26.798611
99
0.628919
afarcat
ff9c16a85d3df00ea4a530f703ce464ba1714c7c
1,854
cpp
C++
Iron/strategy/locutus.cpp
biug/titan
aacb4e2dc4d55601abd45cb8321d8e5160851eec
[ "MIT" ]
null
null
null
Iron/strategy/locutus.cpp
biug/titan
aacb4e2dc4d55601abd45cb8321d8e5160851eec
[ "MIT" ]
null
null
null
Iron/strategy/locutus.cpp
biug/titan
aacb4e2dc4d55601abd45cb8321d8e5160851eec
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////// // // This file is part of Iron's source files. // Iron is free software, licensed under the MIT/X11 License. // A copy of the license is provided with the library in the LICENSE file. // Copyright (c) 2016, 2017, Igor Dimitrijevic // ////////////////////////////////////////////////////////////////////////// #include "locutus.h" #include "strategy.h" #include "zerglingRush.h" #include "expand.h" #include "../units/army.h" #include "../units/his.h" #include "../Iron.h" namespace { auto & bw = Broodwar; } namespace iron { ////////////////////////////////////////////////////////////////////////////////////////////// // // // class Locutus // // ////////////////////////////////////////////////////////////////////////////////////////////// Locutus::Locutus() { std::string enemyName = him().Player()->getName(); if (enemyName == "Locutus" || enemyName == "locutus") { me().SetOpening("SKT"); m_detected = true; } } Locutus::~Locutus() { ai()->GetStrategy()->SetMinScoutingSCVs(1); } string Locutus::StateDescription() const { if (!m_detected) return "-"; if (m_detected) return "detected"; return "-"; } void Locutus::OnFrame_v() { if (him().LostUnits(Protoss_Shuttle) == 1 && him().Units(Protoss_Dark_Templar).size() == 0) { m_detected = false; Discard(); return; } if (him().LostUnits(Protoss_Dark_Templar) >= 4) { m_detected = false; Discard(); return; } if (bw->getFrameCount() > 13000) { m_detected = false; Discard(); return; } } } // namespace iron
21.310345
95
0.434736
biug
ff9c196469416f6b335467100b9fa172436555b0
868
cpp
C++
CO1028/LAB2/Ex4/main.cpp
Smithienious/hcmut-192
4f1dfa322321fc18d151835213a5b544c9d764f2
[ "MIT" ]
null
null
null
CO1028/LAB2/Ex4/main.cpp
Smithienious/hcmut-192
4f1dfa322321fc18d151835213a5b544c9d764f2
[ "MIT" ]
null
null
null
CO1028/LAB2/Ex4/main.cpp
Smithienious/hcmut-192
4f1dfa322321fc18d151835213a5b544c9d764f2
[ "MIT" ]
1
2020-04-26T10:28:41.000Z
2020-04-26T10:28:41.000Z
#include <iostream> #include <fstream> using namespace std; // matrix is two dimensional array. You should transposition matrix void transposition(int rows, int cols, int **matrix) { for (int i = 0; i < cols; i++) { cout << matrix[0][i]; for (int j = 1; j < rows; j++) { cout << " " << matrix[j][i]; } cout << endl; } } int main(int argc, char** argv) { ifstream ifs; ifs.open("test02.txt"); int rows; int cols; ifs >> rows; ifs >> cols; int** matrix = new int*[rows]; try { int i = 0; int j = 0; for (int i = 0; i < rows; i++) { matrix[i] = new int[cols]; for (int j = 0; j < cols; j++) { ifs >> matrix[i][j]; } } transposition(rows, cols, matrix); } catch (char const* s) { printf("An exception occurred. Exception type: %s\n", s); } ifs.close(); return 0; }
18.083333
68
0.534562
Smithienious
ff9c25f5d9589f897515e19182e5a5c422c9ebef
58,463
cpp
C++
source/Geometry/HermiteFieldToMesh.cpp
nsf/nextgame
a2d2f21341489792bafa2519f33287a0b89927ee
[ "MIT" ]
9
2015-03-10T10:20:14.000Z
2020-12-29T15:49:14.000Z
source/Geometry/HermiteFieldToMesh.cpp
nsf/nextgame
a2d2f21341489792bafa2519f33287a0b89927ee
[ "MIT" ]
null
null
null
source/Geometry/HermiteFieldToMesh.cpp
nsf/nextgame
a2d2f21341489792bafa2519f33287a0b89927ee
[ "MIT" ]
2
2019-12-23T17:36:37.000Z
2021-06-18T13:21:46.000Z
#include "Geometry/HermiteField.h" #include "Geometry/DebugDraw.h" #include "Core/Defer.h" #include "OS/ThreadLocal.h" // Two other axes of a given one. static const Vec2i OTHER_AXES_TABLE[] = { {1, 2}, {0, 2}, {0, 1}, }; static const Vec4i VINDEX_EDGES_TABLE_E[] = { Vec4i(3, 2, 1, 0), Vec4i(7, 6, 5, 4), Vec4i(11, 10, 9, 8), }; static const Vec4i VINDEX_EDGES_TABLE_F[3][3] = { {Vec4i(-1), Vec4i(2,3,1,0), Vec4i(1,3,2,0)}, {Vec4i(6,7,5,4), Vec4i(-1), Vec4i(5,7,6,4)}, {Vec4i(10,11,9,8), Vec4i(9,11,10,8), Vec4i(-1)}, }; // Bit array of non-manifold cases: 1 - non-manifold, 0 - manifold /* const uint8_t NON_MANIFOLD_CASES[32] = { 64, 2, 84, 87, 114, 51, 80, 115, 78, 15, 68, 79, 255, 255, 64, 127, 254, 2, 255, 255, 242, 34, 240, 114, 206, 10, 204, 78, 234, 42, 64, 2 }; */ // excludes 3a and 6a cases /* const uint8_t NON_MANIFOLD_CASES[32] = { 64, 2, 84, 87, 114, 51, 80, 19, 78, 15, 68, 7, 127, 63, 0, 67, 254, 2, 255, 87, 114, 2, 80, 32, 78, 2, 68, 8, 130, 2, 0, 0 }; static inline bool IsNonManifoldConfig(uint8_t c) { const uint8_t n = c / 8; const uint8_t b = 1 << (c % 8); return (NON_MANIFOLD_CASES[n] & b) != 0; } */ const uint32_t VCONFIGS[256] = { 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 33817601, 16777216, 16777216, 33620225, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 33624080, 16777216, 33624080, 16777216, 52498968, 16777216, 37749764, 37749764, 33624080, 16777216, 33624080, 16777216, 39059713, 16777216, 16777216, 33832976, 16777216, 16777216, 33832976, 33832976, 34603268, 16777216, 33832976, 55084068, 16777216, 16777216, 33832976, 38863873, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 34603268, 16777216, 33641473, 16777216, 37749764, 33837313, 16777216, 16777216, 33902592, 16777216, 16777216, 16777216, 16777216, 33620225, 33817601, 34607168, 16777216, 16777216, 33817601, 16777216, 37749764, 52502913, 34607168, 38076676, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 33817601, 16777216, 16777216, 16777216, 33620308, 16777216, 37749764, 34603345, 38010885, 16777216, 16777216, 16777216, 16777216, 16777216, 34607168, 51515970, 34607168, 33637648, 33832976, 33624133, 33571857, 16777216, 59000856, 81304684, 37765141, 37830932, 37754176, 37819457, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 34947136, 34881857, 16777216, 16777216, 16777216, 16777216, 37765184, 16777216, 16777216, 37765184, 37765184, 37765184, 34603268, 37765184, 55068738, 34931716, 16777216, 33620225, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 37765184, 37765184, 59016321, 33821968, 51519780, 34607125, 80337106, 34870292, 33624080, 33571908, 33833029, 16777216, 34620736, 16777216, 34881857, 16777216, 16777216, 33620225, 16777216, 16777216, 34603268, 38010960, 37749841, 16777216, 16777216, 33817684, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 38080576, 16777216, 37819457, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 33817601, 16777216, 16777216, 16777216, 33620225, 33817601, 38817792, 16777216, 16777216, 37769476, 16777216, 16777216, 34624516, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 38879248, 16777216, 16777216, 16777216, 37830932, 16777216, 16777216, 16777216, 16777216, 33832976, 16777216, 16777216, 16777216, 16777216, 16777216, 39063568, 16777216, 16777216, 16777216, 16777216, 16777216, 37749764, 16777216, 34870292, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216, 16777216 }; static inline int vconfig_n_vertices(uint32_t vconfig) { return vconfig >> 24; } static inline int vconfig_vertex_index(uint32_t vconfig, int edge) { return (vconfig >> (edge * 2)) & 3; } constexpr uint32_t VF_VIRTUAL = 1 << 31; constexpr uint32_t INDEX_MASK = ~VF_VIRTUAL; static inline bool is_virtual(uint32_t idx) { return (idx & VF_VIRTUAL) != 0; } static inline uint32_t index(uint32_t idx) { return idx & INDEX_MASK; } // For each field a set of closest neighbours is defined along each axis // on negative direction. const Vec3i NEIGHBOUR_FIELDS[8] = { Vec3i(-1, -1, -1), Vec3i( 0, -1, -1), Vec3i(-1, 0, -1), Vec3i( 2, 1, -1), Vec3i(-1, -1, 0), Vec3i( 4, -1, 1), Vec3i(-1, 4, 2), Vec3i( 6, 5, 3), }; // A table of edges for each chunk, it points to EDGES_TABLE below. Each chunk // has 3 edges on the corresponding axes. We also store offsets here, it's from // EDGES_TABLE. const struct { Vec3i edges; Vec3i offsets[3]; } CHUNK_EDGES[8] = { {{1, 3, 5}, {{0,1,1}, {1,0,1}, {1,1,0}}}, {{0, 3, 5}, {{0,1,1}, {0,0,1}, {0,1,0}}}, {{1, 2, 5}, {{0,0,1}, {1,0,1}, {1,0,0}}}, {{0, 2, 5}, {{0,0,1}, {0,0,1}, {0,0,0}}}, {{1, 3, 4}, {{0,1,0}, {1,0,0}, {1,1,0}}}, {{0, 3, 4}, {{0,1,0}, {0,0,0}, {0,1,0}}}, {{1, 2, 4}, {{0,0,0}, {1,0,0}, {1,0,0}}}, {{0, 2, 4}, {{0,0,0}, {0,0,0}, {0,0,0}}}, }; // Lists all 6 edges of 8-field group. The chunk specified all 4 chunks which // share the same edge. Axis is the axis on which the edge lies. And offsets is // where you can find that edge in a given chunk, same convention as above. // 0 is 0 and 1 is size-1. const struct { Vec4i chunks; int axis; Vec3i offsets[4]; } EDGES_TABLE[6] = { {{1,3,5,7}, 0, {{0,1,1}, {0,0,1}, {0,1,0}, {0,0,0}}}, // +x (0) {{0,2,4,6}, 0, {{0,1,1}, {0,0,1}, {0,1,0}, {0,0,0}}}, // -x (1) {{2,3,6,7}, 1, {{1,0,1}, {0,0,1}, {1,0,0}, {0,0,0}}}, // +y (2) {{0,1,4,5}, 1, {{1,0,1}, {0,0,1}, {1,0,0}, {0,0,0}}}, // -y (3) {{4,5,6,7}, 2, {{1,1,0}, {0,1,0}, {1,0,0}, {0,0,0}}}, // +z (4) {{0,1,2,3}, 2, {{1,1,0}, {0,1,0}, {1,0,0}, {0,0,0}}}, // -z (5) }; // A table of faces for each chunk, it points to FACES_TABLE below. Each chunk // has 3 faces on the corresponding axes. We also store offsets here, it's from // FACES_TABLE. Offset is an position on a corresponding axis as usual 0 for 0 // and 1 for size-1. Can be a cube size or voxel size, depending on what you // want. const struct { Vec3i faces; Vec3i offsets; } CHUNK_FACES[8] = { {{0,1,8 }, {1,1,1}}, {{0,2,9 }, {0,1,1}}, {{3,1,10}, {1,0,1}}, {{3,2,11}, {0,0,1}}, {{4,5,8 }, {1,1,0}}, {{4,6,9 }, {0,1,0}}, {{7,5,10}, {1,0,0}}, {{7,6,11}, {0,0,0}}, }; // Lists all 12 faces of 8-field group. const struct { Vec2i chunks; Vec2i axes; Vec3i offsets[2]; } FACES_TABLE[12] = { {{0,1}, {1,2}, {{1,0,0}, {0,0,0}}}, // 0 {{0,2}, {0,2}, {{0,1,0}, {0,0,0}}}, // 1 {{1,3}, {0,2}, {{0,1,0}, {0,0,0}}}, // 2 {{2,3}, {1,2}, {{1,0,0}, {0,0,0}}}, // 3 {{4,5}, {1,2}, {{1,0,0}, {0,0,0}}}, // 4 {{4,6}, {0,2}, {{0,1,0}, {0,0,0}}}, // 5 {{5,7}, {0,2}, {{0,1,0}, {0,0,0}}}, // 6 {{6,7}, {1,2}, {{1,0,0}, {0,0,0}}}, // 7 {{0,4}, {0,1}, {{0,0,1}, {0,0,0}}}, // 8 {{1,5}, {0,1}, {{0,0,1}, {0,0,0}}}, // 9 {{2,6}, {0,1}, {{0,0,1}, {0,0,0}}}, // 10 {{3,7}, {0,1}, {{0,0,1}, {0,0,0}}}, // 11 }; struct FieldAccessHelper { Slice<const int> lods; int local_largest_lod; int local_smallest_lod; int largest_lod; Vec3i m_csize; // local largest lod's size of a field in cubes int m_offset; // local largest lod's offset // Each edge has an authoritative representation, which is a given edge // with the lowest LOD amongst 4 overlapping edges. Offset is in voxels in // work area notation. struct { int chunk; int axis; Vec3i offset; int lod; } auth_edges[6]; // Each face has an authoritative representation, which is a given face // with the lowest LOD amongst 2 overlapping faces. Offset is in voxels in // work area notation. struct { int chunk; Vec2i axes; Vec3i offset; int lod; } auth_faces[12]; // Defines positions of the cubes (in a work area notation) touching the // edges. Basically a copy of CHUNK_EDGES table with proper position values. struct { Vec3i position[3]; } edge_positions[8]; // Same for faces. Except here we define just a position along a // corresponding axis of a face. struct { Vec3i position; } face_positions[8]; // Each chunk contains a certain set of faces which are duplicated when // building neighbour chunks. So, we avoid creating them along one of the // directions. Vec3i dup_faces[8]; FieldAccessHelper(Slice<const int> lods, int largest_lod) { this->lods = lods; this->largest_lod = largest_lod; local_largest_lod = -1; local_smallest_lod = 999; for (int lod : lods) { if (lod > local_largest_lod) local_largest_lod = lod; if (lod >= 0 && lod < local_smallest_lod) local_smallest_lod = lod; } m_csize = CHUNK_SIZE / Vec3i(lod_factor(local_largest_lod)); m_offset = offset_for_lod(local_largest_lod, largest_lod); // setup auth edges for (int i = 0; i < 6; i++) { int smallest_lod = 999; int idx = -1; for (int j = 0; j < 4; j++) { const int lod = lods[EDGES_TABLE[i].chunks[j]]; if (lod != -1 && lod < smallest_lod) { smallest_lod = lod; idx = j; } } if (idx == -1) { auth_edges[i].lod = -1; continue; } const int c = EDGES_TABLE[i].chunks[idx]; const Vec3i dcsize = vsize(c) - Vec3i(1); auth_edges[i].axis = EDGES_TABLE[i].axis; auth_edges[i].chunk = c; auth_edges[i].offset = EDGES_TABLE[i].offsets[idx] * dcsize; auth_edges[i].lod = lods[auth_edges[i].chunk]; } // setup auth faces for (int i = 0; i < 12; i++) { int smallest_lod = 999; int idx = -1; for (int j = 0; j < 2; j++) { const int lod = lods[FACES_TABLE[i].chunks[j]]; if (lod != -1 && lod < smallest_lod) { smallest_lod = lod; idx = j; } } if (idx == -1) { auth_faces[i].lod = -1; continue; } const int c = FACES_TABLE[i].chunks[idx]; const Vec3i dcsize = vsize(c) - Vec3i(1); auth_faces[i].axes = FACES_TABLE[i].axes; auth_faces[i].chunk = c; auth_faces[i].offset = FACES_TABLE[i].offsets[idx] * dcsize; auth_faces[i].lod = lods[auth_faces[i].chunk]; } // edge and face positions, dup faces for (int i = 0; i < 8; i++) { const Vec3i dcsize = vsize(i) - Vec3i(1); for (int j = 0; j < 3; j++) { edge_positions[i].position[j] = CHUNK_EDGES[i].offsets[j] * dcsize; } face_positions[i].position = CHUNK_FACES[i].offsets * dcsize; const Vec3i csize = non_virtual_csize(i); const Vec3i vadd = (dcsize - csize + Vec3i(1)) * rel22(i^7); dup_faces[i] = Vec3i(-1) + vadd; } } // LOD factor for two LODs in 8-field set inline int lodf(int lod) const { return lod < local_largest_lod ? 2 : 1; } // size of a field in cubes for a given lod inline Vec3i csize(int lod) const { return m_csize * Vec3i(lodf(lod)); } // The following sizes are based on the largest lod, therefore for smaller // lods they are larger than the actual need, I do that for simplicity. // Irrelevant stuff is simply ignored later when generating the actual // vertices. // positive size in cubes inline Vec3i pcsize(int lod) const { return (m_csize - Vec3i(m_offset)) * Vec3i(lodf(lod)); } // positive size in cubes (+ dependencies) inline Vec3i pdcsize(int lod) const { return (m_csize - Vec3i(m_offset - 1)) * Vec3i(lodf(lod)); } // negative size in cubes inline Vec3i ncsize(int lod) const { return Vec3i(m_offset + 1) * Vec3i(lodf(lod)); } // negative size in cubes (+ dependencies) inline Vec3i ndcsize(int lod) const { return Vec3i(m_offset + 2) * Vec3i(lodf(lod)); } // voxel size of a work area of a given chunk, according to largest lod Vec3i vsize(int chunk) const { const int lod = lods[chunk]; const Vec3i pdvsize = pdcsize(lod) + Vec3i(1); const Vec3i ndvsize = ndcsize(lod) + Vec3i(1); const Vec3i rel = rel22(chunk); const Vec3i irel = rel^Vec3i(1); return ndvsize * irel + pdvsize * rel; } // voxel offset to a work area of a given chunk, according to largest lod Vec3i voffset(int chunk) const { const int lod = lods[chunk]; const Vec3i vsize = csize(lod) + Vec3i(1); const Vec3i ndvsize = ndcsize(lod) + Vec3i(1); return (vsize - ndvsize) * rel22(chunk^7); } // real size of a chunk in cubes (excluding virtual cubes) Vec3i non_virtual_csize(int chunk) const { const int lod = lods[chunk]; const Vec3i csize = CHUNK_SIZE / Vec3i(lod_factor(lod)); const int offset = offset_for_lod(lod, largest_lod); const Vec3i pcsize = csize - Vec3i(offset); const Vec3i ncsize = Vec3i(offset + 1); const Vec3i rel = rel22(chunk); const Vec3i irel = rel22(chunk^7); return ncsize * irel + pcsize * rel; } }; struct CubeContext { Vec3i accumulator[4] = {Vec3i(0), Vec3i(0), Vec3i(0), Vec3i(0)}; int accumulated_n[4] = {0, 0, 0, 0}; uint8_t materials[20]; int materials_n = 0; inline void add_vector(const Vec3i &v, int i = 0) { accumulator[i] += v; accumulated_n[i]++; } inline Vec3 average_vector(int i = 0) const { const Vec3 v = ToVec3(accumulator[i] / Vec3i(accumulated_n[i])) / Vec3(HermiteData_FullEdgeF()); return v; } inline void add_material(uint8_t m) { materials[materials_n++] = m; } inline uint8_t average_material() { uint8_t m = 0; int n = 0; while (materials_n > 0) { uint8_t cur_m = materials[--materials_n]; int cur_n = 1; int i = 0; while (i < materials_n) { if (materials[i] != cur_m) { i++; continue; } cur_n++; std::swap(materials[i], materials[--materials_n]); } if (cur_m != 0 && cur_n > n) { n = cur_n; m = cur_m; } } return m; } }; struct IndexVConfigPair { uint32_t m_index; uint32_t m_vconfig; // basically adds vertex index preserving the virtual flag uint32_t index(int edge) const { const int vindex = vconfig_vertex_index(m_vconfig, edge); const uint32_t vflag = m_index & VF_VIRTUAL; return (::index(m_index) + vindex) | vflag; } }; struct TemporaryData { Vector<IndexVConfigPair> idxbuf; Vector<Vec3> normals; Vector<Vec3> vertices; HermiteField fs[8]; Vector<IndexVConfigPair> idxbufs[8]; }; static ThreadLocal<TemporaryData> temporary_data; static void hermite_rle_fields_to_mesh_same_lod(Vector<V3N3M1_terrain> &vertices, Vector<uint32_t> &indices, Slice<const HermiteRLEField*> fields, int lod, int largest_lod, const Vec3 &base) { // Size of the chunk in cubes, according to the given LOD const Vec3i csize = CHUNK_SIZE / Vec3i(lod_factor(lod)); // Size of the chunk in voxels, according to the given LOD const Vec3i vsize = csize + Vec3i(1); // Offset to align chunks of all the lods at the same position and to // include the dependencies for smooth normals calculation. For largest lod // it's 1, for largest-1 it's 2, then 4, and so on. const int offset = offset_for_lod(lod, largest_lod); // Positive size in cubes (size of the 7th chunk), according to offset. const Vec3i pcsize = csize - Vec3i(offset); // Same as above, but also including dependencies. const Vec3i pdcsize = pcsize + Vec3i(1); // Negative size in cubes (size of the 0 chunk), according to offset. // +1 because we also include the glue layer const Vec3i ncsize = Vec3i(offset + 1); // Same as above, but also including dependencies. const Vec3i ndcsize = ncsize + Vec3i(1); // Offset for negative chunks in voxels to the beginning of the data. const Vec3i voffset = vsize - (ndcsize + Vec3i(1)); // Total size of the work area in cubes. const Vec3i dcsize = pdcsize + ndcsize; // Size of the cube according to given LOD. const Vec3 cube_size_lod = CUBE_SIZE * Vec3(lod_factor(lod)); // Non-virtual cube boundaries, relative to work area of course const Vec3i nonv_min(1, 1, 1); const Vec3i nonv_max = dcsize - Vec3i(2); // On chunk boundaries we need to know if the neighbour is available, if // true, then it's ok to generate a stitching face. struct { bool x; bool y; bool z; } neighbours[8]; for (int i = 0; i < 8; i++) { neighbours[i].x = NEIGHBOUR_FIELDS[i].x != -1 && fields[NEIGHBOUR_FIELDS[i].x] != nullptr; neighbours[i].y = NEIGHBOUR_FIELDS[i].y != -1 && fields[NEIGHBOUR_FIELDS[i].y] != nullptr; neighbours[i].z = NEIGHBOUR_FIELDS[i].z != -1 && fields[NEIGHBOUR_FIELDS[i].z] != nullptr; } const int base_vertex = vertices.length(); TemporaryData *tmp = temporary_data.get(); Vector<IndexVConfigPair> &idxbuf = tmp->idxbuf; idxbuf.resize(dcsize.x * dcsize.y * 2); Vector<Vec3> &tmp_normals = tmp->normals; tmp_normals.clear(); Vector<Vec3> &virt_vertices = tmp->vertices; virt_vertices.resize(1); auto quad = [&](bool flip, uint32_t ia, uint32_t ib, uint32_t ic, uint32_t id, bool ignore) { if (flip) std::swap(ib, id); Vec3 a, b, c, d, nop; Vec3 *na = &nop; Vec3 *nb = &nop; Vec3 *nc = &nop; Vec3 *nd = &nop; auto i_to_v = [&](uint32_t &ix, Vec3 &x, Vec3 *&nx) { if (is_virtual(ix)) { x = virt_vertices[index(ix)]; } else { x = vertices[base_vertex+index(ix)].position; nx = &tmp_normals[index(ix)]; } }; i_to_v(ia, a, na); i_to_v(ib, b, nb); i_to_v(ic, c, nc); i_to_v(id, d, nd); const Vec3 ab = a - b; const Vec3 cb = c - b; const Vec3 n1 = cross(cb, ab); *na += n1; *nb += n1; *nc += n1; const Vec3 ac = a - c; const Vec3 dc = d - c; const Vec3 n2 = cross(dc, ac); *na += n2; *nc += n2; *nd += n2; if (ignore) return; if (!is_virtual(ia) && !is_virtual(ib) && !is_virtual(ic)) { indices.append(index(ia)); indices.append(index(ib)); indices.append(index(ic)); } if (!is_virtual(ia) && !is_virtual(ic) && !is_virtual(id)) { indices.append(index(ia)); indices.append(index(ic)); indices.append(index(id)); } }; HermiteData hd[8]; auto do_line = [&](const Vec3i coffset, HermiteRLEIterator its[4], bool continuation, int length, int fi) { const Vec3i rel = rel22(fi); // offset in cubes to the current field const Vec3i field_coffset = rel * csize; for (int i = 0; i < length; i++) { if (continuation || i != 0) { hd[0] = hd[1]; hd[2] = hd[3]; hd[4] = hd[5]; hd[6] = hd[7]; } else { hd[0] = *its[0]++; hd[2] = *its[1]++; hd[4] = *its[2]++; hd[6] = *its[3]++; } hd[1] = *its[0]++; hd[3] = *its[1]++; hd[5] = *its[2]++; hd[7] = *its[3]++; const uint8_t config = ((hd[0].material != 0) << 0) | ((hd[1].material != 0) << 1) | ((hd[2].material != 0) << 2) | ((hd[3].material != 0) << 3) | ((hd[4].material != 0) << 4) | ((hd[5].material != 0) << 5) | ((hd[6].material != 0) << 6) | ((hd[7].material != 0) << 7); if (config == 0 || config == 255) { int tmp; int canskip = its[0].can_skip(); if (canskip == 0) continue; tmp = its[1].can_skip(); if (tmp == 0) continue; if (tmp < canskip) canskip = tmp; tmp = its[2].can_skip(); if (tmp == 0) continue; if (tmp < canskip) canskip = tmp; tmp = its[3].can_skip(); if (tmp == 0) continue; if (tmp < canskip) canskip = tmp; int willskip = min(canskip, length-1-i); if (willskip <= 0) continue; i += willskip; its[0].skip(willskip); its[1].skip(willskip); its[2].skip(willskip); its[3].skip(willskip); continue; } const uint32_t vconfig = VCONFIGS[config]; CubeContext cc; const uint8_t M = HermiteData_FullEdge(); auto do_edge = [&](int edge_n, int axis, const Vec2i &value, const HermiteData &hd0, const HermiteData &hd1) { const Vec2i o_axes = OTHER_AXES_TABLE[axis]; if (!edge_has_intersection(hd0, hd1)) return; Vec3i v(0); v[axis] = M - hd1.edges[axis]; v[o_axes[0]] = value[0]; v[o_axes[1]] = value[1]; cc.add_vector(v, vconfig_vertex_index(vconfig, edge_n)); }; do_edge(0, 0, {0, 0}, hd[0], hd[1]); do_edge(1, 0, {M, 0}, hd[2], hd[3]); do_edge(2, 0, {0, M}, hd[4], hd[5]); do_edge(3, 0, {M, M}, hd[6], hd[7]); do_edge(4, 1, {0, 0}, hd[0], hd[2]); do_edge(5, 1, {M, 0}, hd[1], hd[3]); do_edge(6, 1, {0, M}, hd[4], hd[6]); do_edge(7, 1, {M, M}, hd[5], hd[7]); do_edge(8, 2, {0, 0}, hd[0], hd[4]); do_edge(9, 2, {M, 0}, hd[1], hd[5]); do_edge(10, 2, {0, M}, hd[2], hd[6]); do_edge(11, 2, {M, M}, hd[3], hd[7]); // position of the cube relative to fields const Vec3i p = coffset + Vec3i_X(i); // position of the cube relative to work area const Vec3i wp = p - voffset; uint8_t average_material = 0; const bool is_virtual = !(nonv_min <= wp && wp <= nonv_max); const int idxoffset = offset_3d_slab(wp, dcsize); IndexVConfigPair &pair = idxbuf[idxoffset]; pair.m_vconfig = vconfig; if (!is_virtual) { for (int i = 0; i < 8; i++) cc.add_material(hd[i].material); average_material = cc.average_material() - 1; pair.m_index = vertices.length() - base_vertex; } else { pair.m_index = virt_vertices.length() | VF_VIRTUAL; } for (int j = 0, n = vconfig_n_vertices(vconfig); j < n; j++) { // vertex position is relative to 7th (1;1;1) field const Vec3 v = cube_size_lod * (ToVec3(p-csize) + cc.average_vector(j)); if (!is_virtual) { vertices.append({base+v, 0, average_material}); tmp_normals.append(Vec3(0)); } else { virt_vertices.append(base+v); } } // position of the cube relative to the current field const Vec3i lp = p - field_coffset; const bool flip = hd[0].material != 0; if ( (lp.y > 1 || neighbours[fi].y) && (lp.z > 1 || neighbours[fi].z) && wp.y > 0 && wp.z > 0 && edge_has_intersection(hd[0], hd[1]) ) { quad(flip, idxbuf[offset_3d_slab(Vec3i(wp.x, wp.y, wp.z), dcsize)].index(0), idxbuf[offset_3d_slab(Vec3i(wp.x, wp.y, wp.z-1), dcsize)].index(2), idxbuf[offset_3d_slab(Vec3i(wp.x, wp.y-1, wp.z-1), dcsize)].index(3), idxbuf[offset_3d_slab(Vec3i(wp.x, wp.y-1, wp.z), dcsize)].index(1), 1 == wp.x ); } if ( (lp.x > 1 || neighbours[fi].x) && (lp.z > 1 || neighbours[fi].z) && wp.x > 0 && wp.z > 0 && edge_has_intersection(hd[0], hd[2]) ) { quad(flip, idxbuf[offset_3d_slab(Vec3i(wp.x, wp.y, wp.z), dcsize)].index(4), idxbuf[offset_3d_slab(Vec3i(wp.x-1, wp.y, wp.z), dcsize)].index(5), idxbuf[offset_3d_slab(Vec3i(wp.x-1, wp.y, wp.z-1), dcsize)].index(7), idxbuf[offset_3d_slab(Vec3i(wp.x, wp.y, wp.z-1), dcsize)].index(6), 1 == wp.y ); } if ( (lp.x > 1 || neighbours[fi].x) && (lp.y > 1 || neighbours[fi].y) && wp.x > 0 && wp.y > 0 && edge_has_intersection(hd[0], hd[4]) ) { quad(flip, idxbuf[offset_3d_slab(Vec3i(wp.x, wp.y, wp.z), dcsize)].index(8), idxbuf[offset_3d_slab(Vec3i(wp.x, wp.y-1, wp.z), dcsize)].index(10), idxbuf[offset_3d_slab(Vec3i(wp.x-1, wp.y-1, wp.z), dcsize)].index(11), idxbuf[offset_3d_slab(Vec3i(wp.x-1, wp.y, wp.z), dcsize)].index(9), 1 == wp.z ); } } }; // true when the line is a continuation of the previous line bool continuation = false; for (int z = 0; z < dcsize.z; z++) { for (int y = 0; y < dcsize.y; y++) { Vec3i line_starts[4] = { voffset + Vec3i(0, y, z), voffset + Vec3i(0, y+1, z), voffset + Vec3i(0, y, z+1), voffset + Vec3i(0, y+1, z+1), }; // field offsets in [0; 1] range, 1 per each of 4 iterators Vec3i foffsets[4]; // voxel offsets local to fields in [0; CHUNK_SIZE] range Vec3i voffsets[4]; for (int i = 0; i < 4; i++) { for (int j = 1; j < 3; j++) { foffsets[i][j] = line_starts[i][j] > csize[j] ? 1 : 0; voffsets[i][j] = line_starts[i][j] > csize[j] ? line_starts[i][j] - csize[j] : line_starts[i][j]; } } continuation = false; for (int x = 0; x < 2; x++) { // actual fields where we will take the iterators from const HermiteRLEField *fs[4]; for (int i = 0; i < 4; i++) { foffsets[i].x = x; voffsets[i].x = x ? 0 : voffset.x; fs[i] = fields[offset_3d(foffsets[i], Vec3i(2))]; } if (!fs[0] or !fs[1] or !fs[2] or !fs[3]) continue; // the iterators HermiteRLEIterator its[4]; const int add = continuation ? 1 : 0; // skip 1 more on continuations for (int i = 0; i < 4; i++) its[i] = fs[i]->iterator(voffsets[i] + Vec3i_X(add)); const Vec3i lcdsize = foffsets[0] * pdcsize + (foffsets[0]^Vec3i(1)) * ndcsize; const int length = lcdsize.x; const Vec3i coffset = foffsets[0] * csize + voffsets[0]; do_line(coffset, its, continuation, length, offset_3d(foffsets[0], Vec3i(2))); continuation = true; }}} for (int i = base_vertex; i < vertices.length(); i++) vertices[i].normal = pack_normal(normalize(tmp_normals[i-base_vertex])); } static bool has_valid_lod(Slice<const int> lods) { for (int lod : lods) { if (lod >= 0) return true; } return false; } static bool same_lod(Slice<const int> lods, int *thelod) { *thelod = -1; for (int lod : lods) { if (lod >= 0) { *thelod = lod; break; } } for (int lod : lods) { if (lod >= 0 && lod != *thelod) return false; } return true; } static void unpack_fields(Slice<HermiteField> out, Slice<const HermiteRLEField*> fields, const FieldAccessHelper &fah) { for (int i = 0; i < 8; i++) { // skip non-existent chunk if (fah.lods[i] == -1) continue; const Vec3i offset = fah.voffset(i); const Vec3i size = fah.vsize(i); out[i].resize(size); fields[i]->partial_decompress(out[i].data, offset, offset + size); } } // TODO static void sync_fields(Slice<HermiteField> fields, const FieldAccessHelper &fah) { // sync edges for (int i = 0; i < 6; i++) { const int axis = EDGES_TABLE[i].axis; const auto &auth_edge = fah.auth_edges[i]; // no edges here if (auth_edge.lod == -1) continue; const int auth_lod = auth_edge.lod; const int auth_c = auth_edge.chunk; const HermiteField &auth_field = fields[auth_c]; const Vec3i auth_offset = auth_edge.offset; for (int j = 0; j < 4; j++) { const int c = EDGES_TABLE[i].chunks[j]; // no need to sync with ourselves if (c == auth_c) continue; // not a field const int lod = fah.lods[c]; if (lod == -1) continue; const Vec3i vsize = fah.vsize(c); const Vec3i dcsize = vsize - Vec3i(1); const Vec3i offset = EDGES_TABLE[i].offsets[j] * dcsize; HermiteField &field = fields[c]; for (int a = 0; a < vsize[axis]; a++) { Vec3i pos = offset; pos[axis] = a; Vec3i opos = auth_offset; opos[axis] = auth_lod < lod ? a*2 : a; field.get(pos).material = auth_field.get(opos).material; } } } // sync faces for (int i = 0; i < 12; i++) { const Vec2i axes = FACES_TABLE[i].axes; const auto &auth_face = fah.auth_faces[i]; // no faces here if (auth_face.lod == -1) continue; const int auth_lod = auth_face.lod; const int auth_c = auth_face.chunk; const HermiteField &auth_field = fields[auth_c]; const Vec3i auth_offset = auth_face.offset; for (int j = 0; j < 2; j++) { const int c = FACES_TABLE[i].chunks[j]; if (c == auth_c) continue; const int lod = fah.lods[c]; if (lod == -1) continue; const Vec3i vsize = fah.vsize(c); const Vec3i dcsize = vsize - Vec3i(1); const Vec3i offset = FACES_TABLE[i].offsets[j] * dcsize; HermiteField &field = fields[c]; for (int a0 = 0; a0 < vsize[axes[0]]; a0++) { for (int a1 = 0; a1 < vsize[axes[1]]; a1++) { Vec3i pos = offset; pos[axes[0]] = a0; pos[axes[1]] = a1; Vec3i opos = auth_offset; opos[axes[0]] = auth_lod < lod ? a0*2 : a0; opos[axes[1]] = auth_lod < lod ? a1*2 : a1; field.get(pos).material = auth_field.get(opos).material; }} } } } static inline void collect_additional_face_edges(CubeContext *ctx, const Vec3i &pos, int axis, int value, const HermiteField &field) { // a1 // +----+----+ // | | | // | | | // +----+----+ b // | | | // | | | // +----+----+ // a lpos0 // a0 const Vec2i other_axes = OTHER_AXES_TABLE[axis]; Vec3i lpos0a = pos; lpos0a[other_axes[0]]++; Vec3i lpos1a = lpos0a; Vec3i lpos2a = lpos0a; lpos1a[other_axes[1]] += 1; lpos2a[other_axes[1]] += 2; Vec3i lpos0b = pos; lpos0b[other_axes[1]]++; Vec3i lpos2b = lpos0b; lpos2b[other_axes[0]] += 2; const HermiteData &hd0a = field.get(lpos0a); const HermiteData &hd1a = field.get(lpos1a); const HermiteData &hd2a = field.get(lpos2a); const HermiteData &hd0b = field.get(lpos0b); const HermiteData &hd1b = hd1a; const HermiteData &hd2b = field.get(lpos2b); if (edge_has_intersection(hd2b, hd1b)) { Vec3i v(0); v[axis] = value; v[other_axes[1]] = HermiteData_HalfEdge(); v[other_axes[0]] = HermiteData_HalfEdge() + (HermiteData_FullEdge() - hd2b.edges[other_axes[0]]) / 2; ctx->add_vector(v); } if (edge_has_intersection(hd1b, hd0b)) { Vec3i v(0); v[axis] = value; v[other_axes[1]] = HermiteData_HalfEdge(); v[other_axes[0]] = (HermiteData_FullEdge() - hd1b.edges[other_axes[0]]) / 2; ctx->add_vector(v); } if (edge_has_intersection(hd2a, hd1a)) { Vec3i v(0); v[axis] = value; v[other_axes[0]] = HermiteData_HalfEdge(); v[other_axes[1]] = HermiteData_HalfEdge() + (HermiteData_FullEdge() - hd2a.edges[other_axes[1]]) / 2; ctx->add_vector(v); } if (edge_has_intersection(hd1a, hd0a)) { Vec3i v(0); v[axis] = value; v[other_axes[0]] = HermiteData_HalfEdge(); v[other_axes[1]] = (HermiteData_FullEdge() - hd1a.edges[other_axes[1]]) / 2; ctx->add_vector(v); } ctx->add_material(hd1a.material); } static inline void collect_edges(CubeContext *ctx, const Vec3i &pos, int eaxis, const Vec2i &value, const HermiteField &field) { const Vec2i other_axes = OTHER_AXES_TABLE[eaxis]; Vec3i lpos0 = pos; Vec3i lpos1 = lpos0; Vec3i lpos2 = lpos0; lpos1[eaxis] += 1; lpos2[eaxis] += 2; const HermiteData &hd0 = field.get(lpos0); const HermiteData &hd1 = field.get(lpos1); const HermiteData &hd2 = field.get(lpos2); if (edge_has_intersection(hd2, hd1)) { Vec3i v(0); v[eaxis] = HermiteData_HalfEdge() + (HermiteData_FullEdge() - hd2.edges[eaxis]) / 2; v[other_axes[0]] = value[0]; v[other_axes[1]] = value[1]; ctx->add_vector(v); } if (edge_has_intersection(hd1, hd0)) { Vec3i v(0); v[eaxis] = (HermiteData_FullEdge() - hd1.edges[eaxis]) / 2; v[other_axes[0]] = value[0]; v[other_axes[1]] = value[1]; ctx->add_vector(v); } ctx->add_material(hd1.material); } static void create_vertices( Vector<V3N3M1_terrain> &vertices, Vector<Vec3> &tmp_normals, Vector<Vec3> &virt_vertices, Slice<Vector<IndexVConfigPair>> vindices, Slice<const HermiteField> fields, const FieldAccessHelper &fah, const Vec3 &base) { const int base_vertex = vertices.length(); const uint8_t M = HermiteData_FullEdge(); for (int i = 0; i < 8; i++) { const int lod = fah.lods[i]; if (lod == -1) continue; const auto &field = fields[i]; const Vec3i irel = rel22(i^7); // work area of a given field in cubes const Vec3i dcsize = fields[i].size - Vec3i(1); // real size of a field in cubes (excluding virtual vertices/cubes) const Vec3i csize = fah.non_virtual_csize(i); const Vec3i vadd = (dcsize - csize) * irel; const Vec3i vmin = vadd; const Vec3i vmax = csize + vadd - Vec3i(1); // cubes for which we can use quick path const Vec3i qmin = rel22(i); const Vec3i qmax = dcsize-(irel*Vec3i(2)); // prepare indices field auto &indices = vindices[i]; indices.resize(volume(dcsize)); const Vec3 cube_size_lod = CUBE_SIZE * Vec3(lod_factor(lod)); const Vec3 vbase = -ToVec3(dcsize * rel22(i^7)) * cube_size_lod; const Vec3i chunk_faces = CHUNK_FACES[i].faces; const Vec3i chunk_edges = CHUNK_EDGES[i].edges; const Vec3i chunk_face_positions = fah.face_positions[i].position; const Vec3i af_lods( fah.auth_faces[chunk_faces[0]].lod, fah.auth_faces[chunk_faces[1]].lod, fah.auth_faces[chunk_faces[2]].lod ); const Vec3i ae_lods( fah.auth_edges[chunk_edges[0]].lod, fah.auth_edges[chunk_edges[1]].lod, fah.auth_edges[chunk_edges[2]].lod ); const bool af_lods_less_than[3] = { af_lods[0] != -1 && af_lods[0] < lod, af_lods[1] != -1 && af_lods[1] < lod, af_lods[2] != -1 && af_lods[2] < lod, }; const bool ae_lods_less_than[3] = { ae_lods[0] != -1 && ae_lods[0] < lod, ae_lods[1] != -1 && ae_lods[1] < lod, ae_lods[2] != -1 && ae_lods[2] < lod, }; Vec3i chunk_edge_positions[3]; for (int j = 0; j < 3; j++) chunk_edge_positions[j] = fah.edge_positions[i].position[j]; const uint8_t x0mask = 85; // 0b01010101 const uint8_t x1mask = 170; // 0b10101010 uint8_t config = 0; HermiteData hd[8]; for (int z = 0; z < dcsize.z; z++) { for (int y = 0; y < dcsize.y; y++) { for (int x = 0; x < dcsize.x; x++) { const Vec3i pos(x, y, z); if (x == 0) { config &= ~x0mask; hd[0] = field.get({x, y, z}); hd[2] = field.get({x, y+1, z}); hd[4] = field.get({x, y, z+1}); hd[6] = field.get({x, y+1, z+1}); config |= ((hd[0].material != 0) << 0) | ((hd[2].material != 0) << 2) | ((hd[4].material != 0) << 4) | ((hd[6].material != 0) << 6); } else { config >>= 1; hd[0] = hd[1]; hd[2] = hd[3]; hd[4] = hd[5]; hd[6] = hd[7]; } config &= ~x1mask; hd[1] = field.get({x+1, y, z}); hd[3] = field.get({x+1, y+1, z}); hd[5] = field.get({x+1, y, z+1}); hd[7] = field.get({x+1, y+1, z+1}); config |= ((hd[1].material != 0) << 1) | ((hd[3].material != 0) << 3) | ((hd[5].material != 0) << 5) | ((hd[7].material != 0) << 7); CubeContext cc; uint32_t vconfig; if (qmin <= pos && pos <= qmax) { if (config == 0 || config == 255) continue; vconfig = VCONFIGS[config]; auto do_edge_quick = [&](int edge_n, int axis, const Vec2i &value, const HermiteData &hd0, const HermiteData &hd1) { const Vec2i o_axes = OTHER_AXES_TABLE[axis]; if (!edge_has_intersection(hd1, hd0)) return; Vec3i v(0); v[axis] = M - hd1.edges[axis]; v[o_axes[0]] = value[0]; v[o_axes[1]] = value[1]; cc.add_vector(v, vconfig_vertex_index(vconfig, edge_n)); }; do_edge_quick(0, 0, {0, 0}, hd[0], hd[1]); do_edge_quick(1, 0, {M, 0}, hd[2], hd[3]); do_edge_quick(2, 0, {0, M}, hd[4], hd[5]); do_edge_quick(3, 0, {M, M}, hd[6], hd[7]); do_edge_quick(4, 1, {0, 0}, hd[0], hd[2]); do_edge_quick(5, 1, {M, 0}, hd[1], hd[3]); do_edge_quick(6, 1, {0, M}, hd[4], hd[6]); do_edge_quick(7, 1, {M, M}, hd[5], hd[7]); do_edge_quick(8, 2, {0, 0}, hd[0], hd[4]); do_edge_quick(9, 2, {M, 0}, hd[1], hd[5]); do_edge_quick(10, 2, {0, M}, hd[2], hd[6]); do_edge_quick(11, 2, {M, M}, hd[3], hd[7]); } else { bool has_additional_edges = false; for (int j = 0; j < 3; j++) { if (!af_lods_less_than[j]) continue; const int auth_face = chunk_faces[j]; const int c = fah.auth_faces[auth_face].chunk; Vec3i lpos = pos * Vec3i(2); lpos[j] = fah.auth_faces[auth_face].offset[j]; if (pos[j] == chunk_face_positions[j]) { collect_additional_face_edges(&cc, lpos, j, 0, fields[c]); has_additional_edges = true; } else if (pos[j]+1 == chunk_face_positions[j]) { collect_additional_face_edges(&cc, lpos, j, M, fields[c]); has_additional_edges = true; } } uint32_t additional_face_edges_oa0 = 0; uint32_t additional_face_edges_oa1 = 0; uint32_t additional_edges = 0; auto check_edge = [&](int edge_n, const Vec3i &pos, int axis) { const Vec2i o_axes = OTHER_AXES_TABLE[axis]; additional_face_edges_oa0 |= (af_lods_less_than[o_axes[0]] & (chunk_face_positions[o_axes[0]] == pos[o_axes[0]])) << edge_n; additional_face_edges_oa1 |= (af_lods_less_than[o_axes[1]] & (chunk_face_positions[o_axes[1]] == pos[o_axes[1]])) << edge_n; additional_edges |= (ae_lods_less_than[axis] & axes_equal(chunk_edge_positions[axis], pos, o_axes)) << edge_n; }; check_edge(0, {x, y, z}, 0); check_edge(1, {x, y+1, z}, 0); check_edge(2, {x, y, z+1}, 0); check_edge(3, {x, y+1, z+1}, 0); check_edge(4, {x, y, z}, 1); check_edge(5, {x+1, y, z}, 1); check_edge(6, {x, y, z+1}, 1); check_edge(7, {x+1, y, z+1}, 1); check_edge(8, {x, y, z}, 2); check_edge(9, {x+1, y, z}, 2); check_edge(10, {x, y+1, z}, 2); check_edge(11, {x+1, y+1, z}, 2); if (has_additional_edges | (additional_face_edges_oa0 > 0) | (additional_face_edges_oa1 > 0) | (additional_edges > 0)) { vconfig = 1 << 24; } else { vconfig = VCONFIGS[config]; } auto do_edge = [&](int edge_n, const Vec3i &pos, int axis, const Vec2i &value, const HermiteData &hd0, const HermiteData &hd1) { const Vec2i o_axes = OTHER_AXES_TABLE[axis]; if ((additional_face_edges_oa0 >> edge_n) & 1) { const int auth_face = chunk_faces[o_axes[0]]; const int c = fah.auth_faces[auth_face].chunk; Vec3i lpos = pos * Vec3i(2); lpos[o_axes[0]] = fah.auth_faces[auth_face].offset[o_axes[0]]; collect_edges(&cc, lpos, axis, value, fields[c]); } else if ((additional_face_edges_oa1 >> edge_n) & 1) { const int auth_face = chunk_faces[o_axes[1]]; const int c = fah.auth_faces[auth_face].chunk; Vec3i lpos = pos * Vec3i(2); lpos[o_axes[1]] = fah.auth_faces[auth_face].offset[o_axes[1]]; collect_edges(&cc, lpos, axis, value, fields[c]); } else if ((additional_edges >> edge_n) & 1) { const int auth_edge = chunk_edges[axis]; const int c = fah.auth_edges[auth_edge].chunk; Vec3i lpos = fah.auth_edges[auth_edge].offset; lpos[axis] = pos[axis] * 2; collect_edges(&cc, lpos, axis, value, fields[c]); } else if (edge_has_intersection(hd0, hd1)) { Vec3i v(0); v[axis] = M - hd1.edges[axis]; v[o_axes[0]] = value[0]; v[o_axes[1]] = value[1]; cc.add_vector(v, vconfig_vertex_index(vconfig, edge_n)); } }; do_edge(0, {x, y, z}, 0, {0, 0}, hd[0], hd[1]); do_edge(1, {x, y+1, z}, 0, {M, 0}, hd[2], hd[3]); do_edge(2, {x, y, z+1}, 0, {0, M}, hd[4], hd[5]); do_edge(3, {x, y+1, z+1}, 0, {M, M}, hd[6], hd[7]); do_edge(4, {x, y, z}, 1, {0, 0}, hd[0], hd[2]); do_edge(5, {x+1, y, z}, 1, {M, 0}, hd[1], hd[3]); do_edge(6, {x, y, z+1}, 1, {0, M}, hd[4], hd[6]); do_edge(7, {x+1, y, z+1}, 1, {M, M}, hd[5], hd[7]); do_edge(8, {x, y, z}, 2, {0, 0}, hd[0], hd[4]); do_edge(9, {x+1, y, z}, 2, {M, 0}, hd[1], hd[5]); do_edge(10, {x, y+1, z}, 2, {0, M}, hd[2], hd[6]); do_edge(11, {x+1, y+1, z}, 2, {M, M}, hd[3], hd[7]); } // For non-quick vertices we may actually end up in a false // positive, and collect no vertex at all. if (vconfig_n_vertices(vconfig) == 1 && cc.accumulated_n[0] == 0) continue; // From this point, both quick and non-quick vertices follow // same rules. uint8_t average_material = 0; const bool is_virtual = !(vmin <= pos && pos <= vmax); IndexVConfigPair &pair = indices[offset_3d(pos, dcsize)]; pair.m_vconfig = vconfig; if (!is_virtual) { for (int i = 0; i < 8; i++) cc.add_material(hd[i].material); average_material = cc.average_material() - 1; pair.m_index = vertices.length() - base_vertex; } else { pair.m_index = virt_vertices.length() | VF_VIRTUAL; } for (int j = 0, n = vconfig_n_vertices(vconfig); j < n; j++) { const Vec3 v = vbase + cube_size_lod * (ToVec3(pos) + cc.average_vector(j)); if (!is_virtual) { vertices.append({base+v, 0, average_material}); tmp_normals.append(Vec3(0)); } else { virt_vertices.append(base+v); } } }}} } } static bool is_empty(Slice<const HermiteRLEField*> fields) { int first; bool found_first = false; for (int i = 0; i < fields.length; i++) { const HermiteRLEField *f = fields[i]; if (!f) continue; if (f->data.length() > 1) return false; if (!found_first) { first = f->data[0].material; found_first = true; } if (found_first && f->data[0].material != first) return false; } return true; } void hermite_rle_fields_to_mesh(Vector<V3N3M1_terrain> &vertices, Vector<uint32_t> &indices, Slice<const HermiteRLEField*> fields, Slice<const int> lods, int largest_lod, const Vec3 &base) { if (is_empty(fields)) return; if (!has_valid_lod(lods)) return; int thelod = -1; if (same_lod(lods, &thelod)) { hermite_rle_fields_to_mesh_same_lod(vertices, indices, fields, thelod, largest_lod, base); return; } FieldAccessHelper fah(lods, largest_lod); TemporaryData *tmp = temporary_data.get(); Vector<Vec3> &tmp_normals = tmp->normals; tmp_normals.clear(); Vector<Vec3> &virt_vertices = tmp->vertices; virt_vertices.resize(1); HermiteField (&fs)[8] = tmp->fs; Vector<IndexVConfigPair> (&idxbufs)[8] = tmp->idxbufs; const int base_vertex = vertices.length(); unpack_fields(fs, fields, fah); sync_fields(fs, fah); create_vertices(vertices, tmp_normals, virt_vertices, idxbufs, fs, fah, base); if (vertices.length() == base_vertex) return; auto quad = [&](bool flip, uint32_t ia, uint32_t ib, uint32_t ic, uint32_t id, bool ignore) { if (flip) std::swap(ib, id); Vec3 a, b, c, d, nop; Vec3 *na = &nop, *nb = &nop, *nc = &nop, *nd = &nop; auto i_to_v = [&](uint32_t &ix, Vec3 &x, Vec3 *&nx) { if (is_virtual(ix)) { x = virt_vertices[index(ix)]; } else { x = vertices[base_vertex+index(ix)].position; nx = &tmp_normals[index(ix)]; } }; i_to_v(ia, a, na); i_to_v(ib, b, nb); i_to_v(ic, c, nc); i_to_v(id, d, nd); const Vec3 ab = a - b; const Vec3 cb = c - b; const Vec3 n1 = cross(cb, ab); *na += n1; *nb += n1; *nc += n1; const Vec3 ac = a - c; const Vec3 dc = d - c; const Vec3 n2 = cross(dc, ac); *na += n2; *nc += n2; *nd += n2; if (ignore) return; if (!is_virtual(ia) && !is_virtual(ib) && !is_virtual(ic)) { indices.append(ia); indices.append(ib); indices.append(ic); } if (!is_virtual(ia) && !is_virtual(ic) && !is_virtual(id)) { indices.append(ia); indices.append(ic); indices.append(id); } }; auto tri = [&](bool flip, uint32_t ia, uint32_t ib, uint32_t ic, bool ignore) { if (flip) std::swap(ib, ic); Vec3 a, b, c, nop; Vec3 *na = &nop, *nb = &nop, *nc = &nop; auto i_to_v = [&](uint32_t &ix, Vec3 &x, Vec3 *&nx) { if (is_virtual(ix)) { x = virt_vertices[index(ix)]; } else { x = vertices[base_vertex+index(ix)].position; nx = &tmp_normals[index(ix)]; } }; i_to_v(ia, a, na); i_to_v(ib, b, nb); i_to_v(ic, c, nc); const Vec3 ab = a - b; const Vec3 cb = c - b; Vec3 n = cross(cb, ab); *na += n; *nb += n; *nc += n; if (ignore) return; if (!is_virtual(ia) && !is_virtual(ib) && !is_virtual(ic)) { indices.append(ia); indices.append(ib); indices.append(ic); } }; for (int i = 0; i < 8; i++) { const int lod = lods[i]; if (lod == -1) continue; const HermiteField &field = fs[i]; Slice<const IndexVConfigPair> inds = idxbufs[i]; const Vec3i dcsize = field.size - Vec3i(1); const Vec3i dup_faces = fah.dup_faces[i]; for (int z = 0; z < dcsize.z; z++) { for (int y = 0; y < dcsize.y; y++) { for (int x = 0; x < dcsize.x; x++) { const Vec3i pos(x, y, z); const HermiteData &hd0 = field.get({x, y, z}); const HermiteData &hd1 = field.get({x+1, y, z}); const HermiteData &hd2 = field.get({x, y+1, z}); const HermiteData &hd4 = field.get({x, y, z+1}); const uint8_t sign = ((hd0.material != 0) << 0) | ((hd1.material != 0) << 1) | ((hd2.material != 0) << 2) | ((hd4.material != 0) << 3); if (sign == 0 || sign == 15) continue; const bool flip = hd0.material != 0; if (y >= 1 && z >= 1 && edge_has_intersection(hd0, hd1)) { quad(flip, inds[offset_3d({x, y, z}, dcsize)].index(0), inds[offset_3d({x, y, z-1}, dcsize)].index(2), inds[offset_3d({x, y-1, z-1}, dcsize)].index(3), inds[offset_3d({x, y-1, z}, dcsize)].index(1), dup_faces.x == x ); } if (x >= 1 && z >= 1 && edge_has_intersection(hd0, hd2)) { quad(flip, inds[offset_3d({x, y, z}, dcsize)].index(4), inds[offset_3d({x-1, y, z}, dcsize)].index(5), inds[offset_3d({x-1, y, z-1}, dcsize)].index(7), inds[offset_3d({x, y, z-1}, dcsize)].index(6), dup_faces.y == y ); } if (x >= 1 && y >= 1 && edge_has_intersection(hd0, hd4)) { quad(flip, inds[offset_3d({x, y, z}, dcsize)].index(8), inds[offset_3d({x, y-1, z}, dcsize)].index(10), inds[offset_3d({x-1, y-1, z}, dcsize)].index(11), inds[offset_3d({x-1, y, z}, dcsize)].index(9), dup_faces.z == z ); } }}} } for (const auto &t : FACES_TABLE) { const int l0 = lods[t.chunks[0]]; const int l1 = lods[t.chunks[1]]; if (l0 == -1 || l1 == -1) continue; int imin = min_i(l0, l1); Slice<const IndexVConfigPair> inds_s = idxbufs[t.chunks[imin]]; Slice<const IndexVConfigPair> inds_b = idxbufs[t.chunks[imin^1]]; const HermiteField &field_s = fs[t.chunks[imin]]; const Vec3i dup_faces = fah.dup_faces[t.chunks[imin]]; const Vec3i fsize_s = fah.vsize(t.chunks[imin]); const Vec3i csize_s = fsize_s-Vec3i(1); const Vec3i csize_b = fah.vsize(t.chunks[imin^1])-Vec3i(1); for (int j = 0; j < csize_s[t.axes[1]]; j++) { for (int i = 0; i < csize_s[t.axes[0]]; i++) { Vec3i fpos0_s = t.offsets[imin] * (fsize_s-Vec3i(1)); fpos0_s[t.axes[0]] += i; fpos0_s[t.axes[1]] += j; Vec3i fpos1_s = fpos0_s; fpos1_s[t.axes[0]]++; Vec3i fpos2_s = fpos0_s; fpos2_s[t.axes[1]]++; Vec3i cpos0_s = t.offsets[imin] * (csize_s-Vec3i(1)); cpos0_s[t.axes[0]] += i; cpos0_s[t.axes[1]] += j; Vec3i cpos0_b = t.offsets[imin^1] * (csize_b-Vec3i(1)); cpos0_b[t.axes[0]] += i; cpos0_b[t.axes[1]] += j; const HermiteData &hd0 = field_s.get(fpos0_s); const HermiteData &hd1 = field_s.get(fpos1_s); const HermiteData &hd2 = field_s.get(fpos2_s); const uint8_t sign = ((hd0.material != 0) << 0) | ((hd1.material != 0) << 1) | ((hd2.material != 0) << 2); if (sign == 0 || sign == 7) continue; const bool flip = (hd0.material != 0) ^ (t.axes == Vec2i(0, 2)); auto face = [&](int a0, int a1, bool flip, bool ignore) { Vec4i idxtbl = VINDEX_EDGES_TABLE_F[a1][a0]; if (imin == 1) { std::swap(idxtbl[0], idxtbl[3]); std::swap(idxtbl[1], idxtbl[2]); } Vec3i pos_a = cpos0_s; Vec3i pos_b = cpos0_s; pos_b[a0]--; uint32_t a = inds_s[offset_3d(pos_a, csize_s)].index(idxtbl[0]); uint32_t b = inds_s[offset_3d(pos_b, csize_s)].index(idxtbl[1]); if (l0 == l1) { Vec3i pos_c = cpos0_b; Vec3i pos_d = cpos0_b; pos_c[a0]--; uint32_t c = inds_b[offset_3d(pos_c, csize_b)].index(idxtbl[2]); uint32_t d = inds_b[offset_3d(pos_d, csize_b)].index(idxtbl[3]); quad(flip, a, b, c, d, ignore); } else { if (pos_a[a0] % 2) { Vec3i pos_c = cpos0_b; pos_c[a0] = cpos0_s[a0] / 2; pos_c[a1] = cpos0_s[a1] / 2; uint32_t c = inds_b[offset_3d(pos_c, csize_b)].m_index; tri(flip ^ (imin == 0), a, b, c, ignore); } else { Vec3i pos_c = cpos0_b; pos_c[a0] = cpos0_s[a0] / 2; pos_c[a1] = cpos0_s[a1] / 2; Vec3i pos_d = pos_c; pos_c[a0]--; uint32_t c = inds_b[offset_3d(pos_c, csize_b)].index(idxtbl[2]); uint32_t d = inds_b[offset_3d(pos_d, csize_b)].index(idxtbl[3]); quad(flip ^ (imin == 0), a, b, c, d, ignore); } } }; if (j >= 1 && edge_has_intersection(hd0, hd1)) face(t.axes[1], t.axes[0], !flip, dup_faces[t.axes[0]] == i); if (i >= 1 && edge_has_intersection(hd0, hd2)) face(t.axes[0], t.axes[1], flip, dup_faces[t.axes[1]] == j); }} } // TODO: rewrite this using fah.auth_edges for (const auto &t : EDGES_TABLE) { bool found_zero = false; int imin = 0; int minlod = lods[t.chunks[0]]; for (int i = 0; i < 4; i++) { const int lod = lods[t.chunks[i]]; if (lod == -1) { found_zero = true; break; } if (lod < minlod) { minlod = lod; imin = i; } } if (found_zero) continue; const HermiteField &field = fs[t.chunks[imin]]; const Vec3i csizes[4] = { fah.vsize(t.chunks[0]) - Vec3i(1), fah.vsize(t.chunks[1]) - Vec3i(1), fah.vsize(t.chunks[2]) - Vec3i(1), fah.vsize(t.chunks[3]) - Vec3i(1), }; const Vec3i dup_faces = fah.dup_faces[t.chunks[imin]]; const Vec3i fsize_s = fah.vsize(t.chunks[imin]); const Vec3i csize_s = csizes[imin]; for (int i = 0; i < csize_s[t.axis]; i++) { Vec3i pos0 = t.offsets[imin] * (fsize_s-Vec3i(1)); Vec3i pos1 = pos0; pos0[t.axis] = i; pos1[t.axis] = i+1; const HermiteData &hd0 = field.get(pos0); const HermiteData &hd1 = field.get(pos1); if (edge_has_intersection(hd0, hd1)) { const bool flip = (hd0.material != 0) ^ (t.axis != 1); uint32_t qi[4]; for (int j = 0; j < 4; j++) { Slice<const IndexVConfigPair> inds = idxbufs[t.chunks[j]]; const int lod = lods[t.chunks[j]]; const Vec3i csize = csizes[j]; Vec3i pos = t.offsets[j] * (csize-Vec3i(1)); pos[t.axis] = lod > minlod ? i / 2 : i; qi[j] = inds[offset_3d(pos, csize)].index(VINDEX_EDGES_TABLE_E[t.axis][j]); } quad(flip, qi[0], qi[1], qi[3], qi[2], dup_faces[t.axis] == i); } } } for (int i = base_vertex; i < vertices.length(); i++) vertices[i].normal = pack_normal(normalize(tmp_normals[i-base_vertex])); } //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- // basic 14 cases of the marching cubes struct MCConfig { int config[8]; int triangles[3*5+1]; int triangles_alt[3*5+1]; int vindices[12]; int vindices_alt[12]; bool use_alt; bool visited; bool inversion; bool ambiguous; int origin; }; const MCConfig MC_CONFIGS[15] = { // 0 {{0, 0, 0, 0, 0, 0, 0, 0}, {-1}, {-1}, {0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, false, 0}, // 1 {{1, 0, 0, 0, 0, 0, 0, 0}, {0, 4, 8, -1}, {-1}, {0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, false, 0}, // 2 {{1, 1, 0, 0, 0, 0, 0, 0}, {4, 9, 5, 4, 8, 9, -1}, {-1}, {0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, false, 0}, // 3 {{1, 0, 0, 0, 0, 1, 0, 0}, {0, 4, 8, 7, 9, 2, -1}, {8, 2, 4, 4, 2, 7, 4, 7, 9, 4, 9, 0, -1}, {0,0,1,0,0,0,0,1,0,1,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, true, false, true, true, 0}, // 4 {{1, 0, 0, 0, 0, 0, 0, 1}, {0, 4, 8, 3, 11, 7, -1}, {-1}, {0,0,0,1,0,0,0,1,0,0,0,1}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, true, 0}, // 5 {{0, 1, 1, 1, 0, 0, 0, 0}, {4, 0, 9, 4, 9, 10, 10, 9, 11, -1}, {-1}, {0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, false, 0}, // 6 {{1, 1, 0, 0, 0, 0, 0, 1}, {4, 9, 5, 4, 8, 9, 3, 11, 7, -1}, {4, 3, 5, 9, 3, 8, 8, 3, 4, 7, 3, 9, 5, 3, 11, -1}, {0,0,0,1,0,0,0,1,0,0,0,1}, {0,0,0,0,0,0,0,0,0,0,0,0}, true, false, true, true, 0}, // 7 {{0, 1, 0, 0, 1, 0, 0, 1}, {2, 8, 6, 9, 5, 0, 3, 11, 7, -1}, {2, 9, 7, 8, 6, 0, 0, 6, 3, 0, 3, 5, 5, 3, 11, -1}, {1,0,0,2,0,1,0,2,0,1,0,2}, {1,0,0,1,0,1,1,0,1,0,0,1}, true, false, true, true, 0}, // 8 {{1, 1, 1, 1, 0, 0, 0, 0}, {8, 11, 10, 8, 9, 11, -1}, {-1}, {0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, false, 0}, // 9 {{1, 0, 1, 1, 0, 0, 1, 0}, {8, 3, 6, 8, 0, 3, 0, 11, 3, 0, 5, 11, -1}, {-1}, {0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, false, 0}, // 10 {{1, 0, 0, 1, 1, 0, 0, 1}, {2, 4, 6, 2, 0, 4, 3, 5, 7, 3, 1, 5, -1}, {-1}, {0,1,0,1,0,1,0,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, false, true, 0}, // 11 {{1, 0, 1, 1, 0, 0, 0, 1}, {8, 0, 10, 10, 7, 3, 0, 7, 10, 0, 5, 7, -1}, {-1}, {0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, false, 0}, // 12 {{0, 1, 1, 1, 1, 0, 0, 0}, {2, 8, 6, 10, 9, 11, 10, 4, 9, 4, 0, 9, -1}, {-1}, {1,0,0,0,1,0,0,0,0,1,1,1}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, false, true, 0}, // 13 {{1, 0, 0, 1, 0, 1, 1, 0}, {0, 4, 8, 6, 10, 3, 7, 9, 2, 1, 5, 11, -1}, {-1}, {0,3,2,1,0,3,1,2,0,2,1,3}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, false, true, 0}, // 14 {{0, 1, 1, 1, 0, 0, 1, 0}, {6, 11, 3, 6, 0, 11, 0, 9, 11, 4, 0, 6, -1}, {-1}, {0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, true, false, 0}, }; const int CONFIG_ROTATE_X_TABLE[8] = {2, 3, 6, 7, 0, 1, 4, 5}; const int CONFIG_ROTATE_Y_TABLE[8] = {1, 5, 3, 7, 0, 4, 2, 6}; const int CONFIG_ROTATE_Z_TABLE[8] = {1, 3, 0, 2, 5, 7, 4, 6}; const int EDGE_ROTATE_X_TABLE[12] = {2, 0, 3, 1, 8, 9, 10, 11, 6, 7, 4, 5}; const int EDGE_ROTATE_Y_TABLE[12] = {8, 10, 9, 11, 6, 4, 7, 5, 2, 0, 3, 1}; const int EDGE_ROTATE_Z_TABLE[12] = {4, 5, 6, 7, 1, 0, 3, 2, 10, 8, 11, 9}; uint8_t generate_index(const MCConfig &cfg) { uint8_t out = 0; for (int i = 0; i < 8; i++) out |= cfg.config[i] << i; return out; } MCConfig rotate_around_generic(const MCConfig &cfg, const int *config_table, const int *edge_table) { MCConfig out = cfg; for (int i = 0; i < 8; i++) { out.config[i] = cfg.config[config_table[i]]; for (int j = 0;; j++) { if (cfg.triangles[j] == -1) { out.triangles[j] = -1; break; } out.triangles[j] = edge_table[cfg.triangles[j]]; } for (int j = 0;; j++) { if (cfg.triangles_alt[j] == -1) { out.triangles_alt[j] = -1; break; } out.triangles_alt[j] = edge_table[cfg.triangles_alt[j]]; } } for (int i = 0; i < 12; i++) { out.vindices[edge_table[i]] = cfg.vindices[i]; out.vindices_alt[edge_table[i]] = cfg.vindices_alt[i]; } return out; } MCConfig rotate_around_x(const MCConfig &cfg) { return rotate_around_generic(cfg, CONFIG_ROTATE_X_TABLE, EDGE_ROTATE_X_TABLE); } MCConfig rotate_around_y(const MCConfig &cfg) { return rotate_around_generic(cfg, CONFIG_ROTATE_Y_TABLE, EDGE_ROTATE_Y_TABLE); } MCConfig rotate_around_z(const MCConfig &cfg) { return rotate_around_generic(cfg, CONFIG_ROTATE_Z_TABLE, EDGE_ROTATE_Z_TABLE); } MCConfig swap_winding(const MCConfig &cfg) { MCConfig out = cfg; if (cfg.use_alt) { copy(Slice<int>(out.triangles), Slice<const int>(cfg.triangles_alt)); copy(Slice<int>(out.vindices), Slice<const int>(cfg.vindices_alt)); out.use_alt = false; } for (int i = 0;; i += 3) { if (out.triangles[i] == -1) break; std::swap(out.triangles[i+1], out.triangles[i+2]); } return out; } void print_binary_byte(uint8_t n) { for (int i = 0; i < 8; i++) { if (n & (1 << i)) printf("1"); else printf("0"); } } MCConfig all_cases[256]; void generate_marching_cubes() { for (auto &c : all_cases) { c.visited = false; c.triangles[0] = -1; } for (int cfgi = 0; cfgi < 15; cfgi++) { const auto &cfg = MC_CONFIGS[cfgi]; MCConfig tmp = cfg; tmp.origin = cfgi; for (int k = 0; k < 4; k++) { tmp = rotate_around_y(tmp); for (int j = 0; j < 4; j++) { tmp = rotate_around_z(tmp); for (int i = 0; i < 4; i++) { tmp = rotate_around_x(tmp); auto &c = all_cases[generate_index(tmp)]; auto &ic = all_cases[generate_index(tmp)^0xFF]; c = tmp; c.visited = true; if (tmp.inversion) { ic = swap_winding(tmp); ic.visited = true; if (ic.origin == 6 || ic.origin == 3) ic.ambiguous = false; } } } } } int neg = 0; int pos = 0; for (int i = 0; i < 256; i++) { const auto &cfg = all_cases[i]; print_binary_byte(i); printf(": "); for (int j = 0;; j++) { if (cfg.triangles[j] == -1) { break; } printf("%d ", cfg.triangles[j]); } printf("(vindices: "); for (int j = 0; j < 12; j++) { printf("%d", cfg.vindices[j]); if (j != 11) printf(" "); } printf(") (origin: %d)\n", cfg.origin); } printf("uint64_t marching_cube_tris[256] = {"); for (int i = 0; i < 256; i++) { if (i % 4 == 0) printf("\n\t"); const auto &cfg = all_cases[i]; int ntris = 0; for (int j = 0;; j++) { if (cfg.triangles[j] == -1) { ntris = j/3; break; } } uint64_t magic = ntris; int offset = 4; for (int i = 0; i < ntris*3; i++) { magic |= (uint64_t)cfg.triangles[i] << offset; offset += 4; } printf("%luULL, ", magic); } printf("\n};\n"); printf("uint8_t non_manifold[32] = {"); for (int i = 0; i < 32; i++) { uint8_t n = 0; for (int j = 0; j < 8; j++) n |= all_cases[i*8+j].ambiguous << j; printf("%d", n); if (i != 32-1) { printf(", "); } } printf("};\n"); printf("uint32_t vconfigs[256] = {"); for (int i = 0; i < 256; i++) { if (i % 8 == 0) printf("\n\t"); const MCConfig &cfg = all_cases[i]; uint32_t n = 0; int maxn = 0; for (int j = 0; j < 12; j++) { maxn = max(maxn, cfg.vindices[j]); n |= cfg.vindices[j] << (j * 2); } n |= (maxn+1) << 24; printf("%d", n); if (i != 255) printf(", "); } printf("\n};\n"); for (const auto &c : all_cases) { if (c.visited) pos++; else neg++; } printf("pos: %d, neg: %d\n", pos, neg); } //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- //----------------------------------------------------------------------
29.904348
114
0.579033
nsf
ff9ee956272ccb07a5a4f771657487b2715743cb
5,718
cc
C++
source/extensions/filters/http/gfunction/gfunction_filter.cc
adesaegher/envoy-gloo
92d59246ff30199523603d18a969ac9ae5d6e4d3
[ "Apache-2.0" ]
null
null
null
source/extensions/filters/http/gfunction/gfunction_filter.cc
adesaegher/envoy-gloo
92d59246ff30199523603d18a969ac9ae5d6e4d3
[ "Apache-2.0" ]
null
null
null
source/extensions/filters/http/gfunction/gfunction_filter.cc
adesaegher/envoy-gloo
92d59246ff30199523603d18a969ac9ae5d6e4d3
[ "Apache-2.0" ]
null
null
null
#include "extensions/filters/http/gfunction/gfunction_filter.h" #include <algorithm> #include <list> #include <string> #include <vector> #include "envoy/http/header_map.h" #include "common/buffer/buffer_impl.h" #include "common/common/empty_string.h" #include "common/common/hex.h" #include "common/common/utility.h" #include "common/http/headers.h" #include "common/http/solo_filter_utility.h" #include "common/http/utility.h" #include "common/singleton/const_singleton.h" #include "extensions/filters/http/solo_well_known_names.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace GcloudGfunc { struct RcDetailsValues { // The jwt_authn filter rejected the request const std::string FunctionNotFound = "gfunction_function_not_found"; }; typedef ConstSingleton<RcDetailsValues> RcDetails; class GcloudGfuncHeaderValues { public: const Http::LowerCaseString InvocationType{"x-amz-invocation-type"}; const std::string InvocationTypeEvent{"Event"}; const std::string InvocationTypeRequestResponse{"RequestResponse"}; const Http::LowerCaseString LogType{"x-amz-log-type"}; const std::string LogNone{"None"}; const Http::LowerCaseString HostHead{"x-amz-log-type"}; }; typedef ConstSingleton<GcloudGfuncHeaderValues> GcloudGfuncHeaderNames; //const HeaderList GcloudGfuncFilter::HeadersToSign = // GcloudAuthenticator::createHeaderToSign( // {GcloudGfuncHeaderNames::get().InvocationType, // GcloudGfuncHeaderNames::get().LogType, Http::Headers::get().HostLegacy, // Http::Headers::get().ContentType}); GcloudGfuncFilter::GcloudGfuncFilter(Upstream::ClusterManager &cluster_manager ) // TimeSource &time_source) // : gcloud_authenticator_(time_source), cluster_manager_(cluster_manager) {} : cluster_manager_(cluster_manager) {} GcloudGfuncFilter::~GcloudGfuncFilter() {} std::string GcloudGfuncFilter::functionUrlPath(const std::string &url) { std::stringstream val; absl::string_view host; absl::string_view path; Http::Utility::extractHostPathFromUri(url, host, path); val << path; return val.str(); } std::string GcloudGfuncFilter::functionUrlHost(const std::string &url) { std::stringstream val; absl::string_view host; absl::string_view path; Http::Utility::extractHostPathFromUri(url, host, path); val << host; return val.str(); } Http::FilterHeadersStatus GcloudGfuncFilter::decodeHeaders(Http::HeaderMap &headers, bool end_stream) { protocol_options_ = Http::SoloFilterUtility::resolveProtocolOptions< const GcloudGfuncProtocolExtensionConfig>( SoloHttpFilterNames::get().GcloudGfunc, decoder_callbacks_, cluster_manager_); if (!protocol_options_) { return Http::FilterHeadersStatus::Continue; } route_ = decoder_callbacks_->route(); // great! this is an gcloud cluster. get the function information: function_on_route_ = Http::SoloFilterUtility::resolvePerFilterConfig<GcloudGfuncRouteConfig>( SoloHttpFilterNames::get().GcloudGfunc, route_); if (!function_on_route_) { decoder_callbacks_->sendLocalReply(Http::Code::NotFound, "no function present for Gcloud upstream", nullptr, absl::nullopt, RcDetails::get().FunctionNotFound); return Http::FilterHeadersStatus::StopIteration; } // gcloud_authenticator_.init(&protocol_options_->accessKey(), // &protocol_options_->secretKey()); request_headers_ = &headers; request_headers_->insertMethod().value().setReference( Http::Headers::get().MethodValues.Post); request_headers_->insertPath().value(functionUrlPath( function_on_route_->url())); if (end_stream) { gfuncfy(); return Http::FilterHeadersStatus::Continue; } return Http::FilterHeadersStatus::StopIteration; } Http::FilterDataStatus GcloudGfuncFilter::decodeData(Buffer::Instance &data, bool end_stream) { if (!function_on_route_) { return Http::FilterDataStatus::Continue; } if (data.length() != 0) { has_body_ = true; } // gcloud_authenticator_.updatePayloadHash(data); if (end_stream) { gfuncfy(); return Http::FilterDataStatus::Continue; } return Http::FilterDataStatus::StopIterationAndBuffer; } Http::FilterTrailersStatus GcloudGfuncFilter::decodeTrailers(Http::HeaderMap &) { if (function_on_route_ != nullptr) { gfuncfy(); } return Http::FilterTrailersStatus::Continue; } void GcloudGfuncFilter::gfuncfy() { handleDefaultBody(); request_headers_->addReference(GcloudGfuncHeaderNames::get().LogType, GcloudGfuncHeaderNames::get().LogNone); request_headers_->insertHost().value(functionUrlHost( function_on_route_->url())); // gcloud_authenticator_.sign(request_headers_, HeadersToSign, // protocol_options_->region()); cleanup(); } void GcloudGfuncFilter::handleDefaultBody() { if ((!has_body_) && function_on_route_->defaultBody()) { Buffer::OwnedImpl data(function_on_route_->defaultBody().value()); request_headers_->insertContentType().value().setReference( Http::Headers::get().ContentTypeValues.Json); request_headers_->insertContentLength().value(data.length()); // gcloud_authenticator_.updatePayloadHash(data); decoder_callbacks_->addDecodedData(data, false); } } void GcloudGfuncFilter::cleanup() { request_headers_ = nullptr; function_on_route_ = nullptr; protocol_options_.reset(); } } // namespace GcloudGfunc } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
30.741935
98
0.714236
adesaegher
ffa007d102a618ed455985a290c2f8139264002d
1,022
cpp
C++
framework/XML/Sources/XML.cpp
Daniel-Mietchen/kigs
92ab6deaf3e947465781a400c5a791ee171876c8
[ "MIT" ]
null
null
null
framework/XML/Sources/XML.cpp
Daniel-Mietchen/kigs
92ab6deaf3e947465781a400c5a791ee171876c8
[ "MIT" ]
null
null
null
framework/XML/Sources/XML.cpp
Daniel-Mietchen/kigs
92ab6deaf3e947465781a400c5a791ee171876c8
[ "MIT" ]
null
null
null
#include "PrecompiledHeaders.h" #include "XML.h" #include "XMLNode.h" #include "XMLReaderFile.h" #include "XMLWriterFile.h" #include "CoreRawBuffer.h" void XMLBase::WriteFile(const std::string& filename) { if(useStringRef()) { KIGS_ERROR("trying to write string_view XML",2); } else { XMLWriterFile::WriteFile(filename, *(XML*)this); } } XMLBase::XMLBase(CoreRawBuffer* buffer) : mReadedRawBuffer(buffer) { mReadedRawBuffer->GetRef(); mVersion = "1.0"; mEncoding = ""; mStandalone = ""; } XMLBase::~XMLBase() { if (mRoot) { delete mRoot; mRoot = nullptr; } if (mReadedRawBuffer) { mReadedRawBuffer->Destroy(); mReadedRawBuffer = nullptr; } } XMLBase* XMLBase::ReadFile(const std::string& filename, const char* force_as_format) { return XMLReaderFile::ReadFile(filename, force_as_format); } bool XMLBase::ReadFile(const std::string& filename, CoreModifiable* delegateObject, const char* force_as_format) { return XMLReaderFile::ReadFile(filename, delegateObject, force_as_format); }
18.25
112
0.72407
Daniel-Mietchen
ffa0b57fd392dc3feebd62eac702da557b4e2ae3
830
cpp
C++
meta01/main.cpp
NelsonBilber/cpp.metaprogramming
395f54e12219261d4a2647e4495eb795fc6b7aa2
[ "MIT" ]
null
null
null
meta01/main.cpp
NelsonBilber/cpp.metaprogramming
395f54e12219261d4a2647e4495eb795fc6b7aa2
[ "MIT" ]
null
null
null
meta01/main.cpp
NelsonBilber/cpp.metaprogramming
395f54e12219261d4a2647e4495eb795fc6b7aa2
[ "MIT" ]
null
null
null
/* Examples from * https://monoinfinito.wordpress.com/series/introduction-to-c-template-metaprogramming/ */ #include <iostream> template <int N> struct Factorial{ static const int result = N * Factorial<N-1>::result; }; //specialization of template, in this recursive case //is for stoping de loop template <> struct Factorial<0>{ static const int result = 1; }; int main() { std::cout << Factorial<5>::result << std::endl; return 0; } /* * NOTES FROM WEB SITE * * 1. Templates get evaluated on compile time, remember? That means all * that code actually executes when compiling the source, not when executing * the resulting binary (assuming it actually compiles, of course). * Having as a constraint the fact that all your code must resolve on compile * time means only const vars make sense. */
23.714286
88
0.713253
NelsonBilber
ffa0be7f3d371a73b012c4904ffc201e4a404cd1
3,904
cpp
C++
testing/kvstore/kvstore_perf.cpp
ghsecuritylab/comanche
a8862eaed59045377874b95b120832a0cba42193
[ "Apache-2.0" ]
19
2017-10-03T16:01:49.000Z
2021-06-07T10:21:46.000Z
testing/kvstore/kvstore_perf.cpp
dnbaker/comanche
121cd0fa16e55d461b366e83511d3810ea2b11c9
[ "Apache-2.0" ]
25
2018-02-21T23:43:03.000Z
2020-09-02T08:47:32.000Z
testing/kvstore/kvstore_perf.cpp
dnbaker/comanche
121cd0fa16e55d461b366e83511d3810ea2b11c9
[ "Apache-2.0" ]
19
2017-10-24T17:41:40.000Z
2022-02-22T02:17:18.000Z
/* note: we do not include component source, only the API definition */ #include "data.h" #include "exp_put.h" #include "exp_get.h" #include "exp_get_direct.h" #include "exp_erase.h" #include "exp_put_direct.h" #include "exp_throughput.h" #include "exp_update.h" #include "get_cpu_mask_from_string.h" #include "get_vector_from_string.h" #include "program_options.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #include <common/utils.h> #pragma GCC diagnostic pop #include "task.h" #include <api/components.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Wpedantic" #pragma GCC diagnostic ignored "-Wsign-conversion" #pragma GCC diagnostic ignored "-Wunused-parameter" #include <api/kvstore_itf.h> #pragma GCC diagnostic pop #include <boost/program_options.hpp> #undef PROFILE #ifdef PROFILE #include <gperftools/profiler.h> #endif #include <algorithm> #include <chrono> #include <iostream> #include <mutex> #include <thread> using namespace Component; namespace { boost::program_options::options_description po_desc("Options"); boost::program_options::positional_options_description g_pos; template <typename Exp> void run_exp(cpu_mask_t cpus, const ProgramOptions &options) { Core::Per_core_tasking<Exp, ProgramOptions> exp(cpus, options, options.pin); exp.wait_for_all(); auto first_exp = exp.tasklet(cpus.first_core()); first_exp->summarize(); } using exp_f = void(*)(cpu_mask_t, const ProgramOptions &); using test_element = std::pair<std::string, exp_f>; static const std::vector<test_element> test_vector { { "put", run_exp<ExperimentPut> }, { "get", run_exp<ExperimentGet> }, { "get_direct", run_exp<ExperimentGetDirect> }, { "put_direct", run_exp<ExperimentPutDirect> }, { "throughput", run_exp<ExperimentThroughput> }, { "erase", run_exp<ExperimentErase> }, { "update", run_exp<ExperimentUpdate> }, }; } int main(int argc, char * argv[]) { #ifdef PROFILE ProfilerDisable(); #endif namespace po = boost::program_options; try { std::vector<std::string> test_names; std::transform( test_vector.begin() , test_vector.end() , std::back_inserter(test_names) , [] ( const test_element &e ) { return e.first; } ); ProgramOptions::add_program_options(po_desc, test_names); boost::program_options::variables_map vm; po::store(po::command_line_parser(argc, argv).options(po_desc).positional(g_pos).run(), vm); if ( vm.count("help") ) { std::cout << po_desc; return 0; } ProgramOptions Options(vm); bool use_direct_memory = Options.component == "dawn"; Experiment::g_data = new Data(Options.elements, Options.key_length, Options.value_length, use_direct_memory); Options.report_file_name = Options.do_json_reporting ? Experiment::create_report(Options.component) : ""; cpu_mask_t cpus; try { cpus = get_cpu_mask_from_string(Options.cores); } catch (...) { PERR("%s", "couldn't create CPU mask. Exiting."); return 1; } #ifdef PROFILE ProfilerStart("cpu.profile"); #endif if ( Options.test == "all" ) { for ( const auto &e : test_vector ) { e.second(cpus, Options); } } else { const auto it = std::find_if( test_vector.begin() , test_vector.end() , [&Options] (const test_element &a) { return a.first == Options.test; } ); if ( it == test_vector.end() ) { PERR("No such test: %s.", Options.test.c_str()); return 1; } it->second(cpus, Options); } #ifdef PROFILE ProfilerStop(); #endif } catch (const po::error &ex) { std::cerr << ex.what() << '\n'; return -1; } return 0; }
24.866242
113
0.663678
ghsecuritylab
ffa55887123b4003ee5e5f02b8fd138df1fbeb4d
2,552
cpp
C++
catboost/libs/model/model_export/export_helpers.cpp
mikiec84/catboost
d16aa349ba7af265b053967b1938917fbddbca9d
[ "Apache-2.0" ]
null
null
null
catboost/libs/model/model_export/export_helpers.cpp
mikiec84/catboost
d16aa349ba7af265b053967b1938917fbddbca9d
[ "Apache-2.0" ]
null
null
null
catboost/libs/model/model_export/export_helpers.cpp
mikiec84/catboost
d16aa349ba7af265b053967b1938917fbddbca9d
[ "Apache-2.0" ]
null
null
null
#include "export_helpers.h" #include <util/string/builder.h> #include <util/string/cast.h> static TString FloatToStringWithSuffix(float value, bool addFloatingSuffix) { TString str = FloatToString(value, PREC_NDIGITS, 9); if (addFloatingSuffix) { if (int value; TryFromString<int>(str, value)) { str.append('.'); } str.append("f"); } return str; } namespace NCatboostModelExportHelpers { int GetBinaryFeatureCount(const TFullModel& model) { int binaryFeatureCount = 0; for (const auto& floatFeature : model.ModelTrees->GetFloatFeatures()) { if (!floatFeature.UsedInModel()) { continue; } binaryFeatureCount += floatFeature.Borders.size(); } return binaryFeatureCount; } TString OutputBorderCounts(const TFullModel& model) { return OutputArrayInitializer([&model] (size_t i) { return model.ModelTrees->GetFloatFeatures()[i].Borders.size(); }, model.ModelTrees->GetFloatFeatures().size()); } TString OutputBorders(const TFullModel& model, bool addFloatingSuffix) { TStringBuilder outString; TSequenceCommaSeparator comma(model.ModelTrees->GetFloatFeatures().size(), AddSpaceAfterComma); for (const auto& floatFeature : model.ModelTrees->GetFloatFeatures()) { if (!floatFeature.UsedInModel()) { continue; } outString << OutputArrayInitializer([&floatFeature, addFloatingSuffix] (size_t i) { return FloatToStringWithSuffix(floatFeature.Borders[i], addFloatingSuffix); }, floatFeature.Borders.size()) << comma; } return outString; } TString OutputLeafValues(const TFullModel& model, TIndent indent) { TStringBuilder outString; TSequenceCommaSeparator commaOuter(model.ModelTrees->GetTreeSizes().size()); ++indent; auto currentTreeFirstLeafPtr = model.ModelTrees->GetLeafValues().data(); for (const auto& treeSize : model.ModelTrees->GetTreeSizes()) { const auto treeLeafCount = (1uLL << treeSize) * model.ModelTrees->GetDimensionsCount(); outString << '\n' << indent; outString << OutputArrayInitializer([&currentTreeFirstLeafPtr] (size_t i) { return FloatToString(currentTreeFirstLeafPtr[i], PREC_NDIGITS, 16); }, treeLeafCount); outString << commaOuter; currentTreeFirstLeafPtr += treeLeafCount; } --indent; outString << '\n'; return outString; } }
41.16129
213
0.652821
mikiec84
ffa582936f230158ae857b11dd54dac8f154b20c
547
cpp
C++
src/wavetable.cpp
stephanepericat/sb-StochKit
767383b9eda7b61ea5c8187296c676dd4fcf94fa
[ "CC0-1.0" ]
16
2019-05-02T09:42:38.000Z
2022-01-28T02:08:44.000Z
src/wavetable.cpp
stephanepericat/sb-StochKit
767383b9eda7b61ea5c8187296c676dd4fcf94fa
[ "CC0-1.0" ]
4
2019-07-06T13:27:24.000Z
2022-01-27T19:11:10.000Z
src/wavetable.cpp
stephanepericat/sb-StochKit
767383b9eda7b61ea5c8187296c676dd4fcf94fa
[ "CC0-1.0" ]
2
2019-05-23T08:33:52.000Z
2019-07-07T16:56:02.000Z
/* * wavetable.cpp * Samuel Laing - 2019 * * just a few utility functions to be used by the GendyOscillator */ #include "wavetable.hpp" namespace rack { float wrap(float in, float lb, float ub) { float out = in; if (in > ub) out = lb; else if (in < lb) out = ub; return out; } float mirror(float in, float lb, float ub) { float out = in; if (in > ub) { out = out - (in - ub); } else if (in < lb) { out = out - (in - lb); } return out; } }
17.645161
65
0.499086
stephanepericat
ffa5f26ab8bc81d742f1f150d8e1b06714137991
3,019
cpp
C++
Codeforces/CF - 716E - Centeroid Decomposition.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
null
null
null
Codeforces/CF - 716E - Centeroid Decomposition.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
null
null
null
Codeforces/CF - 716E - Centeroid Decomposition.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include "ext/numeric" using namespace __gnu_cxx; using namespace std; typedef long long ll; const int N = 1e5 + 10, M = 2 * N; int tenInvPW[N]; int n,m; int phi(int x){//complexity sqrt(x) int res=x; for(int i=2;i<=x/i;i++) { if (x % i) continue; res -= res / i; while (!(x % i)) { x /= i; } } if(x>1) res-=res/x; return res; } struct Mul{ int m; Mul(int m):m(m){} int operator()(int a,int b){ return (a*1ll*b)%m; } }; int identity_element(const Mul&){ return 1; } int mod_inverse(int x,int m){//x base , m power return power(x,phi(m)-1,Mul(m)); } Mul mul(0); struct ADJ { int head[N], nxt[M],cost[M], to[M], ne, n; void addEdge(int u, int v,int c) { nxt[ne] = head[u]; to[ne] = v; cost[ne]=c; head[u] = ne++; } void addBiEdge(int u, int v,int c) { addEdge(u, v,c); addEdge(v, u,c); } void init(int n) { this->n = n; ne = 0; memset(head, -1, n * sizeof head[0]); } } adj; #define neig(u, v, e, a) for(int e=a.head[u],v;~e and (v=a.to[e],1);e=a.nxt[e]) int treeCentroid,sz[N],treeSz,minChild,deleted[N],delId; void calc_SZ(int u,int p){ sz[u]=1; int mx=0; neig(u,v,e,adj){ if(v==p or deleted[v]==delId) continue; calc_SZ(v,u); sz[u]+=sz[v]; mx=max(mx,sz[v]); } mx=max(mx,treeSz-sz[u]); if(mx<minChild) { minChild=mx; treeCentroid=u; } } int pre[N],Sz,suf[N],len[N]; void calc_paths(int u,int p,int prefix,int suffix,int len,int pw){ pre[Sz]=prefix,suf[Sz]=suffix; ::len[Sz++]=len; neig(u,v,e,adj){ if(v==p or deleted[v]==delId) continue; calc_paths(v,u,(prefix+mul(adj.cost[e],pw))%m,(mul(suffix,10)+adj.cost[e])%m,len+1,mul(pw,10)); } } ll solve(int u,int digit){ Sz=0; calc_paths(u,-1,digit%m,digit%m,digit!=0,(digit!=0)?10:1); unordered_map<int,int > mp; for (int i = 0; i < Sz; ++i) { mp[pre[i]]++; } ll ret=0; for (int i = 0; i < Sz; ++i) { ret+= mp[ mul(m-suf[i],tenInvPW[len[i]]) ]; } return ret; } ll decompose(int u){ ll ret=solve(u,0)-1; deleted[u]=delId; neig(u,v,e,adj) { if (deleted[v] == delId) continue; ret -= solve(v, adj.cost[e]); treeSz = minChild = sz[v]; calc_SZ(v,-1); calc_SZ(treeCentroid,-1); ret+=decompose(treeCentroid); } return ret; } ll centroid(){ treeSz=minChild=adj.n; delId++; calc_SZ(0,-1); calc_SZ(treeCentroid,-1); return decompose(treeCentroid); } int main(){ // freopen("in.txt","r",stdin); scanf("%d%d",&n,&m); int u,v,c; int tenInverse=mod_inverse(10,m); mul=Mul(m); adj.init(n); tenInvPW[0]=1; for (int i = 1; i < n; ++i) { tenInvPW[i]=mul(tenInvPW[i-1],tenInverse); scanf("%d%d%d",&u,&v,&c); adj.addBiEdge(u,v,c); } printf("%lld\n",centroid()); }
22.871212
103
0.516396
bishoy-magdy
ffa61ce10e9af108ca38ed7067f2a914f571e53a
22,001
hpp
C++
include/System/Net/HttpListenerRequest.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
23
2020-08-07T04:09:00.000Z
2022-03-31T22:10:29.000Z
include/System/Net/HttpListenerRequest.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
6
2021-09-29T23:47:31.000Z
2022-03-30T20:49:23.000Z
include/System/Net/HttpListenerRequest.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
17
2020-08-20T19:36:52.000Z
2022-03-30T18:28:24.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" #include "extern/beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Net namespace System::Net { // Forward declaring type: CookieCollection class CookieCollection; // Forward declaring type: WebHeaderCollection class WebHeaderCollection; // Forward declaring type: HttpListenerContext class HttpListenerContext; // Forward declaring type: IPEndPoint class IPEndPoint; } // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: Stream class Stream; } // Forward declaring namespace: System namespace System { // Forward declaring type: Version class Version; // Forward declaring type: Uri class Uri; } // Forward declaring namespace: System::Collections::Specialized namespace System::Collections::Specialized { // Forward declaring type: NameValueCollection class NameValueCollection; } // Completed forward declares // Type namespace: System.Net namespace System::Net { // Forward declaring type: HttpListenerRequest class HttpListenerRequest; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(System::Net::HttpListenerRequest); DEFINE_IL2CPP_ARG_TYPE(System::Net::HttpListenerRequest*, "System.Net", "HttpListenerRequest"); // Type namespace: System.Net namespace System::Net { // Size: 0x83 #pragma pack(push, 1) // Autogenerated type: System.Net.HttpListenerRequest // [TokenAttribute] Offset: FFFFFFFF class HttpListenerRequest : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // private System.String[] accept_types // Size: 0x8 // Offset: 0x10 ::ArrayW<::Il2CppString*> accept_types; // Field size check static_assert(sizeof(::ArrayW<::Il2CppString*>) == 0x8); // private System.Int64 content_length // Size: 0x8 // Offset: 0x18 int64_t content_length; // Field size check static_assert(sizeof(int64_t) == 0x8); // private System.Boolean cl_set // Size: 0x1 // Offset: 0x20 bool cl_set; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: cl_set and: cookies char __padding2[0x7] = {}; // private System.Net.CookieCollection cookies // Size: 0x8 // Offset: 0x28 System::Net::CookieCollection* cookies; // Field size check static_assert(sizeof(System::Net::CookieCollection*) == 0x8); // private System.Net.WebHeaderCollection headers // Size: 0x8 // Offset: 0x30 System::Net::WebHeaderCollection* headers; // Field size check static_assert(sizeof(System::Net::WebHeaderCollection*) == 0x8); // private System.String method // Size: 0x8 // Offset: 0x38 ::Il2CppString* method; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.IO.Stream input_stream // Size: 0x8 // Offset: 0x40 System::IO::Stream* input_stream; // Field size check static_assert(sizeof(System::IO::Stream*) == 0x8); // private System.Version version // Size: 0x8 // Offset: 0x48 System::Version* version; // Field size check static_assert(sizeof(System::Version*) == 0x8); // private System.Collections.Specialized.NameValueCollection query_string // Size: 0x8 // Offset: 0x50 System::Collections::Specialized::NameValueCollection* query_string; // Field size check static_assert(sizeof(System::Collections::Specialized::NameValueCollection*) == 0x8); // private System.String raw_url // Size: 0x8 // Offset: 0x58 ::Il2CppString* raw_url; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.Uri url // Size: 0x8 // Offset: 0x60 System::Uri* url; // Field size check static_assert(sizeof(System::Uri*) == 0x8); // private System.Uri referrer // Size: 0x8 // Offset: 0x68 System::Uri* referrer; // Field size check static_assert(sizeof(System::Uri*) == 0x8); // private System.String[] user_languages // Size: 0x8 // Offset: 0x70 ::ArrayW<::Il2CppString*> user_languages; // Field size check static_assert(sizeof(::ArrayW<::Il2CppString*>) == 0x8); // private System.Net.HttpListenerContext context // Size: 0x8 // Offset: 0x78 System::Net::HttpListenerContext* context; // Field size check static_assert(sizeof(System::Net::HttpListenerContext*) == 0x8); // private System.Boolean is_chunked // Size: 0x1 // Offset: 0x80 bool is_chunked; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean ka_set // Size: 0x1 // Offset: 0x81 bool ka_set; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean keep_alive // Size: 0x1 // Offset: 0x82 bool keep_alive; // Field size check static_assert(sizeof(bool) == 0x1); public: // Get static field: static private System.Byte[] _100continue static ::ArrayW<uint8_t> _get__100continue(); // Set static field: static private System.Byte[] _100continue static void _set__100continue(::ArrayW<uint8_t> value); // Get static field: static private System.Char[] separators static ::ArrayW<::Il2CppChar> _get_separators(); // Set static field: static private System.Char[] separators static void _set_separators(::ArrayW<::Il2CppChar> value); // Get instance field reference: private System.String[] accept_types ::ArrayW<::Il2CppString*>& dyn_accept_types(); // Get instance field reference: private System.Int64 content_length int64_t& dyn_content_length(); // Get instance field reference: private System.Boolean cl_set bool& dyn_cl_set(); // Get instance field reference: private System.Net.CookieCollection cookies System::Net::CookieCollection*& dyn_cookies(); // Get instance field reference: private System.Net.WebHeaderCollection headers System::Net::WebHeaderCollection*& dyn_headers(); // Get instance field reference: private System.String method ::Il2CppString*& dyn_method(); // Get instance field reference: private System.IO.Stream input_stream System::IO::Stream*& dyn_input_stream(); // Get instance field reference: private System.Version version System::Version*& dyn_version(); // Get instance field reference: private System.Collections.Specialized.NameValueCollection query_string System::Collections::Specialized::NameValueCollection*& dyn_query_string(); // Get instance field reference: private System.String raw_url ::Il2CppString*& dyn_raw_url(); // Get instance field reference: private System.Uri url System::Uri*& dyn_url(); // Get instance field reference: private System.Uri referrer System::Uri*& dyn_referrer(); // Get instance field reference: private System.String[] user_languages ::ArrayW<::Il2CppString*>& dyn_user_languages(); // Get instance field reference: private System.Net.HttpListenerContext context System::Net::HttpListenerContext*& dyn_context(); // Get instance field reference: private System.Boolean is_chunked bool& dyn_is_chunked(); // Get instance field reference: private System.Boolean ka_set bool& dyn_ka_set(); // Get instance field reference: private System.Boolean keep_alive bool& dyn_keep_alive(); // public System.Boolean get_HasEntityBody() // Offset: 0x1828C00 bool get_HasEntityBody(); // public System.Collections.Specialized.NameValueCollection get_Headers() // Offset: 0x1828CD8 System::Collections::Specialized::NameValueCollection* get_Headers(); // public System.IO.Stream get_InputStream() // Offset: 0x1828C24 System::IO::Stream* get_InputStream(); // public System.Boolean get_IsSecureConnection() // Offset: 0x1828AAC bool get_IsSecureConnection(); // public System.Boolean get_KeepAlive() // Offset: 0x18249DC bool get_KeepAlive(); // public System.Net.IPEndPoint get_LocalEndPoint() // Offset: 0x1828AD4 System::Net::IPEndPoint* get_LocalEndPoint(); // public System.Version get_ProtocolVersion() // Offset: 0x1828CE0 System::Version* get_ProtocolVersion(); // public System.Uri get_Url() // Offset: 0x1828CE8 System::Uri* get_Url(); // public System.String get_UserHostAddress() // Offset: 0x1828A88 ::Il2CppString* get_UserHostAddress(); // public System.String get_UserHostName() // Offset: 0x1828A2C ::Il2CppString* get_UserHostName(); // System.Void .ctor(System.Net.HttpListenerContext context) // Offset: 0x182784C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HttpListenerRequest* New_ctor(System::Net::HttpListenerContext* context) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::HttpListenerRequest::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HttpListenerRequest*, creationType>(context))); } // static private System.Void .cctor() // Offset: 0x1828CF0 static void _cctor(); // System.Void SetRequestLine(System.String req) // Offset: 0x18237DC void SetRequestLine(::Il2CppString* req); // private System.Void CreateQueryString(System.String query) // Offset: 0x1828594 void CreateQueryString(::Il2CppString* query); // static private System.Boolean MaybeUri(System.String s) // Offset: 0x18287EC static bool MaybeUri(::Il2CppString* s); // static private System.Boolean IsPredefinedScheme(System.String scheme) // Offset: 0x18288A4 static bool IsPredefinedScheme(::Il2CppString* scheme); // System.Void FinishInitialization() // Offset: 0x1822CB8 void FinishInitialization(); // static System.String Unquote(System.String str) // Offset: 0x1828B90 static ::Il2CppString* Unquote(::Il2CppString* str); // System.Void AddHeader(System.String header) // Offset: 0x1823AE0 void AddHeader(::Il2CppString* header); // System.Boolean FlushInput() // Offset: 0x1824B54 bool FlushInput(); }; // System.Net.HttpListenerRequest #pragma pack(pop) static check_size<sizeof(HttpListenerRequest), 130 + sizeof(bool)> __System_Net_HttpListenerRequestSizeCheck; static_assert(sizeof(HttpListenerRequest) == 0x83); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_HasEntityBody // Il2CppName: get_HasEntityBody template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_HasEntityBody)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_HasEntityBody", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_Headers // Il2CppName: get_Headers template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Specialized::NameValueCollection* (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_Headers)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_Headers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_InputStream // Il2CppName: get_InputStream template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IO::Stream* (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_InputStream)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_InputStream", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_IsSecureConnection // Il2CppName: get_IsSecureConnection template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_IsSecureConnection)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_IsSecureConnection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_KeepAlive // Il2CppName: get_KeepAlive template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_KeepAlive)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_KeepAlive", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_LocalEndPoint // Il2CppName: get_LocalEndPoint template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Net::IPEndPoint* (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_LocalEndPoint)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_LocalEndPoint", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_ProtocolVersion // Il2CppName: get_ProtocolVersion template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Version* (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_ProtocolVersion)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_ProtocolVersion", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_Url // Il2CppName: get_Url template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Uri* (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_Url)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_Url", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_UserHostAddress // Il2CppName: get_UserHostAddress template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_UserHostAddress)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_UserHostAddress", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::get_UserHostName // Il2CppName: get_UserHostName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::get_UserHostName)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "get_UserHostName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Net::HttpListenerRequest::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Net::HttpListenerRequest::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::SetRequestLine // Il2CppName: SetRequestLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Net::HttpListenerRequest::*)(::Il2CppString*)>(&System::Net::HttpListenerRequest::SetRequestLine)> { static const MethodInfo* get() { static auto* req = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "SetRequestLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{req}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::CreateQueryString // Il2CppName: CreateQueryString template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Net::HttpListenerRequest::*)(::Il2CppString*)>(&System::Net::HttpListenerRequest::CreateQueryString)> { static const MethodInfo* get() { static auto* query = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "CreateQueryString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{query}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::MaybeUri // Il2CppName: MaybeUri template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*)>(&System::Net::HttpListenerRequest::MaybeUri)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "MaybeUri", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::IsPredefinedScheme // Il2CppName: IsPredefinedScheme template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*)>(&System::Net::HttpListenerRequest::IsPredefinedScheme)> { static const MethodInfo* get() { static auto* scheme = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "IsPredefinedScheme", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{scheme}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::FinishInitialization // Il2CppName: FinishInitialization template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::FinishInitialization)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "FinishInitialization", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::Unquote // Il2CppName: Unquote template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (*)(::Il2CppString*)>(&System::Net::HttpListenerRequest::Unquote)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "Unquote", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::AddHeader // Il2CppName: AddHeader template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Net::HttpListenerRequest::*)(::Il2CppString*)>(&System::Net::HttpListenerRequest::AddHeader)> { static const MethodInfo* get() { static auto* header = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "AddHeader", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{header}); } }; // Writing MetadataGetter for method: System::Net::HttpListenerRequest::FlushInput // Il2CppName: FlushInput template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Net::HttpListenerRequest::*)()>(&System::Net::HttpListenerRequest::FlushInput)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::HttpListenerRequest*), "FlushInput", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
49.551802
216
0.714331
sc2ad
ffa808d49ac671afaa64ee62e09670694cad4b3e
890
cpp
C++
examples/layouts/qtvbox.cpp
sandsmark/qt1
e62eef42291be80065a7f824530aa42b79917a8d
[ "Xnet", "X11" ]
18
2018-02-16T16:57:26.000Z
2022-02-10T21:23:47.000Z
examples/layouts/qtvbox.cpp
sandsmark/qt1
e62eef42291be80065a7f824530aa42b79917a8d
[ "Xnet", "X11" ]
2
2018-08-12T12:46:38.000Z
2020-06-19T16:30:06.000Z
examples/layouts/qtvbox.cpp
sandsmark/qt1
e62eef42291be80065a7f824530aa42b79917a8d
[ "Xnet", "X11" ]
7
2018-06-22T01:17:58.000Z
2021-09-02T21:05:28.000Z
/**************************************************************************** ** $Id: qtvbox.cpp,v 1.3 1998/05/21 19:24:54 agulbra Exp $ ** ** Copyright (C) 1992-1998 Troll Tech AS. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *****************************************************************************/ #include "qtvbox.h" #include "qlayout.h" /*! \class QtVBox qvbox.h \brief The QtVBox widget performs geometry management on its children \ingroup geomanagement All its children will be placed vertically and sized according to their sizeHint()s. \sa QtVBox and QtHBox */ /*! Constructs a vbox widget with parent \a parent and name \a name */ QtVBox::QtVBox( QWidget *parent, const char *name, WFlags f ) :QtHBox( FALSE, parent, name, f ) { }
26.969697
78
0.578652
sandsmark
ffac724073668a2c90de89fb7ec654900e698e06
147,237
cpp
C++
src/runtime/objmodel.cpp
amyvmiwei/pyston
f074ed04f8f680316971513f5c42e9cf7d992e06
[ "Apache-2.0" ]
1
2015-11-06T03:39:51.000Z
2015-11-06T03:39:51.000Z
src/runtime/objmodel.cpp
amyvmiwei/pyston
f074ed04f8f680316971513f5c42e9cf7d992e06
[ "Apache-2.0" ]
null
null
null
src/runtime/objmodel.cpp
amyvmiwei/pyston
f074ed04f8f680316971513f5c42e9cf7d992e06
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2014 Dropbox, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "runtime/objmodel.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <memory> #include <stdint.h> #include "asm_writing/icinfo.h" #include "asm_writing/rewriter.h" #include "codegen/codegen.h" #include "codegen/compvars.h" #include "codegen/irgen/hooks.h" #include "codegen/llvm_interpreter.h" #include "codegen/parser.h" #include "codegen/type_recording.h" #include "core/ast.h" #include "core/options.h" #include "core/stats.h" #include "core/types.h" #include "gc/collector.h" #include "gc/heap.h" #include "runtime/capi.h" #include "runtime/classobj.h" #include "runtime/float.h" #include "runtime/generator.h" #include "runtime/iterobject.h" #include "runtime/types.h" #include "runtime/util.h" #define BOX_CLS_OFFSET ((char*)&(((Box*)0x01)->cls) - (char*)0x1) #define HCATTRS_HCLS_OFFSET ((char*)&(((HCAttrs*)0x01)->hcls) - (char*)0x1) #define HCATTRS_ATTRS_OFFSET ((char*)&(((HCAttrs*)0x01)->attr_list) - (char*)0x1) #define ATTRLIST_ATTRS_OFFSET ((char*)&(((HCAttrs::AttrList*)0x01)->attrs) - (char*)0x1) #define ATTRLIST_KIND_OFFSET ((char*)&(((HCAttrs::AttrList*)0x01)->gc_header.kind_id) - (char*)0x1) #define INSTANCEMETHOD_FUNC_OFFSET ((char*)&(((BoxedInstanceMethod*)0x01)->func) - (char*)0x1) #define INSTANCEMETHOD_OBJ_OFFSET ((char*)&(((BoxedInstanceMethod*)0x01)->obj) - (char*)0x1) #define BOOL_B_OFFSET ((char*)&(((BoxedBool*)0x01)->b) - (char*)0x1) #define INT_N_OFFSET ((char*)&(((BoxedInt*)0x01)->n) - (char*)0x1) namespace pyston { // TODO should centralize all of these: static const std::string _call_str("__call__"), _new_str("__new__"), _init_str("__init__"), _get_str("__get__"); static const std::string _getattr_str("__getattr__"); static const std::string _getattribute_str("__getattribute__"); struct GetattrRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; bool obj_hcls_guarded; GetattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()), obj_hcls_guarded(false) {} ~GetattrRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); } }; struct SetattrRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj, attrval; bool call_done_guarding; bool out_success; SetattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, RewriterVarUsage&& attrval, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), attrval(std::move(attrval)), call_done_guarding(call_done_guarding), out_success(false) {} ~SetattrRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); } }; struct DelattrRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj; bool call_done_guarding; bool out_success; DelattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), call_done_guarding(call_done_guarding), out_success(false) {} ~DelattrRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); } }; struct LenRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; LenRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {} ~LenRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); } }; struct CallRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj; RewriterVarUsage arg1, arg2, arg3, args; bool func_guarded; bool args_guarded; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; CallRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), arg1(RewriterVarUsage::empty()), arg2(RewriterVarUsage::empty()), arg3(RewriterVarUsage::empty()), args(RewriterVarUsage::empty()), func_guarded(false), args_guarded(false), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {} ~CallRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); arg1.ensureDoneUsing(); arg2.ensureDoneUsing(); arg3.ensureDoneUsing(); args.ensureDoneUsing(); } }; struct BinopRewriteArgs { Rewriter* rewriter; RewriterVarUsage lhs, rhs; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; BinopRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& lhs, RewriterVarUsage&& rhs, Location destination, bool call_done_guarding) : rewriter(rewriter), lhs(std::move(lhs)), rhs(std::move(rhs)), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {} ~BinopRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { lhs.ensureDoneUsing(); rhs.ensureDoneUsing(); } }; struct CompareRewriteArgs { Rewriter* rewriter; RewriterVarUsage lhs, rhs; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; CompareRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& lhs, RewriterVarUsage&& rhs, Location destination, bool call_done_guarding) : rewriter(rewriter), lhs(std::move(lhs)), rhs(std::move(rhs)), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {} ~CompareRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { lhs.ensureDoneUsing(); rhs.ensureDoneUsing(); } }; Box* runtimeCallInternal(Box* obj, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names); static Box* (*runtimeCallInternal0)(Box*, CallRewriteArgs*, ArgPassSpec) = (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec))runtimeCallInternal; static Box* (*runtimeCallInternal1)(Box*, CallRewriteArgs*, ArgPassSpec, Box*) = (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*))runtimeCallInternal; static Box* (*runtimeCallInternal2)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*) = (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*))runtimeCallInternal; static Box* (*runtimeCallInternal3)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*) = (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))runtimeCallInternal; static Box* (*typeCallInternal1)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*) = (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*))typeCallInternal; static Box* (*typeCallInternal2)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*, Box*) = (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*, Box*))typeCallInternal; static Box* (*typeCallInternal3)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*, Box*, Box*) = (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))typeCallInternal; bool checkClass(LookupScope scope) { return (scope & CLASS_ONLY) != 0; } bool checkInst(LookupScope scope) { return (scope & INST_ONLY) != 0; } static Box* (*callattrInternal0)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec) = (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec))callattrInternal; static Box* (*callattrInternal1)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*) = (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*))callattrInternal; static Box* (*callattrInternal2)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*) = (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*))callattrInternal; static Box* (*callattrInternal3)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*) = (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))callattrInternal; size_t PyHasher::operator()(Box* b) const { if (b->cls == str_cls) { std::hash<std::string> H; return H(static_cast<BoxedString*>(b)->s); } BoxedInt* i = hash(b); assert(sizeof(size_t) == sizeof(i->n)); size_t rtn = i->n; return rtn; } bool PyEq::operator()(Box* lhs, Box* rhs) const { if (lhs->cls == rhs->cls) { if (lhs->cls == str_cls) { return static_cast<BoxedString*>(lhs)->s == static_cast<BoxedString*>(rhs)->s; } } // TODO fix this Box* cmp = compareInternal(lhs, rhs, AST_TYPE::Eq, NULL); assert(cmp->cls == bool_cls); BoxedBool* b = static_cast<BoxedBool*>(cmp); bool rtn = b->b; return rtn; } bool PyLt::operator()(Box* lhs, Box* rhs) const { // TODO fix this Box* cmp = compareInternal(lhs, rhs, AST_TYPE::Lt, NULL); assert(cmp->cls == bool_cls); BoxedBool* b = static_cast<BoxedBool*>(cmp); bool rtn = b->b; return rtn; } extern "C" bool softspace(Box* b, bool newval) { assert(b); if (isSubclass(b->cls, file_cls)) { bool& ss = static_cast<BoxedFile*>(b)->softspace; bool r = ss; ss = newval; return r; } bool r; Box* gotten = b->getattr("softspace"); if (!gotten) { r = 0; } else { r = nonzero(gotten); } b->setattr("softspace", boxInt(newval), NULL); return r; } extern "C" void my_assert(bool b) { assert(b); } extern "C" bool isSubclass(BoxedClass* child, BoxedClass* parent) { // TODO the class is allowed to override this using __subclasscheck__ while (child) { if (child == parent) return true; child = child->base; } return false; } extern "C" void assertFail(BoxedModule* inModule, Box* msg) { if (msg) { BoxedString* tostr = str(msg); raiseExcHelper(AssertionError, "%s", tostr->s.c_str()); } else { raiseExcHelper(AssertionError, NULL); } } extern "C" void assertNameDefined(bool b, const char* name, BoxedClass* exc_cls, bool local_var_msg) { if (!b) { if (local_var_msg) raiseExcHelper(exc_cls, "local variable '%s' referenced before assignment", name); else raiseExcHelper(exc_cls, "name '%s' is not defined", name); } } extern "C" void raiseAttributeErrorStr(const char* typeName, const char* attr) { raiseExcHelper(AttributeError, "'%s' object has no attribute '%s'", typeName, attr); } extern "C" void raiseAttributeError(Box* obj, const char* attr) { if (obj->cls == type_cls) { // Slightly different error message: raiseExcHelper(AttributeError, "type object '%s' has no attribute '%s'", getNameOfClass(static_cast<BoxedClass*>(obj))->c_str(), attr); } else { raiseAttributeErrorStr(getTypeName(obj)->c_str(), attr); } } extern "C" void raiseNotIterableError(const char* typeName) { raiseExcHelper(TypeError, "'%s' object is not iterable", typeName); } static void _checkUnpackingLength(i64 expected, i64 given) { if (given == expected) return; if (given > expected) raiseExcHelper(ValueError, "too many values to unpack"); else { if (given == 1) raiseExcHelper(ValueError, "need more than %ld value to unpack", given); else raiseExcHelper(ValueError, "need more than %ld values to unpack", given); } } extern "C" Box** unpackIntoArray(Box* obj, int64_t expected_size) { assert(expected_size > 0); if (obj->cls == tuple_cls) { BoxedTuple* t = static_cast<BoxedTuple*>(obj); _checkUnpackingLength(expected_size, t->elts.size()); return &t->elts[0]; } if (obj->cls == list_cls) { BoxedList* l = static_cast<BoxedList*>(obj); _checkUnpackingLength(expected_size, l->size); return &l->elts->elts[0]; } BoxedTuple::GCVector elts; for (auto e : obj->pyElements()) { elts.push_back(e); if (elts.size() > expected_size) break; } _checkUnpackingLength(expected_size, elts.size()); return &elts[0]; } PyObject* Py_CallPythonNew(PyTypeObject* self, PyObject* args, PyObject* kwds) { try { Py_FatalError("this function is untested"); Box* new_attr = typeLookup(self, _new_str, NULL); assert(new_attr); new_attr = processDescriptor(new_attr, None, self); return runtimeCallInternal(new_attr, NULL, ArgPassSpec(1, 0, true, true), self, args, kwds, NULL, NULL); } catch (Box* e) { abort(); } } PyObject* Py_CallPythonCall(PyObject* self, PyObject* args, PyObject* kwds) { try { Py_FatalError("this function is untested"); return runtimeCallInternal(self, NULL, ArgPassSpec(0, 0, true, true), args, kwds, NULL, NULL, NULL); } catch (Box* e) { abort(); } } void BoxedClass::freeze() { assert(!is_constant); assert(getattr("__name__")); // otherwise debugging will be very hard // This will probably share a lot in common with Py_TypeReady: if (!tp_new) { this->tp_new = &Py_CallPythonNew; } else if (tp_new != Py_CallPythonNew) { ASSERT(0, "need to set __new__?"); } if (!tp_call) { this->tp_call = &Py_CallPythonCall; } else if (tp_call != Py_CallPythonCall) { ASSERT(0, "need to set __call__?"); } is_constant = true; } BoxedClass::BoxedClass(BoxedClass* metaclass, BoxedClass* base, gcvisit_func gc_visit, int attrs_offset, int instance_size, bool is_user_defined) : BoxVar(metaclass, 0), base(base), gc_visit(gc_visit), attrs_offset(attrs_offset), is_constant(false), is_user_defined(is_user_defined) { // Zero out the CPython tp_* slots: memset(&tp_name, 0, (char*)(&tp_version_tag + 1) - (char*)(&tp_name)); tp_basicsize = instance_size; if (metaclass == NULL) { assert(type_cls == NULL); } else { assert(isSubclass(metaclass, type_cls)); } assert(tp_dealloc == NULL); if (gc_visit == NULL) { assert(base); this->gc_visit = base->gc_visit; } assert(this->gc_visit); if (!base) { assert(object_cls == nullptr); // we're constructing 'object' // Will have to add __base__ = None later } else { assert(object_cls); if (base->attrs_offset) RELEASE_ASSERT(attrs_offset == base->attrs_offset, ""); assert(tp_basicsize >= base->tp_basicsize); } if (base && cls && str_cls) giveAttr("__base__", base); assert(tp_basicsize % sizeof(void*) == 0); // Not critical I suppose, but probably signals a bug if (attrs_offset) { assert(tp_basicsize >= attrs_offset + sizeof(HCAttrs)); assert(attrs_offset % sizeof(void*) == 0); // Not critical I suppose, but probably signals a bug } if (!is_user_defined) gc::registerPermanentRoot(this); } std::string getFullNameOfClass(BoxedClass* cls) { Box* b = cls->getattr("__name__"); assert(b); ASSERT(b->cls == str_cls, "%p", b->cls); BoxedString* name = static_cast<BoxedString*>(b); b = cls->getattr("__module__"); if (!b) return name->s; assert(b); if (b->cls != str_cls) return name->s; BoxedString* module = static_cast<BoxedString*>(b); return module->s + "." + name->s; } std::string getFullTypeName(Box* o) { return getFullNameOfClass(o->cls); } extern "C" const std::string* getNameOfClass(BoxedClass* cls) { Box* b = cls->getattr("__name__"); assert(b); ASSERT(b->cls == str_cls, "%p", b->cls); BoxedString* sb = static_cast<BoxedString*>(b); return &sb->s; } extern "C" const std::string* getTypeName(Box* o) { return getNameOfClass(o->cls); } HiddenClass* HiddenClass::getOrMakeChild(const std::string& attr) { std::unordered_map<std::string, HiddenClass*>::iterator it = children.find(attr); if (it != children.end()) return it->second; static StatCounter num_hclses("num_hidden_classes"); num_hclses.log(); HiddenClass* rtn = new HiddenClass(this); this->children[attr] = rtn; rtn->attr_offsets[attr] = attr_offsets.size(); return rtn; } /** * del attr from current HiddenClass, pertain the orders of remaining attrs */ HiddenClass* HiddenClass::delAttrToMakeHC(const std::string& attr) { int idx = getOffset(attr); assert(idx >= 0); std::vector<std::string> new_attrs(attr_offsets.size() - 1); for (auto it = attr_offsets.begin(); it != attr_offsets.end(); ++it) { if (it->second < idx) new_attrs[it->second] = it->first; else if (it->second > idx) { new_attrs[it->second - 1] = it->first; } } // TODO we can first locate the parent HiddenClass of the deleted // attribute and hence avoid creation of its ancestors. HiddenClass* cur = root_hcls; for (const auto& attr : new_attrs) { cur = cur->getOrMakeChild(attr); } return cur; } Box::Box(BoxedClass* cls) : cls(cls) { // if (TRACK_ALLOCATIONS) { // int id = Stats::getStatId("allocated_" + *getNameOfClass(c)); // Stats::log(id); //} // the only way cls should be NULL is if we're creating the type_cls // object itself: if (cls == NULL) { ASSERT(type_cls == NULL, "should pass a non-null cls here"); } else { } } HCAttrs* Box::getAttrsPtr() { assert(cls->instancesHaveAttrs()); char* p = reinterpret_cast<char*>(this); p += cls->attrs_offset; return reinterpret_cast<HCAttrs*>(p); } Box* Box::getattr(const std::string& attr, GetattrRewriteArgs* rewrite_args) { // Have to guard on the memory layout of this object. // Right now, guard on the specific Python-class, which in turn // specifies the C structure. // In the future, we could create another field (the flavor?) // that also specifies the structure and can include multiple // classes. // Only matters if we end up getting multiple classes with the same // structure (ex user class) and the same hidden classes, because // otherwise the guard will fail anyway.; if (rewrite_args) { rewrite_args->obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)cls); rewrite_args->out_success = true; } if (!cls->instancesHaveAttrs()) { if (rewrite_args) { rewrite_args->obj.setDoneUsing(); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); } return NULL; } HCAttrs* attrs = getAttrsPtr(); HiddenClass* hcls = attrs->hcls; if (rewrite_args) { if (!rewrite_args->obj_hcls_guarded) rewrite_args->obj.addAttrGuard(cls->attrs_offset + HCATTRS_HCLS_OFFSET, (intptr_t)hcls); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); } int offset = hcls->getOffset(attr); if (offset == -1) { if (rewrite_args) { rewrite_args->obj.setDoneUsing(); } return NULL; } if (rewrite_args) { // TODO using the output register as the temporary makes register allocation easier // since we don't need to clobber a register, but does it make the code slower? RewriterVarUsage attrs = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, RewriterVarUsage::Kill, Location::any()); rewrite_args->out_rtn = attrs.getAttr(offset * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, RewriterVarUsage::Kill, Location::any()); } Box* rtn = attrs->attr_list->attrs[offset]; return rtn; } void Box::setattr(const std::string& attr, Box* val, SetattrRewriteArgs* rewrite_args) { assert(cls->instancesHaveAttrs()); assert(gc::isValidGCObject(val)); // Have to guard on the memory layout of this object. // Right now, guard on the specific Python-class, which in turn // specifies the C structure. // In the future, we could create another field (the flavor?) // that also specifies the structure and can include multiple // classes. // Only matters if we end up getting multiple classes with the same // structure (ex user class) and the same hidden classes, because // otherwise the guard will fail anyway.; if (rewrite_args) rewrite_args->obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)cls); static const std::string none_str("None"); RELEASE_ASSERT(attr != none_str || this == builtins_module, "can't assign to None"); HCAttrs* attrs = getAttrsPtr(); HiddenClass* hcls = attrs->hcls; int numattrs = hcls->attr_offsets.size(); int offset = hcls->getOffset(attr); if (rewrite_args) { rewrite_args->obj.addAttrGuard(cls->attrs_offset + HCATTRS_HCLS_OFFSET, (intptr_t)hcls); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); // rewrite_args->rewriter->addDecision(offset == -1 ? 1 : 0); } if (offset >= 0) { assert(offset < numattrs); Box* prev = attrs->attr_list->attrs[offset]; attrs->attr_list->attrs[offset] = val; if (rewrite_args) { RewriterVarUsage r_hattrs = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, RewriterVarUsage::Kill, Location::any()); r_hattrs.setAttr(offset * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, std::move(rewrite_args->attrval)); r_hattrs.setDoneUsing(); rewrite_args->out_success = true; } return; } assert(offset == -1); HiddenClass* new_hcls = hcls->getOrMakeChild(attr); // TODO need to make sure we don't need to rearrange the attributes assert(new_hcls->attr_offsets[attr] == numattrs); #ifndef NDEBUG for (const auto& p : hcls->attr_offsets) { assert(new_hcls->attr_offsets[p.first] == p.second); } #endif RewriterVarUsage r_new_array2(RewriterVarUsage::empty()); int new_size = sizeof(HCAttrs::AttrList) + sizeof(Box*) * (numattrs + 1); if (numattrs == 0) { attrs->attr_list = (HCAttrs::AttrList*)gc_alloc(new_size, gc::GCKind::UNTRACKED); if (rewrite_args) { RewriterVarUsage r_newsize = rewrite_args->rewriter->loadConst(new_size, Location::forArg(0)); RewriterVarUsage r_kind = rewrite_args->rewriter->loadConst((int)gc::GCKind::UNTRACKED, Location::forArg(1)); r_new_array2 = rewrite_args->rewriter->call(false, (void*)gc::gc_alloc, std::move(r_newsize), std::move(r_kind)); } } else { attrs->attr_list = (HCAttrs::AttrList*)gc::gc_realloc(attrs->attr_list, new_size); if (rewrite_args) { RewriterVarUsage r_oldarray = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, RewriterVarUsage::NoKill, Location::forArg(0)); RewriterVarUsage r_newsize = rewrite_args->rewriter->loadConst(new_size, Location::forArg(1)); r_new_array2 = rewrite_args->rewriter->call(false, (void*)gc::gc_realloc, std::move(r_oldarray), std::move(r_newsize)); } } // Don't set the new hcls until after we do the allocation for the new attr_list; // that allocation can cause a collection, and we want the collector to always // see a consistent state between the hcls and the attr_list attrs->hcls = new_hcls; if (rewrite_args) { r_new_array2.setAttr(numattrs * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, std::move(rewrite_args->attrval)); rewrite_args->obj.setAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, std::move(r_new_array2)); RewriterVarUsage r_hcls = rewrite_args->rewriter->loadConst((intptr_t)new_hcls); rewrite_args->obj.setAttr(cls->attrs_offset + HCATTRS_HCLS_OFFSET, std::move(r_hcls)); rewrite_args->obj.setDoneUsing(); rewrite_args->out_success = true; } attrs->attr_list->attrs[numattrs] = val; } Box* typeLookup(BoxedClass* cls, const std::string& attr, GetattrRewriteArgs* rewrite_args) { Box* val; if (rewrite_args) { assert(!rewrite_args->out_success); RewriterVarUsage obj_saved = rewrite_args->obj.addUse(); bool call_done_guarding = rewrite_args->call_done_guarding; rewrite_args->call_done_guarding = false; val = cls->getattr(attr, rewrite_args); assert(rewrite_args->out_success); if (!val and cls->base) { rewrite_args->out_success = false; rewrite_args->obj = obj_saved.getAttr(offsetof(BoxedClass, base), RewriterVarUsage::Kill); val = typeLookup(cls->base, attr, rewrite_args); } else { obj_saved.setDoneUsing(); } if (call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); return val; } else { val = cls->getattr(attr, NULL); if (!val and cls->base) return typeLookup(cls->base, attr, NULL); return val; } } bool isNondataDescriptorInstanceSpecialCase(Box* descr) { return descr->cls == function_cls || descr->cls == method_cls; } Box* nondataDescriptorInstanceSpecialCases(GetattrRewriteArgs* rewrite_args, Box* obj, Box* descr, RewriterVarUsage& r_descr, bool for_call, bool* should_bind_out) { // Special case: non-data descriptor: function if (descr->cls == function_cls || descr->cls == method_cls) { if (!for_call) { if (rewrite_args) { // can't guard after because we make this call... the call is trivial enough // that we can probably work around it if it's important, but otherwise, if // this triggers, just abort rewriting, I guess assert(rewrite_args->call_done_guarding); rewrite_args->rewriter->setDoneGuarding(); rewrite_args->out_rtn = rewrite_args->rewriter->call(false, (void*)boxInstanceMethod, std::move(rewrite_args->obj), std::move(r_descr)); rewrite_args->out_success = true; } return boxInstanceMethod(obj, descr); } else { if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); rewrite_args->out_rtn = std::move(r_descr); rewrite_args->out_success = true; } *should_bind_out = true; return descr; } } return NULL; } Box* descriptorClsSpecialCases(GetattrRewriteArgs* rewrite_args, BoxedClass* cls, Box* descr, RewriterVarUsage& r_descr, bool for_call, bool* should_bind_out) { // Special case: functions if (descr->cls == function_cls || descr->cls == method_cls) { if (rewrite_args) r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls); if (!for_call && descr->cls == function_cls) { if (rewrite_args) { assert(rewrite_args->call_done_guarding); rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); // return an unbound instancemethod rewrite_args->out_rtn = rewrite_args->rewriter->call(false, (void*)boxUnboundInstanceMethod, std::move(r_descr)); rewrite_args->out_success = true; } return boxUnboundInstanceMethod(descr); } if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); rewrite_args->out_success = true; rewrite_args->out_rtn = std::move(r_descr); } // leave should_bind_out set to false return descr; } // Special case: member descriptor if (descr->cls == member_cls) { if (rewrite_args) r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls); if (rewrite_args) { assert(rewrite_args->call_done_guarding); rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); // Actually just return val (it's a descriptor but only // has special behaviour for instance lookups - see below) rewrite_args->out_rtn = std::move(r_descr); rewrite_args->out_success = true; } return descr; } return NULL; } Box* dataDescriptorInstanceSpecialCases(GetattrRewriteArgs* rewrite_args, Box* obj, Box* descr, RewriterVarUsage& r_descr, bool for_call, bool* should_bind_out) { // Special case: data descriptor: member descriptor if (descr->cls == member_cls) { BoxedMemberDescriptor* member_desc = static_cast<BoxedMemberDescriptor*>(descr); // TODO should also have logic to raise a type error if type of obj is wrong if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); r_descr.setDoneUsing(); } switch (member_desc->type) { case BoxedMemberDescriptor::OBJECT: { assert(member_desc->offset % sizeof(Box*) == 0); Box* rtn = reinterpret_cast<Box**>(obj)[member_desc->offset / sizeof(Box*)]; RELEASE_ASSERT(rtn, ""); if (rewrite_args) { rewrite_args->out_rtn = rewrite_args->obj.getAttr( member_desc->offset, RewriterVarUsage::KillFlag::Kill, rewrite_args->destination); rewrite_args->out_success = true; } return rtn; } case BoxedMemberDescriptor::BYTE: { // TODO rewriter stuff for these other cases as well rewrite_args = NULL; int8_t rtn = reinterpret_cast<int8_t*>(obj)[member_desc->offset]; return boxInt(rtn); } case BoxedMemberDescriptor::BOOL: { rewrite_args = NULL; bool rtn = reinterpret_cast<bool*>(obj)[member_desc->offset]; return boxBool(rtn); } case BoxedMemberDescriptor::INT: { rewrite_args = NULL; int rtn = reinterpret_cast<int*>(obj)[member_desc->offset / sizeof(int)]; return boxInt(rtn); } case BoxedMemberDescriptor::FLOAT: { rewrite_args = NULL; double rtn = reinterpret_cast<double*>(obj)[member_desc->offset / sizeof(double)]; return boxFloat(rtn); } default: RELEASE_ASSERT(0, "%d", member_desc->type); } } return NULL; } inline Box* getclsattr_internal(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args) { return getattrInternalGeneral(obj, attr, rewrite_args, /* cls_only */ true, /* for_call */ false, NULL); } extern "C" Box* getclsattr(Box* obj, const char* attr) { static StatCounter slowpath_getclsattr("slowpath_getclsattr"); slowpath_getclsattr.log(); Box* gotten; #if 0 std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, 1, "getclsattr")); if (rewriter.get()) { //rewriter->trap(); GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0)); gotten = getclsattr_internal(obj, attr, &rewrite_args, NULL); if (rewrite_args.out_success && gotten) { rewrite_args.out_rtn.move(-1); rewriter->commit(); } #else std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getclsattr")); if (rewriter.get()) { // rewriter->trap(); GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true); gotten = getclsattr_internal(obj, attr, &rewrite_args); if (rewrite_args.out_success && gotten) { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } #endif } else { gotten = getclsattr_internal(obj, attr, NULL); } RELEASE_ASSERT(gotten, "%s:%s", getTypeName(obj)->c_str(), attr); return gotten; } // Does a simple call of the descriptor's __get__ if it exists; // this function is useful for custom getattribute implementations that already know whether the descriptor // came from the class or not. Box* processDescriptorOrNull(Box* obj, Box* inst, Box* owner) { Box* descr_r = callattrInternal(obj, &_get_str, LookupScope::CLASS_ONLY, NULL, ArgPassSpec(2), inst, owner, NULL, NULL, NULL); return descr_r; } Box* processDescriptor(Box* obj, Box* inst, Box* owner) { Box* descr_r = processDescriptorOrNull(obj, inst, owner); if (descr_r) return descr_r; return obj; } static Box* (*runtimeCall0)(Box*, ArgPassSpec) = (Box * (*)(Box*, ArgPassSpec))runtimeCall; static Box* (*runtimeCall1)(Box*, ArgPassSpec, Box*) = (Box * (*)(Box*, ArgPassSpec, Box*))runtimeCall; static Box* (*runtimeCall2)(Box*, ArgPassSpec, Box*, Box*) = (Box * (*)(Box*, ArgPassSpec, Box*, Box*))runtimeCall; static Box* (*runtimeCall3)(Box*, ArgPassSpec, Box*, Box*, Box*) = (Box * (*)(Box*, ArgPassSpec, Box*, Box*, Box*))runtimeCall; Box* getattrInternalGeneral(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args, bool cls_only, bool for_call, bool* should_bind_out) { if (for_call) { *should_bind_out = false; } if (obj->cls == closure_cls) { Box* val = NULL; if (rewrite_args) { GetattrRewriteArgs hrewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), rewrite_args->destination, false); val = obj->getattr(attr, &hrewrite_args); if (!hrewrite_args.out_success) { rewrite_args = NULL; } else if (val) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->out_rtn = std::move(hrewrite_args.out_rtn); rewrite_args->out_success = true; rewrite_args->obj.setDoneUsing(); return val; } } else { val = obj->getattr(attr, NULL); if (val) { return val; } } // If val doesn't exist, then we move up to the parent closure // TODO closures should get their own treatment, but now just piggy-back on the // normal hidden-class IC logic. // Can do better since we don't need to guard on the cls (always going to be closure) BoxedClosure* closure = static_cast<BoxedClosure*>(obj); if (closure->parent) { if (rewrite_args) { rewrite_args->obj = rewrite_args->obj.getAttr(offsetof(BoxedClosure, parent), RewriterVarUsage::NoKill); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); } return getattrInternal(closure->parent, attr, rewrite_args); } raiseExcHelper(NameError, "free variable '%s' referenced before assignment in enclosing scope", attr.c_str()); } if (!cls_only) { // Don't need to pass icentry args, since we special-case __getattribtue__ and __getattr__ to use // invalidation rather than guards // TODO since you changed this to typeLookup you need to guard Box* getattribute = typeLookup(obj->cls, "__getattribute__", NULL); if (getattribute) { // TODO this is a good candidate for interning? Box* boxstr = boxString(attr); Box* rtn = runtimeCall2(getattribute, ArgPassSpec(2), obj, boxstr); return rtn; } if (rewrite_args) { rewrite_args->rewriter->addDependenceOn(obj->cls->dependent_icgetattrs); } } // Handle descriptor logic here. // A descriptor is either a data descriptor or a non-data descriptor. // data descriptors define both __get__ and __set__. non-data descriptors // only define __get__. Rules are different for the two types, which means // that even though __get__ is the one we might call, we still have to check // if __set__ exists. // If __set__ exists, it's a data descriptor, and it takes precedence over // the instance attribute. // Otherwise, it's non-data, and we only call __get__ if the instance // attribute doesn't exist. // In the cls_only case, we ignore the instance attribute // (so we don't have to check if __set__ exists at all) // Look up the class attribute (called `descr` here because it might // be a descriptor). Box* descr = NULL; RewriterVarUsage r_descr(RewriterVarUsage::empty()); if (rewrite_args) { RewriterVarUsage r_obj_cls = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_obj_cls), rewrite_args->destination, false); descr = typeLookup(obj->cls, attr, &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (descr) { r_descr = std::move(grewrite_args.out_rtn); } } else { descr = typeLookup(obj->cls, attr, NULL); } // Check if it's a data descriptor Box* _get_ = NULL; RewriterVarUsage r_get(RewriterVarUsage::empty()); if (descr) { if (rewrite_args) r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls); // Special-case data descriptors (e.g., member descriptors) Box* res = dataDescriptorInstanceSpecialCases(rewrite_args, obj, descr, r_descr, for_call, should_bind_out); if (res) { return res; } // Let's only check if __get__ exists if it's not a special case // nondata descriptor. The nondata case is handled below, but // we can immediately know to skip this part if it's one of the // special case nondata descriptors. if (!isNondataDescriptorInstanceSpecialCase(descr)) { // Check if __get__ exists if (rewrite_args) { RewriterVarUsage r_descr_cls = r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_descr_cls), Location::any(), false); _get_ = typeLookup(descr->cls, _get_str, &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (_get_) { r_get = std::move(grewrite_args.out_rtn); } } else { _get_ = typeLookup(descr->cls, _get_str, NULL); } // As an optimization, don't check for __set__ if we're in cls_only mode, since it won't matter. if (_get_ && !cls_only) { // Check if __set__ exists Box* _set_ = NULL; if (rewrite_args) { RewriterVarUsage r_descr_cls = r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_descr_cls), Location::any(), false); _set_ = typeLookup(descr->cls, "__set__", &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (_set_) { grewrite_args.out_rtn.setDoneUsing(); } } else { _set_ = typeLookup(descr->cls, "__set__", NULL); } // Call __get__(descr, obj, obj->cls) if (_set_) { // this could happen for the callattr path... if (rewrite_args && !rewrite_args->call_done_guarding) rewrite_args = NULL; Box* res; if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get), rewrite_args->destination, rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(r_descr); crewrite_args.arg2 = rewrite_args->obj.addUse(); crewrite_args.arg3 = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::Kill, Location::any()); res = runtimeCallInternal(_get_, &crewrite_args, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL); if (!crewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_success = true; rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } } else { r_descr.ensureDoneUsing(); r_get.ensureDoneUsing(); res = runtimeCallInternal(_get_, NULL, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL); } return res; } } } } if (!cls_only) { if (obj->cls != type_cls) { // Look up the val in the object's dictionary and if you find it, return it. Box* val; RewriterVarUsage r_val(RewriterVarUsage::empty()); if (rewrite_args) { GetattrRewriteArgs hrewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), rewrite_args->destination, false); val = obj->getattr(attr, &hrewrite_args); if (!hrewrite_args.out_success) { rewrite_args = NULL; } else if (val) { r_val = std::move(hrewrite_args.out_rtn); } } else { val = obj->getattr(attr, NULL); } if (val) { if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); rewrite_args->out_rtn = std::move(r_val); rewrite_args->out_success = true; } r_descr.ensureDoneUsing(); r_get.ensureDoneUsing(); return val; } } else { // More complicated when obj is a type // We have to look up the attr in the entire // class hierarchy, and we also have to check if it is a descriptor, // in addition to the data/nondata descriptor logic. // (in CPython, see type_getattro in typeobject.c) Box* val; RewriterVarUsage r_val(RewriterVarUsage::empty()); if (rewrite_args) { GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), rewrite_args->destination, false); val = typeLookup(static_cast<BoxedClass*>(obj), attr, &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (val) { r_val = std::move(grewrite_args.out_rtn); } } else { val = typeLookup(static_cast<BoxedClass*>(obj), attr, NULL); } if (val) { r_get.ensureDoneUsing(); r_descr.ensureDoneUsing(); Box* res = descriptorClsSpecialCases(rewrite_args, static_cast<BoxedClass*>(obj), val, r_val, for_call, should_bind_out); if (res) { return res; } // Lookup __get__ RewriterVarUsage r_get(RewriterVarUsage::empty()); Box* local_get; if (rewrite_args) { RewriterVarUsage r_val_cls = r_val.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_val_cls), Location::any(), false); local_get = typeLookup(val->cls, _get_str, &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (local_get) { r_get = std::move(grewrite_args.out_rtn); } } else { local_get = typeLookup(val->cls, _get_str, NULL); } // Call __get__(val, None, obj) if (local_get) { Box* res; // this could happen for the callattr path... if (rewrite_args && !rewrite_args->call_done_guarding) rewrite_args = NULL; if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get), rewrite_args->destination, rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(r_val); crewrite_args.arg2 = rewrite_args->rewriter->loadConst((intptr_t)None, Location::any()); crewrite_args.arg3 = std::move(rewrite_args->obj); res = runtimeCallInternal(local_get, &crewrite_args, ArgPassSpec(3), val, None, obj, NULL, NULL); if (!crewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_success = true; rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } } else { r_val.ensureDoneUsing(); r_get.ensureDoneUsing(); res = runtimeCallInternal(local_get, NULL, ArgPassSpec(3), val, None, obj, NULL, NULL); } return res; } // If there was no local __get__, just return val if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); rewrite_args->out_rtn = std::move(r_val); rewrite_args->out_success = true; } else { r_val.ensureDoneUsing(); } return val; } } } // If descr and __get__ exist, then call __get__ if (descr) { // Special cases first Box* res = nondataDescriptorInstanceSpecialCases(rewrite_args, obj, descr, r_descr, for_call, should_bind_out); if (res) { return res; } // We looked up __get__ above. If we found it, call it and return // the result. if (_get_) { // this could happen for the callattr path... if (rewrite_args && !rewrite_args->call_done_guarding) rewrite_args = NULL; Box* res; if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get), rewrite_args->destination, rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(r_descr); crewrite_args.arg2 = rewrite_args->obj.addUse(); crewrite_args.arg3 = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::Kill, Location::any()); res = runtimeCallInternal(_get_, &crewrite_args, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL); if (!crewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_success = true; rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } } else { r_descr.ensureDoneUsing(); r_get.ensureDoneUsing(); res = runtimeCallInternal(_get_, NULL, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL); } return res; } // Otherwise, just return descr. if (rewrite_args) { rewrite_args->obj.setDoneUsing(); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->out_rtn = std::move(r_descr); rewrite_args->out_success = true; } return descr; } // Finally, check __getattr__ if (!cls_only) { // Don't need to pass icentry args, since we special-case __getattribute__ and __getattr__ to use // invalidation rather than guards rewrite_args = NULL; Box* getattr = typeLookup(obj->cls, "__getattr__", NULL); if (getattr) { Box* boxstr = boxString(attr); Box* rtn = runtimeCall2(getattr, ArgPassSpec(2), obj, boxstr); if (rewrite_args) rewrite_args->out_rtn.ensureDoneUsing(); return rtn; } if (rewrite_args) { rewrite_args->rewriter->addDependenceOn(obj->cls->dependent_icgetattrs); } } if (rewrite_args) { rewrite_args->obj.ensureDoneUsing(); rewrite_args->out_success = true; } return NULL; } Box* getattrInternal(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args) { return getattrInternalGeneral(obj, attr, rewrite_args, /* cls_only */ false, /* for_call */ false, NULL); } extern "C" Box* getattr(Box* obj, const char* attr) { static StatCounter slowpath_getattr("slowpath_getattr"); slowpath_getattr.log(); if (VERBOSITY() >= 2) { #if !DISABLE_STATS std::string per_name_stat_name = "getattr__" + std::string(attr); int id = Stats::getStatId(per_name_stat_name); Stats::log(id); #endif } if (strcmp(attr, "__dict__") == 0) { if (obj->cls->instancesHaveAttrs()) return makeAttrWrapper(obj); } std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getattr")); Box* val; if (rewriter.get()) { Location dest; TypeRecorder* recorder = rewriter->getTypeRecorder(); if (recorder) dest = Location::forArg(1); else dest = rewriter->getReturnDestination(); GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), dest, true); val = getattrInternal(obj, attr, &rewrite_args); // should make sure getattrInternal calls finishes using obj itself // if it is successful if (!rewrite_args.out_success) rewrite_args.obj.ensureDoneUsing(); if (rewrite_args.out_success && val) { if (recorder) { RewriterVarUsage record_rtn = rewriter->call( false, (void*)recordType, rewriter->loadConst((intptr_t)recorder, Location::forArg(0)), std::move(rewrite_args.out_rtn)); rewriter->commitReturning(std::move(record_rtn)); recordType(recorder, val); } else { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } } else { val = getattrInternal(obj, attr, NULL); } if (val) { return val; } raiseAttributeError(obj, attr); } void setattrInternal(Box* obj, const std::string& attr, Box* val, SetattrRewriteArgs* rewrite_args) { assert(gc::isValidGCObject(val)); // Lookup a descriptor Box* descr = NULL; RewriterVarUsage r_descr(RewriterVarUsage::empty()); // TODO probably check that the cls is user-defined or something like that // (figure out exactly what) // (otherwise no need to check descriptor logic) if (rewrite_args) { RewriterVarUsage r_cls = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::KillFlag::NoKill, Location::any()); GetattrRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_cls), rewrite_args->rewriter->getReturnDestination(), false); descr = typeLookup(obj->cls, attr, &crewrite_args); if (!crewrite_args.out_success) { rewrite_args = NULL; } else if (descr) { r_descr = std::move(crewrite_args.out_rtn); } } else { descr = typeLookup(obj->cls, attr, NULL); } if (isSubclass(obj->cls, type_cls)) { BoxedClass* self = static_cast<BoxedClass*>(obj); if (attr == _getattr_str || attr == _getattribute_str) { // Will have to embed the clear in the IC, so just disable the patching for now: rewrite_args = NULL; // TODO should put this clearing behavior somewhere else, since there are probably more // cases in which we want to do it. self->dependent_icgetattrs.invalidateAll(); } if (attr == "__base__" && self->getattr("__base__")) raiseExcHelper(TypeError, "readonly attribute"); if (attr == "__new__") { self->tp_new = &Py_CallPythonNew; // TODO update subclasses rewrite_args = NULL; } if (attr == "__call__") { self->tp_call = &Py_CallPythonCall; // TODO update subclasses rewrite_args = NULL; } } Box* _set_ = NULL; RewriterVarUsage r_set(RewriterVarUsage::empty()); if (descr) { if (rewrite_args) { RewriterVarUsage r_cls = r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::KillFlag::NoKill, Location::any()); GetattrRewriteArgs trewrite_args(rewrite_args->rewriter, std::move(r_cls), Location::any(), false); _set_ = typeLookup(descr->cls, "__set__", &trewrite_args); if (!trewrite_args.out_success) { rewrite_args = NULL; } else if (_set_) { r_set = std::move(trewrite_args.out_rtn); } } else { _set_ = typeLookup(descr->cls, "__set__", NULL); } } // If `descr` has __set__ (thus making it a descriptor) we should call // __set__ with `val` rather than directly calling setattr if (descr && _set_) { if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_set), Location::any(), rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(r_descr); crewrite_args.arg2 = std::move(rewrite_args->obj); crewrite_args.arg3 = std::move(rewrite_args->attrval); runtimeCallInternal(_set_, &crewrite_args, ArgPassSpec(3), descr, obj, val, NULL, NULL); if (crewrite_args.out_success) { crewrite_args.out_rtn.setDoneUsing(); rewrite_args->out_success = true; } } else { runtimeCallInternal(_set_, NULL, ArgPassSpec(3), descr, obj, val, NULL, NULL); } } else { r_descr.ensureDoneUsing(); r_set.ensureDoneUsing(); obj->setattr(attr, val, rewrite_args); } } extern "C" void setattr(Box* obj, const char* attr, Box* attr_val) { assert(strcmp(attr, "__class__") != 0); static StatCounter slowpath_setattr("slowpath_setattr"); slowpath_setattr.log(); if (!obj->cls->instancesHaveAttrs()) { raiseAttributeError(obj, attr); } if (obj->cls == type_cls) { BoxedClass* cobj = static_cast<BoxedClass*>(obj); if (!isUserDefined(cobj)) { raiseExcHelper(TypeError, "can't set attributes of built-in/extension type '%s'", getNameOfClass(cobj)->c_str()); } } std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "setattr")); if (rewriter.get()) { // rewriter->trap(); SetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(2), true); setattrInternal(obj, attr, attr_val, &rewrite_args); if (rewrite_args.out_success) { rewriter->commit(); } else { rewrite_args.obj.ensureDoneUsing(); rewrite_args.attrval.ensureDoneUsing(); } } else { setattrInternal(obj, attr, attr_val, NULL); } } bool isUserDefined(BoxedClass* cls) { return cls->is_user_defined; // return cls->hasattrs && (cls != function_cls && cls != type_cls) && !cls->is_constant; } extern "C" bool nonzero(Box* obj) { static StatCounter slowpath_nonzero("slowpath_nonzero"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 1, "nonzero")); RewriterVarUsage r_obj(RewriterVarUsage::empty()); if (rewriter.get()) { r_obj = std::move(rewriter->getArg(0)); // rewriter->trap(); r_obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)obj->cls); rewriter->setDoneGuarding(); } if (obj->cls == bool_cls) { if (rewriter.get()) { RewriterVarUsage b = r_obj.getAttr(BOOL_B_OFFSET, RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination()); rewriter->commitReturning(std::move(b)); } BoxedBool* bool_obj = static_cast<BoxedBool*>(obj); return bool_obj->b; } else if (obj->cls == int_cls) { if (rewriter.get()) { // TODO should do: // test %rsi, %rsi // setne %al RewriterVarUsage n = r_obj.getAttr(INT_N_OFFSET, RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination()); RewriterVarUsage b = n.toBool(RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination()); rewriter->commitReturning(std::move(b)); } BoxedInt* int_obj = static_cast<BoxedInt*>(obj); return int_obj->n != 0; } else if (obj->cls == float_cls) { if (rewriter.get()) { RewriterVarUsage b = rewriter->call(false, (void*)floatNonzeroUnboxed, std::move(r_obj)); rewriter->commitReturning(std::move(b)); } return static_cast<BoxedFloat*>(obj)->d != 0; } else if (obj->cls == none_cls) { if (rewriter.get()) { r_obj.setDoneUsing(); RewriterVarUsage b = rewriter->loadConst(0, rewriter->getReturnDestination()); rewriter->commitReturning(std::move(b)); } return false; } if (rewriter.get()) { r_obj.setDoneUsing(); } // FIXME we have internal functions calling this method; // instead, we should break this out into an external and internal function. // slowpath_* counters are supposed to count external calls; putting it down // here gets a better representation of that. // TODO move internal callers to nonzeroInternal, and log *all* calls to nonzero slowpath_nonzero.log(); // int id = Stats::getStatId("slowpath_nonzero_" + *getTypeName(obj)); // Stats::log(id); // go through descriptor logic Box* func = getclsattr_internal(obj, "__nonzero__", NULL); if (func == NULL) { ASSERT(isUserDefined(obj->cls) || obj->cls == classobj_cls, "%s.__nonzero__", getTypeName(obj)->c_str()); // TODO return true; } Box* r = runtimeCall0(func, ArgPassSpec(0)); if (r->cls == bool_cls) { BoxedBool* b = static_cast<BoxedBool*>(r); bool rtn = b->b; return rtn; } else if (r->cls == int_cls) { BoxedInt* b = static_cast<BoxedInt*>(r); bool rtn = b->n != 0; return rtn; } else { raiseExcHelper(TypeError, "__nonzero__ should return bool or int, returned %s", getTypeName(r)->c_str()); } } extern "C" BoxedString* str(Box* obj) { static StatCounter slowpath_str("slowpath_str"); slowpath_str.log(); if (obj->cls != str_cls) { static const std::string str_str("__str__"); obj = callattrInternal(obj, &str_str, CLASS_ONLY, NULL, ArgPassSpec(0), NULL, NULL, NULL, NULL, NULL); } if (obj->cls != str_cls) { raiseExcHelper(TypeError, "__str__ did not return a string!"); } return static_cast<BoxedString*>(obj); } extern "C" BoxedString* repr(Box* obj) { static StatCounter slowpath_repr("slowpath_repr"); slowpath_repr.log(); static const std::string repr_str("__repr__"); obj = callattrInternal(obj, &repr_str, CLASS_ONLY, NULL, ArgPassSpec(0), NULL, NULL, NULL, NULL, NULL); if (obj->cls != str_cls) { raiseExcHelper(TypeError, "__repr__ did not return a string!"); } return static_cast<BoxedString*>(obj); } extern "C" BoxedString* reprOrNull(Box* obj) { try { Box* r = repr(obj); assert(r->cls == str_cls); // this should be checked by repr() return static_cast<BoxedString*>(r); } catch (Box* b) { return nullptr; } } extern "C" BoxedString* strOrNull(Box* obj) { try { BoxedString* r = str(obj); return static_cast<BoxedString*>(r); } catch (Box* b) { return nullptr; } } extern "C" bool isinstance(Box* obj, Box* cls, int64_t flags) { bool false_on_noncls = (flags & 0x1); if (cls->cls == tuple_cls) { auto t = static_cast<BoxedTuple*>(cls); for (auto c : t->elts) { if (isinstance(obj, c, flags)) return true; } return false; } if (cls->cls == classobj_cls) { if (!isSubclass(obj->cls, instance_cls)) return false; return instanceIsinstance(static_cast<BoxedInstance*>(obj), static_cast<BoxedClassobj*>(cls)); } if (!false_on_noncls) { assert(cls->cls == type_cls); } else { if (cls->cls != type_cls) return false; } BoxedClass* ccls = static_cast<BoxedClass*>(cls); // TODO the class is allowed to override this using __instancecheck__ return isSubclass(obj->cls, ccls); } extern "C" BoxedInt* hash(Box* obj) { static StatCounter slowpath_hash("slowpath_hash"); slowpath_hash.log(); // goes through descriptor logic Box* hash = getclsattr_internal(obj, "__hash__", NULL); if (hash == NULL) { ASSERT(isUserDefined(obj->cls), "%s.__hash__", getTypeName(obj)->c_str()); // TODO not the best way to handle this... return static_cast<BoxedInt*>(boxInt((i64)obj)); } Box* rtn = runtimeCall0(hash, ArgPassSpec(0)); if (rtn->cls != int_cls) { raiseExcHelper(TypeError, "an integer is required"); } return static_cast<BoxedInt*>(rtn); } extern "C" BoxedInt* lenInternal(Box* obj, LenRewriteArgs* rewrite_args) { Box* rtn; static std::string attr_str("__len__"); if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(rewrite_args->obj), rewrite_args->destination, rewrite_args->call_done_guarding); rtn = callattrInternal0(obj, &attr_str, CLASS_ONLY, &crewrite_args, ArgPassSpec(0)); if (!crewrite_args.out_success) rewrite_args = NULL; else if (rtn) rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } else { rtn = callattrInternal0(obj, &attr_str, CLASS_ONLY, NULL, ArgPassSpec(0)); } if (rtn == NULL) { raiseExcHelper(TypeError, "object of type '%s' has no len()", getTypeName(obj)->c_str()); } if (rtn->cls != int_cls) { raiseExcHelper(TypeError, "an integer is required"); } if (rewrite_args) rewrite_args->out_success = true; return static_cast<BoxedInt*>(rtn); } extern "C" BoxedInt* len(Box* obj) { static StatCounter slowpath_len("slowpath_len"); slowpath_len.log(); return lenInternal(obj, NULL); } extern "C" i64 unboxedLen(Box* obj) { static StatCounter slowpath_unboxedlen("slowpath_unboxedlen"); slowpath_unboxedlen.log(); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 1, "unboxedLen")); BoxedInt* lobj; RewriterVarUsage r_boxed(RewriterVarUsage::empty()); if (rewriter.get()) { // rewriter->trap(); LenRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true); lobj = lenInternal(obj, &rewrite_args); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else r_boxed = std::move(rewrite_args.out_rtn); } else { lobj = lenInternal(obj, NULL); } assert(lobj->cls == int_cls); i64 rtn = lobj->n; if (rewriter.get()) { RewriterVarUsage rtn = std::move(r_boxed.getAttr(INT_N_OFFSET, RewriterVarUsage::KillFlag::Kill, Location(assembler::RAX))); rewriter->commitReturning(std::move(rtn)); } return rtn; } extern "C" void dump(void* p) { printf("\n"); bool is_gc = (gc::global_heap.getAllocationFromInteriorPointer(p) != NULL); if (!is_gc) { printf("non-gc memory\n"); return; } gc::GCAllocation* al = gc::GCAllocation::fromUserData(p); if (al->kind_id == gc::GCKind::UNTRACKED) { printf("gc-untracked object\n"); return; } if (al->kind_id == gc::GCKind::CONSERVATIVE) { printf("conservatively-scanned object object\n"); return; } if (al->kind_id == gc::GCKind::PYTHON) { printf("Python object\n"); Box* b = (Box*)p; printf("Class: %s\n", getFullTypeName(b).c_str()); if (isSubclass(b->cls, type_cls)) { printf("Type name: %s\n", getFullNameOfClass(static_cast<BoxedClass*>(b)).c_str()); } if (isSubclass(b->cls, str_cls)) { printf("String value: %s\n", static_cast<BoxedString*>(b)->s.c_str()); } if (isSubclass(b->cls, tuple_cls)) { printf("%ld elements\n", static_cast<BoxedTuple*>(b)->elts.size()); } return; } RELEASE_ASSERT(0, "%d", (int)al->kind_id); } // For rewriting purposes, this function assumes that nargs will be constant. // That's probably fine for some uses (ex binops), but otherwise it should be guarded on beforehand. extern "C" Box* callattrInternal(Box* obj, const std::string* attr, LookupScope scope, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); if (rewrite_args && !rewrite_args->args_guarded) { // TODO duplication with runtime_call // TODO should know which args don't need to be guarded, ex if we're guaranteed that they // already fit, either since the type inferencer could determine that, // or because they only need to fit into an UNKNOWN slot. if (npassed_args >= 1) rewrite_args->arg1.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg1->cls); if (npassed_args >= 2) rewrite_args->arg2.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg2->cls); if (npassed_args >= 3) rewrite_args->arg3.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg3->cls); if (npassed_args > 3) { for (int i = 3; i < npassed_args; i++) { // TODO if there are a lot of args (>16), might be better to increment a pointer // rather index them directly? RewriterVarUsage v = rewrite_args->args.getAttr((i - 3) * sizeof(Box*), RewriterVarUsage::KillFlag::NoKill, Location::any()); v.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)args[i - 3]->cls); v.setDoneUsing(); } } } // right now I don't think this is ever called with INST_ONLY? assert(scope != INST_ONLY); // Look up the argument. Pass in the arguments to getattrInternalGeneral or getclsattr_general // that will shortcut functions by not putting them into instancemethods bool should_bind; Box* val; RewriterVarUsage r_val(RewriterVarUsage::empty()); if (rewrite_args) { GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), Location::any(), false); val = getattrInternalGeneral(obj, *attr, &grewrite_args, scope == CLASS_ONLY, true, &should_bind); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (val) { r_val = std::move(grewrite_args.out_rtn); } } else { val = getattrInternalGeneral(obj, *attr, NULL, scope == CLASS_ONLY, true, &should_bind); } if (val == NULL) { if (rewrite_args) { rewrite_args->arg1.ensureDoneUsing(); rewrite_args->arg2.ensureDoneUsing(); rewrite_args->arg3.ensureDoneUsing(); rewrite_args->args.ensureDoneUsing(); rewrite_args->out_success = true; rewrite_args->obj.setDoneUsing(); } return val; } if (should_bind) { if (rewrite_args) { r_val.addGuard((int64_t)val); } // TODO copy from runtimeCall // TODO these two branches could probably be folded together (the first one is becoming // a subset of the second) if (npassed_args <= 2) { Box* rtn; if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = std::move(rewrite_args->obj); // should be no-ops: if (npassed_args >= 1) srewrite_args.arg2 = std::move(rewrite_args->arg1); if (npassed_args >= 2) srewrite_args.arg3 = std::move(rewrite_args->arg2); srewrite_args.func_guarded = true; srewrite_args.args_guarded = true; rtn = runtimeCallInternal(val, &srewrite_args, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), obj, arg1, arg2, NULL, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { rtn = runtimeCallInternal(val, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), obj, arg1, arg2, NULL, keyword_names); } if (rewrite_args) rewrite_args->out_success = true; return rtn; } else { int alloca_size = sizeof(Box*) * (npassed_args + 1 - 3); Box** new_args = (Box**)alloca(alloca_size); new_args[0] = arg3; memcpy(new_args + 1, args, (npassed_args - 3) * sizeof(Box*)); Box* rtn; if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = std::move(rewrite_args->obj); srewrite_args.arg2 = std::move(rewrite_args->arg1); srewrite_args.arg3 = std::move(rewrite_args->arg2); srewrite_args.args = rewrite_args->rewriter->allocateAndCopyPlus1( std::move(rewrite_args->arg3), npassed_args == 3 ? RewriterVarUsage::empty() : std::move(rewrite_args->args), npassed_args - 3); srewrite_args.args_guarded = true; srewrite_args.func_guarded = true; rtn = runtimeCallInternal(val, &srewrite_args, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), obj, arg1, arg2, new_args, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); rewrite_args->out_success = true; } } else { rtn = runtimeCallInternal(val, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), obj, arg1, arg2, new_args, keyword_names); } return rtn; } } else { if (rewrite_args) { rewrite_args->obj.setDoneUsing(); } Box* rtn; if (val->cls != function_cls && val->cls != instancemethod_cls) { rewrite_args = NULL; r_val.ensureDoneUsing(); } if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination, rewrite_args->call_done_guarding); if (npassed_args >= 1) srewrite_args.arg1 = std::move(rewrite_args->arg1); if (npassed_args >= 2) srewrite_args.arg2 = std::move(rewrite_args->arg2); if (npassed_args >= 3) srewrite_args.arg3 = std::move(rewrite_args->arg3); if (npassed_args >= 4) srewrite_args.args = std::move(rewrite_args->args); srewrite_args.args_guarded = true; rtn = runtimeCallInternal(val, &srewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { rtn = runtimeCallInternal(val, NULL, argspec, arg1, arg2, arg3, args, keyword_names); } if (!rtn) { raiseExcHelper(TypeError, "'%s' object is not callable", getTypeName(val)->c_str()); } if (rewrite_args) rewrite_args->out_success = true; return rtn; } } extern "C" Box* callattr(Box* obj, const std::string* attr, bool clsonly, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); static StatCounter slowpath_callattr("slowpath_callattr"); slowpath_callattr.log(); assert(attr); int num_orig_args = 4 + std::min(4, npassed_args); if (argspec.num_keywords) num_orig_args++; std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter( __builtin_extract_return_addr(__builtin_return_address(0)), num_orig_args, "callattr")); Box* rtn; LookupScope scope = clsonly ? CLASS_ONLY : CLASS_OR_INST; if (rewriter.get()) { // TODO feel weird about doing this; it either isn't necessary // or this kind of thing is necessary in a lot more places // rewriter->getArg(3).addGuard(npassed_args); CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(), true); if (npassed_args >= 1) rewrite_args.arg1 = std::move(rewriter->getArg(4)); if (npassed_args >= 2) rewrite_args.arg2 = std::move(rewriter->getArg(5)); if (npassed_args >= 3) rewrite_args.arg3 = std::move(rewriter->getArg(6)); if (npassed_args >= 4) rewrite_args.args = std::move(rewriter->getArg(7)); rtn = callattrInternal(obj, attr, scope, &rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn) { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } else { rtn = callattrInternal(obj, attr, scope, NULL, argspec, arg1, arg2, arg3, args, keyword_names); } if (rtn == NULL) { raiseAttributeError(obj, attr->c_str()); } return rtn; } static inline Box*& getArg(int idx, Box*& arg1, Box*& arg2, Box*& arg3, Box** args) { if (idx == 0) return arg1; if (idx == 1) return arg2; if (idx == 2) return arg3; return args[idx - 3]; } static CompiledFunction* pickVersion(CLFunction* f, int num_output_args, Box* oarg1, Box* oarg2, Box* oarg3, Box** oargs) { LOCK_REGION(codegen_rwlock.asWrite()); CompiledFunction* chosen_cf = NULL; for (CompiledFunction* cf : f->versions) { assert(cf->spec->arg_types.size() == num_output_args); if (cf->spec->rtn_type->llvmType() != UNKNOWN->llvmType()) continue; bool works = true; for (int i = 0; i < num_output_args; i++) { Box* arg = getArg(i, oarg1, oarg2, oarg3, oargs); ConcreteCompilerType* t = cf->spec->arg_types[i]; if ((arg && !t->isFitBy(arg->cls)) || (!arg && t != UNKNOWN)) { works = false; break; } } if (!works) continue; chosen_cf = cf; break; } if (chosen_cf == NULL) { if (f->source == NULL) { // TODO I don't think this should be happening any more? printf("Error: couldn't find suitable function version and no source to recompile!\n"); abort(); } std::vector<ConcreteCompilerType*> arg_types; for (int i = 0; i < num_output_args; i++) { Box* arg = getArg(i, oarg1, oarg2, oarg3, oargs); assert(arg); // only builtin functions can pass NULL args arg_types.push_back(typeFromClass(arg->cls)); } FunctionSpecialization* spec = new FunctionSpecialization(UNKNOWN, arg_types); EffortLevel::EffortLevel new_effort = initialEffort(); // this also pushes the new CompiledVersion to the back of the version list: chosen_cf = compileFunction(f, spec, new_effort, NULL); } return chosen_cf; } static void placeKeyword(const std::vector<AST_expr*>& arg_names, std::vector<bool>& params_filled, const std::string& kw_name, Box* kw_val, Box*& oarg1, Box*& oarg2, Box*& oarg3, Box** oargs, BoxedDict* okwargs) { assert(kw_val); bool found = false; for (int j = 0; j < arg_names.size(); j++) { AST_expr* e = arg_names[j]; if (e->type != AST_TYPE::Name) continue; AST_Name* n = ast_cast<AST_Name>(e); if (n->id == kw_name) { if (params_filled[j]) { raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'", kw_name.c_str()); } getArg(j, oarg1, oarg2, oarg3, oargs) = kw_val; params_filled[j] = true; found = true; break; } } if (!found) { if (okwargs) { Box*& v = okwargs->d[boxString(kw_name)]; if (v) { raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'", kw_name.c_str()); } v = kw_val; } else { raiseExcHelper(TypeError, "<function>() got an unexpected keyword argument '%s'", kw_name.c_str()); } } } Box* callFunc(BoxedFunction* func, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { /* * Procedure: * - First match up positional arguments; any extra go to varargs. error if too many. * - Then apply keywords; any extra go to kwargs. error if too many. * - Use defaults to fill in any missing * - error about missing parameters */ static StatCounter slowpath_resolveclfunc("slowpath_callfunc"); slowpath_resolveclfunc.log(); CLFunction* f = func->f; FunctionList& versions = f->versions; int num_output_args = f->numReceivedArgs(); int num_passed_args = argspec.totalPassed(); BoxedClosure* closure = func->closure; if (argspec.has_starargs || argspec.has_kwargs || f->takes_kwargs || func->isGenerator) { rewrite_args = NULL; } // These could be handled: if (argspec.num_keywords) { rewrite_args = NULL; } // TODO Should we guard on the CLFunction or the BoxedFunction? // A single CLFunction could end up forming multiple BoxedFunctions, and we // could emit assembly that handles any of them. But doing this involves some // extra indirection, and it's not clear if that's worth it, since it seems like // the common case will be functions only ever getting a single set of default arguments. bool guard_clfunc = false; assert(!guard_clfunc && "I think there are users that expect the boxedfunction to be guarded"); if (rewrite_args) { assert(rewrite_args->args_guarded && "need to guard args here"); if (!rewrite_args->func_guarded) { if (guard_clfunc) { rewrite_args->obj.addAttrGuard(offsetof(BoxedFunction, f), (intptr_t)f); } else { rewrite_args->obj.addGuard((intptr_t)func); rewrite_args->obj.setDoneUsing(); } } else { rewrite_args->obj.setDoneUsing(); } if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); assert(rewrite_args->rewriter->isDoneGuarding()); // if (guard_clfunc) { // Have to save the defaults array since the object itself will probably get overwritten: // rewrite_args->obj = rewrite_args->obj.move(-2); // r_defaults_array = rewrite_args->obj.getAttr(offsetof(BoxedFunction, defaults), -2); //} } if (rewrite_args) { // We might have trouble if we have more output args than input args, // such as if we need more space to pass defaults. if (num_output_args > 3 && num_output_args > argspec.totalPassed()) { int arg_bytes_required = (num_output_args - 3) * sizeof(Box*); RewriterVarUsage new_args(RewriterVarUsage::empty()); if (rewrite_args->args.isDoneUsing()) { // rewrite_args->args could be empty if there are not more than // 3 input args. new_args = rewrite_args->rewriter->allocate(num_output_args - 3); } else { new_args = rewrite_args->rewriter->allocateAndCopy(std::move(rewrite_args->args), num_output_args - 3); } rewrite_args->args = std::move(new_args); } } std::vector<Box*> varargs; if (argspec.has_starargs) { Box* given_varargs = getArg(argspec.num_args + argspec.num_keywords, arg1, arg2, arg3, args); for (Box* e : given_varargs->pyElements()) { varargs.push_back(e); } } // The "output" args that we will pass to the called function: Box* oarg1 = NULL, * oarg2 = NULL, * oarg3 = NULL; Box** oargs = NULL; if (num_output_args > 3) { int size = (num_output_args - 3) * sizeof(Box*); oargs = (Box**)alloca(size); #ifndef NDEBUG memset(&oargs[0], 0, size); #endif } //// // First, match up positional parameters to positional/varargs: int positional_to_positional = std::min((int)argspec.num_args, f->num_args); for (int i = 0; i < positional_to_positional; i++) { getArg(i, oarg1, oarg2, oarg3, oargs) = getArg(i, arg1, arg2, arg3, args); // we already moved the positional args into position } int varargs_to_positional = std::min((int)varargs.size(), f->num_args - positional_to_positional); for (int i = 0; i < varargs_to_positional; i++) { assert(!rewrite_args && "would need to be handled here"); getArg(i + positional_to_positional, oarg1, oarg2, oarg3, oargs) = varargs[i]; } std::vector<bool> params_filled(num_output_args, false); for (int i = 0; i < positional_to_positional + varargs_to_positional; i++) { params_filled[i] = true; } std::vector<Box*, StlCompatAllocator<Box*> > unused_positional; for (int i = positional_to_positional; i < argspec.num_args; i++) { rewrite_args = NULL; unused_positional.push_back(getArg(i, arg1, arg2, arg3, args)); } for (int i = varargs_to_positional; i < varargs.size(); i++) { rewrite_args = NULL; unused_positional.push_back(varargs[i]); } if (f->takes_varargs) { int varargs_idx = f->num_args; if (rewrite_args) { assert(!unused_positional.size()); // rewrite_args->rewriter->loadConst((intptr_t)EmptyTuple, Location::forArg(varargs_idx)); RewriterVarUsage emptyTupleConst = rewrite_args->rewriter->loadConst( (intptr_t)EmptyTuple, varargs_idx < 3 ? Location::forArg(varargs_idx) : Location::any()); if (varargs_idx == 0) rewrite_args->arg1 = std::move(emptyTupleConst); if (varargs_idx == 1) rewrite_args->arg2 = std::move(emptyTupleConst); if (varargs_idx == 2) rewrite_args->arg3 = std::move(emptyTupleConst); if (varargs_idx >= 3) rewrite_args->args.setAttr((varargs_idx - 3) * sizeof(Box*), std::move(emptyTupleConst)); } Box* ovarargs = new BoxedTuple(std::move(unused_positional)); getArg(varargs_idx, oarg1, oarg2, oarg3, oargs) = ovarargs; } else if (unused_positional.size()) { raiseExcHelper(TypeError, "<function>() takes at most %d argument%s (%d given)", f->num_args, (f->num_args == 1 ? "" : "s"), argspec.num_args + argspec.num_keywords + varargs.size()); } //// // Second, apply any keywords: BoxedDict* okwargs = NULL; if (f->takes_kwargs) { assert(!rewrite_args && "would need to be handled here"); okwargs = new BoxedDict(); getArg(f->num_args + (f->takes_varargs ? 1 : 0), oarg1, oarg2, oarg3, oargs) = okwargs; } const std::vector<AST_expr*>* arg_names = f->source ? f->source->arg_names.args : NULL; if (arg_names == nullptr && argspec.num_keywords && !f->takes_kwargs) { raiseExcHelper(TypeError, "<function @%p>() doesn't take keyword arguments", f->versions[0]->code); } if (argspec.num_keywords) assert(argspec.num_keywords == keyword_names->size()); for (int i = 0; i < argspec.num_keywords; i++) { assert(!rewrite_args && "would need to be handled here"); int arg_idx = i + argspec.num_args; Box* kw_val = getArg(arg_idx, arg1, arg2, arg3, args); if (!arg_names) { assert(okwargs); okwargs->d[boxStringPtr((*keyword_names)[i])] = kw_val; continue; } assert(arg_names); placeKeyword(*arg_names, params_filled, *(*keyword_names)[i], kw_val, oarg1, oarg2, oarg3, oargs, okwargs); } if (argspec.has_kwargs) { assert(!rewrite_args && "would need to be handled here"); Box* kwargs = getArg(argspec.num_args + argspec.num_keywords + (argspec.has_starargs ? 1 : 0), arg1, arg2, arg3, args); RELEASE_ASSERT(kwargs->cls == dict_cls, "haven't implemented this for non-dicts"); BoxedDict* d_kwargs = static_cast<BoxedDict*>(kwargs); for (auto& p : d_kwargs->d) { if (p.first->cls != str_cls) raiseExcHelper(TypeError, "<function>() keywords must be strings"); BoxedString* s = static_cast<BoxedString*>(p.first); if (arg_names) { placeKeyword(*arg_names, params_filled, s->s, p.second, oarg1, oarg2, oarg3, oargs, okwargs); } else { assert(okwargs); Box*& v = okwargs->d[p.first]; if (v) { raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'", s->s.c_str()); } v = p.second; } } } // Fill with defaults: for (int i = 0; i < f->num_args - f->num_defaults; i++) { if (params_filled[i]) continue; // TODO not right error message raiseExcHelper(TypeError, "<function>() did not get a value for positional argument %d", i); } RewriterVarUsage r_defaults_array(RewriterVarUsage::empty()); if (guard_clfunc) { r_defaults_array = rewrite_args->obj.getAttr(offsetof(BoxedFunction, defaults), RewriterVarUsage::KillFlag::Kill, Location::any()); } for (int i = f->num_args - f->num_defaults; i < f->num_args; i++) { if (params_filled[i]) continue; int default_idx = i + f->num_defaults - f->num_args; Box* default_obj = func->defaults->elts[default_idx]; if (rewrite_args) { int offset = offsetof(std::remove_pointer<decltype(BoxedFunction::defaults)>::type, elts) + sizeof(Box*) * default_idx; if (guard_clfunc) { // If we just guarded on the CLFunction, then we have to emit assembly // to fetch the values from the defaults array: if (i < 3) { RewriterVarUsage r_default = r_defaults_array.getAttr(offset, RewriterVarUsage::KillFlag::NoKill, Location::forArg(i)); if (i == 0) rewrite_args->arg1 = std::move(r_default); if (i == 1) rewrite_args->arg2 = std::move(r_default); if (i == 2) rewrite_args->arg3 = std::move(r_default); } else { RewriterVarUsage r_default = r_defaults_array.getAttr(offset, RewriterVarUsage::KillFlag::Kill, Location::any()); rewrite_args->args.setAttr((i - 3) * sizeof(Box*), std::move(r_default)); } } else { // If we guarded on the BoxedFunction, which has a constant set of defaults, // we can embed the default arguments directly into the instructions. if (i < 3) { RewriterVarUsage r_default = rewrite_args->rewriter->loadConst((intptr_t)default_obj, Location::any()); if (i == 0) rewrite_args->arg1 = std::move(r_default); if (i == 1) rewrite_args->arg2 = std::move(r_default); if (i == 2) rewrite_args->arg3 = std::move(r_default); } else { RewriterVarUsage r_default = rewrite_args->rewriter->loadConst((intptr_t)default_obj, Location::any()); rewrite_args->args.setAttr((i - 3) * sizeof(Box*), std::move(r_default)); } } } getArg(i, oarg1, oarg2, oarg3, oargs) = default_obj; } // special handling for generators: // the call to function containing a yield should just create a new generator object. Box* res; if (func->isGenerator) { res = createGenerator(func, oarg1, oarg2, oarg3, oargs); } else { res = callCLFunc(f, rewrite_args, num_output_args, closure, NULL, oarg1, oarg2, oarg3, oargs); } return res; } Box* callCLFunc(CLFunction* f, CallRewriteArgs* rewrite_args, int num_output_args, BoxedClosure* closure, BoxedGenerator* generator, Box* oarg1, Box* oarg2, Box* oarg3, Box** oargs) { CompiledFunction* chosen_cf = pickVersion(f, num_output_args, oarg1, oarg2, oarg3, oargs); assert(chosen_cf->is_interpreted == (chosen_cf->code == NULL)); if (chosen_cf->is_interpreted) { return interpretFunction(chosen_cf->func, num_output_args, closure, generator, oarg1, oarg2, oarg3, oargs); } if (rewrite_args) { rewrite_args->rewriter->addDependenceOn(chosen_cf->dependent_callsites); std::vector<RewriterVarUsage> arg_vec; // TODO this kind of embedded reference needs to be tracked by the GC somehow? // Or maybe it's ok, since we've guarded on the function object? if (closure) arg_vec.push_back(std::move(rewrite_args->rewriter->loadConst((intptr_t)closure, Location::forArg(0)))); if (num_output_args >= 1) arg_vec.push_back(std::move(rewrite_args->arg1)); if (num_output_args >= 2) arg_vec.push_back(std::move(rewrite_args->arg2)); if (num_output_args >= 3) arg_vec.push_back(std::move(rewrite_args->arg3)); if (num_output_args >= 4) arg_vec.push_back(std::move(rewrite_args->args)); rewrite_args->out_rtn = rewrite_args->rewriter->call(true, (void*)chosen_cf->call, std::move(arg_vec)); rewrite_args->out_success = true; } if (closure && generator) return chosen_cf->closure_generator_call(closure, generator, oarg1, oarg2, oarg3, oargs); else if (closure) return chosen_cf->closure_call(closure, oarg1, oarg2, oarg3, oargs); else if (generator) return chosen_cf->generator_call(generator, oarg1, oarg2, oarg3, oargs); else return chosen_cf->call(oarg1, oarg2, oarg3, oargs); } Box* runtimeCallInternal(Box* obj, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); if (obj->cls != function_cls && obj->cls != instancemethod_cls) { Box* rtn; if (rewrite_args) { // TODO is this ok? // rewrite_args->rewriter->trap(); rtn = callattrInternal(obj, &_call_str, CLASS_ONLY, rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); } else { rtn = callattrInternal(obj, &_call_str, CLASS_ONLY, NULL, argspec, arg1, arg2, arg3, args, keyword_names); } if (!rtn) raiseExcHelper(TypeError, "'%s' object is not callable", getTypeName(obj)->c_str()); return rtn; } if (rewrite_args) { if (!rewrite_args->args_guarded) { // TODO should know which args don't need to be guarded, ex if we're guaranteed that they // already fit, either since the type inferencer could determine that, // or because they only need to fit into an UNKNOWN slot. if (npassed_args >= 1) rewrite_args->arg1.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg1->cls); if (npassed_args >= 2) rewrite_args->arg2.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg2->cls); if (npassed_args >= 3) rewrite_args->arg3.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg3->cls); for (int i = 3; i < npassed_args; i++) { RewriterVarUsage v = rewrite_args->args.getAttr((i - 3) * sizeof(Box*), RewriterVarUsage::KillFlag::NoKill, Location::any()); v.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)args[i - 3]->cls); v.setDoneUsing(); } rewrite_args->args_guarded = true; } rewrite_args->rewriter->addDecision(obj->cls == function_cls ? 1 : 0); } if (obj->cls == function_cls) { BoxedFunction* f = static_cast<BoxedFunction*>(obj); // Some functions are sufficiently important that we want them to be able to patchpoint themselves; // they can do this by setting the "internal_callable" field: CLFunction::InternalCallable callable = f->f->internal_callable; if (callable == NULL) { callable = callFunc; } Box* res = callable(f, rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); return res; } else if (obj->cls == instancemethod_cls) { // TODO it's dumb but I should implement patchpoints here as well // duplicated with callattr BoxedInstanceMethod* im = static_cast<BoxedInstanceMethod*>(obj); if (rewrite_args && !rewrite_args->func_guarded) { rewrite_args->obj.addAttrGuard(INSTANCEMETHOD_FUNC_OFFSET, (intptr_t)im->func); } // Guard on which type of instancemethod (bound or unbound) // That is, if im->obj is NULL, guard on it being NULL // otherwise, guard on it being non-NULL if (rewrite_args) { rewrite_args->obj.addAttrGuard(INSTANCEMETHOD_OBJ_OFFSET, 0, im->obj != NULL); } // TODO guard on im->obj being NULL or not if (im->obj == NULL) { Box* f = im->func; if (rewrite_args) { rewrite_args->func_guarded = true; rewrite_args->args_guarded = true; rewrite_args->obj = rewrite_args->obj.getAttr(INSTANCEMETHOD_FUNC_OFFSET, RewriterVarUsage::Kill, Location::any()); } Box* res = runtimeCallInternal(f, rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); return res; } if (npassed_args <= 2) { Box* rtn; if (rewrite_args) { // Kind of weird that we don't need to give this a valid RewriterVar, but it shouldn't need to access it // (since we've already guarded on the function). // rewriter enforce that we give it one, though CallRewriteArgs srewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = rewrite_args->obj.getAttr(INSTANCEMETHOD_OBJ_OFFSET, RewriterVarUsage::KillFlag::Kill, Location::any()); srewrite_args.func_guarded = true; srewrite_args.args_guarded = true; if (npassed_args >= 1) srewrite_args.arg2 = std::move(rewrite_args->arg1); if (npassed_args >= 2) srewrite_args.arg3 = std::move(rewrite_args->arg2); rtn = runtimeCallInternal( im->func, &srewrite_args, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), im->obj, arg1, arg2, NULL, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { rtn = runtimeCallInternal(im->func, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), im->obj, arg1, arg2, NULL, keyword_names); } if (rewrite_args) rewrite_args->out_success = true; return rtn; } else { Box** new_args = (Box**)alloca(sizeof(Box*) * (npassed_args + 1 - 3)); new_args[0] = arg3; memcpy(new_args + 1, args, (npassed_args - 3) * sizeof(Box*)); Box* rtn = runtimeCall(im->func, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), im->obj, arg1, arg2, new_args, keyword_names); return rtn; } } assert(0); abort(); } extern "C" Box* runtimeCall(Box* obj, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); static StatCounter slowpath_runtimecall("slowpath_runtimecall"); slowpath_runtimecall.log(); int num_orig_args = 2 + std::min(4, npassed_args); if (argspec.num_keywords > 0) { assert(argspec.num_keywords == keyword_names->size()); num_orig_args++; } std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter( __builtin_extract_return_addr(__builtin_return_address(0)), num_orig_args, "runtimeCall")); Box* rtn; if (rewriter.get()) { // TODO feel weird about doing this; it either isn't necessary // or this kind of thing is necessary in a lot more places // rewriter->getArg(1).addGuard(npassed_args); CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(), true); if (npassed_args >= 1) rewrite_args.arg1 = std::move(rewriter->getArg(2)); if (npassed_args >= 2) rewrite_args.arg2 = std::move(rewriter->getArg(3)); if (npassed_args >= 3) rewrite_args.arg3 = std::move(rewriter->getArg(4)); if (npassed_args >= 4) rewrite_args.args = std::move(rewriter->getArg(5)); rtn = runtimeCallInternal(obj, &rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn) { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } else { rtn = runtimeCallInternal(obj, NULL, argspec, arg1, arg2, arg3, args, keyword_names); } assert(rtn); return rtn; } extern "C" Box* binopInternal(Box* lhs, Box* rhs, int op_type, bool inplace, BinopRewriteArgs* rewrite_args) { // TODO handle the case of the rhs being a subclass of the lhs // this could get really annoying because you can dynamically make one type a subclass // of the other! if (rewrite_args) { // TODO probably don't need to guard on the lhs_cls since it // will get checked no matter what, but the check that should be // removed is probably the later one. // ie we should have some way of specifying what we know about the values // of objects and their attributes, and the attributes' attributes. rewrite_args->lhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)lhs->cls); rewrite_args->rhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)rhs->cls); } Box* irtn = NULL; if (inplace) { std::string iop_name = getInplaceOpName(op_type); if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, rewrite_args->lhs.addUse(), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = rewrite_args->rhs.addUse(); srewrite_args.args_guarded = true; irtn = callattrInternal1(lhs, &iop_name, CLASS_ONLY, &srewrite_args, ArgPassSpec(1), rhs); if (!srewrite_args.out_success) { rewrite_args = NULL; } else if (irtn) { if (irtn == NotImplemented) srewrite_args.out_rtn.ensureDoneUsing(); else rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { irtn = callattrInternal1(lhs, &iop_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs); } if (irtn) { if (irtn != NotImplemented) { if (rewrite_args) { rewrite_args->lhs.setDoneUsing(); rewrite_args->rhs.setDoneUsing(); rewrite_args->out_success = true; } return irtn; } } } const std::string& op_name = getOpName(op_type); Box* lrtn; if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(rewrite_args->lhs), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = std::move(rewrite_args->rhs); lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, &srewrite_args, ArgPassSpec(1), rhs); if (!srewrite_args.out_success) rewrite_args = NULL; else if (lrtn) { if (lrtn == NotImplemented) srewrite_args.out_rtn.ensureDoneUsing(); else rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs); } if (lrtn) { if (lrtn != NotImplemented) { if (rewrite_args) { rewrite_args->out_success = true; } return lrtn; } } // TODO patch these cases if (rewrite_args) { assert(rewrite_args->out_success == false); rewrite_args = NULL; } std::string rop_name = getReverseOpName(op_type); Box* rrtn = callattrInternal1(rhs, &rop_name, CLASS_ONLY, NULL, ArgPassSpec(1), lhs); if (rrtn != NULL && rrtn != NotImplemented) return rrtn; llvm::StringRef op_sym = getOpSymbol(op_type); const char* op_sym_suffix = ""; if (inplace) { op_sym_suffix = "="; } if (VERBOSITY()) { if (inplace) { std::string iop_name = getInplaceOpName(op_type); if (irtn) fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(lhs)->c_str(), iop_name.c_str()); else fprintf(stderr, "%s does not have %s\n", getTypeName(lhs)->c_str(), iop_name.c_str()); } if (lrtn) fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(lhs)->c_str(), op_name.c_str()); else fprintf(stderr, "%s does not have %s\n", getTypeName(lhs)->c_str(), op_name.c_str()); if (rrtn) fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(rhs)->c_str(), rop_name.c_str()); else fprintf(stderr, "%s does not have %s\n", getTypeName(rhs)->c_str(), rop_name.c_str()); } raiseExcHelper(TypeError, "unsupported operand type(s) for %s%s: '%s' and '%s'", op_sym.data(), op_sym_suffix, getTypeName(lhs)->c_str(), getTypeName(rhs)->c_str()); } extern "C" Box* binop(Box* lhs, Box* rhs, int op_type) { static StatCounter slowpath_binop("slowpath_binop"); slowpath_binop.log(); // static StatCounter nopatch_binop("nopatch_binop"); // int id = Stats::getStatId("slowpath_binop_" + *getTypeName(lhs) + op_name + *getTypeName(rhs)); // Stats::log(id); std::unique_ptr<Rewriter> rewriter((Rewriter*)NULL); // Currently can't patchpoint user-defined binops since we can't assume that just because // resolving it one way right now (ex, using the value from lhs.__add__) means that later // we'll resolve it the same way, even for the same argument types. // TODO implement full resolving semantics inside the rewrite? bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls); if (can_patchpoint) rewriter.reset( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "binop")); Box* rtn; if (rewriter.get()) { // rewriter->trap(); BinopRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(1), rewriter->getReturnDestination(), true); rtn = binopInternal(lhs, rhs, op_type, false, &rewrite_args); assert(rtn); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } else { rtn = binopInternal(lhs, rhs, op_type, false, NULL); } return rtn; } extern "C" Box* augbinop(Box* lhs, Box* rhs, int op_type) { static StatCounter slowpath_binop("slowpath_binop"); slowpath_binop.log(); // static StatCounter nopatch_binop("nopatch_binop"); // int id = Stats::getStatId("slowpath_binop_" + *getTypeName(lhs) + op_name + *getTypeName(rhs)); // Stats::log(id); std::unique_ptr<Rewriter> rewriter((Rewriter*)NULL); // Currently can't patchpoint user-defined binops since we can't assume that just because // resolving it one way right now (ex, using the value from lhs.__add__) means that later // we'll resolve it the same way, even for the same argument types. // TODO implement full resolving semantics inside the rewrite? bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls); if (can_patchpoint) rewriter.reset( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "binop")); Box* rtn; if (rewriter.get()) { BinopRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(1), rewriter->getReturnDestination(), true); rtn = binopInternal(lhs, rhs, op_type, true, &rewrite_args); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } else { rtn = binopInternal(lhs, rhs, op_type, true, NULL); } return rtn; } Box* compareInternal(Box* lhs, Box* rhs, int op_type, CompareRewriteArgs* rewrite_args) { if (op_type == AST_TYPE::Is || op_type == AST_TYPE::IsNot) { bool neg = (op_type == AST_TYPE::IsNot); if (rewrite_args) { rewrite_args->rewriter->setDoneGuarding(); RewriterVarUsage cmpres = rewrite_args->lhs.cmp(neg ? AST_TYPE::NotEq : AST_TYPE::Eq, std::move(rewrite_args->rhs), rewrite_args->destination); rewrite_args->lhs.setDoneUsing(); rewrite_args->out_rtn = rewrite_args->rewriter->call(false, (void*)boxBool, std::move(cmpres)); rewrite_args->out_success = true; } return boxBool((lhs == rhs) ^ neg); } if (op_type == AST_TYPE::In || op_type == AST_TYPE::NotIn) { // TODO do rewrite static const std::string str_contains("__contains__"); Box* contained = callattrInternal1(rhs, &str_contains, CLASS_ONLY, NULL, ArgPassSpec(1), lhs); if (contained == NULL) { static const std::string str_iter("__iter__"); Box* iter = callattrInternal0(rhs, &str_iter, CLASS_ONLY, NULL, ArgPassSpec(0)); if (iter) ASSERT(isUserDefined(rhs->cls), "%s should probably have a __contains__", getTypeName(rhs)->c_str()); RELEASE_ASSERT(iter == NULL, "need to try iterating"); Box* getitem = typeLookup(rhs->cls, "__getitem__", NULL); if (getitem) ASSERT(isUserDefined(rhs->cls), "%s should probably have a __contains__", getTypeName(rhs)->c_str()); RELEASE_ASSERT(getitem == NULL, "need to try old iteration protocol"); raiseExcHelper(TypeError, "argument of type '%s' is not iterable", getTypeName(rhs)->c_str()); } bool b = nonzero(contained); if (op_type == AST_TYPE::NotIn) return boxBool(!b); return boxBool(b); } // Can do the guard checks after the Is/IsNot handling, since that is // irrespective of the object classes if (rewrite_args) { // TODO probably don't need to guard on the lhs_cls since it // will get checked no matter what, but the check that should be // removed is probably the later one. // ie we should have some way of specifying what we know about the values // of objects and their attributes, and the attributes' attributes. rewrite_args->lhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)lhs->cls); rewrite_args->rhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)rhs->cls); } const std::string& op_name = getOpName(op_type); Box* lrtn; if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(rewrite_args->lhs), rewrite_args->destination, rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(rewrite_args->rhs); lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, &crewrite_args, ArgPassSpec(1), rhs); if (!crewrite_args.out_success) rewrite_args = NULL; else if (lrtn) rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } else { lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs); } if (lrtn) { if (lrtn != NotImplemented) { bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls); if (rewrite_args) { if (can_patchpoint) { rewrite_args->out_success = true; } else { rewrite_args->out_rtn.ensureDoneUsing(); } } return lrtn; } } // TODO patch these cases if (rewrite_args) { rewrite_args->out_rtn.ensureDoneUsing(); assert(rewrite_args->out_success == false); rewrite_args = NULL; } std::string rop_name = getReverseOpName(op_type); Box* rrtn = callattrInternal1(rhs, &rop_name, CLASS_ONLY, NULL, ArgPassSpec(1), lhs); if (rrtn != NULL && rrtn != NotImplemented) return rrtn; if (op_type == AST_TYPE::Eq) return boxBool(lhs == rhs); if (op_type == AST_TYPE::NotEq) return boxBool(lhs != rhs); #ifndef NDEBUG if ((lhs->cls == int_cls || lhs->cls == float_cls || lhs->cls == long_cls) && (rhs->cls == int_cls || rhs->cls == float_cls || rhs->cls == long_cls)) { Py_FatalError("missing comparison between these classes"); } #endif // TODO // According to http://docs.python.org/2/library/stdtypes.html#comparisons // CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects // of the same types that don’t support proper comparison are ordered by their address. if (op_type == AST_TYPE::Gt || op_type == AST_TYPE::GtE || op_type == AST_TYPE::Lt || op_type == AST_TYPE::LtE) { intptr_t cmp1, cmp2; if (lhs->cls == rhs->cls) { cmp1 = (intptr_t)lhs; cmp2 = (intptr_t)rhs; } else { // This isn't really necessary, but try to make sure that numbers get sorted first if (lhs->cls == int_cls || lhs->cls == float_cls) cmp1 = 0; else cmp1 = (intptr_t)lhs->cls; if (rhs->cls == int_cls || rhs->cls == float_cls) cmp2 = 0; else cmp2 = (intptr_t)rhs->cls; } if (op_type == AST_TYPE::Gt) return boxBool(cmp1 > cmp2); if (op_type == AST_TYPE::GtE) return boxBool(cmp1 >= cmp2); if (op_type == AST_TYPE::Lt) return boxBool(cmp1 < cmp2); if (op_type == AST_TYPE::LtE) return boxBool(cmp1 <= cmp2); } RELEASE_ASSERT(0, "%d", op_type); } extern "C" Box* compare(Box* lhs, Box* rhs, int op_type) { static StatCounter slowpath_compare("slowpath_compare"); slowpath_compare.log(); static StatCounter nopatch_compare("nopatch_compare"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "compare")); Box* rtn; if (rewriter.get()) { // rewriter->trap(); CompareRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), std::move(rewriter->getArg(1)), rewriter->getReturnDestination(), true); rtn = compareInternal(lhs, rhs, op_type, &rewrite_args); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } else { rtn = compareInternal(lhs, rhs, op_type, NULL); } return rtn; } extern "C" Box* unaryop(Box* operand, int op_type) { static StatCounter slowpath_unaryop("slowpath_unaryop"); slowpath_unaryop.log(); const std::string& op_name = getOpName(op_type); Box* attr_func = getclsattr_internal(operand, op_name, NULL); ASSERT(attr_func, "%s.%s", getTypeName(operand)->c_str(), op_name.c_str()); Box* rtn = runtimeCall0(attr_func, ArgPassSpec(0)); return rtn; } extern "C" Box* getitem(Box* value, Box* slice) { // This possibly could just be represented as a single callattr; the only tricky part // are the error messages. // Ex "(1)[1]" and "(1).__getitem__(1)" give different error messages. static StatCounter slowpath_getitem("slowpath_getitem"); slowpath_getitem.log(); static std::string str_getitem("__getitem__"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getitem")); Box* rtn; if (rewriter.get()) { CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(), true); rewrite_args.arg1 = std::move(rewriter->getArg(1)); rtn = callattrInternal1(value, &str_getitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(1), slice); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn) rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } else { rtn = callattrInternal1(value, &str_getitem, CLASS_ONLY, NULL, ArgPassSpec(1), slice); } if (rtn == NULL) { // different versions of python give different error messages for this: if (PYTHON_VERSION_MAJOR == 2 && PYTHON_VERSION_MINOR < 7) { raiseExcHelper(TypeError, "'%s' object is unsubscriptable", getTypeName(value)->c_str()); // tested on 2.6.6 } else if (PYTHON_VERSION_MAJOR == 2 && PYTHON_VERSION_MINOR == 7 && PYTHON_VERSION_MICRO < 3) { raiseExcHelper(TypeError, "'%s' object is not subscriptable", getTypeName(value)->c_str()); // tested on 2.7.1 } else { // Changed to this in 2.7.3: raiseExcHelper(TypeError, "'%s' object has no attribute '__getitem__'", getTypeName(value)->c_str()); // tested on 2.7.3 } } return rtn; } // target[slice] = value extern "C" void setitem(Box* target, Box* slice, Box* value) { static StatCounter slowpath_setitem("slowpath_setitem"); slowpath_setitem.log(); static std::string str_setitem("__setitem__"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "setitem")); Box* rtn; if (rewriter.get()) { CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(), true); rewrite_args.arg1 = std::move(rewriter->getArg(1)); rewrite_args.arg2 = std::move(rewriter->getArg(2)); rtn = callattrInternal2(target, &str_setitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(2), slice, value); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn) rewrite_args.out_rtn.setDoneUsing(); } else { rtn = callattrInternal2(target, &str_setitem, CLASS_ONLY, NULL, ArgPassSpec(2), slice, value); } if (rtn == NULL) { raiseExcHelper(TypeError, "'%s' object does not support item assignment", getTypeName(target)->c_str()); } if (rewriter.get()) { rewriter->commit(); } } // del target[start:end:step] extern "C" void delitem(Box* target, Box* slice) { static StatCounter slowpath_delitem("slowpath_delitem"); slowpath_delitem.log(); static std::string str_delitem("__delitem__"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "delitem")); Box* rtn; if (rewriter.get()) { CallRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true); rewrite_args.arg1 = std::move(rewriter->getArg(1)); rtn = callattrInternal1(target, &str_delitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(1), slice); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn != NULL) { rewrite_args.out_rtn.setDoneUsing(); } } else { rtn = callattrInternal1(target, &str_delitem, CLASS_ONLY, NULL, ArgPassSpec(1), slice); } if (rtn == NULL) { raiseExcHelper(TypeError, "'%s' object does not support item deletion", getTypeName(target)->c_str()); } if (rewriter.get()) { rewriter->commit(); } } void Box::delattr(const std::string& attr, DelattrRewriteArgs* rewrite_args) { // as soon as the hcls changes, the guard on hidden class won't pass. HCAttrs* attrs = getAttrsPtr(); HiddenClass* hcls = attrs->hcls; HiddenClass* new_hcls = hcls->delAttrToMakeHC(attr); // The order of attributes is pertained as delAttrToMakeHC constructs // the new HiddenClass by invoking getOrMakeChild in the prevous order // of remaining attributes int num_attrs = hcls->attr_offsets.size(); int offset = hcls->getOffset(attr); assert(offset >= 0); Box** start = attrs->attr_list->attrs; memmove(start + offset, start + offset + 1, (num_attrs - offset - 1) * sizeof(Box*)); attrs->hcls = new_hcls; // guarantee the size of the attr_list equals the number of attrs int new_size = sizeof(HCAttrs::AttrList) + sizeof(Box*) * (num_attrs - 1); attrs->attr_list = (HCAttrs::AttrList*)gc::gc_realloc(attrs->attr_list, new_size); } extern "C" void delattr_internal(Box* obj, const std::string& attr, bool allow_custom, DelattrRewriteArgs* rewrite_args) { static const std::string delattr_str("__delattr__"); static const std::string delete_str("__delete__"); // custom __delattr__ if (allow_custom) { Box* delAttr = typeLookup(obj->cls, delattr_str, NULL); if (delAttr != NULL) { Box* boxstr = boxString(attr); Box* rtn = runtimeCall2(delAttr, ArgPassSpec(2), obj, boxstr); return; } } // first check whether the deleting attribute is a descriptor Box* clsAttr = typeLookup(obj->cls, attr, NULL); if (clsAttr != NULL) { Box* delAttr = typeLookup(static_cast<BoxedClass*>(clsAttr->cls), delete_str, NULL); if (delAttr != NULL) { Box* boxstr = boxString(attr); Box* rtn = runtimeCall2(delAttr, ArgPassSpec(2), clsAttr, obj); return; } } // check if the attribute is in the instance's __dict__ Box* attrVal = obj->getattr(attr, NULL); if (attrVal != NULL) { obj->delattr(attr, NULL); } else { // the exception cpthon throws is different when the class contains the attribute if (clsAttr != NULL) { raiseExcHelper(AttributeError, "'%s' object attribute '%s' is read-only", getTypeName(obj)->c_str(), attr.c_str()); } else { raiseAttributeError(obj, attr.c_str()); } } } // del target.attr extern "C" void delattr(Box* obj, const char* attr) { static StatCounter slowpath_delattr("slowpath_delattr"); slowpath_delattr.log(); if (obj->cls == type_cls) { BoxedClass* cobj = static_cast<BoxedClass*>(obj); if (!isUserDefined(cobj)) { raiseExcHelper(TypeError, "can't set attributes of built-in/extension type '%s'\n", getNameOfClass(cobj)->c_str()); } } delattr_internal(obj, attr, true, NULL); } extern "C" Box* getiter(Box* o) { // TODO add rewriting to this? probably want to try to avoid this path though static const std::string iter_str("__iter__"); Box* r = callattrInternal0(o, &iter_str, LookupScope::CLASS_ONLY, NULL, ArgPassSpec(0)); if (r) return r; static const std::string getitem_str("__getitem__"); if (typeLookup(o->cls, getitem_str, NULL)) { return new BoxedSeqIter(o); } raiseExcHelper(TypeError, "'%s' object is not iterable", getTypeName(o)->c_str()); } llvm::iterator_range<BoxIterator> Box::pyElements() { Box* iter = getiter(this); assert(iter); return llvm::iterator_range<BoxIterator>(++BoxIterator(iter), BoxIterator(nullptr)); } // For use on __init__ return values static void assertInitNone(Box* obj) { if (obj != None) { raiseExcHelper(TypeError, "__init__() should return None, not '%s'", getTypeName(obj)->c_str()); } } Box* typeNew(Box* _cls, Box* arg1, Box* arg2, Box** _args) { Box* arg3 = _args[0]; if (!isSubclass(_cls->cls, type_cls)) raiseExcHelper(TypeError, "type.__new__(X): X is not a type object (%s)", getTypeName(_cls)->c_str()); BoxedClass* cls = static_cast<BoxedClass*>(_cls); if (!isSubclass(cls, type_cls)) raiseExcHelper(TypeError, "type.__new__(%s): %s is not a subtype of type", getNameOfClass(cls)->c_str(), getNameOfClass(cls)->c_str()); if (arg2 == NULL) { assert(arg3 == NULL); BoxedClass* rtn = arg1->cls; return rtn; } RELEASE_ASSERT(arg3->cls == dict_cls, "%s", getTypeName(arg3)->c_str()); BoxedDict* attr_dict = static_cast<BoxedDict*>(arg3); RELEASE_ASSERT(arg2->cls == tuple_cls, ""); BoxedTuple* bases = static_cast<BoxedTuple*>(arg2); RELEASE_ASSERT(arg1->cls == str_cls, ""); BoxedString* name = static_cast<BoxedString*>(arg1); BoxedClass* base; if (bases->elts.size() == 0) { bases = new BoxedTuple({ object_cls }); } RELEASE_ASSERT(bases->elts.size() == 1, ""); Box* _base = bases->elts[0]; RELEASE_ASSERT(_base->cls == type_cls, ""); base = static_cast<BoxedClass*>(_base); BoxedClass* made; if (base->instancesHaveAttrs()) { made = new BoxedClass(cls, base, NULL, base->attrs_offset, base->tp_basicsize, true); } else { assert(base->tp_basicsize % sizeof(void*) == 0); made = new BoxedClass(cls, base, NULL, base->tp_basicsize, base->tp_basicsize + sizeof(HCAttrs), true); } made->giveAttr("__module__", boxString(getCurrentModule()->name())); made->giveAttr("__doc__", None); for (const auto& p : attr_dict->d) { assert(p.first->cls == str_cls); made->setattr(static_cast<BoxedString*>(p.first)->s, p.second, NULL); } // Note: make sure to do this after assigning the attrs, since it will overwrite any defined __name__ made->setattr("__name__", name, NULL); // TODO this function (typeNew) should probably call PyType_Ready made->tp_new = base->tp_new; made->tp_alloc = reinterpret_cast<decltype(cls->tp_alloc)>(PyType_GenericAlloc); return made; } Box* typeCallInternal(BoxedFunction* f, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); static StatCounter slowpath_typecall("slowpath_typecall"); slowpath_typecall.log(); // TODO shouldn't have to redo this argument handling here... if (argspec.has_starargs) { rewrite_args = NULL; assert(argspec.num_args == 0); // doesn't need to be true, but assumed here Box* starargs = arg1; assert(starargs->cls == tuple_cls); BoxedTuple* targs = static_cast<BoxedTuple*>(starargs); int n = targs->elts.size(); if (n >= 1) arg1 = targs->elts[0]; if (n >= 2) arg2 = targs->elts[1]; if (n >= 3) arg3 = targs->elts[2]; if (n >= 4) args = &targs->elts[3]; argspec = ArgPassSpec(n); } Box* _cls = arg1; RewriterVarUsage r_ccls(RewriterVarUsage::empty()); RewriterVarUsage r_new(RewriterVarUsage::empty()); RewriterVarUsage r_init(RewriterVarUsage::empty()); Box* new_attr, *init_attr; if (rewrite_args) { assert(!argspec.has_starargs); assert(argspec.num_args > 0); rewrite_args->obj.setDoneUsing(); // rewrite_args->rewriter->annotate(0); // rewrite_args->rewriter->trap(); r_ccls = std::move(rewrite_args->arg1); // This is probably a duplicate, but it's hard to really convince myself of that. // Need to create a clear contract of who guards on what r_ccls.addGuard((intptr_t)arg1); } if (!isSubclass(_cls->cls, type_cls)) { raiseExcHelper(TypeError, "descriptor '__call__' requires a 'type' object but received an '%s'", getTypeName(_cls)->c_str()); } BoxedClass* cls = static_cast<BoxedClass*>(_cls); if (rewrite_args) { GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, r_ccls.addUse(), rewrite_args->destination, false); // TODO: if tp_new != Py_CallPythonNew, call that instead? new_attr = typeLookup(cls, _new_str, &grewrite_args); if (!grewrite_args.out_success) rewrite_args = NULL; else { assert(new_attr); r_new = std::move(grewrite_args.out_rtn); r_new.addGuard((intptr_t)new_attr); } // Special-case functions to allow them to still rewrite: if (new_attr->cls != function_cls) { Box* descr_r = processDescriptorOrNull(new_attr, None, cls); if (descr_r) { new_attr = descr_r; rewrite_args = NULL; } } } else { new_attr = typeLookup(cls, _new_str, NULL); new_attr = processDescriptor(new_attr, None, cls); } assert(new_attr && "This should always resolve"); if (rewrite_args) { GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, r_ccls.addUse(), rewrite_args->destination, false); init_attr = typeLookup(cls, _init_str, &grewrite_args); if (!grewrite_args.out_success) rewrite_args = NULL; else { if (init_attr) { r_init = std::move(grewrite_args.out_rtn); r_init.addGuard((intptr_t)init_attr); } } } else { init_attr = typeLookup(cls, _init_str, NULL); } // The init_attr should always resolve as well, but doesn't yet Box* made; RewriterVarUsage r_made(RewriterVarUsage::empty()); ArgPassSpec new_argspec = argspec; if (npassed_args > 1 && new_attr == typeLookup(object_cls, _new_str, NULL)) { if (init_attr == typeLookup(object_cls, _init_str, NULL)) { raiseExcHelper(TypeError, objectNewParameterTypeErrorMsg()); } else { new_argspec = ArgPassSpec(1); } } if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_new), rewrite_args->destination, rewrite_args->call_done_guarding); int new_npassed_args = new_argspec.totalPassed(); if (new_npassed_args >= 1) srewrite_args.arg1 = std::move(r_ccls); if (new_npassed_args >= 2) srewrite_args.arg2 = rewrite_args->arg2.addUse(); if (new_npassed_args >= 3) srewrite_args.arg3 = rewrite_args->arg3.addUse(); if (new_npassed_args >= 4) srewrite_args.args = rewrite_args->args.addUse(); srewrite_args.args_guarded = true; srewrite_args.func_guarded = true; made = runtimeCallInternal(new_attr, &srewrite_args, new_argspec, cls, arg2, arg3, args, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { assert(rewrite_args->rewriter->isDoneGuarding()); r_made = std::move(srewrite_args.out_rtn); } } else { made = runtimeCallInternal(new_attr, NULL, new_argspec, cls, arg2, arg3, args, keyword_names); } assert(made); // Special-case (also a special case in CPython): if we just called type.__new__(arg), don't call __init__ if (cls == type_cls && argspec == ArgPassSpec(2)) return made; // If this is true, not supposed to call __init__: RELEASE_ASSERT(made->cls == cls, "allowed but unsupported (%s vs %s)", getNameOfClass(made->cls)->c_str(), getNameOfClass(cls)->c_str()); if (init_attr && init_attr != typeLookup(object_cls, _init_str, NULL)) { // TODO apply the same descriptor special-casing as in callattr? Box* initrtn; // Attempt to rewrite the basic case: if (rewrite_args && init_attr->cls == function_cls) { // Note: this code path includes the descriptor logic CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_init), rewrite_args->destination, false); if (npassed_args >= 1) srewrite_args.arg1 = r_made.addUse(); if (npassed_args >= 2) srewrite_args.arg2 = std::move(rewrite_args->arg2); if (npassed_args >= 3) srewrite_args.arg3 = std::move(rewrite_args->arg3); if (npassed_args >= 4) srewrite_args.args = std::move(rewrite_args->args); srewrite_args.args_guarded = true; srewrite_args.func_guarded = true; // initrtn = callattrInternal(cls, &_init_str, INST_ONLY, &srewrite_args, argspec, made, arg2, arg3, args, // keyword_names); initrtn = runtimeCallInternal(init_attr, &srewrite_args, argspec, made, arg2, arg3, args, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->rewriter->call(false, (void*)assertInitNone, std::move(srewrite_args.out_rtn)) .setDoneUsing(); } } else { init_attr = processDescriptor(init_attr, made, cls); ArgPassSpec init_argspec = argspec; init_argspec.num_args--; int passed = init_argspec.totalPassed(); // If we weren't passed the args array, it's not safe to index into it if (passed <= 2) initrtn = runtimeCallInternal(init_attr, NULL, init_argspec, arg2, arg3, NULL, NULL, keyword_names); else initrtn = runtimeCallInternal(init_attr, NULL, init_argspec, arg2, arg3, args[0], &args[1], keyword_names); } assertInitNone(initrtn); } else { if (new_attr == NULL && npassed_args != 1) { // TODO not npassed args, since the starargs or kwargs could be null raiseExcHelper(TypeError, objectNewParameterTypeErrorMsg()); } } if (rewrite_args) { rewrite_args->out_rtn = std::move(r_made); rewrite_args->out_success = true; } // Some of these might still be in use if rewrite_args was set to NULL r_init.ensureDoneUsing(); r_ccls.ensureDoneUsing(); r_made.ensureDoneUsing(); r_init.ensureDoneUsing(); if (rewrite_args) { rewrite_args->arg2.ensureDoneUsing(); rewrite_args->arg3.ensureDoneUsing(); rewrite_args->args.ensureDoneUsing(); } return made; } Box* typeCall(Box* obj, BoxedList* vararg) { assert(vararg->cls == list_cls); if (vararg->size == 0) return typeCallInternal1(NULL, NULL, ArgPassSpec(1), obj); else if (vararg->size == 1) return typeCallInternal2(NULL, NULL, ArgPassSpec(2), obj, vararg->elts->elts[0]); else if (vararg->size == 2) return typeCallInternal3(NULL, NULL, ArgPassSpec(3), obj, vararg->elts->elts[0], vararg->elts->elts[1]); else abort(); } extern "C" void delGlobal(BoxedModule* m, std::string* name) { if (!m->getattr(*name)) { raiseExcHelper(NameError, "name '%s' is not defined", name->c_str()); } m->delattr(*name, NULL); } extern "C" Box* getGlobal(BoxedModule* m, std::string* name) { static StatCounter slowpath_getglobal("slowpath_getglobal"); slowpath_getglobal.log(); static StatCounter nopatch_getglobal("nopatch_getglobal"); if (VERBOSITY() >= 2) { #if !DISABLE_STATS std::string per_name_stat_name = "getglobal__" + *name; int id = Stats::getStatId(per_name_stat_name); Stats::log(id); #endif } { /* anonymous scope to make sure destructors get run before we err out */ std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "getGlobal")); Box* r; if (rewriter.get()) { // rewriter->trap(); GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), false); r = m->getattr(*name, &rewrite_args); if (!rewrite_args.obj.isDoneUsing()) { rewrite_args.obj.setDoneUsing(); } if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } if (r) { if (rewriter.get()) { rewriter->setDoneGuarding(); rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } else { rewrite_args.out_rtn.setDoneUsing(); } return r; } } else { r = m->getattr(*name, NULL); nopatch_getglobal.log(); if (r) { return r; } } static StatCounter stat_builtins("getglobal_builtins"); stat_builtins.log(); if ((*name) == "__builtins__") { if (rewriter.get()) { RewriterVarUsage r_rtn = rewriter->loadConst((intptr_t)builtins_module, rewriter->getReturnDestination()); rewriter->setDoneGuarding(); rewriter->commitReturning(std::move(r_rtn)); } return builtins_module; } Box* rtn; if (rewriter.get()) { RewriterVarUsage builtins = rewriter->loadConst((intptr_t)builtins_module, Location::any()); GetattrRewriteArgs rewrite_args(rewriter.get(), std::move(builtins), rewriter->getReturnDestination(), true); rtn = builtins_module->getattr(*name, &rewrite_args); if (!rtn || !rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } if (rewriter.get()) { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } else { rtn = builtins_module->getattr(*name, NULL); } if (rtn) return rtn; } raiseExcHelper(NameError, "global name '%s' is not defined", name->c_str()); } extern "C" Box* importFrom(Box* _m, const std::string* name) { assert(_m->cls == module_cls); BoxedModule* m = static_cast<BoxedModule*>(_m); Box* r = m->getattr(*name, NULL); if (r) return r; raiseExcHelper(ImportError, "cannot import name %s", name->c_str()); } extern "C" Box* importStar(Box* _from_module, BoxedModule* to_module) { assert(_from_module->cls == module_cls); BoxedModule* from_module = static_cast<BoxedModule*>(_from_module); static std::string all_str("__all__"); static std::string getitem_str("__getitem__"); Box* all = from_module->getattr(all_str); if (all) { Box* all_getitem = typeLookup(all->cls, getitem_str, NULL); if (!all_getitem) raiseExcHelper(TypeError, "'%s' object does not support indexing", getTypeName(all)->c_str()); int idx = 0; while (true) { Box* attr_name; try { attr_name = runtimeCallInternal2(all_getitem, NULL, ArgPassSpec(2), all, boxInt(idx)); } catch (Box* b) { if (b->cls == IndexError) break; throw; } idx++; if (attr_name->cls != str_cls) raiseExcHelper(TypeError, "attribute name must be string, not '%s'", getTypeName(attr_name)->c_str()); BoxedString* casted_attr_name = static_cast<BoxedString*>(attr_name); Box* attr_value = from_module->getattr(casted_attr_name->s); if (!attr_value) raiseExcHelper(AttributeError, "'module' object has no attribute '%s'", casted_attr_name->s.c_str()); to_module->setattr(casted_attr_name->s, attr_value, NULL); } return None; } HCAttrs* module_attrs = from_module->getAttrsPtr(); for (auto& p : module_attrs->hcls->attr_offsets) { if (p.first[0] == '_') continue; to_module->setattr(p.first, module_attrs->attr_list->attrs[p.second], NULL); } return None; } }
38.594233
145
0.59301
amyvmiwei
ffaeb5b6af46af8b75dfd837172594f1836cdbf0
762
cpp
C++
Example/smartpointers_09/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
Example/smartpointers_09/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
Example/smartpointers_09/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
#include <boost/intrusive_ptr.hpp> #include <atlbase.h> #include <iostream> void intrusive_ptr_add_ref(IDispatch *p) { p->AddRef(); } void intrusive_ptr_release(IDispatch *p) { p->Release(); } void check_windows_folder() { CLSID clsid; CLSIDFromProgID(CComBSTR{"Scripting.FileSystemObject"}, &clsid); void *p; CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER, __uuidof(IDispatch), &p); boost::intrusive_ptr<IDispatch> disp{static_cast<IDispatch*>(p), false}; CComDispatchDriver dd{disp.get()}; CComVariant arg{"C:\\Windows"}; CComVariant ret{false}; dd.Invoke1(CComBSTR{"FolderExists"}, &arg, &ret); std::cout << std::boolalpha << (ret.boolVal != 0) << '\n'; } int main() { CoInitialize(0); check_windows_folder(); CoUninitialize(); }
28.222222
76
0.708661
KwangjoJeong
ffafcf6b5fc675838607d321fcad75ca54ed0b10
9,914
cc
C++
src/test/testogl.cc
gitrah/cuMatrix
cab0239d0ec141528c7832275bac9c7daefdebf4
[ "Unlicense" ]
null
null
null
src/test/testogl.cc
gitrah/cuMatrix
cab0239d0ec141528c7832275bac9c7daefdebf4
[ "Unlicense" ]
null
null
null
src/test/testogl.cc
gitrah/cuMatrix
cab0239d0ec141528c7832275bac9c7daefdebf4
[ "Unlicense" ]
null
null
null
#include "../CuMatrix.h" #include "../util.h" #include "tests.h" #include <GL/gl.h> #include <GL/glut.h> #include "../ogl/AccelEvents.h" #include "../ogl/Point.h" #include "../ogl/Perspective.h" #include "../ogl/Arrow.h" #include "../ogl/LookAt.h" #include "../ogl/Text.h" #ifdef CuMatrix_Enable_Ogl void display(void) { /* clear all pixels */ glClear (GL_COLOR_BUFFER_BIT); glColor3f (1.0, 1.0, 1.0); glBegin(GL_POINTS); glVertex3f (0.25, 0.25, 0.0); glVertex3f (0.75, 0.25, 0.0); glVertex3f (0.75, 0.75, 0.0); glVertex3f (0.25, 0.75, 0.0); glutSolidCube(2); glEnd(); glFlush (); } void init (void) { /* select clearing (background) color */ glClearColor (0.0, 0.0, 0.0, 0.0); /* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); } void reshape(int x, int y) { printf("reshape! %d %d\n", x,y); } void keybd(unsigned char key, int x, int y) { printf("keybd %c %d %d\n", key, x,y); } void mouse(int button, int state, int x, int y) { printf("mouse btn %d state %d %d %d\n", button, state, x,y); } void idle() { printf("^"); } template int testOglHelloworld<float>::operator()(int argc, const char **argv) const; template int testOglHelloworld<double>::operator()(int argc, const char **argv) const; template <typename T> int testOglHelloworld<T>::operator()(int argc, const char **argv) const { glutInit(&argc, (char **)args); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (250, 250); glutInitWindowPosition (100, 100); glutCreateWindow ("hello"); init (); glutReshapeFunc(reshape); glutDisplayFunc(display); glutKeyboardFunc(keybd); glutMouseFunc(mouse); // glutIdleFunc(idle); glutMainLoop(); return 0; } // // // // // static GLfloat spin = 0.0; void initAnim0(void) { glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_FLAT); } void displayAnim0(void) { glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glRotatef(spin, 0.0, 1.0, 1.0); glColor3f(1.0, 1.0, 1.0); glRectf(-25.0, -25.0, 25.0, 25.0); glutWireCube(10); glPopMatrix(); glutSwapBuffers(); } void spinDisplay(void) { spin = spin + 2.0; if (spin > 360.0) spin = spin - 360.0; glutPostRedisplay(); } void reshapeAnim0(int w, int h) { printf("reshaped"); glViewport (0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-50.0, 50.0, -50.0, 50.0, -300.0, 300.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void mouseAnim0(int button, int state, int x, int y) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) glutIdleFunc(spinDisplay); break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) glutIdleFunc(NULL); break; default: break; } } template int testOglAnim0<float>::operator()(int argc, const char **argv) const; template int testOglAnim0<double>::operator()(int argc, const char **argv) const; template <typename T> int testOglAnim0<T>::operator()(int argc, const char **argv) const { glutInit(&argc, (char**)args); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(250, 250); glutInitWindowPosition(100, 100); glutCreateWindow(args[0]); initAnim0(); glutDisplayFunc(displayAnim0); glutReshapeFunc(reshapeAnim0); glutMouseFunc(mouseAnim0); glutMainLoop(); return 0; } // // // testOglPointAnim // // void initPointAnim(void) { glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_FLAT); } template <typename T> void mousePointAnim(int button, int state, int x, int y) { outln("mousePointAnim here"); switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) glutIdleFunc(Steppable<T>::stepCb); break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) glutIdleFunc(NULL); break; default: break; } } Perspective* thePersp; LookAt* theLookAt; double* p1; double* p2; double* p3; double *thePoints[6];// = {&theLookAt->eyeX,&theLookAt->eyeY,&theLookAt->eyeZ,&theLookAt->centerX,&theLookAt->centerY,&theLookAt->centerZ}; const char* theVars[] = {"eyeX","eyeY","eyeZ","centerX","centerY","centerZ"}; int idx = 0; const char * * theText = null; template <typename T> void keyboardFn(unsigned char key, int x, int y) { outln("keyboardFn here key " << key); switch (key) { case 'q': thePersp->setFovy(thePersp->getFovy() * .9); outln("fovy " << thePersp->getFovy()); Drawable<T>::reshapeCb(x,y); break; case 'w': thePersp->setFovy(thePersp->getFovy()* 1.1); outln("fovy " << thePersp->getFovy()); Drawable<T>::reshapeCb(x,y); break; case 'a': thePersp->setAspect(thePersp->getAspect() * .9); outln("getAspect " << thePersp->getAspect()); Drawable<T>::reshapeCb(x,y); break; case 's': thePersp->setAspect(thePersp->getAspect() *1.1); outln("getAspect " << thePersp->getAspect()); Drawable<T>::reshapeCb(x,y); break; case '1': if(p1) { *p1 -= .01 * (*p1); outln("pos " << niceVec(p1)); } break; case '!': if(p1) { *p1 += .01 * (*p1); outln("pos " << niceVec(p1)); } break; case '2': if(p2) { *p2 -= .01 * (*p2); outln("pos " << niceVec(p1)); } break; case '@': if(p2) { *p2 += .01 * (*p2); outln("pos " << niceVec(p1)); } break; case '3': if(p3) { *p3 -= .01 * (*p3); outln("pos " << niceVec(p1)); } break; case '#': if(p3) { *p3 += .01 * (*p3); outln("pos " << niceVec(p1)); } break; case 'z': idx++; if(idx > 5) { idx = 5; } *theText = theVars[idx]; break; case 'x': idx--; if(idx < 0) { idx = 0; } *theText = theVars[idx]; break; case 'c': *thePoints[idx] -= 1; break; case 'v': *thePoints[idx] += 1; break; case 'p': Drawable<T>::enablePath = !Drawable<T>::enablePath; Drawable<T>::enablePaths(); break; default: break; } } template int testOglPointAnim<float>::operator()(int argc, const char **argv) const; template int testOglPointAnim<double>::operator()(int argc, const char **argv) const; template <typename T> int testOglPointAnim<T>::operator()(int argc, const char **argv) const { glutInit(&argc, (char**)args); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(750, 750); glutInitWindowPosition(100, 100); glutCreateWindow(args[0]); initPointAnim(); const T pos[] ={(T).25,(T).25,(T)0}; Point<T> pt; pt.setPos(pos); glutDisplayFunc(Drawable<T>::drawCb); glutReshapeFunc(reshapeAnim0); glutMouseFunc(mousePointAnim<T>); glutMainLoop(); return 0; } const char* sevenSamples = "/home/reid/kaggle/accel/frag7.csv"; template int testFrag7Csv<float>::operator()(int argc, const char **argv) const; template int testFrag7Csv<double>::operator()(int argc, const char **argv) const; template<typename T> int testFrag7Csv<T>::operator()(int argc, const char **argv) const { outln( "opening " << sevenSamples); map<string, CuMatrix<T>*> results = util<T>::parseCsvDataFile(sevenSamples,",",false, true, false); if(!results.size()) { outln("no " << sevenSamples << "; exiting"); return -1; } outln("loaded " << sevenSamples); CuMatrix<T>& x = *results["x"]; outln("x " << x); CuMatrix<T>means(1,x.n,true,true); CuTimer timer; timer.start(); x.featureMeans(means,false); outln("mean calc took " << timer.stop()/1000 << "s, means: " << means.syncBuffers()); AccelEvents<T>* events = AccelEvents<T>::fromMatrix(x); //events->syncToNow(1000 ); outln("events " << events->toString()); outln("first " << events->first() << ", last " << events->last()); const T pos[] ={(T)0.0,(T)0,(T)0}; Bbox<T> bbx(-50.0, 50.0, -50.0, 50.0, -300.0, 300.0); Drawable<T>::bbx = &bbx; Point<T> pt(pos); Drawable<T>::enablePath =false; pt.setWithPath( false); Perspective persp(80.0, 1.0, 1.5, 70.0); LookAt lookAt; thePersp = &persp; theLookAt = &lookAt; thePoints[0] = &theLookAt->eyeX; thePoints[1] = &theLookAt->eyeY; thePoints[2] = &theLookAt->eyeZ; thePoints[3] = &theLookAt->centerX; thePoints[4] = &theLookAt->centerY; thePoints[5] = &theLookAt->centerZ; Drawable<T>::vision = thePersp; Drawable<T>::lookAt = theLookAt; p1 = (double*)pt.pos; p2 = (double*)pt.pos+1; p3 = (double*)pt.pos+2; outln("made pt " << &pt); //pt.setBbx(&bbx); pt.setMass(10000); outln("after set mass made pt " << niceVec(pt.getGravity())); outln("making current"); pt.makeCurrent(); Text<T> msg(theVars[idx]); theText = msg.getTextAdr(); T tpos[] = {0,1,15}; T tnrm[] = {0,1,0}; msg.set(tpos,tnrm); outln("adding events"); pt.addEvents(events); Arrow<T> accArrow; pt.setTwin(&accArrow); glutInit(&argc, (char**)args); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(750, 750); glutInitWindowPosition(100, 100); glutCreateWindow(args[0]); initPointAnim(); glutDisplayFunc(Drawable<T>::drawCb); glutReshapeFunc(Drawable<T>::reshapeCb); glutMouseFunc(mousePointAnim<T>); glutKeyboardFunc(keyboardFn<T>); glutMainLoop(); return 0; util<CuMatrix<T> >::deletePtrMap(results); delete events; Drawable<T>::freeDrawList(); Steppable<T>::freeStepList(); return 0; } #endif // CuMatrix_Enable_Ogl #include "tests.cc"
24.972292
139
0.593202
gitrah
ffafe8964fc691f8d19fe82fc728b7f7a5c4cbcf
1,267
cpp
C++
src/core/qloaderdata.cpp
sergeynaumovio/qtloader
21e17c62e63afe4b65a163402c77b51bda85be34
[ "0BSD" ]
null
null
null
src/core/qloaderdata.cpp
sergeynaumovio/qtloader
21e17c62e63afe4b65a163402c77b51bda85be34
[ "0BSD" ]
null
null
null
src/core/qloaderdata.cpp
sergeynaumovio/qtloader
21e17c62e63afe4b65a163402c77b51bda85be34
[ "0BSD" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2022 Sergey Naumov ** ** Permission to use, copy, modify, and/or distribute this ** software for any purpose with or without fee is hereby granted. ** ** 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 "qloaderdata.h" #include "qloaderstorage.h" class QLoaderDataPrivate { public: QList<QLoaderStorage*> storageList{}; }; QLoaderData::QLoaderData(QLoaderSettings *settings, QObject *parent) : QObject(parent), QLoaderSettings(settings), d_ptr(new QLoaderDataPrivate) { } QLoaderData::~QLoaderData() { } void QLoaderData::addStorage(QLoaderStorage *storage) { d_ptr->storageList.append(storage); }
30.902439
77
0.659826
sergeynaumovio
ffb1a662683e1316af7c9ee2b85e7a8afb7db277
1,954
cpp
C++
nucleus/applications/utilities/mdate.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2019-01-22T23:34:37.000Z
2021-10-31T15:44:15.000Z
nucleus/applications/utilities/mdate.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2020-06-01T16:35:46.000Z
2021-10-05T21:02:09.000Z
nucleus/applications/utilities/mdate.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
null
null
null
/*****************************************************************************\ * * * Name : mdate * * Author : Chris Koeritz * * * * Purpose: * * * * Provides a more informative date command, providing milliseconds also. * * * ******************************************************************************* * Copyright (c) 2002-$now By Author. 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 is online at: * * http://www.fsf.org/copyleft/gpl.html * * Please send any updates to: fred@gruntose.com * \*****************************************************************************/ #include <basis/astring.h> #include <application/hoople_main.h> #include <loggers/console_logger.h> #include <timely/time_stamp.h> #include <structures/static_memory_gremlin.h> #include <math.h> using namespace application; using namespace basis; using namespace loggers; using namespace structures; using namespace timely; class mdate_app : public application_shell { public: virtual int execute() { SETUP_CONSOLE_LOGGER; program_wide_logger::get().log(time_stamp::notarize(false), ALWAYS_PRINT); return 0; } DEFINE_CLASS_NAME("mdate_app"); }; HOOPLE_MAIN(mdate_app, )
42.478261
79
0.432958
fredhamster
ffb1b9aafc0edf334eeb15a3d4572f46dc106289
7,441
cpp
C++
Contests/USACO Solutions/2018-19/Dec 2018/Plat/gathering.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
1,760
2017-05-21T21:07:06.000Z
2022-03-29T13:15:08.000Z
Contests/USACO Solutions/2018-19/Dec 2018/Plat/gathering.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
12
2018-01-24T02:41:53.000Z
2022-03-17T13:09:26.000Z
Contests/USACO Solutions/2018-19/Dec 2018/Plat/gathering.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
473
2017-07-06T04:53:41.000Z
2022-03-28T13:03:28.000Z
#pragma GCC optimize ("O3") #pragma GCC target ("sse4") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; typedef long long ll; typedef long double ld; typedef complex<ld> cd; typedef pair<int, int> pi; typedef pair<ll,ll> pl; typedef pair<ld,ld> pd; typedef vector<int> vi; typedef vector<ld> vd; typedef vector<ll> vl; typedef vector<pi> vpi; typedef vector<pl> vpl; typedef vector<cd> vcd; template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>; #define FOR(i, a, b) for (int i = (a); i < (b); i++) #define F0R(i, a) for (int i = 0; i < (a); i++) #define FORd(i,a,b) for (int i = (b)-1; i >= (a); i--) #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) #define trav(a, x) for (auto& a : x) #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound #define sz(x) (int)x.size() #define beg(x) x.begin() #define en(x) x.end() #define all(x) beg(x), en(x) #define resz resize const int MOD = 1000000007; const ll INF = 1e18; const int MX = 100001; const ld PI = 4*atan((ld)1); template<class T> void ckmin(T &a, T b) { a = min(a, b); } template<class T> void ckmax(T &a, T b) { a = max(a, b); } namespace io { // TYPE ID (StackOverflow) template<class T> struct like_array : is_array<T>{}; template<class T, size_t N> struct like_array<array<T,N>> : true_type{}; template<class T> struct like_array<vector<T>> : true_type{}; template<class T> bool is_like_array(const T& a) { return like_array<T>::value; } // I/O void setIn(string s) { freopen(s.c_str(),"r",stdin); } void setOut(string s) { freopen(s.c_str(),"w",stdout); } void setIO(string s = "") { ios_base::sync_with_stdio(0); cin.tie(0); if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } } // INPUT template<class T> void re(T& x) { cin >> x; } template<class Arg, class... Args> void re(Arg& first, Args&... rest); void re(double& x) { string t; re(t); x = stod(t); } void re(ld& x) { string t; re(t); x = stold(t); } template<class T> void re(complex<T>& x); template<class T1, class T2> void re(pair<T1,T2>& p); template<class T> void re(vector<T>& a); template<class T, size_t SZ> void re(array<T,SZ>& a); template<class Arg, class... Args> void re(Arg& first, Args&... rest) { re(first); re(rest...); } template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = cd(a,b); } template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); } template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); } template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); } // OUTPUT template<class T1, class T2> ostream& operator<<(ostream& os, const pair<T1,T2>& a) { os << '{' << a.f << ", " << a.s << '}'; return os; } template<class T> ostream& printArray(ostream& os, const T& a, int SZ) { os << '{'; F0R(i,SZ) { if (i) { os << ", "; if (is_like_array(a[i])) cout << "\n"; } os << a[i]; } os << '}'; return os; } template<class T> ostream& operator<<(ostream& os, const vector<T>& a) { return printArray(os,a,sz(a)); } template<class T, size_t SZ> ostream& operator<<(ostream& os, const array<T,SZ>& a) { return printArray(os,a,SZ); } template<class T> void pr(const T& x) { cout << x << '\n'; } template<class Arg, class... Args> void pr(const Arg& first, const Args&... rest) { cout << first << ' '; pr(rest...); } } using namespace io; int N,M, dir[MX]; void finish() { FOR(i,1,N+1) pr(0); exit(0); } template<int SZ> struct Topo { int N, in[SZ], ok[SZ]; vi res, adj[SZ]; void addEdge(int x, int y) { adj[x].pb(y), in[y] ++; } void sort() { queue<int> todo; FOR(i,1,N+1) if (in[i] == 0) { ok[i] = 1; todo.push(i); } while (sz(todo)) { int x = todo.front(); todo.pop(); res.pb(x); for (int i: adj[x]) { in[i] --; if (!in[i]) todo.push(i); } } if (sz(res) == N) { FOR(i,1,N+1) pr(ok[i]); } else { finish(); } } }; template<int SZ> struct LCA { const int MAXK = 32-__builtin_clz(SZ); int N, R = 1; // vertices from 1 to N, R = root vi adj[SZ]; int par[32-__builtin_clz(SZ)][SZ], depth[SZ]; void addEdge(int u, int v) { adj[u].pb(v), adj[v].pb(u); } void dfs(int u, int prev){ par[0][u] = prev; depth[u] = depth[prev]+1; for (int v: adj[u]) if (v != prev) dfs(v, u); } void init(int _N) { N = _N; dfs(R, 0); FOR(k,1,MAXK) FOR(i,1,N+1) par[k][i] = par[k-1][par[k-1][i]]; } int lca(int u, int v){ if (depth[u] < depth[v]) swap(u,v); F0Rd(k,MAXK) if (depth[u] >= depth[v]+(1<<k)) u = par[k][u]; F0Rd(k,MAXK) if (par[k][u] != par[k][v]) u = par[k][u], v = par[k][v]; if(u != v) u = par[0][u], v = par[0][v]; return u; } int dist(int u, int v) { return depth[u]+depth[v]-2*depth[lca(u,v)]; } bool isAnc(int a, int b) { F0Rd(i,MAXK) if (depth[b]-depth[a] >= (1<<i)) b = par[i][b]; return a == b; } int getAnc(int a, int b) { F0Rd(i,MAXK) if (depth[b]-depth[a]-1 >= (1<<i)) b = par[i][b]; return b; } }; LCA<MX> L; Topo<MX> T; void setDir(int x, int y) { if (dir[x] && dir[x] != y) finish(); dir[x] = y; } void dfs0(int x) { for (int y: L.adj[x]) if (y != L.par[0][x]) { dfs0(y); if (x != 1 && dir[y] == -1) setDir(x,-1); } } void dfs1(int x) { int co = 0; if (dir[x] == 1) co ++; for (int y: L.adj[x]) if (y != L.par[0][x]) { if (dir[y] == -1) co ++; } for (int y: L.adj[x]) if (y != L.par[0][x]) { if (dir[y] == -1) co --; if (co) setDir(y,1); if (dir[y] == -1) co ++; } for (int y: L.adj[x]) if (y != L.par[0][x]) dfs1(y); } void genEdge() { dfs0(1); dfs1(1); FOR(i,2,N+1) { if (dir[i] == -1) { T.addEdge(i,L.par[0][i]); } else if (dir[i] == 1) { T.addEdge(L.par[0][i],i); } } } int main() { // you should actually read the stuff at the bottom setIO("gathering"); re(N,M); F0R(i,N-1) { int a,b; re(a,b); L.addEdge(a,b); } L.init(N); F0R(i,M) { int a,b; re(a,b); // if you root the tree at b, then every node in the subtree corresponding to a is bad if (L.isAnc(a,b)) { // a is ancestor of b int B = L.getAnc(a,b); setDir(B,-1); } else { setDir(a,1); } T.addEdge(b,a); } genEdge(); T.N = N; T.sort(); // you should actually read the stuff at the bottom } /* stuff you should look for * int overflow, array bounds * special cases (n=1?), set tle * do smth instead of nothing and stay organized */
26.670251
112
0.504233
nocrizwang
ffb4c0c4060be1a4e2fc5f7e9bb8a832189466dd
10,820
cpp
C++
examples/Planar2D/Planar2D.cpp
felipeek/bullet3
6a59241074720e9df119f2f86bc01765917feb1e
[ "Zlib" ]
9,136
2015-01-02T00:41:45.000Z
2022-03-31T15:30:02.000Z
examples/Planar2D/Planar2D.cpp
felipeek/bullet3
6a59241074720e9df119f2f86bc01765917feb1e
[ "Zlib" ]
2,424
2015-01-05T08:55:58.000Z
2022-03-30T19:34:55.000Z
examples/Planar2D/Planar2D.cpp
felipeek/bullet3
6a59241074720e9df119f2f86bc01765917feb1e
[ "Zlib" ]
2,921
2015-01-02T10:19:30.000Z
2022-03-31T02:48:42.000Z
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "BulletCollision/CollisionShapes/btBox2dShape.h" #include "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.h" #include "BulletCollision/CollisionShapes/btBox2dShape.h" #include "BulletCollision/CollisionShapes/btConvex2dShape.h" #include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h" ///create 125 (5x5x5) dynamic object #define ARRAY_SIZE_X 5 #define ARRAY_SIZE_Y 5 #define ARRAY_SIZE_Z 1 //maximum number of objects (and allow user to shoot additional boxes) #define MAX_PROXIES (ARRAY_SIZE_X * ARRAY_SIZE_Y * ARRAY_SIZE_Z + 1024) ///scaling of the objects (0.1 = 20 centimeter boxes ) #define SCALING 1 #define START_POS_X -5 #define START_POS_Y -5 #define START_POS_Z -3 #include "Planar2D.h" ///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files. #include "btBulletDynamicsCommon.h" #include <stdio.h> //printf debugging #include "LinearMath/btAlignedObjectArray.h" class btBroadphaseInterface; class btCollisionShape; class btOverlappingPairCache; class btCollisionDispatcher; class btConstraintSolver; struct btCollisionAlgorithmCreateFunc; class btDefaultCollisionConfiguration; class GL_DialogDynamicsWorld; #include "../CommonInterfaces/CommonRigidBodyBase.h" class Planar2D : public CommonRigidBodyBase { //keep the collision shapes, for deletion/cleanup btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btBroadphaseInterface* m_broadphase; btCollisionDispatcher* m_dispatcher; btConstraintSolver* m_solver; btDefaultCollisionConfiguration* m_collisionConfiguration; btConvex2dConvex2dAlgorithm::CreateFunc* m_convexAlgo2d; btVoronoiSimplexSolver* m_simplexSolver; btMinkowskiPenetrationDepthSolver* m_pdSolver; btBox2dBox2dCollisionAlgorithm::CreateFunc* m_box2dbox2dAlgo; public: Planar2D(struct GUIHelperInterface* helper) : CommonRigidBodyBase(helper) { } virtual ~Planar2D() { exitPhysics(); } void initPhysics(); void exitPhysics(); void resetCamera() { float dist = 9; float pitch = -11; float yaw = 539; float targetPos[3] = {8.6, 10.5, -20.6}; m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]); } }; void Planar2D::initPhysics() { m_guiHelper->setUpAxis(1); ///collision configuration contains default setup for memory, collision setup m_collisionConfiguration = new btDefaultCollisionConfiguration(); //m_collisionConfiguration->setConvexConvexMultipointIterations(); ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded) m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_simplexSolver = new btVoronoiSimplexSolver(); m_pdSolver = new btMinkowskiPenetrationDepthSolver(); m_convexAlgo2d = new btConvex2dConvex2dAlgorithm::CreateFunc(m_simplexSolver, m_pdSolver); m_box2dbox2dAlgo = new btBox2dBox2dCollisionAlgorithm::CreateFunc(); m_dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE, CONVEX_2D_SHAPE_PROXYTYPE, m_convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE, CONVEX_2D_SHAPE_PROXYTYPE, m_convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE, BOX_2D_SHAPE_PROXYTYPE, m_convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE, BOX_2D_SHAPE_PROXYTYPE, m_box2dbox2dAlgo); m_broadphase = new btDbvtBroadphase(); //m_broadphase = new btSimpleBroadphase(); ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded) btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver; m_solver = sol; m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration); //m_dynamicsWorld->getSolverInfo().m_erp = 1.f; //m_dynamicsWorld->getSolverInfo().m_numIterations = 4; m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld); m_dynamicsWorld->setGravity(btVector3(0, -10, 0)); ///create a few basic rigid bodies btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(150.), btScalar(50.), btScalar(150.))); // btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50); m_collisionShapes.push_back(groundShape); btTransform groundTransform; groundTransform.setIdentity(); groundTransform.setOrigin(btVector3(0, -43, 0)); //We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here: { btScalar mass(0.); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0, 0, 0); if (isDynamic) groundShape->calculateLocalInertia(mass, localInertia); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, groundShape, localInertia); btRigidBody* body = new btRigidBody(rbInfo); //add the body to the dynamics world m_dynamicsWorld->addRigidBody(body); } { //create a few dynamic rigidbodies // Re-using the same collision is better for memory usage and performance btScalar u = btScalar(1 * SCALING - 0.04); btVector3 points[3] = {btVector3(0, u, 0), btVector3(-u, -u, 0), btVector3(u, -u, 0)}; btConvexShape* childShape0 = new btBoxShape(btVector3(btScalar(SCALING * 1), btScalar(SCALING * 1), btScalar(0.04))); btConvexShape* colShape = new btConvex2dShape(childShape0); //btCollisionShape* colShape = new btBox2dShape(btVector3(SCALING*1,SCALING*1,0.04)); btConvexShape* childShape1 = new btConvexHullShape(&points[0].getX(), 3); btConvexShape* colShape2 = new btConvex2dShape(childShape1); btConvexShape* childShape2 = new btCylinderShapeZ(btVector3(btScalar(SCALING * 1), btScalar(SCALING * 1), btScalar(0.04))); btConvexShape* colShape3 = new btConvex2dShape(childShape2); m_collisionShapes.push_back(colShape); m_collisionShapes.push_back(colShape2); m_collisionShapes.push_back(colShape3); m_collisionShapes.push_back(childShape0); m_collisionShapes.push_back(childShape1); m_collisionShapes.push_back(childShape2); //btUniformScalingShape* colShape = new btUniformScalingShape(convexColShape,1.f); colShape->setMargin(btScalar(0.03)); //btCollisionShape* colShape = new btSphereShape(btScalar(1.)); /// Create Dynamic Objects btTransform startTransform; startTransform.setIdentity(); btScalar mass(1.f); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0, 0, 0); if (isDynamic) colShape->calculateLocalInertia(mass, localInertia); // float start_x = START_POS_X - ARRAY_SIZE_X/2; // float start_y = START_POS_Y; // float start_z = START_POS_Z - ARRAY_SIZE_Z/2; btVector3 x(-ARRAY_SIZE_X, 8.0f, -20.f); btVector3 y; btVector3 deltaX(SCALING * 1, SCALING * 2, 0.f); btVector3 deltaY(SCALING * 2, 0.0f, 0.f); for (int i = 0; i < ARRAY_SIZE_X; ++i) { y = x; for (int j = i; j < ARRAY_SIZE_Y; ++j) { startTransform.setOrigin(y - btVector3(-10, 0, 0)); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(0, 0, 0); switch (j % 3) { #if 1 case 0: rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); break; case 1: rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass, myMotionState, colShape3, localInertia); break; #endif default: rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass, myMotionState, colShape2, localInertia); } btRigidBody* body = new btRigidBody(rbInfo); //body->setContactProcessingThreshold(colShape->getContactBreakingThreshold()); body->setActivationState(ISLAND_SLEEPING); body->setLinearFactor(btVector3(1, 1, 0)); body->setAngularFactor(btVector3(0, 0, 1)); m_dynamicsWorld->addRigidBody(body); body->setActivationState(ISLAND_SLEEPING); // y += -0.8*deltaY; y += deltaY; } x += deltaX; } } m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld); } void Planar2D::exitPhysics() { //cleanup in the reverse order of creation/initialization //remove the rigidbodies from the dynamics world and delete them int i; if (m_dynamicsWorld) for (i = m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--) { btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } m_dynamicsWorld->removeCollisionObject(obj); delete obj; } //delete collision shapes for (int j = 0; j < m_collisionShapes.size(); j++) { btCollisionShape* shape = m_collisionShapes[j]; delete shape; } m_collisionShapes.clear(); delete m_dynamicsWorld; delete m_solver; delete m_broadphase; delete m_dispatcher; delete m_collisionConfiguration; delete m_convexAlgo2d; delete m_pdSolver; delete m_simplexSolver; delete m_box2dbox2dAlgo; m_dynamicsWorld = 0; m_solver = 0; m_broadphase = 0; m_dispatcher = 0; m_collisionConfiguration = 0; m_convexAlgo2d = 0; m_pdSolver = 0; m_simplexSolver = 0; m_box2dbox2dAlgo = 0; } CommonExampleInterface* Planar2DCreateFunc(struct CommonExampleOptions& options) { return new Planar2D(options.m_guiHelper); }
34.349206
243
0.77366
felipeek
ffb7247aa8dc214775abccb10e9feb1a4297ed2f
3,577
hpp
C++
Math/Algebra/Round.hpp
AProgrammerFemale/Yet-another-c-framework
30fddcbff23cd3d95db4e8b83f0a30d060e1128f
[ "MIT" ]
10
2019-08-25T07:59:43.000Z
2020-04-22T21:06:19.000Z
Math/Algebra/Round.hpp
AProgrammerFemale/Yet-another-c-framework
30fddcbff23cd3d95db4e8b83f0a30d060e1128f
[ "MIT" ]
2
2019-08-25T18:17:32.000Z
2019-09-05T05:51:41.000Z
Math/Algebra/Round.hpp
AProgrammerFemale/Yet-another-c-framework
30fddcbff23cd3d95db4e8b83f0a30d060e1128f
[ "MIT" ]
1
2019-09-05T21:04:02.000Z
2019-09-05T21:04:02.000Z
//Copyright Alice Framework, All Rights Reserved #pragma once #include <Basic/Types.hpp> #include <Basic/Inline.hpp> #include <Configuration.hpp> #if defined(AliceSse) #if defined(_MSC_VER) #include <intrin.h> #else #include <xmmintrin.h> #endif #endif #if defined(AliceSse2) #if defined(_MSC_VER) #if !defined(AliceSse) #include <intrin.h> #endif #else #include <emmintrin.h> #endif #endif namespace Alice { namespace Math { namespace Algebra { template<class T> AliceInline T Round(f32 a) noexcept { return static_cast<T>(a + 0.5f); } template<> AliceInline f32 Round<f32>(f32 a) noexcept { #if defined(AliceSse) __m128 b, c; #if defined(_MSC_VER) b.m128_f32[0] = a; c.m128_f32[0] = 0.5f; return _mm_cvt_si2ss(b, _mm_cvt_ss2si(_mm_add_ss(b, c))).m128_f32[0]; #else b[0] = a; c[0] = 0.5f; return _mm_cvt_si2ss(b, _mm_cvt_ss2si(_mm_add_ss(b, c)))[0]; #endif #else return static_cast<f32>(static_cast<s32>(a + 0.5f)); #endif } template<> AliceInline f64 Round<f64>(f32 a) noexcept { #if defined(AliceSse2) __m128 b, c; __m128d d; #if defined(_MSC_VER) b.m128_f32[0] = a; c.m128_f32[0] = 0.5f; return _mm_cvtsi64_sd(d, _mm_cvttss_si64(_mm_add_ss(b, c))).m128d_f64[0]; #else b[0] = a; c[0] = 0.5f; return _mm_cvtsi64_sd(d, _mm_cvttss_si64(_mm_add_ss(b, c)))[0]; #endif #else return static_cast<f64>(static_cast<s64>(a + 0.5f)); #endif } template<class T> AliceInline T Round(f64 a) noexcept { return static_cast<T>(static_cast<s64>(a + 0.5)); } template<> AliceInline f32 Round<f32>(f64 a) noexcept { #if defined(AliceSse2) __m128d b, c; __m128 d; #if defined(_MSC_VER) b.m128d_f64[0] = a; c.m128d_f64[0] = 0.5; return _mm_cvtsi64_ss(d, _mm_cvtsd_si64(_mm_add_sd(b, c))).m128_f32[0]; #else b[0] = a; c[0] = 0.5; return _mm_cvtsi64_ss(d, _mm_cvtsd_si64(_mm_add_sd(b, c)))[0]; #endif #else return static_cast<f32>(static_cast<s64>(a + 0.5)); #endif } template<> AliceInline f64 Round<f64>(f64 a) noexcept { #if defined(AliceSse2) __m128d b, c; #if defined(_MSC_VER) b.m128d_f64[0] = a; c.m128d_f64[0] = 0.5; return _mm_cvtsi64_sd(b, _mm_cvtsd_si64(_mm_add_sd(b, c))).m128d_f64[0]; #else b[0] = a; c[0] = 0.5; return _mm_cvtsi64_sd(b, _mm_cvtsd_si64(_mm_add_sd(b, c)))[0]; #endif #else return static_cast<f64>(static_cast<s64>(a + 0.5)); #endif } } } }
31.377193
90
0.448141
AProgrammerFemale
ffb84e55963aa3a2421bdaf8bf6f79b4cbfc520b
1,031
hpp
C++
addons/Outdated_WIP_Reference/Test_Weapon_01_Reference/CfgMagazines.hpp
hoxxii/Autismo_Seals_Unit_Mod
5e27dbac2066c435215859b70c861b0abbfb3b95
[ "OLDAP-2.3" ]
null
null
null
addons/Outdated_WIP_Reference/Test_Weapon_01_Reference/CfgMagazines.hpp
hoxxii/Autismo_Seals_Unit_Mod
5e27dbac2066c435215859b70c861b0abbfb3b95
[ "OLDAP-2.3" ]
null
null
null
addons/Outdated_WIP_Reference/Test_Weapon_01_Reference/CfgMagazines.hpp
hoxxii/Autismo_Seals_Unit_Mod
5e27dbac2066c435215859b70c861b0abbfb3b95
[ "OLDAP-2.3" ]
null
null
null
class CfgMagazines { class Default; class CA_Magazine; class 30Rnd_test_mag: CA_Magazine { scope = public; /// or 2, to be precise displayName = "Test magazine"; picture = "\A3\Weapons_F\Data\placeholder_co.paa"; /// just some icon ammo = B_Test_Caseless; count = 30; /// 30 rounds is enough initSpeed = 795; /// standard muzzle speed tracersEvery = 0; /// disable tracers by default lastRoundsTracer = 4; /// tracers to track low ammo descriptionShort = "Used to shoot test bullets"; /// on mouse-over in Inventory magazineGroup[] = {"test_mag_group"}; /// all magazines in the same group may be used in weapon that has the group defined as compatible }; class 30Rnd_test_mag_Tracer: 30Rnd_test_mag /// a magazine full of tracer rounds { tracersEvery = 1; /// moar tracers lastRoundsTracer = 30; /// tracers everywhere displayName = "Test tracer magazine"; descriptionShort = "Used to shoot test tracer bullets"; displaynameshort = "Tracers"; magazineGroup[] = {"test_mag_group"}; }; };
34.366667
138
0.71193
hoxxii
ffb99033e5b6d71c788f01de44631e784064f8a7
3,067
cpp
C++
data-server/src/common/socket_session_impl.cpp
apaqi/sharkstore
88e0e0f29c8c170b6021dd0743560a94b9fc8b6a
[ "Apache-2.0" ]
1
2019-01-24T07:09:19.000Z
2019-01-24T07:09:19.000Z
data-server/src/common/socket_session_impl.cpp
apaqi/sharkstore
88e0e0f29c8c170b6021dd0743560a94b9fc8b6a
[ "Apache-2.0" ]
null
null
null
data-server/src/common/socket_session_impl.cpp
apaqi/sharkstore
88e0e0f29c8c170b6021dd0743560a94b9fc8b6a
[ "Apache-2.0" ]
3
2019-01-24T07:09:19.000Z
2021-06-21T07:54:09.000Z
#include "socket_session_impl.h" #include <assert.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include "frame/sf_logger.h" #include "ds_proto.h" namespace fbase { namespace dataserver { namespace common { // const int header_size = sizeof(ds_proto_header_t); ProtoMessage *SocketSessionImpl::GetProtoMessage(const void *data) { assert(data != nullptr); ProtoMessage *msg = new ProtoMessage; if (msg == nullptr) return nullptr; // 解析头部 ds_proto_header_t *proto_header = (ds_proto_header_t *)(data); ds_unserialize_header(proto_header, &(msg->header)); //FLOG_INFO("new proto message. msgid: %" PRId64 ", func_id: %d, body_len: %d", // msg->header.msg_id, msg->header.func_id, msg->header.body_len); // 拷贝数据 if (msg->header.body_len > 0) { msg->body.resize(msg->header.body_len); memcpy(msg->body.data(), (char *)data + header_size, msg->body.size()); } return msg; } bool SocketSessionImpl::GetMessage(const char *data, size_t size, google::protobuf::Message *req) { google::protobuf::io::ArrayInputStream input(data, size); return req->ParseFromZeroCopyStream(&input); } void SocketSessionImpl::Send(ProtoMessage *msg, google::protobuf::Message *resp) { // // 分配回应内存 size_t body_len = resp == nullptr ? 0 : resp->ByteSizeLong(); size_t data_len = header_size + body_len; response_buff_t *response = new_response_buff(data_len); // 填充应答头部 ds_header_t header; header.magic_number = DS_PROTO_MAGIC_NUMBER; header.body_len = body_len; header.msg_id = msg->header.msg_id; header.version = DS_PROTO_VERSION_CURRENT; header.msg_type = DS_PROTO_FID_RPC_RESP; header.func_id = msg->header.func_id; header.proto_type = msg->header.proto_type; ds_serialize_header(&header, (ds_proto_header_t *)(response->buff)); response->session_id = msg->session_id; response->msg_id = header.msg_id; response->begin_time = msg->begin_time; response->expire_time = msg->expire_time; response->buff_len = data_len; do { if (resp != nullptr) { char *data = response->buff + header_size; if (!resp->SerializeToArray(data, body_len)) { FLOG_ERROR("serialize response failed, func_id: %d", header.func_id); delete_response_buff(response); break; } } //处理完成,socket send msg->socket->Send(response); } while (false); delete msg; delete resp; } void SocketSessionImpl::SetResponseHeader(const kvrpcpb::RequestHeader &req, kvrpcpb::ResponseHeader *resp, errorpb::Error *err) { // TODO // set timestamp resp->set_cluster_id(req.cluster_id()); resp->set_trace_id(req.trace_id()); if (err != nullptr) { resp->set_allocated_error(err); } } } // namespace common } // namespace dataserver } // namespace fbase
29.490385
85
0.636127
apaqi
ffbba62a7a936f5f7dde492389c4548c2d692817
1,556
cpp
C++
src/Core/Resources/ShaderLoader.cpp
Rexagon/2drift
31d687c9b4a289ca2c62757cba7b4f6e3c0b5d14
[ "Apache-2.0" ]
null
null
null
src/Core/Resources/ShaderLoader.cpp
Rexagon/2drift
31d687c9b4a289ca2c62757cba7b4f6e3c0b5d14
[ "Apache-2.0" ]
null
null
null
src/Core/Resources/ShaderLoader.cpp
Rexagon/2drift
31d687c9b4a289ca2c62757cba7b4f6e3c0b5d14
[ "Apache-2.0" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "ShaderLoader.hpp" #include "Core/Core.hpp" #include "Core/Rendering/Shader.hpp" namespace core { ShaderLoader::ShaderLoader(Core &core, const std::string &vertexShaderPath, const std::string &fragmentShaderPath) : m_core{core} , m_fileManager{core.get<FileManager>().lock()} , m_vertexShaderPath{vertexShaderPath} , m_fragmentShaderPath{fragmentShaderPath} { } std::shared_ptr<void> ShaderLoader::operator()() { auto shader = std::make_shared<Shader>(m_core); std::string error; // Load vertex shader part { const auto data = m_fileManager->load(m_vertexShaderPath); if (!shader->attachPart(data, GL_VERTEX_SHADER, error)) { throw std::runtime_error{"Unable to load vertex shader: " + m_vertexShaderPath + ". \n" + error}; } } // Load fragment shader part { const auto data = m_fileManager->load(m_fragmentShaderPath); if (!shader->attachPart(data, GL_FRAGMENT_SHADER, error)) { throw std::runtime_error{"Unable to load fragment shader: " + m_fragmentShaderPath + ".\n" + error}; } } if (!shader->link(error)) { throw std::runtime_error{"Unable to link shader programs: " + m_vertexShaderPath + ", " + m_fragmentShaderPath + ".\n" + error}; } return shader; } } // namespace core
28.290909
120
0.642031
Rexagon
ffbd103c7a0a75cc4b37445da092e94c7af1b95c
1,732
cpp
C++
sources/Modules/Upnp/UdpConnection.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Modules/Upnp/UdpConnection.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Modules/Upnp/UdpConnection.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
/************************************************************************** * Created: 2010/06/07 2:09 * Author: Eugene V. Palchukovsky * E-mail: eugene@palchukovsky.com * ------------------------------------------------------------------- * Project: TunnelEx * URL: http://tunnelex.net **************************************************************************/ #include "Prec.h" #include "UdpConnection.hpp" #include "Modules/Inet/InetEndpointAddress.hpp" using namespace TunnelEx; using namespace TunnelEx::Mods; using namespace TunnelEx::Mods::Upnp; UdpConnection::UdpConnection( unsigned short externalPort, const Inet::UdpEndpointAddress &address, const RuleEndpoint &ruleEndpoint, SharedPtr<const EndpointAddress> ruleEndpointAddress) : Base(address, ruleEndpoint, ruleEndpointAddress) { const AutoPtr<EndpointAddress> openedAddress = Base::GetLocalAddress(); ServiceRule::Service service; service.uuid = Helpers::Uuid().GetAsString().c_str(); service.name = L"Upnpc"; service.param = UpnpcService::CreateParam( Client::PROTO_UDP, externalPort, boost::polymorphic_downcast<Inet::InetEndpointAddress *>( openedAddress.Get())->GetHostName(), boost::polymorphic_downcast<Inet::InetEndpointAddress *>( openedAddress.Get())->GetPort(), true, // @todo: see TEX-610 false); SharedPtr<ServiceRule> rule(new ServiceRule); // WString ruleUuid = rule->GetUuid(); rule->GetServices().Append(service); //! @todo: see TEX-611 [2010/06/07 1:39] /* m_server.UpdateRule(rule); ruleUuid.Swap(m_upnpRuleUuid); */ m_upnpcService.reset(new UpnpcService(rule, rule->GetServices()[0])); m_upnpcService->Start(); } UdpConnection::~UdpConnection() throw() { //...// }
29.355932
76
0.632794
palchukovsky
ffbdec6bb0d5c58b44e382c02c0f7256af7257aa
61,718
cpp
C++
hgt_optimizer.cpp
lpsztemp/Bogdan-httpserv
068ac3504144d6907ad428e1359b00954c755f1b
[ "MIT" ]
null
null
null
hgt_optimizer.cpp
lpsztemp/Bogdan-httpserv
068ac3504144d6907ad428e1359b00954c755f1b
[ "MIT" ]
null
null
null
hgt_optimizer.cpp
lpsztemp/Bogdan-httpserv
068ac3504144d6907ad428e1359b00954c755f1b
[ "MIT" ]
null
null
null
#include <list> #include <memory> #include <algorithm> #include <vector> #include <iterator> #include <cassert> #include <tuple> #include <array> #include <thread> #include <future> #include <atomic> #include <cmath> #include <cstring> #include "basedefs.h" #include "face.h" #include "hgt_optimizer.h" #include "binary_streams.h" constexpr static double ADDITIVE_ERROR = 1E-6; constexpr static short MIN_VALID_HGT_VALUE = -500; constexpr static bool vertex_has_zero_height(const point_t& pt) noexcept { return pt.z >= 0?pt.z <= ADDITIVE_ERROR:pt.z >= -ADDITIVE_ERROR; } inline static bool vertex_has_zero_height(unsigned pt) noexcept; constexpr static short bswap(short w) noexcept { return (short) ((unsigned short) w << 8) | ((unsigned short) w >> 8); } template <class FaceType> inline static ConstantDomainDataId GetFaceDomainDataId(const FaceType& face) noexcept { for (const auto& pt:face) { if (!vertex_has_zero_height(pt)) return ConstantDomainDataId::SurfaceLand; } return ConstantDomainDataId::SurfaceWater; } template <class FaceType> inline static bool SameDomainData(const FaceType& left, const FaceType& right) noexcept { return GetFaceDomainDataId(left) == GetFaceDomainDataId(right); } class Matrix { short* m_points = nullptr; std::unique_ptr<std::int8_t[]> m_pVertexStatus; unsigned short m_cColumns = 0, m_cRows = 0; double m_eColumnResolution = 0, m_eRowResolution = 0; short m_min_height = std::numeric_limits<short>::max(); short m_max_height = std::numeric_limits<short>::min(); public: Matrix() = default; Matrix(short* pPoints, unsigned short cColumns, unsigned short cRows, double eColumnResolution, double eRowResolution) :m_points(pPoints), m_pVertexStatus(std::make_unique<std::int8_t[]>(std::size_t(cColumns) * cRows)), m_cColumns(cColumns), m_cRows(cRows), m_eColumnResolution(eColumnResolution), m_eRowResolution(eRowResolution) { auto cBlocks = std::thread::hardware_concurrency(); auto cItemsTotal = unsigned(cColumns) * cRows; auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks; std::list<std::thread> threads; std::atomic<unsigned> fence_1(unsigned(0)), fence_2(unsigned(0)); auto pMinMax = std::make_unique<std::pair<std::atomic<short>, std::atomic<short>>[]>(std::size_t(cBlocks)); for (unsigned iThread = 0; iThread < cBlocks; ++iThread) { threads.emplace_back([this, iThread, cBlock, cBlocks, cItemsTotal, &fence_1, &fence_2](std::pair<std::atomic<short>, std::atomic<short>>& prMinMax) -> void { auto iBegin = iThread * cBlock; auto iEnd = std::min((iThread + 1) * cBlock, cItemsTotal); for (auto iElement = iBegin; iElement < iEnd; ++iElement) m_points[iElement] = height_data_bswap(iElement); if (fence_1.fetch_add(1, std::memory_order_acq_rel) + 1 < cBlocks) do {std::this_thread::yield();} while (fence_1.load(std::memory_order_acquire) < cBlocks); std::unique_ptr<short[]> pBuf; unsigned buf_begin; { for (auto iElement = iBegin; iElement < iEnd; ++iElement) { if (m_points[iElement] < MIN_VALID_HGT_VALUE) { pBuf = std::make_unique<short[]>(std::size_t(iEnd - iElement)); std::memcpy(pBuf.get(), &m_points[iElement], std::size_t(iEnd - iElement) * sizeof(short)); buf_begin = iElement; do { pBuf[iElement - buf_begin] = average_invalid_height(iElement); }while (++iElement < iEnd); } } } if (fence_2.fetch_add(1, std::memory_order_acq_rel) + 1 < cBlocks) do {std::this_thread::yield();} while (fence_2.load(std::memory_order_acquire) < cBlocks); if (bool(pBuf)) std::memcpy(&m_points[buf_begin], pBuf.get(), std::size_t(iEnd - buf_begin) * sizeof(short)); if (fence_1.fetch_sub(1, std::memory_order_acq_rel) - 1 > 0) do {std::this_thread::yield();} while (fence_1.load(std::memory_order_acquire) > 0); short min_height = std::numeric_limits<short>::max(); short max_height = std::numeric_limits<short>::min(); for (auto iElement = iThread * cBlock; iElement < iEnd; ++iElement) { m_pVertexStatus[iElement] = this->is_empty_point_no_cache(iElement); if (m_points[iElement] < min_height) min_height = m_points[iElement]; if (m_points[iElement] > max_height) max_height = m_points[iElement]; } prMinMax.first.store(min_height, std::memory_order_relaxed); prMinMax.second.store(max_height, std::memory_order_relaxed); }, std::ref(pMinMax[iThread])); } unsigned iThread = 0; for (auto& thr:threads) { thr.join(); auto l_min_height = pMinMax[iThread].first.load(std::memory_order_relaxed); auto l_max_height = pMinMax[iThread].second.load(std::memory_order_relaxed); if (l_min_height < m_min_height) m_min_height = l_min_height; if (l_max_height > m_max_height) m_max_height = l_max_height; ++iThread; } } inline unsigned short columns() const noexcept { return m_cColumns; } inline unsigned short rows() const noexcept { return m_cRows; } bool is_empty_point(unsigned short col, unsigned short row) const noexcept { return is_empty_point(this->locate(col, row)); } inline bool is_empty_point(unsigned index) const noexcept { return bool(m_pVertexStatus[index]); } inline unsigned short point_x(unsigned index) const noexcept { return index % this->columns(); } inline unsigned short point_y(unsigned index) const noexcept { return index / this->columns(); } inline short point_z(unsigned index) const noexcept { return m_points[index]; } inline short point_z(unsigned short col, unsigned short row) const noexcept { return this->point_z(this->locate(col, row)); } inline unsigned locate(unsigned short col, unsigned short row) const noexcept { return row * this->columns() + col; } inline point_t get_external_point(unsigned short col, unsigned short row) const noexcept { return {double(col) * m_eColumnResolution, double(row) * m_eRowResolution, double(point_z(col, row))}; } inline point_t get_external_point(unsigned index) const noexcept { return {double(this->point_x(index)) * m_eColumnResolution, double(this->point_y(index)) * m_eRowResolution, double(point_z(index))}; } inline short min_height() const { return m_min_height; } inline short max_height() const { return m_max_height; } private: bool is_empty_point_no_cache(unsigned point_index) const { auto col = this->point_x(point_index); auto row = this->point_y(point_index); if (col > 0 && col < this->columns() - 1 && row > 0 && row < this->rows() - 1 && this->point_z(col, row) - this->point_z(col - 1, row) == this->point_z(col + 1, row) - this->point_z(col, row) && this->point_z(col, row) - this->point_z(col, row - 1) == this->point_z(col, row + 1) - this->point_z(col, row) && this->point_z(col, row - 1) - this->point_z(col - 1, row - 1) == this->point_z(col, row) - this->point_z(col - 1, row) && this->point_z(col, row + 1) - this->point_z(col - 1, row + 1) == this->point_z(col, row) - this->point_z(col - 1, row) && this->point_z(col + 1, row - 1) - this->point_z(col, row - 1) == this->point_z(col + 1, row) - this->point_z(col, row) && this->point_z(col + 1, row + 1) - this->point_z(col, row + 1) == this->point_z(col + 1, row) - this->point_z(col, row)) { point_t v_tl = this->get_external_point(col - 1, row - 1); point_t v_tp = this->get_external_point(col, row - 1); point_t v_tr = this->get_external_point(col + 1, row - 1); point_t v_lf = this->get_external_point(col - 1, row); point_t v_md = this->get_external_point(col, row); point_t v_rt = this->get_external_point(col + 1, row); point_t v_bl = this->get_external_point(col - 1, row + 1); point_t v_bt = this->get_external_point(col, row + 1); point_t v_br = this->get_external_point(col + 1, row + 1); point_t f_tl_lb[] = {v_tl, v_md, v_lf}; point_t f_tl_rt[] = {v_tl, v_tp, v_md}; point_t f_tr_lb[] = {v_tp, v_rt, v_md}; point_t f_tr_rt[] = {v_tp, v_tr, v_rt}; point_t f_bl_lb[] = {v_lf, v_bt, v_bl}; point_t f_bl_rt[] = {v_lf, v_md, v_bt}; point_t f_br_lb[] = {v_md, v_br, v_bt}; point_t f_br_rt[] = {v_md, v_rt, v_br}; return std::int8_t(SameDomainData(face_t(std::begin(f_tl_lb), std::end(f_tl_lb)), face_t(std::begin(f_tl_rt), std::end(f_tl_rt))) && SameDomainData(face_t(std::begin(f_tl_rt), std::end(f_tl_rt)), face_t(std::begin(f_tr_lb), std::end(f_tr_lb))) && SameDomainData(face_t(std::begin(f_tr_lb), std::end(f_tr_lb)), face_t(std::begin(f_tr_rt), std::end(f_tr_rt))) && SameDomainData(face_t(std::begin(f_tr_rt), std::end(f_tr_rt)), face_t(std::begin(f_bl_lb), std::end(f_bl_lb))) && SameDomainData(face_t(std::begin(f_bl_lb), std::end(f_bl_lb)), face_t(std::begin(f_bl_rt), std::end(f_bl_rt))) && SameDomainData(face_t(std::begin(f_bl_rt), std::end(f_bl_rt)), face_t(std::begin(f_br_lb), std::end(f_br_lb))) && SameDomainData(face_t(std::begin(f_br_lb), std::end(f_br_lb)), face_t(std::begin(f_br_rt), std::end(f_br_rt)))); } return false; } inline short height_data_bswap(unsigned point_index) const noexcept { return bswap(m_points[point_index]); } short average_invalid_height(unsigned point_index) const noexcept { unsigned short cl, cr; short vl = short(), vr = short(); unsigned short rt, rb; short vt = short(), vb = short(); auto col = this->point_x(point_index); auto row = this->point_y(point_index); for (cr = col + 1; cr < this->columns(); ++cr) { if (m_points[point_index + cr - col] >= MIN_VALID_HGT_VALUE) { vr = m_points[point_index + cr - col]; break; } } for (cl = 1; cl <= col; ++cl) { if (m_points[point_index - cl] >= MIN_VALID_HGT_VALUE) { cl = point_index - cl; vl = m_points[cl]; break; } } for (rb = row + 1; rb < this->rows(); ++rb) { if (this->point_z(col, rb) >= MIN_VALID_HGT_VALUE) { vb = this->point_z(col, rb); break; } } for (rt = 1; rt <= row; ++rt) { if (this->point_z(col, row - rt) >= MIN_VALID_HGT_VALUE) { rt = row - rt; vt = this->point_z(col, rt); break; } } double eAve; if (cr > cl) { eAve = double(vr - vl) / double(cr - cl) * (col - cl) + vl; if (rb > rt) return short((eAve + double(vb - vt) / double(rb - rt) * (row - rt) + vt) / 2); return short(eAve); } return short(double(vb - vt) / double(rb - rt) * (row - rt) + vt); } }; Matrix g_matrix; class Face { public: typedef unsigned value_type; //index pointing to the matrix element typedef unsigned* pointer; typedef const unsigned* const_pointer; typedef unsigned& reference; typedef const unsigned& const_reference; typedef unsigned* iterator; typedef const unsigned* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef unsigned size_type; typedef signed difference_type; private: static constexpr size_type SMALL_NUMBER = 4; union { pointer m_vertices_big; value_type m_vertices_small[SMALL_NUMBER]; }; pointer m_pVertices; size_type m_vertices_count = 0; public: explicit operator face_t() const; inline value_type point(size_type in_face_index) const noexcept { return m_pVertices[in_face_index]; } inline size_type size() const noexcept { return m_vertices_count; } inline iterator begin() noexcept {return &m_pVertices[0];} inline const_iterator cbegin() const noexcept {return const_cast<const unsigned*>(&m_pVertices[0]);} inline const_iterator begin() const noexcept {return this->cbegin();} inline iterator end() noexcept {return &m_pVertices[m_vertices_count];} inline const_iterator cend() const noexcept {return const_cast<const unsigned*>(&m_pVertices[m_vertices_count]);} inline const_iterator end() const noexcept {return this->cend();} inline reverse_iterator rbegin() noexcept {return std::make_reverse_iterator(this->end());} inline const_reverse_iterator crbegin() const noexcept {return std::make_reverse_iterator(this->end());} inline const_reverse_iterator rbegin() const noexcept {return std::make_reverse_iterator(this->end());} inline reverse_iterator rend() noexcept {return std::make_reverse_iterator(this->begin());} inline const_reverse_iterator crend() const noexcept {return std::make_reverse_iterator(this->begin());} inline const_reverse_iterator rend() const noexcept {return std::make_reverse_iterator(this->begin());} bool is_complanar_to(const Face& right) const { auto n1 = cross_product(g_matrix.get_external_point(m_pVertices[1]) - g_matrix.get_external_point(m_pVertices[0]), g_matrix.get_external_point(m_pVertices[2]) - g_matrix.get_external_point(m_pVertices[1])); assert(fabs(n1.x) > ADDITIVE_ERROR || fabs(n1.y) > ADDITIVE_ERROR || fabs(n1.z) > ADDITIVE_ERROR); auto n2 = cross_product(g_matrix.get_external_point(right.m_pVertices[1]) - g_matrix.get_external_point(right.m_pVertices[0]), g_matrix.get_external_point(right.m_pVertices[2]) - g_matrix.get_external_point(right.m_pVertices[1])); assert(fabs(n2.x) > ADDITIVE_ERROR || fabs(n2.y) > ADDITIVE_ERROR || fabs(n2.z) > ADDITIVE_ERROR); auto res = cross_product(n1, n2); return fabs(res.x) <= ADDITIVE_ERROR && fabs(res.y) <= ADDITIVE_ERROR && fabs(res.z) <= ADDITIVE_ERROR; } bool can_unite_with_quadruplet_left_edge(unsigned short quad_left_col, unsigned short quad_top_row) const; bool can_unite_with_quadruplet_top_edge(unsigned short quad_left_col, unsigned short quad_top_row) const; bool can_unite_with_quadruplet_right_edge(unsigned short quad_left_col, unsigned short quad_top_row) const; bool can_unite_with_quadruplet_bottom_edge(unsigned short quad_left_col, unsigned short quad_top_row) const; bool can_unite_with(const Face& right) const { return this->is_complanar_to(right) && SameDomainData(*this, right); } private: class ReversedConstructor; public: Face() = default; class Constructor { std::list<unsigned> m_lstEdgeVertices; public: Constructor() = default; void add_point(unsigned short col, unsigned short row) noexcept { assert(!g_matrix.is_empty_point(col, row)); if (this->size() >= 2) { auto it_pp = m_lstEdgeVertices.rbegin(); auto it_p = it_pp++; if ((g_matrix.point_y(*it_p) - g_matrix.point_y(*it_pp)) * (col - g_matrix.point_x(*it_p)) == (row - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_p) - g_matrix.point_x(*it_pp))) *it_p = g_matrix.locate(col, row); else m_lstEdgeVertices.emplace_back(g_matrix.locate(col, row)); }else m_lstEdgeVertices.emplace_back(g_matrix.locate(col, row)); } void add_list(const Face& face) { auto it = face.begin(); auto pt = *it++; this->add_point(g_matrix.point_x(pt), g_matrix.point_y(pt)); while (it != face.end()) m_lstEdgeVertices.emplace_back(*it); } void add_list(Face::Constructor&& right) { if (!right.empty()) { if (m_lstEdgeVertices.empty()) m_lstEdgeVertices = std::move(right.m_lstEdgeVertices); else { auto it_p = std::prev(m_lstEdgeVertices.end()); m_lstEdgeVertices.splice(m_lstEdgeVertices.end(), std::move(right.m_lstEdgeVertices)); auto it_n = it_p--; auto it = it_n++; if (it_n != m_lstEdgeVertices.end() && (g_matrix.point_y(*it) - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_n) - g_matrix.point_x(*it)) == (g_matrix.point_y(*it_n) - g_matrix.point_y(*it)) * (g_matrix.point_x(*it) - g_matrix.point_x(*it_p))) m_lstEdgeVertices.erase(it); } } } typedef Face::ReversedConstructor Reversed; void add_reversed_list(Reversed&& right); //returns an index of the next quadruplet to analyze unsigned add_face_to_the_right(unsigned short col, unsigned short row); void add_face_to_the_bottom(unsigned short col, unsigned short row); auto begin() {return m_lstEdgeVertices.begin();} auto begin() const {return m_lstEdgeVertices.begin();} auto cbegin() const {return m_lstEdgeVertices.cbegin();} auto end() {return m_lstEdgeVertices.end();} auto end() const {return m_lstEdgeVertices.end();} auto cend() const {return m_lstEdgeVertices.cend();} auto rbegin() {return m_lstEdgeVertices.rbegin();} auto rbegin() const {return m_lstEdgeVertices.rbegin();} auto crbegin() const {return m_lstEdgeVertices.crbegin();} auto rend() {return m_lstEdgeVertices.rend();} auto rend() const {return m_lstEdgeVertices.rend();} auto crend() const {return m_lstEdgeVertices.crend();} unsigned size() const {return unsigned(m_lstEdgeVertices.size());} bool empty() const {return m_lstEdgeVertices.empty();} }; Face(Constructor&& constr):Face(std::move(constr), int()) {} //MSVC bug with fold expressions: https://developercommunity.visualstudio.com/content/problem/301623/fold-expressions-in-template-instantiations-fail-t.html template <class ... Points, class = std::enable_if_t< (sizeof ... (Points) > 1) && (sizeof ... (Points) <= SMALL_NUMBER) && std::conjunction_v<std::is_integral<Points> ...>>> explicit Face(Points ... vertices):m_vertices_small{vertices...}, m_pVertices(m_vertices_small), m_vertices_count(unsigned(sizeof...(Points))) { static_assert(sizeof...(Points) >= 3, "Invalid number of vertices specified for a face"); /*assert((g_matrix.point_y(m_pVertices[sizeof...(Points) - 2]) - g_matrix.point_y(m_pVertices[sizeof...(Points) - 3])) * (g_matrix.point_x(m_pVertices[sizeof...(Points) - 1]) - g_matrix.point_x(m_pVertices[sizeof...(Points) - 2])) == (g_matrix.point_y(m_pVertices[sizeof...(Points) - 1]) - g_matrix.point_y(m_pVertices[sizeof...(Points) - 2])) * (g_matrix.point_x(m_pVertices[sizeof...(Points) - 2]) - g_matrix.point_x(m_pVertices[sizeof...(Points) - 3])));*/ } template <class ... Points, class = void, class = std::enable_if_t<(sizeof ... (Points) > SMALL_NUMBER) && std::conjunction_v<std::is_integral<Points> ...>>> explicit Face(Points ... vertices):Face(std::array<typename std::tuple_element<0, std::tuple<Points...>>::type, sizeof ... (Points)>{vertices...}, int()) {} Face(const Face&) = delete; Face(Face&& right) { *this = std::move(right); } Face& operator=(const Face&) = delete; Face& operator=(Face&& right) { if (this == &right) return *this; if (m_vertices_count > SMALL_NUMBER) delete [] m_vertices_big; if (right.m_vertices_count <= SMALL_NUMBER) { std::copy(&right.m_vertices_small[0], &right.m_vertices_small[right.m_vertices_count], &m_vertices_small[0]); m_pVertices = m_vertices_small; }else { m_vertices_big = right.m_vertices_big; m_pVertices = m_vertices_big; } m_vertices_count = right.m_vertices_count; right.m_vertices_count = 0; return *this; } ~Face() noexcept { if (m_vertices_count > SMALL_NUMBER) delete [] m_vertices_big; } private: class ReversedConstructor { Face::Constructor m_list; public: void add_point(unsigned short col, unsigned short row) { m_list.add_point(col, row); } auto begin() {return m_list.begin();} auto begin() const {return m_list.begin();} auto cbegin() const {return m_list.cbegin();} auto end() {return m_list.end();} auto end() const {return m_list.end();} auto cend() const {return m_list.cend();} auto rbegin() {return m_list.rbegin();} auto rbegin() const {return m_list.rbegin();} auto crbegin() const {return m_list.crbegin();} auto rend() {return m_list.rend();} auto rend() const {return m_list.rend();} auto crend() const {return m_list.crend();} unsigned size() const {return unsigned(m_list.size());} bool empty() const {return m_list.empty();} }; template <class Container> Face(Container&& constr, int) noexcept { assert(constr.size() >= 3); auto it_end = std::end(constr); { auto it_pp = std::rbegin(constr); auto it_p = it_pp++; auto col = g_matrix.point_x(*std::begin(constr)); auto row = g_matrix.point_y(*std::begin(constr)); if ((g_matrix.point_y(*it_p) - g_matrix.point_y(*it_pp)) * (col - g_matrix.point_x(*it_p)) == (row - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_p) - g_matrix.point_x(*it_pp))) { assert(constr.size() - 1 >= 3); --it_end; m_vertices_count = unsigned(constr.size() - 1); }else m_vertices_count = unsigned(constr.size()); } if (m_vertices_count <= SMALL_NUMBER) m_pVertices = m_vertices_small; else { m_vertices_big = new unsigned [m_vertices_count]; m_pVertices = m_vertices_big; } std::move(std::begin(constr), it_end, &m_pVertices[0]); } }; void Face::Constructor::add_reversed_list(Face::Constructor::Reversed&& right) { for (auto it = std::rbegin(right); it != std::rend(right); ++it) this->add_point(g_matrix.point_x(*it), g_matrix.point_y(*it)); } struct vertex_converting_iterator { typedef std::input_iterator_tag iterator_category; typedef point_t value_type; typedef const point_t *pointer, &reference; typedef unsigned size_type; typedef signed difference_type; reference operator*() const { if (!m_fLastVal) { m_ptLastVal = g_matrix.get_external_point(*m_it); m_fLastVal = true; } return m_ptLastVal; } pointer operator->() const { if (!m_fLastVal) { m_ptLastVal = g_matrix.get_external_point(*m_it); m_fLastVal = true; } return &m_ptLastVal; } vertex_converting_iterator& operator++() { ++m_it; this->invalidate_value(); return *this; } vertex_converting_iterator operator++(int) { auto old = *this; ++*this; return old; } bool operator==(const vertex_converting_iterator& right) const { return m_it == right.m_it; } bool operator!=(const vertex_converting_iterator& right) const { return m_it != right.m_it; } vertex_converting_iterator() = default; explicit vertex_converting_iterator(Face::const_iterator it):m_it(it) {} vertex_converting_iterator(const vertex_converting_iterator& right):m_fLastVal(right.m_fLastVal), m_it(right.m_it) { if (m_fLastVal) m_ptLastVal = right.m_ptLastVal; } vertex_converting_iterator(vertex_converting_iterator&& right):vertex_converting_iterator(right) {} vertex_converting_iterator& operator=(const vertex_converting_iterator& right) { m_fLastVal = right.m_fLastVal; m_it = right.m_it; if (m_fLastVal) m_ptLastVal = right.m_ptLastVal; return *this; } vertex_converting_iterator& operator=(vertex_converting_iterator&& right) { return *this = right; } private: mutable bool m_fLastVal = false; mutable point_t m_ptLastVal; Face::const_iterator m_it; inline void invalidate_value() noexcept { m_fLastVal = false; } }; Face::operator face_t() const { return face_t(vertex_converting_iterator(this->begin()), vertex_converting_iterator(this->end()), this->size()); } inline static bool vertex_has_zero_height(unsigned pt) noexcept { return g_matrix.point_z(pt) == 0; } struct FaceCompareLess { inline bool operator()(const Face& left, const Face& right) const noexcept { return std::lexicographical_compare(std::begin(left), std::end(left), std::begin(right), std::end(right)); } }; struct FaceCompareEqual { inline bool operator()(const Face& left, const Face& right) const noexcept { return std::equal(std::begin(left), std::end(left), std::begin(right), std::end(right)); } }; class FaceSet { std::vector<Face> m_vFaces; public: struct Constructor { Constructor() { m_vFaces.reserve((g_matrix.columns() - 1) * (g_matrix.rows() - 1) * 2); } Face& add_face(Face&& face) { m_vFaces.emplace_back(std::move(face)); return *m_vFaces.rbegin(); } private: friend class FaceSet; std::vector<Face> m_vFaces; }; FaceSet() = default; FaceSet(Constructor&& constr):m_vFaces(std::move(constr.m_vFaces)) { m_vFaces.shrink_to_fit(); #ifndef NDEBUG if (m_vFaces.empty()) return; std::sort(m_vFaces.begin(), m_vFaces.end(), FaceCompareLess()); FaceCompareEqual eq; for (auto it = m_vFaces.begin(), it_n = std::next(m_vFaces.begin()); it_n != m_vFaces.end(); it = it_n++) { if (eq(*it, *it_n)) throw std::invalid_argument("Non-unique face is found in the input set"); //replace to it_n = m_vFaces.erase(++it, ++it_n); } #endif } auto begin() noexcept {return m_vFaces.begin();} auto begin() const noexcept {return m_vFaces.begin();} auto cbegin() const noexcept {return m_vFaces.cbegin();} auto end() noexcept {return m_vFaces.end();} auto end() const noexcept {return m_vFaces.end();} auto cend() const noexcept {return m_vFaces.cend();} auto size() const noexcept {return m_vFaces.size();} bool empty() const noexcept {return m_vFaces.empty();} }; /* 3 2 x x x x 0 1 0) o o 1) o o 2) o o 3) o o o o . o o . . . 4) o . 5) o . 6) o . 7) o . o o . o o . . . 8) . o 9) . o 10) . o 11) . o o o . o o . . . 12) . . 13) . . 14) . . 15) . . o o . o o . . . */ unsigned char GetPointQuadrupletType(unsigned short quad_left_col, unsigned short quad_top_row) { assert(quad_left_col < g_matrix.columns() && quad_top_row < g_matrix.rows()); return ((unsigned char) (!g_matrix.is_empty_point(quad_left_col, quad_top_row)) << 3) | ((unsigned char)(!g_matrix.is_empty_point(quad_left_col + 1, quad_top_row)) << 2) | ((unsigned char) (!g_matrix.is_empty_point(quad_left_col, quad_top_row + 1)) << 0) | ((unsigned char) (!g_matrix.is_empty_point(quad_left_col + 1, quad_top_row + 1)) << 1); } bool Face::can_unite_with_quadruplet_left_edge(unsigned short quad_left_col, unsigned short quad_top_row) const { assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1); switch (GetPointQuadrupletType(quad_left_col, quad_top_row)) { case 11: { Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)}; return this->can_unite_with(cur_face); } case 13: { Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col, quad_top_row + 1)}; if (!this->can_unite_with(cur_face)) return false; if (quad_top_row > 0) return !cur_face.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1); return true; } case 15: { Face face_lb = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)}; if (!this->can_unite_with(face_lb)) return false; if (quad_top_row < g_matrix.rows() - 2 && face_lb.can_unite_with_quadruplet_top_edge(quad_left_col, quad_top_row + 1)) return false; Face face_rt = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)}; return !face_lb.can_unite_with(face_rt) || quad_top_row == 0 || !face_rt.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1); } default: return false; }; } bool Face::can_unite_with_quadruplet_top_edge(unsigned short quad_left_col, unsigned short quad_top_row) const { assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1); switch (GetPointQuadrupletType(quad_left_col, quad_top_row)) { case 13: { Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col, quad_top_row + 1)}; return this->can_unite_with(cur_face); } case 14: case 15: { Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)}; return this->can_unite_with(cur_face); } default: return false; }; } bool Face::can_unite_with_quadruplet_right_edge(unsigned short quad_left_col, unsigned short quad_top_row) const { assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1); switch (GetPointQuadrupletType(quad_left_col, quad_top_row)) { case 7: { Face cur_face = Face{g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)}; return this->can_unite_with(cur_face); } case 14: case 15: { Face face_rt = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)}; if (!this->can_unite_with(face_rt)) return false; if (quad_top_row > 0 && face_rt.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1)) return false; Face face_lb = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)}; return !face_lb.can_unite_with(face_rt) || quad_top_row >= g_matrix.rows() - 2 || !face_lb.can_unite_with_quadruplet_top_edge(quad_left_col, quad_top_row + 1); } default: return false; }; } bool Face::can_unite_with_quadruplet_bottom_edge(unsigned short quad_left_col, unsigned short quad_top_row) const { assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1); switch (GetPointQuadrupletType(quad_left_col, quad_top_row)) { case 7: { Face cur_face = Face{g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)}; return this->can_unite_with(cur_face); } case 11: case 15: { Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)}; return this->can_unite_with(cur_face); } default: return false; }; } //returns an index of the next quadruplet to analyze unsigned Face::Constructor::add_face_to_the_right(unsigned short col, unsigned short row) { Face::Constructor::Reversed constrEnd; unsigned short cur_col = col; unsigned ret_index; do { switch (GetPointQuadrupletType(cur_col, row)) { case 11: this->add_point(cur_col + 1, row + 1); ret_index = g_matrix.locate(cur_col, row) + 1; break; case 13: this->add_point(cur_col + 1, row); ret_index = g_matrix.locate(cur_col, row) + 1; break; case 15: { Face lb_face = Face{g_matrix.locate(cur_col, row), g_matrix.locate(cur_col + 1, row + 1), g_matrix.locate(cur_col, row + 1)}; Face rt_face = Face{g_matrix.locate(cur_col, row), g_matrix.locate(cur_col + 1, row), g_matrix.locate(cur_col + 1, row + 1)}; if (lb_face.can_unite_with(rt_face) && (row == 0 || !rt_face.can_unite_with_quadruplet_bottom_edge(cur_col, row - 1))) { this->add_point(cur_col + 1, row); constrEnd.add_point(cur_col + 1, row + 1); if (cur_col < g_matrix.columns() - 2 && rt_face.can_unite_with_quadruplet_left_edge(cur_col + 1, row)) { ++cur_col; continue; } ret_index = g_matrix.locate(cur_col, row) + 1; }else { this->add_point(cur_col + 1, row + 1); ret_index = g_matrix.locate(cur_col, row); } break; } default: #ifndef NDEBUG assert(false); #endif ret_index = g_matrix.locate(g_matrix.columns() - 1, g_matrix.rows() - 1) + 1; } break; }while (true); this->add_reversed_list(std::move(constrEnd)); return ret_index; } void Face::Constructor::add_face_to_the_bottom(unsigned short col, unsigned short row) { Face::Constructor::Reversed constrEnd; unsigned short cur_row = row; unsigned char cur_type = GetPointQuadrupletType(col, cur_row); do { switch (cur_type) { case 13: this->add_point(col, cur_row + 1); break; case 14: this->add_point(col + 1, cur_row + 1); break; case 15: { Face rt_face = Face{g_matrix.locate(col, cur_row), g_matrix.locate(col + 1, cur_row), g_matrix.locate(col + 1, cur_row + 1)}; Face lb_face = Face{g_matrix.locate(col, cur_row), g_matrix.locate(col + 1, cur_row + 1), g_matrix.locate(col, cur_row + 1)}; if (lb_face.can_unite_with(rt_face)) { this->add_point(col + 1, cur_row + 1); constrEnd.add_point(col, cur_row + 1); if (cur_row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, cur_row + 1)) { cur_type = GetPointQuadrupletType(col, ++cur_row); continue; } break; }else this->add_point(col + 1, cur_row + 1); break; } #ifndef NDEBUG default: assert(false); #endif } break; }while (true); this->add_reversed_list(std::move(constrEnd)); } //returned object will be empty, if a vertex V is encountered for which V < g_matrix.locate(v1_col, v1_row)) is true Face::Constructor obtain_big_face(unsigned short v1_col, unsigned short v1_row, unsigned short v2_col, unsigned short v2_row) { unsigned start = g_matrix.locate(v1_col, v1_row); Face::Constructor constr; unsigned short cur_col = v1_col; unsigned short cur_row = v1_row; unsigned short next_col = v2_col; unsigned short next_row = v2_row; unsigned next_index = g_matrix.locate(next_col, next_row); constr.add_point(v1_col, v1_row); do { if (next_index < start) return Face::Constructor(); if (next_row == cur_row + 1) { if (next_col == cur_col + 1) { if (!g_matrix.is_empty_point(next_col - 1, next_row + 1)) { cur_col = next_col--; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col, next_row + 1)) { cur_col = next_col; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1)) { cur_col = next_col++; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col + 1, next_row)) { cur_col = next_col++; cur_row = next_row; }else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1)) { cur_col = next_col++; cur_row = next_row--; }else //if (!g_matrix.is_empty_point(next_col, next_row - 1)) { assert(!g_matrix.is_empty_point(next_col, next_row - 1)); cur_col = next_col; cur_row = next_row--; } }else if (next_col == cur_col) { if (!g_matrix.is_empty_point(next_col - 1, next_row)) { cur_col = next_col--; cur_row = next_row; }else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1)) { cur_col = next_col--; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col, next_row + 1)) { cur_col = next_col; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1)) { cur_col = next_col++; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col + 1, next_row)) { cur_col = next_col++; cur_row = next_row; }else //if (!g_matrix.is_empty_point(next_col + 1, next_row - 1)) { assert(!g_matrix.is_empty_point(next_col + 1, next_row - 1)); cur_col = next_col++; cur_row = next_row--; } }else { assert(next_col == cur_col - 1); if (!g_matrix.is_empty_point(next_col - 1, next_row - 1)) { cur_col = next_col--; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col - 1, next_row)) { cur_col = next_col--; cur_row = next_row; }else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1)) { cur_col = next_col--; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col, next_row + 1)) { cur_col = next_col; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1)) { cur_col = next_col++; cur_row = next_row++; }else //if (!g_matrix.is_empty_point(next_col + 1, next_row)) { assert(!g_matrix.is_empty_point(next_col + 1, next_row)); cur_col = next_col++; cur_row = next_row; } } }else if (next_row == cur_row) { if (next_col == cur_col + 1) { if (!g_matrix.is_empty_point(next_col, next_row + 1)) { cur_col = next_col; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1)) { cur_col = next_col++; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col + 1, next_row)) { cur_col = next_col++; cur_row = next_row; }else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1)) { cur_col = next_col++; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col, next_row - 1)) { cur_col = next_col; cur_row = next_row--; }else //if (!g_matrix.is_empty_point(next_col - 1, next_row - 1)) { assert(!g_matrix.is_empty_point(next_col - 1, next_row - 1)); cur_col = next_col--; cur_row = next_row--; } }else { assert(next_col == cur_col - 1); if (!g_matrix.is_empty_point(next_col, next_row - 1)) { cur_col = next_col; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1)) { cur_col = next_col--; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col - 1, next_row)) { cur_col = next_col--; cur_row = next_row; }else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1)) { cur_col = next_col--; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col, next_row + 1)) { cur_col = next_col; cur_row = next_row++; }else //if (!g_matrix.is_empty_point(next_col + 1, next_row + 1)) { assert((!g_matrix.is_empty_point(next_col + 1, next_row + 1))); cur_col = next_col++; cur_row = next_row++; } } }else { assert(next_row == cur_row - 1); if (next_col == cur_col + 1) { if (!g_matrix.is_empty_point(next_col + 1, next_row + 1)) { cur_col = next_col++; cur_row = next_row++; }else if (!g_matrix.is_empty_point(next_col + 1, next_row)) { cur_col = next_col++; cur_row = next_row; }else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1)) { cur_col = next_col++; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col, next_row - 1)) { cur_col = next_col; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1)) { cur_col = next_col--; cur_row = next_row--; }else // if (!g_matrix.is_empty_point(next_col - 1, next_row)) { assert(!g_matrix.is_empty_point(next_col - 1, next_row)); cur_col = next_col--; cur_row = next_row; } }else if (next_col == cur_col) { if (!g_matrix.is_empty_point(next_col + 1, next_row)) { cur_col = next_col++; cur_row = next_row; }else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1)) { cur_col = next_col++; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col, next_row - 1)) { cur_col = next_col; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1)) { cur_col = next_col--; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col - 1, next_row)) { cur_col = next_col--; cur_row = next_row; }else //if (!g_matrix.is_empty_point(next_col - 1, next_row + 1)) { assert(!g_matrix.is_empty_point(next_col - 1, next_row + 1)); cur_col = next_col--; cur_row = next_row++; } }else { assert(next_col == cur_col - 1); if (!g_matrix.is_empty_point(next_col + 1, next_row - 1)) { cur_col = next_col++; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col, next_row - 1)) { cur_col = next_col; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1)) { cur_col = next_col--; cur_row = next_row--; }else if (!g_matrix.is_empty_point(next_col - 1, next_row)) { cur_col = next_col--; cur_row = next_row; }else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1)) { cur_col = next_col--; cur_row = next_row++; }else //if (!g_matrix.is_empty_point(next_col, next_row + 1)) { assert(!g_matrix.is_empty_point(next_col, next_row + 1)); cur_col = next_col; cur_row = next_row++; } } } constr.add_point(cur_col, cur_row); }while ((next_index = g_matrix.locate(next_col, next_row)) != start); return constr; } //returns an index of the last quadruplet included in the face unsigned parse_vertex(FaceSet::Constructor& faces, unsigned short col, unsigned short row) { assert(col < g_matrix.columns() && row < g_matrix.rows()); if (col == g_matrix.columns() - 1) return g_matrix.locate(col, row) + 1; if (row == g_matrix.rows() - 1) return g_matrix.columns() * g_matrix.rows(); switch (GetPointQuadrupletType(col, row)) { case 7: { Face cur_face = Face{g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)}; if (row < g_matrix.rows() - 2 && cur_face.can_unite_with_quadruplet_top_edge(col, row + 1)) { Face::Constructor constr; constr.add_point(col + 1, row); constr.add_point(col + 1, row + 1); constr.add_face_to_the_bottom(col, row + 1); constr.add_point(col, row + 1); faces.add_face(Face(std::move(constr))); return g_matrix.locate(col, row) + 1; }else if (col < g_matrix.columns() - 2 && cur_face.can_unite_with_quadruplet_left_edge(col + 1, row)) { Face::Constructor constr; constr.add_point(col + 1, row); auto ret = constr.add_face_to_the_right(col + 1, row); constr.add_point(col + 1, row + 1); constr.add_point(col, row + 1); faces.add_face(Face(std::move(constr))); return ret; }else { faces.add_face(std::move(cur_face)); return g_matrix.locate(col, row) + 1; } } case 10: { if (g_matrix.is_empty_point(col - 1, row + 1)) return g_matrix.locate(col, row) + 1; auto constr = obtain_big_face(col, row, col + 1, row + 1); if (!constr.empty()) faces.add_face(std::move(constr)); return g_matrix.locate(col, row) + 1; } case 11: { Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)}; if (row < g_matrix.rows() - 2 && cur_face.can_unite_with_quadruplet_top_edge(col, row + 1)) { Face::Constructor constr; constr.add_point(col, row); constr.add_point(col + 1, row + 1); constr.add_face_to_the_bottom(col, row + 1); constr.add_point(col, row + 1); faces.add_face(Face(std::move(constr))); }else if (col == 0 || !cur_face.can_unite_with_quadruplet_right_edge(col - 1, row)) faces.add_face(std::move(cur_face)); return g_matrix.locate(col, row) + 1; } case 12: { if (g_matrix.is_empty_point(col - 1, row + 1)) return g_matrix.locate(col, row) + 1; auto constr = obtain_big_face(col, row, col + 1, row); if (!constr.empty()) faces.add_face(std::move(constr)); return g_matrix.locate(col, row) + 1; } case 13: { Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col, row + 1)}; if ((col == 0 || !cur_face.can_unite_with_quadruplet_right_edge(col - 1, row)) && (row == 0 || !cur_face.can_unite_with_quadruplet_bottom_edge(col, row - 1))) faces.add_face(std::move(cur_face)); return g_matrix.locate(col, row) + 1; } case 14: { if (!g_matrix.is_empty_point(col - 1, row + 1)) { auto constr = obtain_big_face(col, row, col + 1, row + 1); if (!constr.empty()) faces.add_face(std::move(constr)); } Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1)}; if (row > 0 && cur_face.can_unite_with_quadruplet_bottom_edge(col, row - 1)) return g_matrix.locate(col, row) + 1; if (col < g_matrix.columns() - 2 && cur_face.can_unite_with_quadruplet_left_edge(col + 1, row)) { Face::Constructor constr; constr.add_point(col, row); constr.add_point(col + 1, row); auto ret = constr.add_face_to_the_right(col + 1, row); constr.add_point(col + 1, row + 1); faces.add_face(Face(std::move(constr))); return ret; }else { faces.add_face(std::move(cur_face)); return g_matrix.locate(col, row) + 1; } } case 15: { Face lb_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)}; Face rt_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1)}; if (lb_face.can_unite_with(rt_face)) { if (row > 0 && rt_face.can_unite_with_quadruplet_bottom_edge(col, row - 1)) return g_matrix.locate(col, row) + 1; if (row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, row + 1)) { Face::Constructor constr; constr.add_point(col, row); constr.add_point(col + 1, row); constr.add_point(col + 1, row + 1); constr.add_face_to_the_bottom(col, row + 1); constr.add_point(col, row + 1); faces.add_face(Face(std::move(constr))); return g_matrix.locate(col, row) + 1; } if (col > 0 && lb_face.can_unite_with_quadruplet_right_edge(col - 1, row)) return g_matrix.locate(col, row) + 1; if (col == g_matrix.columns() - 2 || !rt_face.can_unite_with_quadruplet_left_edge(col + 1, row)) { faces.add_face(Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)}); return g_matrix.locate(col, row) + 1; }else { Face::Constructor constr; constr.add_point(col, row); constr.add_point(col + 1, row); auto ret = constr.add_face_to_the_right(col + 1, row); constr.add_point(col + 1, row + 1); constr.add_point(col, row + 1); faces.add_face(Face(std::move(constr))); return ret; } }else { if (row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, row + 1)) { Face::Constructor constr; constr.add_point(col, row); constr.add_point(col + 1, row + 1); constr.add_face_to_the_bottom(col, row + 1); constr.add_point(col, row + 1); faces.add_face(Face(std::move(constr))); }else if (col == 0 || !lb_face.can_unite_with_quadruplet_right_edge(col - 1, row)) faces.add_face(std::move(lb_face)); if (row == 0 || !rt_face.can_unite_with_quadruplet_bottom_edge(col, row - 1)) { if (col < g_matrix.columns() - 2 && rt_face.can_unite_with_quadruplet_left_edge(col + 1, row)) { Face::Constructor constr; constr.add_point(col, row); constr.add_point(col + 1, row); auto ret = constr.add_face_to_the_right(col + 1, row); constr.add_point(col + 1, row + 1); faces.add_face(Face(std::move(constr))); return ret; }else { faces.add_face(std::move(rt_face)); return g_matrix.locate(col, row) + 1; } }else return g_matrix.locate(col, row) + 1; } } default: return g_matrix.locate(col, row) + 1; } } FaceSet parse_matrix(unsigned start_element /*= 0*/, unsigned end_element /*= g_matrix.columns() * g_matrix.rows()*/) { FaceSet::Constructor set; for (unsigned index = start_element; index < end_element; ) { index = parse_vertex(set, g_matrix.point_x(index), g_matrix.point_y(index)); } return set; } #include <ostream> static std::atomic_flag g_matrix_busy = ATOMIC_FLAG_INIT; static unsigned convert_hgt_to_index_based_face(binary_ostream& os, short* pInput, unsigned short cColumns, unsigned short cRows, double eColumnResolution, double eRowResolution) { std::list<std::future<FaceSet>> futures; while (g_matrix_busy.test_and_set(std::memory_order_acquire)) continue; g_matrix = Matrix(pInput, cColumns, cRows, eColumnResolution, eRowResolution); //auto cBlocks = unsigned(1); auto cBlocks = unsigned(std::thread::hardware_concurrency()); auto cItemsTotal = unsigned(cColumns) * cRows; auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks; for (unsigned i = 0; i < cBlocks; ++i) futures.emplace_back(std::async(std::launch::async, [i, cBlock, cItemsTotal]() -> auto { return parse_matrix(i * cBlock, std::min((i + 1) * cBlock, cItemsTotal)); })); unsigned face_count = 0; auto face_count_pos = os.tellp(); os.seekp(sizeof(unsigned), std::ios_base::cur); for (auto& fut:futures) { auto set = fut.get(); face_count += unsigned(set.size()); for (const auto& face:set) { os << face.size(); for (auto pt:face) os << g_matrix.point_x(pt) << g_matrix.point_y(pt) << g_matrix.point_z(pt); } } g_matrix_busy.clear(std::memory_order_release); auto endp = os.tellp(); os.seekp(face_count_pos); os << face_count; os.seekp(endp); return face_count; } #if FILESYSTEM_CPP17 unsigned convert_hgt_to_index_based_face(std::filesystem::path input, std::filesystem::path output) { auto os = binary_ofstream(output); std::ifstream is(input, std::ios_base::in | std::ios_base::binary); is.seekg(0, std::ios_base::end); auto cb = is.tellg(); if (cb % sizeof(short) != 0) throw std::invalid_argument("Unexpected HGT file size"); is.seekg(0, std::ios_base::beg); switch (cb) { case HGT_1.cColumns * HGT_1.cRows * sizeof(short): { auto pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short)); is.read(reinterpret_cast<char*>(pInput.get()), cb); return convert_hgt_to_index_based_face(os, pInput.get(), (unsigned short) (HGT_1.cColumns), (unsigned short) (HGT_1.cRows), HGT_1.dx, HGT_1.dy); } case HGT_3.cColumns * HGT_3.cRows * sizeof(short): { auto pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short)); is.read(reinterpret_cast<char*>(pInput.get()), cb); return convert_hgt_to_index_based_face(os, pInput.get(), (unsigned short) (HGT_3.cColumns), (unsigned short) (HGT_3.cRows), HGT_3.dx, HGT_3.dy); } default: throw std::invalid_argument("Unexpected HGT file size"); }; } #endif //FILESYSTEM_CPP17 struct conversion_result { conversion_result() = default; conversion_result(std::vector<face_t>&& lstWater, std::vector<face_t>&& lstLand) :m_WaterFaces(std::move(lstWater)), m_LandFaces(std::move(lstLand)) {} inline std::vector<face_t>& water_faces() noexcept { return m_WaterFaces; } inline std::vector<face_t>& land_faces() noexcept { return m_LandFaces; } inline const std::vector<face_t>& water_faces() const noexcept { return m_WaterFaces; } inline const std::vector<face_t>& land_faces() const noexcept { return m_LandFaces; } private: std::vector<face_t> m_WaterFaces; std::vector<face_t> m_LandFaces; }; template <class FaceType, class LandFacePlacementCallable, class WaterFacePlacementCallable> static void internal_face_to_external_face(std::true_type /*do_shift*/, FaceType&& face, LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable) { auto domain_id = GetFaceDomainDataId(face); auto ext = face_t(std::forward<FaceType>(face)); for (auto& pt:ext) pt.z += -double(g_matrix.min_height()); switch (domain_id) { case ConstantDomainDataId::SurfaceLand: std::forward<LandFacePlacementCallable>(land_callable)(std::move(ext)); break; case ConstantDomainDataId::SurfaceWater: std::forward<WaterFacePlacementCallable>(water_callable)(std::move(ext)); break; default: throw std::invalid_argument("Invalid face domain data in HGT"); } } template <class FaceType, class LandFacePlacementCallable, class WaterFacePlacementCallable> static void internal_face_to_external_face(std::false_type /*do_shift*/, FaceType&& face, LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable) { switch (GetFaceDomainDataId(face)) { case ConstantDomainDataId::SurfaceLand: std::forward<LandFacePlacementCallable>(land_callable)(face_t(std::forward<FaceType>(face))); break; case ConstantDomainDataId::SurfaceWater: std::forward<WaterFacePlacementCallable>(water_callable)(face_t(std::forward<FaceType>(face))); break; default: throw std::invalid_argument("Invalid face domain data in HGT"); } } template <class fDoShift, class InternalFaceSetBeginIteratorType, class InternalFaceSetEndIteratorType, class LandFacePlacementCallable, class WaterFacePlacementCallable> static void translate_internal_face_set(fDoShift do_shift, InternalFaceSetBeginIteratorType internal_set_begin, InternalFaceSetEndIteratorType internal_set_end, LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable) { static_assert(std::is_same_v<fDoShift, std::true_type> || std::is_same_v<fDoShift, std::false_type>); for (auto itFace = internal_set_begin; itFace != internal_set_end; ++itFace) internal_face_to_external_face(do_shift, *itFace, std::forward<LandFacePlacementCallable>(land_callable), std::forward<WaterFacePlacementCallable>(water_callable)); } template <class FaceSetType, class LandFacePlacementCallable, class WaterFacePlacementCallable> static void translate_internal_face_set(FaceSetType&& face_set, LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable) { if (g_matrix.min_height() < 0) translate_internal_face_set(std::true_type(), std::begin(face_set), std::end(face_set), std::forward<LandFacePlacementCallable>(land_callable), std::forward<WaterFacePlacementCallable>(water_callable)); else translate_internal_face_set(std::false_type(), std::begin(face_set), std::end(face_set), std::forward<LandFacePlacementCallable>(land_callable), std::forward<WaterFacePlacementCallable>(water_callable)); } struct hgt_state { void start(binary_ostream& os, IDomainConverter& converter, unsigned points_to_process_at_start) { assert(m_pOs == nullptr && m_faces.empty() && process_land_face_ptr == nullptr && process_water_face_ptr == nullptr); m_pOs = &os; m_face_water_domain_data = converter.constant_face_domain_data(ConstantDomainDataId::SurfaceWater); m_poly_water_domain_data = converter.constant_poly_domain_data(ConstantDomainDataId::SurfaceWater); m_face_land_domain_data = converter.constant_face_domain_data(ConstantDomainDataId::SurfaceLand); m_poly_land_domain_data = converter.constant_poly_domain_data(ConstantDomainDataId::SurfaceLand); auto internal_set = parse_matrix(0, points_to_process_at_start); process_land_face_ptr = &hgt_state::write_land_face_and_poly_header_to_stream; process_water_face_ptr = &hgt_state::write_water_face_and_poly_header_to_stream; std::vector<face_t> stored_faces; stored_faces.reserve(internal_set.size()); translate_internal_face_set(internal_set, [this](face_t&& face) {this->process_land_face(std::move(face));}, [&stored_faces](face_t&& face) {stored_faces.emplace_back(std::move(face));}); stored_faces.shrink_to_fit(); m_face_count_water = unsigned(stored_faces.size()); m_face_count_land = unsigned(internal_set.size()) - m_face_count_water; m_faces.emplace_back(std::move(stored_faces)); } void add_results(conversion_result&& res) { m_face_count_land += CAMaaS::size_type(res.land_faces().size()); m_face_count_water += CAMaaS::size_type(res.water_faces().size()); for (auto& face:res.land_faces()) process_land_face(std::move(face)); res.land_faces().clear(); m_faces.emplace_back(std::move(res.water_faces())); } hgt_t::conversion_statistics_t finalize() { if (m_face_count_land != 0) { m_pOs->seekp(m_face_count_pos); *m_pOs << CAMaaS::size_type(m_face_count_land); m_pOs->seekp(0, std::ios_base::end); } if (m_face_count_water != 0) { for (auto& vWater:m_faces) { for (auto& face:vWater) this->process_water_face(std::move(face)); } } short min_height = g_matrix.min_height(), max_height = g_matrix.max_height(); if (min_height < 0) { max_height -= min_height; min_height = 0; } hgt_t::conversion_statistics_t res{m_objects}; *this = hgt_state(); return res; } private: CAMaaS::size_type m_objects = 0; binary_ostream* m_pOs = nullptr; binary_ostream::pos_type m_face_count_pos = 0; CAMaaS::size_type m_face_count_land = 0; CAMaaS::size_type m_face_count_water = 0; std::list<std::vector<face_t>> m_faces; void (hgt_state::*process_land_face_ptr)(face_t&& face) = nullptr; void (hgt_state::*process_water_face_ptr)(face_t&& face) = nullptr; domain_data_map m_face_water_domain_data, m_poly_water_domain_data, m_face_land_domain_data, m_poly_land_domain_data; void write_poly_header(std::string_view poly_name, const domain_data_map& domain_data) { *m_pOs << std::uint32_t(poly_name.size()); m_pOs->write(poly_name.data(), poly_name.size()); *m_pOs << std::uint32_t(domain_data.size()); for (auto& prDomain:domain_data) { *m_pOs << std::uint32_t(prDomain.first.size()); m_pOs->write(prDomain.first.data(), prDomain.first.size()); *m_pOs << std::uint32_t(prDomain.second.size()); m_pOs->write(prDomain.second.data(), prDomain.second.size()); } *m_pOs << CAMaaS::ObjectPoly; m_face_count_pos = m_pOs->tellp(); } inline void write_land_poly_header() { this->write_poly_header("HGT land", m_poly_land_domain_data); *m_pOs << m_face_count_land; } void write_water_poly_header() { this->write_poly_header("HGT water", m_poly_water_domain_data); *m_pOs << m_face_count_water; } void write_face_to_stream(face_t&& face, const domain_data_map& domain_data) { *m_pOs << std::uint32_t(face.size()); for (auto& pt:face) *m_pOs << std::uint32_t(3) << pt.x << pt.y << pt.z; *m_pOs << std::uint32_t(domain_data.size()); for (auto& prDomain:domain_data) { *m_pOs << std::uint32_t(prDomain.first.size()); m_pOs->write(prDomain.first.data(), prDomain.first.size()); *m_pOs << std::uint32_t(prDomain.second.size()); m_pOs->write(prDomain.second.data(), prDomain.second.size()); } } void write_water_face_to_stream(face_t&& face) { this->write_face_to_stream(std::move(face), m_face_water_domain_data); } void write_land_face_to_stream(face_t&& face) { this->write_face_to_stream(std::move(face), m_face_land_domain_data); } void write_water_face_and_poly_header_to_stream(face_t&& face) { ++m_objects; this->write_water_poly_header(); this->write_water_face_to_stream(std::move(face)); process_water_face_ptr = &hgt_state::write_water_face_to_stream; } void write_land_face_and_poly_header_to_stream(face_t&& face) { ++m_objects; this->write_land_poly_header(); this->write_land_face_to_stream(std::move(face)); process_land_face_ptr = &hgt_state::write_land_face_to_stream; } inline void process_land_face(face_t&& face) { return (this->*process_land_face_ptr)(std::move(face)); } inline void process_water_face(face_t&& face) { return (this->*process_water_face_ptr)(std::move(face)); } }; class hgt_impl_t:public hgt_t { std::unique_ptr<short[]> m_pInput; IDomainConverter* m_pConverter; hgt_t::attributes_t m_attr; public: hgt_impl_t() = default; hgt_impl_t(std::istream& is_data, IDomainConverter& converter):m_pConverter(std::addressof(converter)) { is_data.seekg(0, std::ios_base::end); auto cb = is_data.tellg(); if (cb % sizeof(short) != 0) throw std::invalid_argument("Unexpected HGT file size"); is_data.seekg(0, std::ios_base::beg); switch (cb) { case HGT_1.cColumns * HGT_1.cRows * sizeof(short): { m_attr.resolution = HGT_1; m_pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short)); is_data.read(reinterpret_cast<char*>(m_pInput.get()), cb); break; } case HGT_3.cColumns * HGT_3.cRows * sizeof(short): { m_attr.resolution = HGT_3; m_pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short)); is_data.read(reinterpret_cast<char*>(m_pInput.get()), cb); break; } default: throw std::invalid_argument("Unexpected HGT file size"); }; while (g_matrix_busy.test_and_set(std::memory_order_acquire)) continue; g_matrix = Matrix(m_pInput.get(), (unsigned short) m_attr.resolution.cColumns, (unsigned short) m_attr.resolution.cRows, m_attr.resolution.dx, m_attr.resolution.dy); m_attr.min_height = g_matrix.min_height(); m_attr.max_height = g_matrix.max_height(); m_attr.height_offset = m_attr.min_height < 0?-m_attr.min_height:0; } hgt_impl_t(const hgt_impl_t&) = default; hgt_impl_t(hgt_impl_t&&) = default; hgt_impl_t& operator=(const hgt_impl_t&) = default; hgt_impl_t& operator=(hgt_impl_t&&) = default; virtual ~hgt_impl_t() { g_matrix_busy.clear(std::memory_order_relaxed); } virtual const attributes_t& attributes() const { return m_attr; } virtual conversion_statistics_t write(binary_ostream& os) const { auto cBlocks = unsigned(std::thread::hardware_concurrency()); auto cItemsTotal = unsigned(m_attr.resolution.cColumns * m_attr.resolution.cRows); auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks; std::list<std::future<conversion_result>> futures; for (unsigned i = 1; i < cBlocks; ++i) futures.emplace_back(std::async(std::launch::async, [i, cBlock, cItemsTotal]() -> auto { std::vector<face_t> land_faces, water_faces; unsigned start_element = i * cBlock; unsigned end_element = std::min(start_element + cBlock, cItemsTotal); auto internal_set = parse_matrix(start_element, end_element); land_faces.reserve(internal_set.size()); water_faces.reserve(internal_set.size()); translate_internal_face_set(internal_set, [&land_faces](face_t&& face) {land_faces.emplace_back(std::move(face));}, [&water_faces](face_t&& face) {water_faces.emplace_back(std::move(face));}); water_faces.shrink_to_fit(); land_faces.shrink_to_fit(); return conversion_result(std::move(water_faces), std::move(land_faces)); })); hgt_state face_converter; face_converter.start(os, *m_pConverter, std::min(cBlock, cItemsTotal)); for (auto& fut:futures) face_converter.add_results(fut.get()); return face_converter.finalize(); } }; std::unique_ptr<hgt_t> hgt_t::read(std::istream& is_data, IDomainConverter& converter) { return std::make_unique<hgt_impl_t>(is_data, converter); }
35.778551
178
0.696312
lpsztemp
ffbedafd1c1ffd4835eac9d1aa99cbb8bc48a4f4
11,033
cpp
C++
project/src/backend/sdl/SDLSystem.cpp
ubald/lime
4c0d09368ebff06742dd062bb6872306a8a44d95
[ "MIT" ]
null
null
null
project/src/backend/sdl/SDLSystem.cpp
ubald/lime
4c0d09368ebff06742dd062bb6872306a8a44d95
[ "MIT" ]
null
null
null
project/src/backend/sdl/SDLSystem.cpp
ubald/lime
4c0d09368ebff06742dd062bb6872306a8a44d95
[ "MIT" ]
null
null
null
#include <graphics/PixelFormat.h> #include <math/Rectangle.h> #include <system/Clipboard.h> #include <system/JNI.h> #include <system/System.h> #ifdef HX_MACOS #include <CoreFoundation/CoreFoundation.h> #endif #ifdef HX_WINDOWS #include <shlobj.h> #include <stdio.h> //#include <io.h> //#include <fcntl.h> #ifdef __MINGW32__ #ifndef CSIDL_MYDOCUMENTS #define CSIDL_MYDOCUMENTS CSIDL_PERSONAL #endif #ifndef SHGFP_TYPE_CURRENT #define SHGFP_TYPE_CURRENT 0 #endif #endif #if UNICODE #define WIN_StringToUTF8(S) SDL_iconv_string("UTF-8", "UTF-16LE", (char *)(S), (SDL_wcslen(S)+1)*sizeof(WCHAR)) #define WIN_UTF8ToString(S) (WCHAR *)SDL_iconv_string("UTF-16LE", "UTF-8", (char *)(S), SDL_strlen(S)+1) #else #define WIN_StringToUTF8(S) SDL_iconv_string("UTF-8", "ASCII", (char *)(S), (SDL_strlen(S)+1)) #define WIN_UTF8ToString(S) SDL_iconv_string("ASCII", "UTF-8", (char *)(S), SDL_strlen(S)+1) #endif #endif #include <SDL.h> #include <string> namespace lime { static int id_bounds; static int id_currentMode; static int id_height; static int id_name; static int id_pixelFormat; static int id_refreshRate; static int id_supportedModes; static int id_width; static bool init = false; const char* Clipboard::GetText () { return SDL_GetClipboardText (); } bool Clipboard::HasText () { return SDL_HasClipboardText (); } void Clipboard::SetText (const char* text) { SDL_SetClipboardText (text); } void *JNI::GetEnv () { #ifdef ANDROID return SDL_AndroidGetJNIEnv (); #else return 0; #endif } const char* System::GetDirectory (SystemDirectory type, const char* company, const char* title) { switch (type) { case APPLICATION: return SDL_GetBasePath (); break; case APPLICATION_STORAGE: return SDL_GetPrefPath (company, title); break; case DESKTOP: { #if defined (HX_WINRT) Windows::Storage::StorageFolder folder = Windows::Storage::KnownFolders::HomeGroup; std::wstring resultW (folder->Begin ()); std::string result (resultW.begin (), resultW.end ()); return result.c_str (); #elif defined (HX_WINDOWS) char result[MAX_PATH] = ""; SHGetFolderPath (NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, result); return WIN_StringToUTF8 (result); #else std::string result = std::string (getenv ("HOME")) + std::string ("/Desktop"); return result.c_str (); #endif break; } case DOCUMENTS: { #if defined (HX_WINRT) Windows::Storage::StorageFolder folder = Windows::Storage::KnownFolders::DocumentsLibrary; std::wstring resultW (folder->Begin ()); std::string result (resultW.begin (), resultW.end ()); return result.c_str (); #elif defined (HX_WINDOWS) char result[MAX_PATH] = ""; SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, result); return WIN_StringToUTF8 (result); #else std::string result = std::string (getenv ("HOME")) + std::string ("/Documents"); return result.c_str (); #endif break; } case FONTS: { #if defined (HX_WINRT) return 0; #elif defined (HX_WINDOWS) char result[MAX_PATH] = ""; SHGetFolderPath (NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, result); return WIN_StringToUTF8 (result); #elif defined (HX_MACOS) return "/Library/Fonts"; #elif defined (IPHONEOS) return "/System/Library/Fonts/Cache"; #elif defined (ANDROID) return "/system/fonts"; #elif defined (BLACKBERRY) return "/usr/fonts/font_repository/monotype"; #else return "/usr/share/fonts/truetype"; #endif break; } case USER: { #if defined (HX_WINRT) Windows::Storage::StorageFolder folder = Windows::Storage::ApplicationData::Current->RoamingFolder; std::wstring resultW (folder->Begin ()); std::string result (resultW.begin (), resultW.end ()); return result.c_str (); #elif defined (HX_WINDOWS) char result[MAX_PATH] = ""; SHGetFolderPath (NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, result); return WIN_StringToUTF8 (result); #else std::string result = getenv ("HOME"); return result.c_str (); #endif break; } } return 0; } value System::GetDisplay (int id) { if (!init) { id_bounds = val_id ("bounds"); id_currentMode = val_id ("currentMode"); id_height = val_id ("height"); id_name = val_id ("name"); id_pixelFormat = val_id ("pixelFormat"); id_refreshRate = val_id ("refreshRate"); id_supportedModes = val_id ("supportedModes"); id_width = val_id ("width"); init = true; } int numDisplays = GetNumDisplays (); if (id < 0 || id >= numDisplays) { return alloc_null (); } value display = alloc_empty_object (); alloc_field (display, id_name, alloc_string (SDL_GetDisplayName (id))); SDL_Rect bounds = { 0, 0, 0, 0 }; SDL_GetDisplayBounds (id, &bounds); alloc_field (display, id_bounds, Rectangle (bounds.x, bounds.y, bounds.w, bounds.h).Value ()); SDL_DisplayMode currentDisplayMode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 }; SDL_DisplayMode displayMode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 }; SDL_GetCurrentDisplayMode (id, &currentDisplayMode); int numDisplayModes = SDL_GetNumDisplayModes (id); value supportedModes = alloc_array (numDisplayModes); value mode; for (int i = 0; i < numDisplayModes; i++) { SDL_GetDisplayMode (id, i, &displayMode); if (displayMode.format == currentDisplayMode.format && displayMode.w == currentDisplayMode.w && displayMode.h == currentDisplayMode.h && displayMode.refresh_rate == currentDisplayMode.refresh_rate) { alloc_field (display, id_currentMode, alloc_int (i)); } mode = alloc_empty_object (); alloc_field (mode, id_height, alloc_int (displayMode.h)); switch (displayMode.format) { case SDL_PIXELFORMAT_ARGB8888: alloc_field (mode, id_pixelFormat, alloc_int (ARGB32)); break; case SDL_PIXELFORMAT_BGRA8888: case SDL_PIXELFORMAT_BGRX8888: alloc_field (mode, id_pixelFormat, alloc_int (BGRA32)); break; default: alloc_field (mode, id_pixelFormat, alloc_int (RGBA32)); } alloc_field (mode, id_refreshRate, alloc_int (displayMode.refresh_rate)); alloc_field (mode, id_width, alloc_int (displayMode.w)); val_array_set_i (supportedModes, i, mode); } alloc_field (display, id_supportedModes, supportedModes); return display; } int System::GetNumDisplays () { return SDL_GetNumVideoDisplays (); } double System::GetTimer () { return SDL_GetTicks (); } FILE* FILE_HANDLE::getFile () { #ifndef HX_WINDOWS switch (((SDL_RWops*)handle)->type) { case SDL_RWOPS_STDFILE: return ((SDL_RWops*)handle)->hidden.stdio.fp; case SDL_RWOPS_JNIFILE: { #ifdef ANDROID FILE* file = ::fdopen (((SDL_RWops*)handle)->hidden.androidio.fd, "rb"); ::fseek (file, ((SDL_RWops*)handle)->hidden.androidio.offset, 0); return file; #endif } case SDL_RWOPS_WINFILE: { /*#ifdef HX_WINDOWS printf("SDKFLJDSLFKJ\n"); int fd = _open_osfhandle ((intptr_t)((SDL_RWops*)handle)->hidden.windowsio.h, _O_RDONLY); if (fd != -1) { printf("SDKFLJDSLFKJ\n"); return ::fdopen (fd, "rb"); } #endif*/ } } return NULL; #else return (FILE*)handle; #endif } int FILE_HANDLE::getLength () { #ifndef HX_WINDOWS return SDL_RWsize (((SDL_RWops*)handle)); #else return 0; #endif } bool FILE_HANDLE::isFile () { #ifndef HX_WINDOWS return ((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE; #else return true; #endif } int fclose (FILE_HANDLE *stream) { #ifndef HX_WINDOWS if (stream) { int code = SDL_RWclose ((SDL_RWops*)stream->handle); delete stream; return code; } return 0; #else if (stream) { int code = ::fclose ((FILE*)stream->handle); delete stream; return code; } return 0; #endif } FILE_HANDLE *fdopen (int fd, const char *mode) { #ifndef HX_WINDOWS FILE* fp = ::fdopen (fd, mode); SDL_RWops *result = SDL_RWFromFP (fp, SDL_TRUE); if (result) { return new FILE_HANDLE (result); } return NULL; #else FILE* result = ::fdopen (fd, mode); if (result) { return new FILE_HANDLE (result); } return NULL; #endif } FILE_HANDLE *fopen (const char *filename, const char *mode) { #ifndef HX_WINDOWS SDL_RWops *result; #ifdef HX_MACOS result = SDL_RWFromFile (filename, "rb"); if (!result) { CFStringRef str = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8); CFURLRef path = CFBundleCopyResourceURL (CFBundleGetMainBundle (), str, NULL, NULL); CFRelease (str); if (path) { str = CFURLCopyPath (path); CFIndex maxSize = CFStringGetMaximumSizeForEncoding (CFStringGetLength (str), kCFStringEncodingUTF8); char *buffer = (char *)malloc (maxSize); if (CFStringGetCString (str, buffer, maxSize, kCFStringEncodingUTF8)) { result = SDL_RWFromFP (::fopen (buffer, "rb"), SDL_TRUE); free (buffer); } CFRelease (str); CFRelease (path); } } #else result = SDL_RWFromFile (filename, mode); #endif if (result) { return new FILE_HANDLE (result); } return NULL; #else FILE* result = ::fopen (filename, mode); if (result) { return new FILE_HANDLE (result); } return NULL; #endif } size_t fread (void *ptr, size_t size, size_t count, FILE_HANDLE *stream) { #ifndef HX_WINDOWS return SDL_RWread (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count); #else return ::fread (ptr, size, count, (FILE*)stream->handle); #endif } int fseek (FILE_HANDLE *stream, long int offset, int origin) { #ifndef HX_WINDOWS return SDL_RWseek (stream ? (SDL_RWops*)stream->handle : NULL, offset, origin); #else return ::fseek ((FILE*)stream->handle, offset, origin); #endif } long int ftell (FILE_HANDLE *stream) { #ifndef HX_WINDOWS return SDL_RWtell (stream ? (SDL_RWops*)stream->handle : NULL); #else return ::ftell ((FILE*)stream->handle); #endif } size_t fwrite (const void *ptr, size_t size, size_t count, FILE_HANDLE *stream) { #ifndef HX_WINDOWS return SDL_RWwrite (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count); #else return ::fwrite (ptr, size, count, (FILE*)stream->handle); #endif } }
19.088235
202
0.628388
ubald
ffbf7e11e20dd95107c6ac3bcd024ed2ab30fbe9
707
cpp
C++
weekly-contest-129/binary-string-with-substrings-representing-1-to-n/binary-string-with-substrings-representing-1-to-n.cpp
Shuumatsu/leetcode-weekly-contest
6cc5cf8e8b57775e68b5bdeb932e30e327502c65
[ "MIT" ]
1
2019-05-28T01:53:36.000Z
2019-05-28T01:53:36.000Z
weekly-contest-129/binary-string-with-substrings-representing-1-to-n/binary-string-with-substrings-representing-1-to-n.cpp
Shuumatsu/leetcode-weekly-contest
6cc5cf8e8b57775e68b5bdeb932e30e327502c65
[ "MIT" ]
null
null
null
weekly-contest-129/binary-string-with-substrings-representing-1-to-n/binary-string-with-substrings-representing-1-to-n.cpp
Shuumatsu/leetcode-weekly-contest
6cc5cf8e8b57775e68b5bdeb932e30e327502c65
[ "MIT" ]
null
null
null
#include <functional> #include <iostream> #include <iterator> #include <map> #include <queue> #include <set> #include <sstream> #include <vector> using namespace std; auto to_binary = [&](auto n) { vector<char> b; while (n != 0) { b.push_back(n & 1 == 1 ? '1' : '0'); n /= 2; } reverse(b.begin(), b.end()); ostringstream bss; std::copy(b.begin(), b.end(), ostream_iterator<char>(bss)); return bss.str(); }; class Solution { public: bool queryString(string str, int N) { for (auto i = 0; i <= N; i++) { if (str.find(to_binary(i)) == string::npos) { return false; } } return true; } };
19.108108
63
0.523338
Shuumatsu
ffc1ec7b7db76f37d39ecd7a2bc03c0e050477eb
11,817
cpp
C++
vlr-util/util.Unicode.cpp
nick42/vlr-util
937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91
[ "Artistic-2.0" ]
null
null
null
vlr-util/util.Unicode.cpp
nick42/vlr-util
937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91
[ "Artistic-2.0" ]
null
null
null
vlr-util/util.Unicode.cpp
nick42/vlr-util
937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91
[ "Artistic-2.0" ]
null
null
null
#include "pch.h" #include "util.Unicode.h" #include "UtilMacros.Assertions.h" #include "UtilMacros.General.h" #include "util.range_checked_cast.h" #include "util.CStringBufferAccess.h" NAMESPACE_BEGIN( vlr ) NAMESPACE_BEGIN( util ) HRESULT CStringConversion::MultiByte_to_UTF16( std::string_view svValue, wchar_t* pOutputBuffer, size_t nOutputBufferLengthBytes, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { if (svValue.empty()) { return S_FALSE; } bool bInputBufferShouldIncludeNullTerminator = true && oStringConversionOptions.m_bInputStringIsNullTerminated && (!oStringConversionOptions.m_bGenerateResultNotNullTerminated) ; auto nEffectiveInputBufferLengthChars = svValue.length() + (bInputBufferShouldIncludeNullTerminator ? 1 : 0); auto nOutputBufferLengthChars = (nOutputBufferLengthBytes / sizeof( wchar_t )); bool bNeedAdditionalSpaceInOutputBufferToAddNullTerminator = true && (!bInputBufferShouldIncludeNullTerminator) && (!oStringConversionOptions.m_bGenerateResultNotNullTerminated) && (!oStringConversionOptions.m_bInputStringIsNullTerminated) ; size_t nOutputBufferLengthAdjustmentBytes = bNeedAdditionalSpaceInOutputBufferToAddNullTerminator ? sizeof( wchar_t ) : 0; // Be sure we don't underflow, if we passed a zero for buffer length auto nUsableOutputBufferLengthChars = (nOutputBufferLengthChars == 0) ? 0 : nOutputBufferLengthChars - nOutputBufferLengthAdjustmentBytes; auto nResult = ::MultiByteToWideChar( oStringConversionOptions.GetCodePageIdentifier(), oStringConversionOptions.OnMultiByteToWideChar_GetFlags(), svValue.data(), range_checked_cast<int>(nEffectiveInputBufferLengthChars), pOutputBuffer, range_checked_cast<int>(nUsableOutputBufferLengthChars) ); if (nResult == 0) { return HRESULT_FROM_WIN32( GetLastError() ); } VLR_IF_NOT_NULL( pStringConversionResults )->m_nOuputSizeBytes = (range_checked_cast<size_t>(nResult) * sizeof( wchar_t )) + nOutputBufferLengthAdjustmentBytes; if (range_checked_cast<size_t>(nResult) > nUsableOutputBufferLengthChars) { return S_FALSE; } if (bNeedAdditionalSpaceInOutputBufferToAddNullTerminator) { ASSERT( range_checked_cast<size_t>(nResult) < nOutputBufferLengthChars ); pOutputBuffer[nResult] = L'\0'; } return S_OK; } HRESULT CStringConversion::UTF16_to_MultiByte( std::wstring_view svValue, char* pOutputBuffer, size_t nOutputBufferLengthBytes, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { if (svValue.empty()) { return S_FALSE; } bool bInputBufferShouldIncludeNullTerminator = true && oStringConversionOptions.m_bInputStringIsNullTerminated && (!oStringConversionOptions.m_bGenerateResultNotNullTerminated) ; auto nEffectiveInputBufferLengthChars = svValue.length() + (bInputBufferShouldIncludeNullTerminator ? 1 : 0); auto nOutputBufferLengthChars = (nOutputBufferLengthBytes / sizeof( char )); bool bNeedAdditionalSpaceInOutputBufferToAddNullTerminator = true && (!bInputBufferShouldIncludeNullTerminator) && (!oStringConversionOptions.m_bGenerateResultNotNullTerminated) && (!oStringConversionOptions.m_bInputStringIsNullTerminated) ; size_t nOutputBufferLengthAdjustmentBytes = bNeedAdditionalSpaceInOutputBufferToAddNullTerminator ? sizeof( char ) : 0; // Be sure we don't underflow, if we passed a zero for buffer length auto nUsableOutputBufferLengthChars = (nOutputBufferLengthChars == 0) ? 0 : nOutputBufferLengthChars - nOutputBufferLengthAdjustmentBytes; auto nResult = ::WideCharToMultiByte( oStringConversionOptions.GetCodePageIdentifier(), oStringConversionOptions.OnWideCharToMultiByte_GetFlags(), svValue.data(), range_checked_cast<int>(nEffectiveInputBufferLengthChars), pOutputBuffer, range_checked_cast<int>(nUsableOutputBufferLengthChars), oStringConversionOptions.OnWideCharToMultiByte_GetDefaultChar(), oStringConversionOptions.OnWideCharToMultiByte_GetUsedDefaultChar( pStringConversionResults ) ); if (nResult == 0) { return HRESULT_FROM_WIN32( GetLastError() ); } VLR_IF_NOT_NULL( pStringConversionResults )->m_nOuputSizeBytes = (range_checked_cast<size_t>(nResult) * sizeof( char )) + nOutputBufferLengthAdjustmentBytes; if (range_checked_cast<size_t>(nResult) > nUsableOutputBufferLengthChars) { return S_FALSE; } if (bNeedAdditionalSpaceInOutputBufferToAddNullTerminator) { ASSERT( range_checked_cast<size_t>(nResult) < nOutputBufferLengthChars ); pOutputBuffer[nResult] = '\0'; } return S_OK; } HRESULT CStringConversion::MultiByte_to_UTF16( vlr::zstring_view svValue, wchar_t* pOutputBuffer, size_t nOutputBufferLengthBytes, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { auto oStringConversionOptions_Updated = StringConversionOptions{ oStringConversionOptions }.WithNullTerminatedString( true ); return MultiByte_to_UTF16( static_cast<std::string_view>(svValue), pOutputBuffer, nOutputBufferLengthBytes, oStringConversionOptions_Updated, pStringConversionResults ); } HRESULT CStringConversion::UTF16_to_MultiByte( vlr::wzstring_view svValue, char* pOutputBuffer, size_t nOutputBufferLengthBytes, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { auto oStringConversionOptions_Updated = StringConversionOptions{ oStringConversionOptions }.WithNullTerminatedString( true ); return UTF16_to_MultiByte( static_cast<std::wstring_view>(svValue), pOutputBuffer, nOutputBufferLengthBytes, oStringConversionOptions_Updated, pStringConversionResults ); } HRESULT CStringConversion::MultiByte_to_UTF16( std::string_view svValue, std::wstring& strOutput, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { HRESULT hr; auto nOutputBufferSizeChars = svValue.length(); while (true) { strOutput.resize( nOutputBufferSizeChars ); auto nOutputBufferSizeBytes = nOutputBufferSizeChars * sizeof( wchar_t ); auto oStringConversionOptions_Local = StringConversionOptions{ oStringConversionOptions }.With_GenerateResultNotNullTerminated( true ); auto oStringConversionResults = StringConversionResults{}; hr = MultiByte_to_UTF16( svValue, strOutput.data(), nOutputBufferSizeBytes, oStringConversionOptions_Local, &oStringConversionResults ); ON_HR_NON_S_OK__RETURN_HRESULT( hr ); auto nOutputSizeChars = oStringConversionResults.m_nOuputSizeBytes / sizeof( wchar_t ); if (oStringConversionResults.m_nOuputSizeBytes > nOutputBufferSizeBytes) { nOutputBufferSizeChars = nOutputSizeChars; continue; } // resize() again to truncate as necessary strOutput.resize( nOutputSizeChars ); VLR_IF_NOT_NULL_DEREF( pStringConversionResults ) = oStringConversionResults; break; } return S_OK; } HRESULT CStringConversion::UTF16_to_MultiByte( std::wstring_view svValue, std::string& strOutput, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { HRESULT hr; auto nOutputBufferSizeChars = svValue.length(); while (true) { strOutput.resize( nOutputBufferSizeChars ); auto nOutputBufferSizeBytes = nOutputBufferSizeChars * sizeof( char ); auto oStringConversionOptions_Local = StringConversionOptions{ oStringConversionOptions }.With_GenerateResultNotNullTerminated( true ); auto oStringConversionResults = StringConversionResults{}; hr = UTF16_to_MultiByte( svValue, strOutput.data(), nOutputBufferSizeBytes, oStringConversionOptions_Local, &oStringConversionResults ); ON_HR_NON_S_OK__RETURN_HRESULT( hr ); auto nOutputSizeChars = oStringConversionResults.m_nOuputSizeBytes / sizeof( char ); if (oStringConversionResults.m_nOuputSizeBytes > nOutputBufferSizeBytes) { nOutputBufferSizeChars = nOutputSizeChars; continue; } // resize() again to truncate as necessary strOutput.resize( nOutputSizeChars ); VLR_IF_NOT_NULL_DEREF( pStringConversionResults ) = oStringConversionResults; break; } return S_OK; } HRESULT CStringConversion::MultiByte_to_UTF16( const std::string& strValue, std::wstring& strOutput, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { return MultiByte_to_UTF16( std::string_view{ strValue.c_str(), strValue.length() }, strOutput, oStringConversionOptions, pStringConversionResults ); } HRESULT CStringConversion::UTF16_to_MultiByte( const std::wstring& strValue, std::string& strOutput, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { return UTF16_to_MultiByte( std::wstring_view{ strValue.c_str(), strValue.length() }, strOutput, oStringConversionOptions, pStringConversionResults ); } HRESULT CStringConversion::MultiByte_to_UTF16( std::string_view svValue, CStringW& sOutput, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { HRESULT hr; auto nOutputBufferSizeChars = svValue.length(); while (true) { auto oOutputBufferAccess = GetCStringBufferAccess( sOutput, range_checked_cast<int>(nOutputBufferSizeChars) ); auto nOutputBufferSizeBytes = nOutputBufferSizeChars * sizeof( wchar_t ); auto oStringConversionOptions_Local = StringConversionOptions{ oStringConversionOptions }.With_GenerateResultNotNullTerminated( true ); auto oStringConversionResults = StringConversionResults{}; hr = MultiByte_to_UTF16( svValue, oOutputBufferAccess, nOutputBufferSizeBytes, oStringConversionOptions_Local, &oStringConversionResults ); ON_HR_NON_S_OK__RETURN_HRESULT( hr ); auto nOutputSizeChars = oStringConversionResults.m_nOuputSizeBytes / sizeof( wchar_t ); if (oStringConversionResults.m_nOuputSizeBytes > nOutputBufferSizeBytes) { nOutputBufferSizeChars = nOutputSizeChars; continue; } oOutputBufferAccess.ReleaseBufferPtr( range_checked_cast<int>(nOutputSizeChars) ); VLR_IF_NOT_NULL_DEREF( pStringConversionResults ) = oStringConversionResults; break; } return S_OK; } HRESULT CStringConversion::UTF16_to_MultiByte( std::wstring_view svValue, CStringA& sOutput, const StringConversionOptions& oStringConversionOptions /*= {}*/, StringConversionResults* pStringConversionResults /*= nullptr*/ ) { HRESULT hr; auto nOutputBufferSizeChars = svValue.length(); while (true) { auto oOutputBufferAccess = GetCStringBufferAccess( sOutput, range_checked_cast<int>(nOutputBufferSizeChars) ); auto nOutputBufferSizeBytes = nOutputBufferSizeChars * sizeof( char ); auto oStringConversionOptions_Local = StringConversionOptions{ oStringConversionOptions }.With_GenerateResultNotNullTerminated( true ); auto oStringConversionResults = StringConversionResults{}; hr = UTF16_to_MultiByte( svValue, oOutputBufferAccess, nOutputBufferSizeBytes, oStringConversionOptions_Local, &oStringConversionResults ); ON_HR_NON_S_OK__RETURN_HRESULT( hr ); auto nOutputSizeChars = oStringConversionResults.m_nOuputSizeBytes / sizeof( char ); if (oStringConversionResults.m_nOuputSizeBytes > nOutputBufferSizeBytes) { nOutputBufferSizeChars = nOutputSizeChars; continue; } oOutputBufferAccess.ReleaseBufferPtr( range_checked_cast<int>(nOutputSizeChars) ); VLR_IF_NOT_NULL_DEREF( pStringConversionResults ) = oStringConversionResults; break; } return S_OK; } NAMESPACE_END //( util ) NAMESPACE_END //( vlr )
32.643646
161
0.800288
nick42