hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
f1d751e953d0eed8d2a4d0d74293687e75404e1c
2,719
cpp
C++
Shadows/Game.cpp
EmilianC/Jewel3D-Samples
077c5f2531814ffe9041021c5ba5fe93e0461348
[ "MIT" ]
6
2017-02-04T21:47:01.000Z
2019-06-01T00:33:56.000Z
Shadows/Game.cpp
EmilianC/Gemcutter-Samples
077c5f2531814ffe9041021c5ba5fe93e0461348
[ "MIT" ]
null
null
null
Shadows/Game.cpp
EmilianC/Gemcutter-Samples
077c5f2531814ffe9041021c5ba5fe93e0461348
[ "MIT" ]
3
2018-04-12T04:09:15.000Z
2019-12-19T20:06:49.000Z
#include "Game.h" #include <gemcutter/Entity/Hierarchy.h> #include <gemcutter/Input/Input.h> #include <gemcutter/Math/Matrix.h> #include <gemcutter/Rendering/Camera.h> #include <gemcutter/Rendering/Light.h> #include <gemcutter/Rendering/Mesh.h> #include <gemcutter/Resource/Material.h> #include <gemcutter/Resource/Model.h> Game::Game(ConfigTable &config) : config(config) { onResized = [this](auto& e) { mainCamera->Get<Camera>().SetAspectRatio(e.GetAspectRatio()); }; } bool Game::Init() { // Setup Light. shadowCamera->Add<Camera>(-20.0f, 20.0f, 20.0f, -20.0f, -100.0f, 100.0f); shadowCamera->Add<Light>(vec3(1.0f), Light::Type::Directional); shadowCamera->LookAt(vec3(2.0f, 1.0f, 0.5f), vec3(0.0f)); // Prepare ground object. ground->Add<Mesh>(Load<Model>("Models/Ground"), Load<Material>("Materials/GroundShadowed")); ground->scale = vec3(15.0f); // Prepare shack object. shack->Add<Mesh>(Load<Model>("Models/Shack"), Load<Material>("Materials/ShackShadowed")); shack->scale = vec3(1.33f); // Link light data. auto shader = shack->Get<Renderable>().GetMaterial().shader; shader->buffers.Add(shadowCamera->Get<Light>().GetBuffer(), 0); worldToShadow = shader->buffers[2].MakeHandle<mat4>("WorldToShadow"); // Setup Scene. rootNode->Get<Hierarchy>().AddChild(ground); rootNode->Get<Hierarchy>().AddChild(shack); // Setup Camera. mainCamera->Add<Camera>(60.0f, Application.GetAspectRatio(), 1.0f, 10000.0f); mainCamera->position = vec3(0.0f, 10.0f, 25.0f); mainCamera->RotateX(-20.0f); // Setup up renderer. shadowMap = RenderTarget::MakeNew(1024, 1024, 0, true); shadowMap->GetDepthTexture()->SetPCF(true); if (!shadowMap->Validate()) return false; shadowRenderPass.SetCamera(shadowCamera); shadowRenderPass.SetShader(Shader::MakeNewPassThrough()); shadowRenderPass.SetTarget(shadowMap); mainRenderPass.textures.Add(shadowMap->GetDepthTexture(), 1); mainRenderPass.SetCamera(mainCamera); // Set background color to black. SetClearColor(0.0f, 0.0f, 0.0f, 0.0f); return true; } void Game::Update() { if (Input.IsDown(Key::Escape)) { Application.Exit(); return; } rootNode->RotateY(Application.GetDeltaTime() * -12.0f); // Keep shadow direction and world-space to shadowMap matrix up to date. worldToShadow = mat4(0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f) * shadowCamera->Get<Camera>().GetViewProjMatrix(); // Engine systems and components are updated here. Application.UpdateEngine(); } void Game::Draw() { ClearBackBuffer(); shadowMap->Clear(); shadowRenderPass.Bind(); shadowRenderPass.RenderRoot(*rootNode); mainRenderPass.Bind(); mainRenderPass.RenderRoot(*rootNode); }
26.920792
93
0.709084
EmilianC
f1d81120239f2881c17133155996f17f280e2788
1,966
ipp
C++
implement/oglplus/images/sphere_bmap.ipp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
364
2015-01-01T09:38:23.000Z
2022-03-22T05:32:00.000Z
implement/oglplus/images/sphere_bmap.ipp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
55
2015-01-06T16:42:55.000Z
2020-07-09T04:21:41.000Z
implement/oglplus/images/sphere_bmap.ipp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
57
2015-01-07T18:35:49.000Z
2022-03-22T05:32:04.000Z
/** * @file oglplus/images/sphere_bmap.ipp * @brief Implementation of images::SphereBumpMap * * @author Matus Chochlik * * Copyright 2010-2019 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include <oglplus/lib/incl_begin.ipp> #include <oglplus/lib/incl_end.ipp> #include <oglplus/math/vector.hpp> #include <cassert> #include <cmath> namespace oglplus { namespace images { OGLPLUS_LIB_FUNC SphereBumpMap::SphereBumpMap( SizeType width, SizeType height, SizeType xrep, SizeType yrep) : Image( width, height, 1, 4, &TypeTag<GLfloat>(), PixelDataFormat::RGBA, PixelDataInternalFormat::RGBA16F) { assert(width != 0 && height != 0); assert(xrep != 0 && yrep != 0); using number = double; number one = number(1); number invw = number(2 * xrep) / number(width); number invh = number(2 * yrep) / number(height); GLsizei hi = width / xrep; GLsizei hj = height / yrep; auto p = this->_begin<GLfloat>(); for(GLsizei j = 0; j < height; ++j) { number y = number((j % hj) - hj / 2) * invh; for(GLsizei i = 0; i < width; ++i) { number x = number((i % hi) - hi / 2) * invw; number l = std::sqrt(x * x + y * y); number d = sqrt(one - l * l); Vector<number, 3> z(0.0, 0.0, one); Vector<number, 3> n(-x, -y, d); Vector<number, 3> v = (l >= one) ? z : Normalized(z + n); if(l >= one) d = 0; assert(p != this->_end<GLfloat>()); *p = GLfloat(v.x()); ++p; *p = GLfloat(v.y()); ++p; *p = GLfloat(v.z()); ++p; *p = GLfloat(d); ++p; } } assert(p == this->_end<GLfloat>()); } } // namespace images } // namespace oglplus
27.690141
69
0.539166
matus-chochlik
f1ed79f793e5fa7fe143dcd2981a49c9d124d13a
2,795
cpp
C++
Source/BehaviorTreeExtension/Private/BTStateMachineSelector.cpp
bretvincent/UnrealBehaviorTreeExtension
dc82c9297a43bb5096c25c262d661609534f9897
[ "MIT" ]
2
2021-09-11T11:45:31.000Z
2021-12-23T07:35:41.000Z
Source/BehaviorTreeExtension/Private/BTStateMachineSelector.cpp
bretvincent/UnrealBehaviorTreeExtension
dc82c9297a43bb5096c25c262d661609534f9897
[ "MIT" ]
null
null
null
Source/BehaviorTreeExtension/Private/BTStateMachineSelector.cpp
bretvincent/UnrealBehaviorTreeExtension
dc82c9297a43bb5096c25c262d661609534f9897
[ "MIT" ]
1
2021-09-11T11:45:34.000Z
2021-09-11T11:45:34.000Z
// Copyright 2019 Vincent Breton Kochanowski. All Rights Reserved. #include "BTStateMachineSelector.h" #include "BTStateTransitionDecorator.h" void UBTStateMachineSelector::OnGameplayTaskActivated(UGameplayTask& Task) { } void UBTStateMachineSelector::OnGameplayTaskDeactivated(UGameplayTask& Task) { } UBTStateMachineSelector::UBTStateMachineSelector(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), InitialStateId(0), ExitStateMachineId(0) { NodeName = "StateMachineSelector"; } int32 UBTStateMachineSelector::GetNextChildHandler(FBehaviorTreeSearchData& SearchData, int32 PrevChild, EBTNodeResult::Type LastResult) const { if (PrevChild == BTSpecialChild::NotInitialized) { // go to initial state of state machine return FindChildIndexFromStateId(InitialStateId); } // if we failed we exit state machine if (LastResult == EBTNodeResult::Failed) { return BTSpecialChild::ReturnToParent; } return ShouldTransition(SearchData, PrevChild); } int32 UBTStateMachineSelector::FindChildIndexFromStateId(int32 StateId) const { if (StateId == ExitStateMachineId) { return BTSpecialChild::ReturnToParent; } for (int i = 0; i < Children.Num(); ++i) { auto const& ChildInfo = Children[i]; for (auto Decorator : ChildInfo.Decorators) { const auto StateTransitionDecorator = Cast<UBTStateTransitionDecorator>(Decorator); if (StateTransitionDecorator) { if (StateTransitionDecorator->StateId == StateId) { return i; } } } } UE_LOG(LogBehaviorTree, Error, TEXT("No State with Id: %d found!"), StateId); return 0; } int32 UBTStateMachineSelector::ShouldTransition(FBehaviorTreeSearchData& SearchData, int32 ChildIndex) const { if (ChildIndex < 0 || ChildIndex > Children.Num()) { // no children means that something went wrong return BTSpecialChild::ReturnToParent; } auto const& ChildInfo = Children[ChildIndex]; for (auto Decorator : ChildInfo.Decorators) { const auto StateTransitionDecorator = Cast<UBTStateTransitionDecorator>(Decorator); if (StateTransitionDecorator) { // search if any transitions have activated; will return first one found if (StateTransitionDecorator->ShouldTransition(SearchData)) { const auto StateDecoratorMemory = StateTransitionDecorator->GetNodeMemory<FBTStateDecoratorMemory>(SearchData); int32 childId = StateDecoratorMemory->ChildToTransitionToId; return FindChildIndexFromStateId(childId); } } } // if no transitions have activated; just continue executing node return ChildIndex; } #if WITH_EDITOR FName UBTStateMachineSelector::GetNodeIconName() const { return FName("BTEditor.Graph.BTNode.Composite.Selector.Icon"); } #endif
28.814433
143
0.743828
bretvincent
f1f069dbe0c7d96784f129f043ead6c4d09d247d
4,291
cc
C++
engine/Node.cc
zhouzhiyong18/SubgraphMatch
e34b088ed5efc67556c91ad9591dc8718a048d59
[ "Apache-2.0" ]
4
2018-11-19T08:05:41.000Z
2018-11-19T11:55:55.000Z
engine/Node.cc
ChengTsang/SSSP
6d6680b87e0edaac5668cbf9cb4d39ee7a77d150
[ "Apache-2.0" ]
null
null
null
engine/Node.cc
ChengTsang/SSSP
6d6680b87e0edaac5668cbf9cb4d39ee7a77d150
[ "Apache-2.0" ]
null
null
null
/** * @file Node.cc * @author Songjie Niu, Shimin Chen * @version 0.1 * * @section LICENSE * * Copyright 2016 Shimin Chen (chensm@ict.ac.cn) and * Songjie Niu (niusongjie@ict.ac.cn) * * 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. * * @section DESCRIPTION * * @see Node.h * */ #include <new> #include <string.h> #include "Node.h" #include "Worker.h" extern Worker worker; int Edge::e_value_size; int Edge::e_size; int Msg::m_value_size; int Msg::m_size; int Node::n_value_size; int Node::n_size; Node& Node::getNode(int index) { return *( (Node *)( (char *)(worker.m_pnode) + index * Node::n_size ) ); } Edge& Node::getEdge(int index) { return *( (Edge *)( (char *)(worker.m_pedge) + index * Edge::e_size ) ); } void Node::initInMsg() { new(&m_cur_in_msg) std::vector<Msg*>(); } void Node::recvNewMsg(Msg* pmsg) { m_cur_in_msg.push_back(pmsg); if (! m_active) { m_active = true; ++worker.m_wm_curssfinish.act_vertex; } } void Node::clearCurInMsg() { if ( m_cur_in_msg.size() ) { for (int i = m_cur_in_msg.size() - 1; i >= 0; --i) { worker.m_free_list.free(m_cur_in_msg[i]); } m_cur_in_msg.clear(); } } void Node::freeInMsgVector() { (&m_cur_in_msg)->~vector<Msg*>(); } int Node::getSuperstep() const { return worker.m_wm_curssfinish.superstep; } int64_t Node::getVertexId() const { return m_v_id; } void Node::voteToHalt() { m_active = false; --worker.m_wm_curssfinish.act_vertex; } GenericLinkIterator* Node::getGenericLinkIterator() { return new GenericLinkIterator(&m_cur_in_msg); } /* GenericArrayIterator* Node::getGenericArrayIterator() { return new GenericArrayIterator( (char *)(worker.m_pedge) + m_edge_index * Edge::e_size, (char *)(worker.m_pedge) + (m_edge_index + m_out_degree) * Edge::e_size, Edge::e_size ); } */ void Node::sendMessageTo(int64_t dest_vertex, const char* pmessage) { int wk = dest_vertex % (worker.m_machine_cnt - 1) + 1; // hash partition if (wk == worker.m_addr_self.id) { // self message, can be commented for debug 1 Msg* pmsg = (Msg *)( worker.m_free_list.allocate() ); pmsg->s_id = m_v_id; pmsg->d_id = dest_vertex; memcpy(pmsg->message, pmessage, Msg::m_value_size); worker.recvNewNodeMsg(pmsg); // self message certainly not for next next // superstep but for next } else { // message to another worker // check if we should send messages if (worker.m_psendlist_curpos[wk] == SENDLIST_LEN) { while ( worker.sendNodeMessage(wk, worker.m_psendlist_curpos[wk]) ); // How to change into wait ? worker.m_psendlist_curpos[wk] = 0; ++worker.m_wm_curssfinish.worker_msg[wk]; } // copy the message into send message list Msg* pmsg = (Msg *)(worker.m_pww_sendlist[wk].msgs.data + worker.m_psendlist_curpos[wk] * Msg::m_size); pmsg->s_id = m_v_id; pmsg->d_id = dest_vertex; memcpy(pmsg->message, pmessage, Msg::m_value_size); ++worker.m_psendlist_curpos[wk]; // printf("wrote one piece of node2node message to sendlist[%d]\n", wk); // } ++worker.m_wm_curssfinish.sent_msg; } void Node::sendMessageToAllNeighbors(const char* pmessage) { char* pedge = (char *)(worker.m_pedge) + m_edge_index * Edge::e_size; for (int i = 0; i < m_out_degree; ++i) { sendMessageTo( ( (Edge *)pedge )->to, pmessage ); pedge += Edge::e_size; } } const void* Node::getAggrGlobal(int aggr) { return worker.m_pmy_aggregator[aggr]->getGlobal(); } void Node::accumulateAggr(int aggr, const void* p) { worker.m_pmy_aggregator[aggr]->accumulate(p); }
28.230263
111
0.646003
zhouzhiyong18
7b008b951d5d37d8e11c711155bc85bb79ee924b
1,483
cpp
C++
src/2015/day03.cpp
AnthonyN1/Advent-of-Code
28782b219a50d92b2621dc88ecf00ae2e3b45b0a
[ "MIT" ]
null
null
null
src/2015/day03.cpp
AnthonyN1/Advent-of-Code
28782b219a50d92b2621dc88ecf00ae2e3b45b0a
[ "MIT" ]
null
null
null
src/2015/day03.cpp
AnthonyN1/Advent-of-Code
28782b219a50d92b2621dc88ecf00ae2e3b45b0a
[ "MIT" ]
null
null
null
/* Advent of Code - 2015: Day 03 Author: Anthony Nool (AnthonyN1) */ #include <iostream> #include <set> #include <string> #include <vector> #include "../../includes/point.h" /* Updates pt based on the direction ch is pointing. ch is either '^', 'v', '<', or '>'. */ void updatePoint(Point &pt, char ch){ switch(ch){ case '^': pt.shift(0, 1); break; case 'v': pt.shift(0, -1); break; case '<': pt.shift(-1, 0); break; case '>': pt.shift(1, 0); break; } } void partOne(const std::vector<std::string> &input){ std::set<Point> visited; // The origin is visited. Point curr; visited.insert(curr); for(const std::string &str : input){ for(char ch : str){ // Keeps track of every visited point, and the number of times visited. updatePoint(curr, ch); visited.insert(curr); } } std::cout << visited.size() << std::endl; } void partTwo(const std::vector<std::string> &input){ std::set<Point> visited; // The origin is visited. Point santa, robot; visited.insert(santa); bool toggle = false; for(const std::string &str : input){ for(char ch : str){ // Keeps track of every visited point, and the number of times visited. // toggle switches after every char. // This represents Santa and Robo-Santa taking turns. if(!toggle){ updatePoint(santa, ch); visited.insert(santa); } else{ updatePoint(robot, ch); visited.insert(robot); } toggle = !toggle; } } std::cout << visited.size() << std::endl; }
20.040541
74
0.633176
AnthonyN1
7b0277669cf1498f84f4fd55b963de55dc6848df
13,608
cpp
C++
AppForm.cpp
DarknessFX/UEPlugins_DisableDefault
dbaf4c83a8dbe1bb745bb00bd0a5f5a87c0b3271
[ "MIT" ]
1
2021-12-01T13:57:54.000Z
2021-12-01T13:57:54.000Z
AppForm.cpp
DarknessFX/UEPlugins_DisableDefault
dbaf4c83a8dbe1bb745bb00bd0a5f5a87c0b3271
[ "MIT" ]
null
null
null
AppForm.cpp
DarknessFX/UEPlugins_DisableDefault
dbaf4c83a8dbe1bb745bb00bd0a5f5a87c0b3271
[ "MIT" ]
null
null
null
/// /// Created by DarknessFX - https://dfx.lv - @DrkFX /// Source Code at https://github.com/DarknessFX/UEPlugins_DisableDefault /// #include <windows.h> #include "AppForm.h" using namespace System; using namespace System::Windows::Forms; using namespace System::IO; using namespace Microsoft::Win32; using namespace UEPluginsDisableDefault; void AppForm::AppForm_Load ( System::Object^ sender, System::EventArgs^ e ) { StateUpdate(AppState::Wait); cmbUEFolder->Items->Clear(); dtbPlugins->Clear(); StatusUpdate("Finding default Unreal Engine folder in Registry."); String^ UEDefaultPath = Registry::ClassesRoot->OpenSubKey("Unreal.ProjectFile\\shell\\open\\command")->GetValue("")->ToString(); StatusUpdate("Reading Unreal Engine folder path in Registry \\\\HKEY_LOCAL_MACHINE\\SOFTWARE\\EpicGames\\Unreal Engine"); RegistryKey^ UEKey = Registry::LocalMachine->OpenSubKey("SOFTWARE\\EpicGames\\Unreal Engine"); for each (String^ SubKey in UEKey->GetSubKeyNames()) { RegistryKey^ BuildKey = UEKey->OpenSubKey(SubKey); String^ UEPath = BuildKey->GetValue("InstalledDirectory")->ToString(); cmbUEFolder->Items->Add(UEPath); if ( UEDefaultPath->Contains(UEPath) ) { cmbUEFolder->SelectedIndex = cmbUEFolder->Items->Count - 1; } } StatusUpdate(""); UpdateFlow(); StateUpdate(AppState::Default); } void AppForm::AppForm_SizeChanged ( System::Object^ sender, System::EventArgs^ e ) { UpdateFlow(); } void AppForm::UpdateFlow ( ) { cmbUEFolder->Width = AppForm::ClientSize.Width - btnBrowse->Width - lblUEFolder->Width - 20; } void AppForm::StatusUpdate(String^ Message) { AppForm::lblStatus->Text = Message; } void AppForm::mnuShowAll_Click ( System::Object^ sender, System::EventArgs^ e ) { if (mnuShowDefault->Checked) { mnuShowDefault->Checked = false; } btnMenu->Text = mnuShowAll->Text; for ( int iRow = 0; iRow < AppForm::grdPlugins->Rows->Count; iRow++ ) { AppForm::grdPlugins->Rows[iRow]->Visible = true; } } void AppForm::mnuShowDefault_Click ( System::Object^ sender, System::EventArgs^ e ) { if (mnuShowAll->Checked) { mnuShowAll->Checked = false; } btnMenu->Text = mnuShowDefault->Text; for ( int iRow = 0; iRow < AppForm::grdPlugins->Rows->Count; iRow++ ) { if ((bool)AppForm::grdPlugins->Rows[iRow]->Cells[0]->Value != true) { AppForm::grdPlugins->Rows[iRow]->Visible = false; } } } void AppForm::cmbUEFolder_SelectedIndexChanged ( System::Object^ sender, System::EventArgs^ e ) { Searching(cmbUEFolder->SelectedItem->ToString()); } void AppForm::btnBrowse_Click ( System::Object^ sender, System::EventArgs^ e ) { ::DialogResult result = dlgBrowse->ShowDialog(); if( result == ::DialogResult::OK ) { if ( !cmbUEFolder->Items->Contains(dlgBrowse->SelectedPath) ) { StatusUpdate(Append("Adding UE Folder Path: ", dlgBrowse->SelectedPath)); cmbUEFolder->Items->Add(dlgBrowse->SelectedPath); cmbUEFolder->SelectedIndex = cmbUEFolder->Items->Count - 1; } else { StatusUpdate(Append("Path already added : ", dlgBrowse->SelectedPath)); } } } void AppForm::btnMinimal_Click ( System::Object^ sender, System::EventArgs^ e ) { array<String^>^ aMinimal = {"AISupport", "ContentBrowserAssetDataSource", "ContentBrowserClassDataSource", "CurveEditorTools", "TextureFormateOodle", "OodleData", "PluginBrowser", "PluginUtils", "PropertyAccessEditor"}; for ( int iRow = 0; iRow < AppForm::dtbPlugins->Rows->Count; iRow++ ) { DataRow^ mDR = AppForm::dtbPlugins->Rows[iRow]; mDR["celEnabledByDefault"] = false; for each (String^ sPlugin in aMinimal) { if (mDR["celName"]->ToString()->ToLower() == sPlugin->ToLower() ) { mDR["celEnabledByDefault"] = true; break; } } } } void AppForm::btnSave_Click ( System::Object^ sender, System::EventArgs^ e ) { StateUpdate(AppState::Wait); AppForm::StatusUpdate("Saving .uplugin changes..."); ControlsStateChange(ControlsState::Wait); String^ dirPlugin = Append(cmbUEFolder->SelectedItem->ToString(), "\\Engine\\Plugins\\"); String^ filePlugin = ""; int iMod = 0; for each (DataRow^ mDRPlug in dtbPlugins->Rows) { for each (DataRow^ mDROrig in dtbPluginsOrig->Rows) { if (mDRPlug["celName"] == mDROrig["celName"]) { if ((bool)mDRPlug["celEnabledByDefault"] != (bool)mDROrig["celEnabledByDefault"]) { filePlugin = Append(dirPlugin, mDRPlug["celPath"]->ToString()); File::Move(filePlugin, Append(filePlugin, "_UEPlugins_DisableDefault")); Application::DoEvents(); FileStream^ origStream = gcnew FileStream(Append(filePlugin, "_UEPlugins_DisableDefault"), FileMode::Open); StreamReader^ origReader = gcnew StreamReader(origStream); FileStream^ newStream = gcnew FileStream(filePlugin, FileMode::CreateNew); StreamWriter^ newWriter = gcnew StreamWriter(newStream); while ( !origReader->EndOfStream ) { String^ line = origReader->ReadLine(); if ( line->Contains("EnabledByDefault") ) { line = line->Replace(mDROrig["celEnabledByDefault"]->ToString()->ToLower(), mDRPlug["celEnabledByDefault"]->ToString()->ToLower()); } newWriter->WriteLine(line); } origStream->Close(); origStream->Close(); newWriter->Close(); newStream->Close(); File::Delete(Append(filePlugin, "_UEPlugins_DisableDefault")); iMod++; mDROrig->Delete(); dtbPluginsOrig->AcceptChanges(); } break; } } } dtbPluginsOrig = dtbPlugins->Copy(); ControlsStateChange(ControlsState::Default); StatusUpdate(Append(iMod.ToString(), " plugins changed.")); StateUpdate(AppState::Default); } void AppForm::grdPlugins_CurrentCellDirtyStateChanged ( System::Object^ sender, System::EventArgs^ e ) { if ( grdPlugins->IsCurrentCellDirty ) { grdPlugins->CommitEdit(DataGridViewDataErrorContexts::Commit); grdPlugins->EndEdit(); dtbPlugins->AcceptChanges(); } } void StateUpdate(AppState State) { switch ( State ) { case AppState::Default: Application::UseWaitCursor = false; break; case AppState::Wait: Application::UseWaitCursor = true; break; } } String^ Append(String^ str0, String^ str1) { return str0->Insert(str0->Length, str1); } String^ ReplaceSlashes(String^ Path) { Path = Path->Replace("\\\\", "\\"); Path = Path->Replace("\\", "/"); return Path; } void Searching(String^ Path) { StateUpdate(AppState::Wait); AppForm::StatusUpdate("Searching UPlugins ..."); ControlsStateChange(ControlsState::Wait); AppForm::dtbPlugins->Clear(); AppForm::dtbPluginsOrig->Clear(); AppForm::grdPlugins->DataSource = nullptr; if ( !Path->Contains("Plugins") ) { Path = Append(Path, "\\Engine\\Plugins"); } //for each (String^ dirCategory in Directory::EnumerateDirectories(Path) ) //{ FindUPlugin(Path); //} AppForm::dtbPlugins->DefaultView->Sort = "celEnabledByDefault DESC, celFriendlyName ASC, celCategory ASC"; AppForm::dtbPlugins->AcceptChanges(); AppForm::dtbPluginsOrig = AppForm::dtbPlugins->Copy(); AppForm::dtbPluginsOrig->DefaultView->Sort = "celEnabledByDefault DESC, celFriendlyName ASC, celCategory ASC"; AppForm::grdPlugins->DataSource = AppForm::dtbPlugins; AppForm::grdPlugins->CurrentCell = AppForm::grdPlugins[0,0]; ControlsStateChange(ControlsState::Default); AppForm::StatusUpdate(Append(Append(Append(CountEnabledByDefault().ToString(), " plugins Enabled By Default. " ), AppForm::dtbPlugins->Rows->Count.ToString()), " plugins total.")); StateUpdate(AppState::Default); } void FindUPlugin(String^ Path) { for each (String^ dirPlugin in Directory::EnumerateDirectories(Path) ) { if ( IsIgnoredFolder(dirPlugin) ) { continue; } AppForm::StatusUpdate(Append("Searching UPlugins :", dirPlugin)); Application::DoEvents(); for each (String^ mFile in Directory::GetFiles( dirPlugin, "*.uplugin" ) ) { AddUPlugin(mFile); break; } if ( Directory::GetDirectories(dirPlugin)->Length != 0 ) { FindUPlugin(dirPlugin); } } } void AddUPlugin(String^ FileUPlugin) { DataRow^ mDR = AppForm::dtbPlugins->NewRow(); ReadUPlugin(FileUPlugin, mDR); AppForm::dtbPlugins->Rows->Add(mDR); } void ReadUPlugin(String^ FileUPlugin, DataRow^& mDataRow) { FileStream^ filestream = gcnew FileStream(FileUPlugin, FileMode::Open); StreamReader^ reader = gcnew StreamReader(filestream); mDataRow["celName"] = Path::GetFileNameWithoutExtension(FileUPlugin); mDataRow["celPath"] = FileUPlugin->Substring(FileUPlugin->IndexOf("plugins", StringComparison::CurrentCultureIgnoreCase) + 8); if ( File::Exists(Append(Path::GetDirectoryName(FileUPlugin), "\\Resources\\icon128.png")) ) { mDataRow["celIcon"] = Drawing::Image::FromFile( Append(Path::GetDirectoryName(FileUPlugin), "\\Resources\\icon128.png") ); } else { mDataRow["celIcon"] = Drawing::Image::FromFile( Append(AppForm::cmbUEFolder->SelectedItem->ToString(), "\\Engine\\Plugins\\Editor\\PluginBrowser\\Resources\\DefaultIcon128.png") ); } while ( !reader->EndOfStream ) { String^ line = reader->ReadLine(); if ( line->Contains("VersionName") ) { GetJSONValue(line); mDataRow["celVersionName"] = line; continue; } if ( line->Contains("EnabledByDefault") ) { GetJSONValue(line); mDataRow["celEnabledByDefault"] = line; continue; } if ( line->Contains("FriendlyName") ) { GetJSONValue(line); mDataRow["celFriendlyName"] = line; continue; } if ( line->Contains("Description") ) { GetJSONValue(line); mDataRow["celDescription"] = line; continue; } if ( line->Contains("Category") ) { GetJSONValue(line); mDataRow["celCategory"] = line; continue; } } reader->Close(); filestream->Close(); }; void GetJSONValue(String^& str0) { if ( str0->Contains(": \"") ) { str0 = str0->Substring(str0->IndexOf(": \"") + 3); str0 = str0->Substring(0, str0->Length - 2); } else { str0 = str0->Substring(str0->IndexOf(": ") + 2); str0 = str0->Substring(0, str0->Length - 1); } } int CountEnabledByDefault() { int iCounted = 0; for each ( DataRow^ mDR in AppForm::dtbPlugins->Rows ) { if ((bool)mDR["celEnabledByDefault"] == true) { iCounted++; } } return iCounted; } bool IsIgnoredFolder(String^ Path) { bool bIsIgnoreFolder = false; array<String^>^ aIgnoreFolders = {"Binaries", "Config", "Content", "Docs", "Intermediate", "Library", "Private", "Public", "Resources", "SDK", "SDKs", "Shaders", "Source", "SourceArt", "ThirdParty"}; for each (String^ sIgnoreFolder in aIgnoreFolders) { if (sIgnoreFolder->ToLower() == Path->Substring(System::IO::Path::GetDirectoryName(Path)->Length + 1)->ToLower() ) { bIsIgnoreFolder = true; break; } } return bIsIgnoreFolder; } void ControlsStateChange(ControlsState State) { bool bState = (bool)State; AppForm::cmbUEFolder->Enabled = bState; AppForm::btnBrowse->Enabled = bState; AppForm::btnMenu->Enabled = bState; AppForm::btnMinimal->Enabled = bState; AppForm::btnSave->Enabled = bState; AppForm::grdPlugins->Enabled = bState; switch ( bState ) { case false: AppForm::btnSave->BackColor = Color::Empty; break; case true: AppForm::btnSave->BackColor = Color::LightGreen; break; } }
33.935162
378
0.568122
DarknessFX
7b039b471b189e5416aa8eebf51d95d078696b02
8,365
cpp
C++
LifeBrush/Source/LifeBrush/VRInterface/CollectionSpace.cpp
timdecode/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
33
2019-04-23T23:00:09.000Z
2021-11-09T11:44:09.000Z
LifeBrush/Source/LifeBrush/VRInterface/CollectionSpace.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
1
2019-10-09T15:57:56.000Z
2020-03-05T20:01:01.000Z
LifeBrush/Source/LifeBrush/VRInterface/CollectionSpace.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
6
2019-04-25T00:10:55.000Z
2021-04-12T05:16:28.000Z
// Copyright 2018, Timothy Davison. All rights reserved. #include "LifeBrush.h" #include <cmath> #include "CollectionSpace.h" #include <../Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/Deploy/include/OpenEXR/halfLimits.h> UInteractionSpace::UInteractionSpace() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = true; // ... } UCollectionSpace::UCollectionSpace() { PrimaryComponentTick.bCanEverTick = true; bAutoActivate = true; bTickInEditor = false; } void UCollectionSpace::BeginPlay() { Super::BeginPlay(); _boundsMesh = NewObject<UStaticMeshComponent>(this); _boundsMesh->AttachToComponent(this, FAttachmentTransformRules::KeepRelativeTransform); _boundsMesh->SetStaticMesh(backgroundMesh); _boundsMesh->SetMaterial(0, backgroundMaterial); _boundsMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision); _boundsMesh->RegisterComponent(); } // Called every frame void UCollectionSpace::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); _velocity -= _velocity * damping * DeltaTime; // apply velocity this->AddRelativeLocation(_velocity * DeltaTime, false, nullptr, ETeleportType::TeleportPhysics); FVector location = GetRelativeTransform().GetLocation(); FBox boundsInRoot = _bounds.TransformBy(GetRelativeTransform()); const float halfWidth = width * 0.5f; if( boundsInRoot.Min[Forward] > -halfWidth ) { _velocity = FVector::ZeroVector; location[Forward] += (-halfWidth - boundsInRoot.Min[Forward]); this->SetRelativeLocation(location, false, nullptr, ETeleportType::TeleportPhysics); } else if( boundsInRoot.Max[Forward] < halfWidth ) { _velocity = FVector::ZeroVector; location[Forward] += (halfWidth - boundsInRoot.Max[Forward]); this->SetRelativeLocation(location, false, nullptr, ETeleportType::TeleportPhysics); } } void UCollectionSpace::insertItemsAt(TArray<uint32> indices) { } void UCollectionSpace::reloadData() { _cells.Empty(); if(!dataSource->Implements<UCollectionSpaceDataSource>()) return; int32 n = ICollectionSpaceDataSource::Execute_count(dataSource); for (int32 i = 0; i < n; ++i) { UPrimitiveComponent * cell = ICollectionSpaceDataSource::Execute_primitiveCellAt(dataSource, i); _cells.Add(cell); } _layout(); } FVector UCollectionSpace::nearest(UPrimitiveComponent * interactionPoint) { FVector localPoint = this->GetComponentTransform().InverseTransformPosition(interactionPoint->GetComponentLocation()); FVector nearestPoint = FVector::ZeroVector; float nearestDistanceSqrd = std::numeric_limits<float>::max(); auto updateNearest = [&](FBox& bounds) { if (bounds.IsInside(localPoint)) { FVector point = bounds.GetClosestPointTo(localPoint); float distSqrd = FVector::DistSquared(localPoint, point); if (distSqrd < nearestDistanceSqrd) { nearestDistanceSqrd = distSqrd; nearestPoint = point; } } }; // check if we overlap one of the items for (int i = 0; i < _localBounds.Num(); ++i) { FBox& bounds = _localBounds[i]; updateNearest(bounds); } { FTransform toLocal = this->GetComponentTransform().Inverse(); FBox bounds = _boundsMesh->Bounds.GetBox().TransformBy(toLocal); updateNearest(bounds); } return GetComponentTransform().TransformPosition(nearestPoint); } void UCollectionSpace::begin_oneHand(UPrimitiveComponent * interactionPoint) { FVector localPoint = this->GetComponentTransform().InverseTransformPosition(interactionPoint->GetComponentLocation()); if (_bounds.IsInside(localPoint)) _interactionMode = InteractionMode::Pan; else _interactionMode = InteractionMode::None; // check if we overlap one of the items for (int i = 0; i < _localBounds.Num(); ++i) { FBox& bounds = _localBounds[i]; if (bounds.IsInside(localPoint) && delegate) { ICollectionSpaceDelegate::Execute_didGrab(delegate, i, interactionPoint->GetComponentTransform(), _cells[i], _cells[i]->GetComponentTransform(), bounds); _interactionMode = InteractionMode::Grab; return; } } } void UCollectionSpace::update_oneHand(float dt, UPrimitiveComponent * interactionPoint, FTransform lastTransform) { if (_interactionMode == InteractionMode::Pan) { _update_pan(dt, interactionPoint, lastTransform); } } void UCollectionSpace::_update_pan(float dt, UPrimitiveComponent * interactionPoint, FTransform lastTransform) { FVector localPoint = this->GetComponentTransform().InverseTransformPosition(interactionPoint->GetComponentLocation()); if (_bounds.IsInside(localPoint)) { FTransform parentTransform = this->GetAttachParent()->GetComponentTransform(); FVector pointInParent = parentTransform.InverseTransformPosition(interactionPoint->GetComponentLocation()); FVector lastInParent = parentTransform.InverseTransformPosition(lastTransform.GetLocation()); FVector delta = pointInParent - lastInParent; // only move in forward direction delta.X = 0.0f; delta.Z = 0.0f; _velocity = delta / dt; } } void UCollectionSpace::end_oneHand(UPrimitiveComponent * interactionPoint) { } void UCollectionSpace::grab(UPrimitiveComponent * interactionPoint) { } void UCollectionSpace::query(UPrimitiveComponent * interactionPoint) { } TSet<int32> UCollectionSpace::selection() { return _selection; } void UCollectionSpace::_layout() { _layoutCells(); _layoutBackground(); } void UCollectionSpace::_layoutCells() { const float totalWidth = _totalWidth(); const float stepSize = _stepSize(); FVector _startP = FVector::ZeroVector; _startP[Forward] = -totalWidth / 2.0f; _startP.Z = -(cellExtents * rows + cellSpacing * (rows - 1)) * .5f; const FVector startP = _startP; _bounds = FBox(EForceInit::ForceInitToZero); int n = _cells.Num(); _localBounds.SetNumZeroed(_cells.Num(), true); FTransform toComponent = this->GetComponentTransform().Inverse(); const int32 nColumns = std::ceil(float(n) / float(rows)); for (int32 i = 0; i < n; ++i) { UPrimitiveComponent * cell = _cells[i]; // cell->SetCollisionEnabled(ECollisionEnabled::QueryOnly); checkf(cell->GetAttachParent() == this, TEXT("The AttachParent of the cell must be the UCollectionSpace")); const float scale = _scaleForCell(*cell); const FVector offset = _offsetForCell(toComponent, *cell); FVector p = startP;; { const int32 rowIndex = std::floor(i / nColumns); const int32 colIndex = i % nColumns; p[Forward] += stepSize * colIndex; p.Z += stepSize * rowIndex; } FTransform transform(FQuat::Identity, p + offset, FVector(scale)); cell->SetRelativeTransform(transform, false, nullptr, ETeleportType::TeleportPhysics); //p[Forward] += stepSize; FBoxSphereBounds localBounds = cell->Bounds.TransformBy(toComponent); _localBounds[i] = localBounds.GetBox(); _bounds += localBounds.GetBox(); } _bounds.Min.Z -= cellSpacing; _bounds.Max.Z += cellSpacing; _bounds.Min.Z -= cellSpacing; _bounds.Max.Z += cellSpacing; } void UCollectionSpace::_layoutBackground() { FBoxSphereBounds bounds = _boundsMesh->GetStaticMesh()->GetBounds(); const float yScale = _bounds.GetSize()[Forward] / bounds.GetBox().GetSize()[Forward]; const float zScale = _bounds.GetSize().Z / bounds.GetBox().GetSize().Z; FVector location = _bounds.GetCenter(); location.X = _bounds.Min.X; _boundsMesh->SetRelativeLocation(location); FVector scaleVector(0.02f, yScale, zScale); _boundsMesh->SetRelativeScale3D(scaleVector); } float UCollectionSpace::_totalWidth() { return (float(_cells.Num()) * cellExtents) - (float(_cells.Num() - 1) * cellSpacing); } float UCollectionSpace::_stepSize() { return cellExtents + cellSpacing; } float UCollectionSpace::_scaleForCell(UPrimitiveComponent& component) { return (cellExtents * 0.5f) / component.Bounds.SphereRadius; } FVector UCollectionSpace::_offsetForCell(const FTransform& toComponent, UPrimitiveComponent& component) { FBoxSphereBounds bounds = component.Bounds; // get it into the coordinate frame of this bounds = bounds.TransformBy(toComponent); FVector offset = bounds.Origin; offset[Forward] = -bounds.GetBox().Max[Forward]; return -offset * _scaleForCell(component); }
24.895833
157
0.749671
timdecode
7b0885fff9dc7b16718e7cdc3d7d0b364df2b9b0
861
cpp
C++
unit_tests/test_flush.cpp
brridder/nanoarq
5aa9e5d9dda002f569aa70dcec0eded67404c44d
[ "Unlicense" ]
1
2021-12-07T18:33:20.000Z
2021-12-07T18:33:20.000Z
unit_tests/test_flush.cpp
skyformat99/nanoarq
167425b0a073c4e41f4d32eafc21cb1a71b186e3
[ "Unlicense" ]
null
null
null
unit_tests/test_flush.cpp
skyformat99/nanoarq
167425b0a073c4e41f4d32eafc21cb1a71b186e3
[ "Unlicense" ]
null
null
null
#include "arq_in_unit_tests.h" #include "arq_runtime_mock_plugin.h" #include <CppUTest/TestHarness.h> #include <CppUTestExt/MockSupport.h> #include <cstring> TEST_GROUP(flush) {}; namespace { TEST(flush, invalid_params) { CHECK_EQUAL(ARQ_ERR_INVALID_PARAM, arq_flush(nullptr)); } void MockSendWndFlush(arq__send_wnd_t *sw) { mock().actualCall("arq__send_wnd_flush").withParameter("sw", sw); } TEST(flush, forwards_send_window_to_send_wnd_flush) { arq_t arq; ARQ_MOCK_HOOK(arq__send_wnd_flush, MockSendWndFlush); mock().expectOneCall("arq__send_wnd_flush").withParameter("sw", &arq.send_wnd); arq_flush(&arq); } TEST(flush, returns_success) { arq_t arq; ARQ_MOCK_HOOK(arq__send_wnd_flush, MockSendWndFlush); mock().ignoreOtherCalls(); arq_err_t const e = arq_flush(&arq); CHECK_EQUAL(ARQ_OK_COMPLETED, e); } }
21.525
83
0.744483
brridder
7b0bb8a60fa230961fe485904d1fc910c3f6be90
333
cpp
C++
C++/bulb-switcher-iv.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/bulb-switcher-iv.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/bulb-switcher-iv.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) // Space: O(1) class Solution { public: int minFlips(string target) { int result = 0; char curr = '0'; for (const auto& c : target) { if (c == curr) { continue; } curr = c; ++result; } return result; } };
17.526316
38
0.393393
Akhil-Kashyap
7b0c268235e24726c5e4271e75d91c71fe37a633
1,691
cpp
C++
libs/modelmd3/impl/src/model/md3/impl/read_string.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/modelmd3/impl/src/model/md3/impl/read_string.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/modelmd3/impl/src/model/md3/impl/read_string.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/model/md3/exception.hpp> #include <sge/model/md3/string.hpp> #include <sge/model/md3/impl/max_qpath.hpp> #include <sge/model/md3/impl/read_string.hpp> #include <fcppt/no_init.hpp> #include <fcppt/text.hpp> #include <fcppt/array/object_impl.hpp> #include <fcppt/cast/size.hpp> #include <fcppt/cast/to_char_ptr.hpp> #include <fcppt/cast/to_signed.hpp> #include <fcppt/config/external_begin.hpp> #include <algorithm> #include <ios> #include <istream> #include <fcppt/config/external_end.hpp> template <sge::model::md3::string::size_type Max> sge::model::md3::string sge::model::md3::impl::read_string(std::istream &_stream) { fcppt::array::object<sge::model::md3::string::value_type, Max> tmp_name{fcppt::no_init{}}; if (!_stream.read( fcppt::cast::to_char_ptr<char *>(tmp_name.data()), fcppt::cast::size<std::streamsize>(fcppt::cast::to_signed(tmp_name.size())))) { throw sge::model::md3::exception(FCPPT_TEXT("Reading a string failed")); } if (!std::count(tmp_name.begin(), tmp_name.end(), 0)) { throw sge::model::md3::exception(FCPPT_TEXT("String in md3 file not ended with a 0!")); } return sge::model::md3::string{tmp_name.data()}; } #define SGE_MODEL_MD3_INSTANTIATE_READ_STRING(maxc) \ template sge::model::md3::string sge::model::md3::impl::read_string<maxc>(std::istream &) SGE_MODEL_MD3_INSTANTIATE_READ_STRING(sge::model::md3::impl::max_qpath::value); SGE_MODEL_MD3_INSTANTIATE_READ_STRING(16);
35.229167
92
0.716144
cpreh
7b0df066af04530745ec08a92576b72a336a1dee
5,864
cpp
C++
oja_unsupervised/main.cpp
Shimmen/NeuralNetworkStuff
f9058a7ce8aa9d1929083e974568795245304159
[ "MIT" ]
null
null
null
oja_unsupervised/main.cpp
Shimmen/NeuralNetworkStuff
f9058a7ce8aa9d1929083e974568795245304159
[ "MIT" ]
null
null
null
oja_unsupervised/main.cpp
Shimmen/NeuralNetworkStuff
f9058a7ce8aa9d1929083e974568795245304159
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <random> #define WITHOUT_NUMPY #include <matplotlib-cpp/matplotlibcpp.h> namespace plt = matplotlibcpp; /////////////////////////////////////////////// // Data reading, parsing, preprocessing struct Pattern { double x; double y; Pattern(double x, double y) : x(x), y(y) {} }; std::vector<Pattern> read_and_parse_data(const std::string& file_name) { std::vector<Pattern> patterns; std::ifstream ifs(file_name); double x; double y; while (ifs >> x >> y) { patterns.emplace_back(x, y); } return patterns; } void normalize_training_data_mean(std::vector<Pattern>& training_data) { double length = training_data.size(); double x_sum = 0.0; double y_sum = 0.0; for (auto &pattern : training_data) { x_sum += pattern.x; y_sum += pattern.y; } double x_mean = x_sum / length; double y_mean = y_sum / length; for (size_t i = 0; i < training_data.size(); ++i) { training_data[i].x -= x_mean; training_data[i].y -= y_mean; } } /////////////////////////////////////////////// // Plotting void plot_weight_and_training_data(const double weights[2], const std::vector<Pattern>& training_data) { // Plot input data size_t num_inputs = training_data.size(); std::vector<double> input_x(num_inputs); std::vector<double> input_y(num_inputs); for (size_t i = 0; i < num_inputs; ++i) { auto& point = training_data[i]; input_x[i] = point.x; input_y[i] = point.y; } plt::named_plot("Input patterns", input_x, input_y, "rx"); // Plot network weight (hopefully the principle direction) plt::named_plot("Weights", { 0.0, weights[0] }, { 0.0, weights[1] }, "b-"); plt::plot({ weights[0] }, { weights[1] }, "bo"); plt::grid(true); plt::legend(); plt::xlabel("x1"); plt::ylabel("x2"); } /////////////////////////////////////////////// // Test procedure void train_network(double weights[2], const Pattern& pattern, const double learning_rate) { // Oja's rule double target = pattern.x * weights[0] + pattern.y * weights[1]; double delta_x = learning_rate * target * (pattern.x - target * weights[0]); double delta_y = learning_rate * target * (pattern.y - target * weights[1]); weights[0] += delta_x; weights[1] += delta_y; } int main() { clock_t start_time = std::clock(); std::default_random_engine rng; rng.seed(static_cast<unsigned int>(start_time)); const double LEARNING_RATE = 0.001; const size_t NUM_UPDATE_STEPS = 20000; // Load training data std::vector<Pattern> training_data = read_and_parse_data("oja_unsupervised/data.txt"); std::uniform_int_distribution<size_t> random_training_data_sample_index(0, training_data.size() - 1); std::uniform_real_distribution<double> random_double(-1.0, 1.0); // Set up for plotting std::vector<double> weight_magnitude_key(NUM_UPDATE_STEPS); std::vector<double> weight_magnitude_val(NUM_UPDATE_STEPS); plt::plot(); // // Train with un-normalized data // { // Set up network double weights[2] = { random_double(rng), random_double(rng) }; for (size_t step = 0; step < NUM_UPDATE_STEPS; ++step) { // Perform one training step size_t i = random_training_data_sample_index(rng); train_network(weights, training_data[i], LEARNING_RATE); // Record weight magnitude weight_magnitude_key[step] = step; weight_magnitude_val[step] = std::sqrt(weights[0] * weights[0] + weights[1] * weights[1]); } // Plot weight magnitude/modulus in panel 1 plt::subplot(2, 2, 1); plt::title("Weight magnitude over time"); plt::named_plot("Weight magnitude", weight_magnitude_key, weight_magnitude_val, "r-"); plt::ylim(0.0, 1.25); plt::grid(true); plt::legend(); // Plot input data and weights plt::subplot(2, 2, 3); plt::title("Input patterns & network weight"); plot_weight_and_training_data(weights, training_data); plt::xlim(-2.0, 13.0); plt::ylim(-1.0, 4.0); plt::grid(true); plt::legend(); } // // Train with normalized data // { // Set up network double weights[2] = { random_double(rng), random_double(rng) }; // This time, normalize the training data! normalize_training_data_mean(training_data); for (size_t step = 0; step < NUM_UPDATE_STEPS; ++step) { // Perform one training step size_t i = random_training_data_sample_index(rng); train_network(weights, training_data[i], LEARNING_RATE); // Record weight magnitude weight_magnitude_key[step] = step; weight_magnitude_val[step] = std::sqrt(weights[0] * weights[0] + weights[1] * weights[1]); } // Plot weight magnitude/modulus in panel 2 plt::subplot(2, 2, 2); plt::title("Weight magnitude over time (data with zero mean)"); plt::named_plot("Weight magnitude", weight_magnitude_key, weight_magnitude_val, "r-"); plt::ylim(0.0, 1.25); plt::grid(true); plt::legend(); // Plot input data and weights plt::subplot(2, 2, 4); plt::title("Input patterns & network weight (data with zero mean)"); plot_weight_and_training_data(weights, training_data); plt::grid(true); plt::legend(); } clock_t end_time = std::clock(); double time_elapsed_s = static_cast<double>(end_time - start_time) / CLOCKS_PER_SEC; std::cout << "Time elapsed: " << time_elapsed_s << " s" << std::endl; // Blocks, so perform timing before this call plt::show(); return 0; }
28.8867
105
0.604707
Shimmen
7b16248afcbad5b4b9806804ed397b811651c375
9,742
cpp
C++
source/folders/camera/camera.cpp
jacoblammert/programmiersprachen-raytracer-cpp
d40ead374762094ee67d04c487764196f94748d6
[ "MIT" ]
null
null
null
source/folders/camera/camera.cpp
jacoblammert/programmiersprachen-raytracer-cpp
d40ead374762094ee67d04c487764196f94748d6
[ "MIT" ]
null
null
null
source/folders/camera/camera.cpp
jacoblammert/programmiersprachen-raytracer-cpp
d40ead374762094ee67d04c487764196f94748d6
[ "MIT" ]
null
null
null
#include "camera.hpp" /** Camera constructor with angle/ fov @param name of the camera @param fov field of view in degrees */ Camera::Camera (std::string const& name, float fov_x) : name_ {name}, position_ {0.0f, 0.0f, 0.0f}, direction_ {0.0000001f, 0.00000001f, -1.0f}, width_ {1}, height_ {1}, //TODO Berechnen durch fov in y Richtung? distance_ {fov_x}, fov_x_ {fov_x} { distance_ *= MATH_PI / 360.0f; distance_ = (float) (0.5f / std::tan(distance_)); // from presentation } /** Camera constructor with angle/ fov + position + direction + up-vector of camera @param name of the camera @param fov field of view in degrees @param eye position of the camera as vec3 @param direction of the camera as vec3 @param up up-vector of the camera as vec3 */ Camera::Camera (std::string const& name, float fov_x, glm::vec3 const& eye, glm::vec3 const& direction, glm::vec3 const& up) : name_ {name}, position_ {eye}, direction_ {direction}, width_{1}, height_{1}, //TODO Berechnen durch fov in y Richtung? distance_{fov_x}, up_vector_ {up}, fov_x_ {fov_x} { distance_ *= MATH_PI / 360.0f; distance_ = (float) (0.5f / std::tan(distance_)); // from presentation } /** * Camera constructor without angle / fov * @param position of the camera as vec3 * @param direction of the camera as vec3 * @param width of the screen in pixel/ int * @param height of the screen in pixel/ int * @param distance of the cameraplane from the cameraorigin to the cameraplane */ Camera::Camera (glm::vec3 const &position, glm::vec3 const &direction, int width, int height, float distance) : position_ {position}, direction_ {direction}, width_ {width}, height_ {height}, distance_ {distance} { this->direction_ = glm::normalize(this->direction_); } /** * * Camera constructor with fov - looks at 0, 0, -1 * @param position of the camera as vec3 * @param direction of the camera as vec3 * @param width of the screen in pixel/ int * @param height of the screen in pixel/ int * @param fov field of view in degrees */ Camera::Camera (glm::vec3 const &position, int width, int height, float fov_x) : position_ {position}, direction_ {0.0f, 0.0f, -1.0f}, width_ {width}, height_ {height}, distance_ {fov_x} { distance_ *= MATH_PI / 360.0f; distance_ = (float) (0.5f / std::tan(distance_)); // from presentation } /** * Generates a ray from the cameras position onto the camera plane. If the fov should be changed, the distance of the camera plane needs to change. * The x and y positions are in pixelspace, like the width and the height of the camera * * @param x pos of the Pixel on the screen 0 to width * @param y pos of the Pixel on the screen 0 to height * @return a new Ray with the pos of the Camera and the direction onto the camera plane in worldspace */ Ray Camera::generate_ray (int x, int y) const { // from the left of the camera plane to the right (normalized) glm::vec3 right = glm::normalize (glm::cross(direction_, up_vector_)); // from bottom of the camera plane to the top (normalized) glm::vec3 top = glm::normalize (glm::cross(direction_, right)); // TODO could be simplified to save two variables float x_percentage = (float) x / (float) width_; float y_percentage = (float) y / (float) height_; // now a range from -1 to 1 depending on the x to width ratio float scale_x = -(x_percentage - 0.5f) * 2 * ((float) width_ / (float) height_); // now a range from -1 to 1 depending on the y to height ratio float scale_y = -(y_percentage - 0.5f) * 2; // makes image blurry - like looking through the rong glasses / uneven glass float a = random_float(); float b = random_float(); float c = random_float(); // vector in random direction glm::vec3 blur = glm::normalize (glm::vec3 {a, b, c}); // depth of field // "strength of depth effect" - standard 0 blur *= dof_strength_; glm::vec3 direction = glm::normalize((direction_ * distance_) + (top * scale_y) + (right * scale_x)); /// The focal point will be set to a given distance, therefore there must be an offset in position and direction which cancel at the direction direction *= focal_length_; // new custom camera ray for the given pixel return {- blur + position_, direction + blur}; } /** * Sets the position of the camera to a new vector * @param pos new position of the camera */ void Camera::set_position (glm::vec3 const& pos) { position_ = pos; } /** Sets the width and height of the screen @param width of the screen in pixel/ int @param height of the screen in pixel/ int */ void Camera::set_width_height (int width, int height) { width_ = width; height_ = height; } /** Sets the direction in which the camera faces - camera can be moved by changing mouse position @param window of scene */ void Camera::set_direction (Window const &window) { glm::vec2 mouse = window.mouse_position(); // looks if mouse is in window if (0 < mouse[0] && mouse[0] < window.window_size()[0] && 0 < mouse[1] && mouse[1] < window.window_size()[1]) { float mouse_x = -mouse[0] / window.window_size()[0]; float mouse_y = mouse[1] / window.window_size()[1]; // x, y and z are calculated by the position of the mouse (moving mose to the left side = direction goes to a position on the "left" side) float x = sin (3.14f * 2 * mouse_x); // sin -> rotation around origin, 3.14f * 2 * mouse_x for a range from 0 to 2 pi float y = cos (3.14f * 2 * mouse_x); // cos -> rotation around origin, 3.14f * 2 * mouse_y for a range from 0 to 2 pi float z = cos (3.14f * mouse_y); // Need to be scaled because we dont have a cylinder, but a sphere (z = 1/ z = 0) => x or y must be close to zero and not 1 as largest possible value x *= (1 - abs(z)); // Need to be scaled because we dont have a cylinder, but a sphere (z = 1/ z = 0) => x or y must be close to zero and not 1 as largest possible value y *= (1 - abs(z)); direction_ = glm::normalize(glm::vec3 {x, z, -y}); } } /** Sets the depth of field by getting the strength of the depth effect and the length of the focal area @param dof_strength strength of depth effect - standard 0 @param focal_length legth of focal area */ void Camera::set_depth_of_field (float dof_strength, float focal_length) { // The focal point will be set to a given distance, therefore there must be an offset in position and direction which cancel at the direction dof_strength_ = focal_length < INFINITY ? (focal_length / 250) : 0.1f; focal_length_ = focal_length < INFINITY ? focal_length : 4.0f; } /** Gives the position of the camera */ glm::vec3 Camera::get_position() const { return position_; } /** Gives the name of the camera */ std::string Camera::get_name() const { return name_; } /** Gives informations of the camera (name, position, ..) as a string - for creating the .sdf */ std::string Camera::get_information() const { std::string information = " " + name_ + " " + std::to_string(fov_x_) + " " + std::to_string(position_[0]) + " " + std::to_string(position_[1]) + " " + std::to_string(position_[2]) + " " + std::to_string(direction_[0]) + " " + std::to_string(direction_[1]) + " " + std::to_string(direction_[2]) + " " + std::to_string(up_vector_[0]) + " " + std::to_string(up_vector_[1]) + " " + std::to_string(up_vector_[2]) + "\n"; return information; } /** Prints the position and direction of the camera */ void Camera::print() const { std::cout << "Camera position: x: " << this->position_[0] << " y: " << this->position_[1] << " z: " << this->position_[2] << std::endl; std::cout << "Camera direction: x: " << this->direction_[0] << " y: " << this->direction_[1] << " z: " << this->direction_[2] << std::endl; } /** Translates the camera by using given position @param pos vector the camera is translated by */ void Camera::translate (glm::vec3 const &pos) { // translating the camera by pos position_ += pos; } /** * Giving the camera a position to point at - we can change the direction * @param pos position to look at */ void Camera::look_at (glm::vec3 const &pos) { direction_ = pos - position_; direction_ = glm::normalize (direction_); } /** Camera can be moved by using wasd, space and shift @param window of the scene */ void Camera::move (Window const &window) { int w = window.get_key(87); int s = window.get_key(83); int a = window.get_key(65); int d = window.get_key(68); int space = window.get_key(32); int shift = window.get_key(340); // w: forwards movement // a: left movement // s: backwards movement // d: right movement // space: up movement // shift: down movement float x = w - s; float z = a - d; float y = space - shift; // Calculating the direction the camera moves in with when one of the w a s d Keys are pressed (ws in one direction (dir) and dir_orthogonal for a and d) glm::vec3 dir = glm::normalize (glm::vec3 {direction_[0], 0, direction_[2]}); glm::vec3 dir_orthogonal = glm::normalize (glm::cross (dir, up_vector_)); dir *= x; dir_orthogonal *= z; // New position calculated position_ += glm::vec3 {0, y, 0} + dir + dir_orthogonal; } /** * for roughness - get a value between -1 and 1 * @return random float value */ float Camera::random_float() const { // range from -range to range return ((((float) rand()) / (float) (RAND_MAX / 2.0f)) - 1.0f); }
32.912162
419
0.649559
jacoblammert
7b17e7e7fb6a568984fbf6c4e5913cb6c01ed11a
10,347
cpp
C++
Source/Scene/imstkcpdScene.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
2
2020-08-14T07:21:30.000Z
2021-08-30T09:39:09.000Z
Source/Scene/imstkcpdScene.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
null
null
null
Source/Scene/imstkcpdScene.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
1
2020-08-14T07:00:31.000Z
2020-08-14T07:00:31.000Z
#include "imstkcpdScene.h" #include <chrono> using Clock = std::chrono::steady_clock; const int nit = 1000; namespace cpd { Scene::Scene() { m_constraintSolver = std::make_shared<ConstraintSolver>(); m_externalForceSolver = std::make_shared<ExternalForceSolver>(); m_time.setZero(nit); m_pos.setZero(nit); //Eigen::initParallel(); } unsigned Scene::getParticleCount() { unsigned nbrParticle = 0; for (auto& object : m_objects) { nbrParticle += object->getParticleCount(); } return nbrParticle; } void Scene::addCollisionPair(ParticleObjectPtr p_object1, ParticleObjectPtr p_object2) { auto& pair = std::make_shared<CollisionPair>(p_object1, p_object2, COLLISION_SOLVER_ITERATION); m_constraintSolver->addCollisionPair(pair); } void Scene::initializeConstraints() { unsigned priority = 0; for (auto& object : m_objects) { ConstraintSetPtr constraintSet = std::make_shared<ConstraintSet>(object, priority); object->addConstraintSet(constraintSet); auto& types = object->getConstraintTypes(); for (auto& type : types) { auto subtype = type.getSubType(); switch (type.getType()) { case ConstraintBase::Type::Distance: constraintSet->initializeDistanceConstraints(subtype); break; case ConstraintBase::Type::Dihedral: constraintSet->initializeDihedralConstraints(); break; case ConstraintBase::Type::Area: constraintSet->initializeAreaConstraints(); break; case ConstraintBase::Type::CST2D: constraintSet->initializeCSTEnergyConstraints(subtype); break; case ConstraintBase::Type::CST3D: constraintSet->initializeCSVEnergyConstraints(subtype); break; case ConstraintBase::Type::Linear1D: constraintSet->initializeOneDEnergyConstraints(); break; default: break; } } constraintSet->setTimeStepSize(m_dt); std::cout << "dt = " << m_dt << std::endl; m_constraintSolver->addConstraintSet(constraintSet); std::cout << "Number of constraints = " << constraintSet->getConstraints().size() << std::endl; } } void Scene::preSimulation() { std::cout << "Initialization ..." << std::endl; for (auto& object : m_objects) { object->preSimulation(m_dt); } m_externalForceSolver->setTimeStepSize(m_dt); for (auto& force : m_externalForceSolver->getExternalForces()) { if (force->isForAll()) { for (auto& obj : m_objects) { force->addAffectedObject(obj); obj->addExternalForce(force->getForce()); } } else { for (auto& obj : force->getAffectedObjects()) { obj->addExternalForce(force->getForce()); } } } for (auto& force : m_externalForceSolver->getDistributedForces()) { if (force->isForAll()) { for (auto& obj : m_objects) { force->addAffectedObject(obj); obj->addDistributedForce(force->getForce()); } } else { for (auto& obj : force->getAffectedObjects()) { obj->addDistributedForce(force->getForce()); } } } m_externalForceSolver->updateAffectedObject(); for (auto& object : m_objects) { object->updateParticleAcceleration(); } initializeConstraints(); std::cout << "Initialization Finished." << std::endl; } bool Scene::simulate() { // reset objects and constraints if requested bool resetConstraint = false; for (auto& obj : m_objects) { if (obj->checkForReset()) { obj->reset(); resetConstraint = true; } } if (resetConstraint) { m_constraintSolver->resetLambda(); } auto tStart = Clock::now(); unsigned iter; // time-stepping for external force m_externalForceSolver->exertForces(); // solve constraints and collisions iter = m_constraintSolver->solve(); auto tSolveEnd = Clock::now(); double pos; double res = 0.0; // update position and velocity for (auto& obj : m_objects) { //if (!obj->isPBD()) // obj->updateTempPositions(); obj->updatePositions(); } auto tEnd = Clock::now(); double time = std::chrono::duration_cast<std::chrono::nanoseconds>(tEnd - tStart).count(); bool finalstate = tempPrint(time, iter); return finalstate; } void Scene::postSimulation() { std::cout << "Cleaning up ..." << std::endl; bool write = true; if (write) { writeVectorMatlabPlot(m_time, "time.m"); writeVectorMatlabPlot(m_pos, "res.m"); for (auto& obj : m_objects) { obj->writePositions(); auto& sets = obj->getConstraintSets(); std::ofstream mfile("test.m"); mfile << "strain = ["; mfile.close(); for (auto& s : sets) { auto& cs = s->getConstraints(); for (auto& c : cs) { c->writeResults("test.m"); } } mfile.open("test.m", std::ofstream::out | std::ofstream::app); mfile << "];"; mfile.close(); } } std::cout << "Clean-up Finished." << std::endl; } bool Scene::tempPrint(double time, double res) { //std::cout << '.'; const int step = 150; const int size = 21; static double xx[step][size][3]; static int cstep = 0; static int st = 0; static int dt = ceil((1.3 / m_dt) / step); static bool chain = false; if (chain) { if (st%dt == 0) { for (auto& obj : m_objects) { auto& ps = obj->getPositions();//obj->getPrevPositions(); for (int k = 0; k < size; k++) { xx[cstep][k][0] = ps[k][0]; xx[cstep][k][1] = ps[k][1]; xx[cstep][k][2] = ps[k][2]; } } cstep++; std::cout << cstep << '/' << st << std::endl; } st++; if (cstep == step) { chain = false; std::ofstream mfile("chaincpd4.m"); if (!mfile.is_open()) { std::cout << "Unable to create or open file."; } std::string tempstr = std::string("chaincpd.m"); mfile << "u = [\n"; for (int c = 0; c < step; ++c) { for (auto i = 0; i < size; ++i) { mfile << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << xx[c][i][0] << ' '; } mfile << "\n"; } mfile << "];\n"; mfile << "v = [\n"; for (int c = 0; c < step; ++c) { for (auto i = 0; i < size; ++i) { mfile << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << xx[c][i][1] << ' '; } mfile << "\n"; } mfile << "];\n"; mfile << "w = [\n"; for (int c = 0; c < step; ++c) { for (auto i = 0; i < size; ++i) { mfile << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << xx[c][i][2] << ' '; } mfile << "\n"; } mfile << "];\n"; mfile.close(); std::cout << "Write finished."; } } bool printout = true; if (printout) for (auto& obj : m_objects) { static int it = 0; static double max = 900.0; static bool tryit = true; // iteration at which max x displacement is reached if (tryit) { if ((obj->getPosition(obj->getParticleCount() - 1)).y() <= max) max = (obj->getPosition(obj->getParticleCount() - 1)).y(); else { tryit = false; std::cout << "it = " << it << ", max = " << max << std::endl; } } static double totaltime = 0; static int totaliter = 0; if (it < nit) { m_time[it] = time; m_pos[it] = res; std::cout << it << std::endl; totaltime += time; totaliter += res; } else if (it == nit) { double average = totaltime / nit; for (unsigned ave = 0; ave < nit; ave++) { if (m_time[ave] > 1.5*average) totaltime += average - m_time[ave]; } std::cout << std::endl << "Average time = " << totaltime / nit << std::endl << std::endl; std::cout << std::endl << "Average iter = " << totaliter / nit << std::endl << std::endl; } it++; // static state static double dist = 1.0; static Vec3d pos = Vec3d(0, 0, 0); static Vec3d posp = Vec3d(0, 0, 0); static bool onetime = true; pos = obj->getDisplacement(obj->getParticleCount() - 1); static bool first = true; if (first) { first = false; pos = Vec3d(1.0, 0.0, 0.0); } dist = (pos - posp).norm() / pos.norm(); int n = int(1 / TIMESTEP); //n = 1; if ((it%n) == 0) { std::cout << "it = " << it << ':' << dist * n << std::endl; printVector(obj->getPosition(obj->getParticleCount() - 1)); std::cout << (pos - posp).norm() << ',' << pos.norm() << ',' << dist << ", cr = " << dist / TIMESTEP << std::endl; } posp = pos; static bool converge = false; static int cv = 0; if (onetime) { if (dist / TIMESTEP < 1e-6) { printVector(obj->getPosition(obj->getParticleCount() - 2)); printVector(obj->getPosition(obj->getParticleCount() - 1)); std::cout << std::endl; if (cv > 10) { onetime = false; } converge = true; cv++; std::cout << "it = " << it << ':' << dist / TIMESTEP << std::endl; printVector(obj->getPosition(obj->getParticleCount() - 1)); } else { converge = false; cv = 0; } } if (it > nit) onetime = false; return onetime; } } }
25.802993
124
0.50662
quantingxie
7b2292fa629b25a62f8a6ccb64d25887a6cf388d
1,757
cpp
C++
Codes/Codes_for_xStar/diploidSequence.cpp
CasperLumby/Bottleneck_Size_Estimation
9f9d81e35c1ac9dc74541401e8da70d428be1ad1
[ "MIT" ]
null
null
null
Codes/Codes_for_xStar/diploidSequence.cpp
CasperLumby/Bottleneck_Size_Estimation
9f9d81e35c1ac9dc74541401e8da70d428be1ad1
[ "MIT" ]
null
null
null
Codes/Codes_for_xStar/diploidSequence.cpp
CasperLumby/Bottleneck_Size_Estimation
9f9d81e35c1ac9dc74541401e8da70d428be1ad1
[ "MIT" ]
1
2019-06-12T13:25:36.000Z
2019-06-12T13:25:36.000Z
// // diploidSequence.cpp // TransmissionProject // // Created by Casper Lumby on 28/10/2015. // Copyright © 2015 Casper Lumby. All rights reserved. // #include <stdio.h> #include "iostream" #include "diploidSequence.h" using namespace std; DiploidSequence::DiploidSequence() {} DiploidSequence::DiploidSequence(int length) : majorSeq(Sequence(length)), minorSeq(Sequence(length)) { } DiploidSequence::DiploidSequence(Sequence & ma, Sequence & mi) : majorSeq(ma), minorSeq(mi) { } DiploidSequence::DiploidSequence(string ma, string mi) : majorSeq(Sequence(ma)), minorSeq(Sequence(mi)) { } DiploidSequence::~DiploidSequence() {} //Getters and setters void DiploidSequence::setMajor(Sequence & ma) { majorSeq = ma; } void DiploidSequence::setMinor(Sequence & mi){ minorSeq = mi; } Sequence DiploidSequence::getMajor() { return majorSeq; } Sequence DiploidSequence::getMinor() { return minorSeq; } void DiploidSequence::setMajor(int index, char ma) { majorSeq.setBase(index, ma); } void DiploidSequence::setMinor(int index, char mi) { minorSeq.setBase(index, mi); } void DiploidSequence::print() { for(int i=0;i<majorSeq.getLength();i++) { cout << majorSeq.getBase(i) << "/" << minorSeq.getBase(i) << ","; } cout << "\n"; } string DiploidSequence::printToString() { string output; for(int i=0;i<majorSeq.getLength();i++) { output += majorSeq.getBase(i); output += "/"; output += minorSeq.getBase(i); if(i<majorSeq.getLength()-1) { output += " , "; //Don't add after the last pair of bases } } return output; } int DiploidSequence::getLength() { return majorSeq.getLength(); } void DiploidSequence::removeBase(int index) { majorSeq.removeBase(index); minorSeq.removeBase(index); }
27.888889
107
0.69152
CasperLumby
7b28229a8e9f3c34ef1117d7f38cc381de7f3050
778
cpp
C++
Code/src/engine/graphics/fonts/FontContainer.cpp
Thraix/MasterThesis
4e4cb94b2a4ee261b2b9974aa4b20f6643eb6595
[ "MIT" ]
1
2021-04-16T10:54:38.000Z
2021-04-16T10:54:38.000Z
Code/src/engine/graphics/fonts/FontContainer.cpp
Thraix/MasterThesis
4e4cb94b2a4ee261b2b9974aa4b20f6643eb6595
[ "MIT" ]
null
null
null
Code/src/engine/graphics/fonts/FontContainer.cpp
Thraix/MasterThesis
4e4cb94b2a4ee261b2b9974aa4b20f6643eb6595
[ "MIT" ]
null
null
null
#include "FontContainer.h" namespace Greet{ FontContainer::FontContainer(const std::string& filename, const std::string& name) : m_filename(filename),m_data(NULL),m_datasize(0), m_name(name) { } FontContainer::FontContainer(const byte* data, uint datasize, const std::string& name) : m_filename(""),m_data(data),m_datasize(datasize), m_name(name) { } FontContainer::~FontContainer() { auto it = m_fonts.begin(); while(it != m_fonts.end()) { delete (*it); it++; } m_fonts.clear(); } Font* FontContainer::GetSize(uint size) { auto it = m_fonts.find(size); if (it == m_fonts.end()) { Font* font = new Font(this,size); m_fonts.emplace(font); return font; } return *it; } }
19.45
88
0.611825
Thraix
7b2c9e3024ec3150c3e3013fa41163fbcf564d2c
400
cpp
C++
engine/source/private/core/threads.cpp
kociap/GameEngine
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
[ "MIT" ]
12
2019-01-02T11:13:19.000Z
2020-06-02T10:58:20.000Z
engine/source/private/core/threads.cpp
kociap/GameEngine
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
[ "MIT" ]
null
null
null
engine/source/private/core/threads.cpp
kociap/GameEngine
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
[ "MIT" ]
1
2020-04-03T11:54:53.000Z
2020-04-03T11:54:53.000Z
#include <core/threads.hpp> #include <thread> #if defined(_WIN32) || defined(_WIN64) extern "C" { // xthreads.h struct xtime; void _Thrd_sleep(const xtime*); } namespace anton_engine::threads { void sleep(Timespec const& duration) { _Thrd_sleep(reinterpret_cast<xtime const*>(&duration)); } } #else #error threads not implemented for non-windows builds. #endif
16.666667
63
0.6775
kociap
7b343a347a312d83c60063c15f44403f4a925f51
22,936
cpp
C++
comp477-a1/src/glMain.cpp
aidendeom/comp477-assignment
a2b4d752c40c23416f518047e92c29beaacf5e2c
[ "MIT" ]
null
null
null
comp477-a1/src/glMain.cpp
aidendeom/comp477-assignment
a2b4d752c40c23416f518047e92c29beaacf5e2c
[ "MIT" ]
null
null
null
comp477-a1/src/glMain.cpp
aidendeom/comp477-assignment
a2b4d752c40c23416f518047e92c29beaacf5e2c
[ "MIT" ]
null
null
null
#ifdef __APPLE__ #include <GLUT/glut.h> #else #ifdef _WIN32 #include "GL/glut.h" #else #include <GL/freeglut.h> #endif #endif #include <iostream> #include <fstream> #include <cmath> #include <cstring> #include <csignal> #include <chrono> #include <functional> #include <string> #include <Shlwapi.h> #include <Windows.h> #include "skeleton.h" #include "defMesh.h" #include "AnimationMode.h" #include "Quatf.h" using namespace std; // Constants const string ANIMATIONS_PATH{ "resources/animations/" }; const float durationDelta = 0.25f; const float durationMin = 0.1f; const float durationMax = 5.0f; // Function declarations auto displayInstructions() -> void; auto nextKeyFrameEdit() -> void; auto prevKeyFrameEdit() -> void; auto captureCurrentPose() -> void; auto nextKeyFramePlayback() -> void; auto prevKeyFramePlayback() -> void; auto chooseInterpFunction(char c) -> void; auto matLerp(const Quatf& from, const Quatf& to, float t) -> Quatf; auto eurlerAngleLerp(const Quatf& from, const Quatf& to, float t) -> Quatf; auto increaseSpeed() -> void; auto decreaseSpeed() -> void; auto clampSpeed() -> void; auto saveCurrentAnimation() -> void; auto loadAnimation() -> void; auto togglePlayAnimation() -> void; auto playAnimation() -> void; auto stopAnimation() -> void; auto updateCurrentFrame() -> void; float animDuration = 1.0f; bool playingAnimation = false; bool loopAnimation = false; AnimationMode animationMode{ AnimationMode::Edit }; //Create Mesh DefMesh myDefMesh; //Switches int meshModel=0; bool drawSkeleton=true; //Window parameters int width = 1024; int height = 768; ///* Ortho (if used) */ double _left = 0.0; /* ortho view volume params */ double _right = 0.0; double _bottom = 0.0; double _top = 0.0; double _zNear = 0.1; double _zFar = 50.0; double fovy = 45.0; double prev_z = 0; //Model matrices double _matrix[16]; double _matrixI[16]; /* Mouse Interface */ int _mouseX = 0; /* mouse control variables */ int _mouseY = 0; bool _mouseLeft = false; bool _mouseMiddle = false; bool _mouseRight = false; double _dragPosX = 0.0; double _dragPosY = 0.0; double _dragPosZ = 0.0; double vlen(double x, double y, double z) { return sqrt(x * x + y * y + z * z); } float getAngle(Vector2f v1, Vector2f v2) { auto l1 = v1.lengthSq(); auto l2 = v2.lengthSq(); // Make sure we don't divide by zero if (std::abs(l1) < EPSILON || std::abs(l2) < EPSILON) return 0; v1.normalize(); v2.normalize(); auto angle = std::acos(Vector2f::dot(v1, v2)); auto orientation = (v1.x * v2.y) - (v2.x * v1.y); if (orientation > 0) angle = -angle; // Radians to degrees return static_cast<float>(angle * (180.0 / M_PI)); } Vector3f getEyePosition() { auto& m = _matrix; return -Vector3f { static_cast<float>(m[12]), static_cast<float>(m[13]), static_cast<float>(m[14]) }; } Vector3f getEyeDirection() { Matrix4d m{ _matrixI }; Vector4d forward{ 0, 0, -1, 0 }; Vector4f f{ m * forward }; return Vector3f{ f.x, f.y, f.z }; } void invertMatrix(const GLdouble * m, GLdouble * out) { /* NB. OpenGL Matrices are COLUMN major. */ #define MAT(m,r,c) (m)[(c)*4+(r)] /* Here's some shorthand converting standard (row,column) to index. */ #define m11 MAT(m,0,0) #define m12 MAT(m,0,1) #define m13 MAT(m,0,2) #define m14 MAT(m,0,3) #define m21 MAT(m,1,0) #define m22 MAT(m,1,1) #define m23 MAT(m,1,2) #define m24 MAT(m,1,3) #define m31 MAT(m,2,0) #define m32 MAT(m,2,1) #define m33 MAT(m,2,2) #define m34 MAT(m,2,3) #define m41 MAT(m,3,0) #define m42 MAT(m,3,1) #define m43 MAT(m,3,2) #define m44 MAT(m,3,3) GLdouble det; GLdouble d12, d13, d23, d24, d34, d41; GLdouble tmp[16]; /* Allow out == in. */ /* Inverse = adjoint / det. (See linear algebra texts.) */ /* pre-compute 2x2 dets for last two rows when computing */ /* cofactors of first two rows. */ d12 = (m31 * m42 - m41 * m32); d13 = (m31 * m43 - m41 * m33); d23 = (m32 * m43 - m42 * m33); d24 = (m32 * m44 - m42 * m34); d34 = (m33 * m44 - m43 * m34); d41 = (m34 * m41 - m44 * m31); tmp[0] = (m22 * d34 - m23 * d24 + m24 * d23); tmp[1] = -(m21 * d34 + m23 * d41 + m24 * d13); tmp[2] = (m21 * d24 + m22 * d41 + m24 * d12); tmp[3] = -(m21 * d23 - m22 * d13 + m23 * d12); /* Compute determinant as early as possible using these cofactors. */ det = m11 * tmp[0] + m12 * tmp[1] + m13 * tmp[2] + m14 * tmp[3]; /* Run singularity test. */ if (det == 0.0) { /* printf("invert_matrix: Warning: Singular matrix.\n"); */ /* memcpy(out,_identity,16*sizeof(double)); */ } else { GLdouble invDet = 1.0 / det; /* Compute rest of inverse. */ tmp[0] *= invDet; tmp[1] *= invDet; tmp[2] *= invDet; tmp[3] *= invDet; tmp[4] = -(m12 * d34 - m13 * d24 + m14 * d23) * invDet; tmp[5] = (m11 * d34 + m13 * d41 + m14 * d13) * invDet; tmp[6] = -(m11 * d24 + m12 * d41 + m14 * d12) * invDet; tmp[7] = (m11 * d23 - m12 * d13 + m13 * d12) * invDet; /* Pre-compute 2x2 dets for first two rows when computing */ /* cofactors of last two rows. */ d12 = m11 * m22 - m21 * m12; d13 = m11 * m23 - m21 * m13; d23 = m12 * m23 - m22 * m13; d24 = m12 * m24 - m22 * m14; d34 = m13 * m24 - m23 * m14; d41 = m14 * m21 - m24 * m11; tmp[8] = (m42 * d34 - m43 * d24 + m44 * d23) * invDet; tmp[9] = -(m41 * d34 + m43 * d41 + m44 * d13) * invDet; tmp[10] = (m41 * d24 + m42 * d41 + m44 * d12) * invDet; tmp[11] = -(m41 * d23 - m42 * d13 + m43 * d12) * invDet; tmp[12] = -(m32 * d34 - m33 * d24 + m34 * d23) * invDet; tmp[13] = (m31 * d34 + m33 * d41 + m34 * d13) * invDet; tmp[14] = -(m31 * d24 + m32 * d41 + m34 * d12) * invDet; tmp[15] = (m31 * d23 - m32 * d13 + m33 * d12) * invDet; memcpy(out, tmp, 16 * sizeof(GLdouble)); } #undef m11 #undef m12 #undef m13 #undef m14 #undef m21 #undef m22 #undef m23 #undef m24 #undef m31 #undef m32 #undef m33 #undef m34 #undef m41 #undef m42 #undef m43 #undef m44 #undef MAT } void screenToWorldPos(double *px, double *py, double *pz, const int x, const int y, const int *viewport) { /* Use the ortho projection and viewport information to map from mouse co-ordinates back into world co-ordinates */ *px = (double) (x - viewport[0]) / (double) (viewport[2]); *py = (double) (y - viewport[1]) / (double) (viewport[3]); *px = _left + (*px) * (_right - _left); *py = _top + (*py) * (_bottom - _top); *pz = _zNear; } void getMatrix() { glGetDoublev(GL_MODELVIEW_MATRIX, _matrix); invertMatrix(_matrix, _matrixI); } void init() { //OpenGL initialize functions goes here /*glutInitContextVersion(4, 2); glutInitContextProfile(GLUT_CORE_PROFILE); glutInitContextFlags(GLUT_DEBUG); std::cout<<"Vendor: "<<glGetString(GL_VENDOR)<<std::endl; std::cout<<"Version: "<<glGetString(GL_VERSION)<<std::endl; std::cout<<"GLSL: "<<glGetString(GL_SHADING_LANGUAGE_VERSION)<<std::endl;*/ //Light values and coordinates GLfloat ambientLight[] = { 0.3f, 0.3f, 0.3f, 1.0f }; GLfloat diffuseLight[] = { 0.7f, 0.7f, 0.7f, 1.0f }; GLfloat lightPos[] = {20.0f, 20.0f, 50.0f}; glEnable(GL_DEPTH_TEST); glFrontFace(GL_CCW); //glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Hidden surface removal // Counterclockwise polygons face out // Do not calculate inside of jet // Enable lighting glEnable(GL_LIGHTING); // Set up and enable light 0 glLightfv(GL_LIGHT0,GL_AMBIENT,ambientLight); glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuseLight); glEnable(GL_LIGHT0); // Enable color tracking glEnable(GL_COLOR_MATERIAL); // Set material properties to follow glColor values glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); glClearColor(0.2f, 0.2f, 0.2f, 3.0f ); //Rescale normals to unit length glEnable(GL_NORMALIZE); glLightfv(GL_LIGHT0,GL_POSITION,lightPos); glShadeModel(GL_FLAT); getMatrix(); //Init matrix //Translate camera glPushMatrix(); glLoadIdentity(); glTranslatef(0,0,-5.0); glMultMatrixd(_matrix); getMatrix(); glPopMatrix(); } void changeSize(int w, int h) { //GLfloat aspectRatio; //if(h==0) // h = 1; //glViewport(0, 0, w, h); //glMatrixMode(GL_PROJECTION); //glLoadIdentity(); //aspectRatio = (GLfloat)w / (GLfloat)h; //gluPerspective(45.0f, aspectRatio, 1.0f, 900.0f); //using perspective // //glMatrixMode(GL_MODELVIEW); //glLoadIdentity(); glViewport(0, 0, w, h); _top = 1.0; _bottom = -1.0; _left = -(double) w / (double) h; _right = -_left; glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* glOrtho(_left,_right,_bottom,_top,_zNear,_zFar); Ortho */ gluPerspective(fovy, (double) w / (double) h, _zNear, _zFar); /* PErspective for stereo */ glMatrixMode(GL_MODELVIEW); } void timerFunction(int value) { glutTimerFunc(10,timerFunction,1); glutPostRedisplay(); } void handleKeyPress(unsigned char key, int x, int y) { int i{ 0 }; // have to init here, or compiler will complain switch(key) { case 'n': i = static_cast<int>(animationMode); i++; i = i % static_cast<int>(AnimationMode::Count); animationMode = static_cast<AnimationMode>(i); cout << getAnimationModeString(animationMode) << " mode activated" << endl; break; case '=': if (animationMode == AnimationMode::Edit) nextKeyFrameEdit(); else if (animationMode == AnimationMode::Playback) nextKeyFramePlayback(); break; case '-': if (animationMode == AnimationMode::Edit) prevKeyFrameEdit(); else if (animationMode == AnimationMode::Playback) prevKeyFramePlayback(); break; case 13: // Enter key if (animationMode == AnimationMode::Edit) captureCurrentPose(); break; case 'j': decreaseSpeed(); break; case 'k': increaseSpeed(); break; case '1': case '2': case '3': case '4': chooseInterpFunction(key); break; case 's': saveCurrentAnimation(); break; case 'l': loadAnimation(); break; case 'p': togglePlayAnimation(); break; case 'o': loopAnimation = !loopAnimation; cout << "Loop animation: " << (loopAnimation ? "true" : "false") << endl; break; case 'm': meshModel = (meshModel + 1) % 3; break; case 27: // ESC key case 'q': exit(0); break; //default: //cout << key << endl; } } auto nextKeyFrameEdit() -> void { // Alias to the list of keyframes auto& frames = myDefMesh.mySkeleton.animation.keyframes; auto& idx = myDefMesh.mySkeleton.currentFrameIdx; // It's at the last, add a new frame if (idx == frames.size() - 1) { idx++; cout << "Adding new key frame " << idx + 1 << endl; auto frameCopy = frames.back(); frames.push_back(frameCopy); } else { idx++; auto& f = frames[idx]; myDefMesh.mySkeleton.setPose(f); cout << "Frame " << idx + 1 << "/" << frames.size() << endl; } } auto prevKeyFrameEdit() -> void { auto& frames = myDefMesh.mySkeleton.animation.keyframes; auto& idx = myDefMesh.mySkeleton.currentFrameIdx; if (idx > 0) { idx--; auto& f = frames[idx]; myDefMesh.mySkeleton.setPose(f); cout << "Frame " << idx + 1 << "/" << frames.size() << endl; } } auto captureCurrentPose() -> void { auto& skel = myDefMesh.mySkeleton; auto& anim = skel.animation; auto& idx = skel.currentFrameIdx; auto& frame = anim.keyframes[idx]; frame.capture(skel); cout << (idx + 1) << "/" << anim.keyframes.size() << " captured" << endl; } auto nextKeyFramePlayback() -> void { auto& frames = myDefMesh.mySkeleton.animation.keyframes; auto& idx = myDefMesh.mySkeleton.currentFrameIdx; if (idx < frames.size() - 1) { auto& skel = myDefMesh.mySkeleton; skel.from = &frames[idx]; idx++; skel.to = &frames[idx]; skel.time = 0; skel.duration = animDuration; } } auto prevKeyFramePlayback() -> void { auto& frames = myDefMesh.mySkeleton.animation.keyframes; auto& idx = myDefMesh.mySkeleton.currentFrameIdx; if (idx > 0) { auto& skel = myDefMesh.mySkeleton; skel.from = &frames[idx]; idx--; skel.to = &frames[idx]; skel.time = 0; skel.duration = animDuration; } } auto increaseSpeed() -> void { animDuration -= durationDelta; clampSpeed(); } auto decreaseSpeed() -> void { animDuration += durationDelta; clampSpeed(); } auto clampSpeed() -> void { animDuration = max(durationMin, min(animDuration, durationMax)); cout << "Duration is now " << animDuration << endl; } auto saveCurrentAnimation() -> void { string filename; cout << "== SAVE ==\n" << "Enter filename: "; cin >> filename; string filepath = ANIMATIONS_PATH + filename; wstring wfilepath{ begin(filepath), end(filepath) }; BOOL exists = PathFileExists(wfilepath.c_str()); while (exists) { cout << "That file already exists.\nChoose a different name: "; cin >> filename; filepath = ANIMATIONS_PATH + filename; wfilepath = wstring{ begin(filepath), end(filepath) }; exists = PathFileExists(wfilepath.c_str()); } myDefMesh.mySkeleton.animation.saveToFile(filepath); cout << "Animation saved to " << filepath << endl; } auto loadAnimation() -> void { string filename; cout << "== LOAD ==\n" << "Enter filename: "; cin >> filename; string filepath = ANIMATIONS_PATH + filename; wstring wfilepath{ begin(filepath), end(filepath) }; BOOL exists = PathFileExists(wfilepath.c_str()); while (!exists) { cout << "That file does not exists.\nEnter filename: "; cin >> filename; filepath = ANIMATIONS_PATH + filename; wfilepath = wstring{ begin(filepath), end(filepath) }; exists = PathFileExists(wfilepath.c_str()); } Animation anim = Animation::loadFromFile(filepath); auto& skel = myDefMesh.mySkeleton; skel.animation = anim; skel.currentFrameIdx = 0; skel.resetAnimParams(); cout << "Animation " << filename << " loaded successfully" << endl; } auto togglePlayAnimation() -> void { if (animationMode != AnimationMode::Playback) return; if (!playingAnimation) playAnimation(); else stopAnimation(); } auto playAnimation() -> void { auto& skel = myDefMesh.mySkeleton; skel.currentFrameIdx = 0; playingAnimation = true; cout << "Playing animation" << endl; } auto stopAnimation() -> void { playingAnimation = false; cout << "Stopping animation" << endl; } auto updateCurrentFrame() -> void { if (!playingAnimation) return; auto& skel = myDefMesh.mySkeleton; // It's time to play next frame if (skel.from == nullptr && skel.to == nullptr) nextKeyFramePlayback(); if (skel.currentFrameIdx >= skel.animation.keyframes.size() - 1 && skel.from == nullptr && skel.to == nullptr) { if (loopAnimation) { auto& frames = skel.animation.keyframes; auto& idx = skel.currentFrameIdx; skel.from = &frames[idx]; idx = 0; skel.to = &frames[idx]; skel.time = 0; skel.duration = animDuration; skel.currentFrameIdx = 0; } else stopAnimation(); } } auto chooseInterpFunction(char c) -> void { auto& f = myDefMesh.mySkeleton.interpFunction; string msg; switch (c) { case '1': msg = "Using matrix lerp"; f = matLerp; break; case '2': msg = "Using euler angle lerp"; f = eurlerAngleLerp; break; case '3': f = Quatf::lerp; msg = "Using lerp"; break; case '4': f = Quatf::slerp; msg = "Using slerp"; break; } cout << msg << endl; } auto matLerp(const Quatf& from, const Quatf& to, float t) -> Quatf { t = max(0.0f, min(t, 1.0f)); float t2 = 1 - t; const auto mf = from.mat4(); const auto mt = to.mat4(); auto res = mf * t2 + mt * t; return Quatf::fromMat4(res); } auto eurlerAngleLerp(const Quatf& from, const Quatf& to, float t) -> Quatf { t = max(0.0f, min(t, 1.0f)); float t2 = 1 - t; const auto ef = from.toEulerAngles(); const auto et = to.toEulerAngles(); auto res = ef * t2 + et * t; return Quatf::fromEulerAngles(res); } void mouseEvent(int button, int state, int x, int y) { int viewport[4]; _mouseX = x; _mouseY = y; if (state == GLUT_UP) switch (button) { case GLUT_LEFT_BUTTON: if (myDefMesh.mySkeleton.hasJointSelected) captureCurrentPose(); myDefMesh.mySkeleton.release(); _mouseLeft = false; break; case GLUT_MIDDLE_BUTTON: _mouseMiddle = false; break; case GLUT_RIGHT_BUTTON: _mouseRight = false; break; } else switch (button) { case GLUT_LEFT_BUTTON: myDefMesh.mySkeleton.selectOrReleaseJoint(); _mouseLeft = true; break; case GLUT_MIDDLE_BUTTON: _mouseMiddle = true; break; case GLUT_RIGHT_BUTTON: _mouseRight = true; break; case 4: //Zoomout glLoadIdentity(); glTranslatef(0.0f, 0.0f, -0.1f); glMultMatrixd(_matrix); getMatrix(); glutPostRedisplay(); break; case 3: //Zoomin glLoadIdentity(); glTranslatef(0.0f,0.0f,0.1f); glMultMatrixd(_matrix); getMatrix(); glutPostRedisplay(); break; default: break; //std::cout<<button<<std::endl; } glGetIntegerv(GL_VIEWPORT, viewport); screenToWorldPos(&_dragPosX, &_dragPosY, &_dragPosZ, x, y, viewport); } void mousePassiveFunc(int x, int y) { myDefMesh.mySkeleton.checkHoveringStatus(x, y); } void mouseMoveEvent(int x, int y) { const int dx = x - _mouseX; const int dy = y - _mouseY; int viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); if (!myDefMesh.mySkeleton.hasJointSelected) { bool changed = false; if (dx == 0 && dy == 0) return; if (_mouseMiddle || (_mouseLeft && _mouseRight)) { /* double s = exp((double)dy*0.01); */ /* glScalef(s,s,s); */ /* if(abs(prev_z) <= 1.0) */ glLoadIdentity(); glTranslatef(0.0f, 0.0f, dy * 0.01f); glMultMatrixd(_matrix); changed = true; } else if (_mouseLeft) { double ax, ay, az; double bx, by, bz; double angle; ax = dy; ay = dx; az = 0.0; angle = vlen(ax, ay, az) / (double) (viewport[2] + 1) * 180.0; /* Use inverse matrix to determine local axis of rotation */ bx = _matrixI[0] * ax + _matrixI[4] * ay + _matrixI[8] * az; by = _matrixI[1] * ax + _matrixI[5] * ay + _matrixI[9] * az; bz = _matrixI[2] * ax + _matrixI[6] * ay + _matrixI[10] * az; glRotated(angle, bx, by, bz); changed = true; } else if (_mouseRight) { double px, py, pz; screenToWorldPos(&px, &py, &pz, x, y, viewport); glLoadIdentity(); glTranslated(px - _dragPosX, py - _dragPosY, pz - _dragPosZ); glMultMatrixd(_matrix); _dragPosX = px; _dragPosY = py; _dragPosZ = pz; changed = true; } _mouseX = x; _mouseY = y; if (changed) { getMatrix(); glutPostRedisplay(); } } /* * Do joint jobs */ else if (animationMode == AnimationMode::Edit) { Joint* selectedJoint = myDefMesh.mySkeleton.getSelectedJoint(); // Leave if there is no selected joint or if it is the root // Might be fun to translate the model if the root is selected if (selectedJoint == nullptr || selectedJoint->transform.getParent() == nullptr) return; auto& j = *selectedJoint; auto& p = *j.transform.getParent()->getJoint(); Vector2i mousePos{ x, y }; Vector2f v1 = mousePos - p.screenCoord; Vector2f v2 = j.screenCoord - p.screenCoord; float angle = getAngle(v1, v2); Quatf rot = Quatf::angleAxis(angle, getEyeDirection()); auto newRot = rot * j.transform.getLocalRotation(); // Set the delta for this frame //j.delta.setLocalRotation(rot); //j.setDelta(true); j.transform.setLocalRotation(newRot); } } // Timer stuff using fast_clock = std::chrono::high_resolution_clock; using time_unit = std::chrono::milliseconds; auto t1 = fast_clock::now(); auto t2 = t1; void display() { auto diff = t2 - t1; auto delta = std::chrono::duration_cast<time_unit>(diff).count(); auto deltaSeconds = delta / 1000.0f; t1 = fast_clock::now(); updateCurrentFrame(); myDefMesh.mySkeleton.updateAnimation(deltaSeconds); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glMultMatrixd(_matrix); //draw terrain //glColor3f(0.5,0.5,0.5); glPushMatrix(); glColor3f(0.7f, 0.7f, 0.7f); glBegin(GL_QUADS); glVertex3f(-3.0f, -0.85f, 3.0f); glVertex3f(3.0f, -0.85f, 3.0f); glVertex3f(3.0f, -0.85f, -3.0f); glVertex3f(-3.0f, -0.85f, -3.0f); glEnd(); glPopMatrix(); glPushMatrix(); myDefMesh.glDraw(meshModel); myDefMesh.resetSkeletonDeltas(); glPopMatrix(); // Drawing reference coord system const int length = 3; const GLfloat r[]{ 1, 0, 0, 1 }; const GLfloat g[]{ 0, 1, 0, 1 }; const GLfloat b[]{ 0, 0, 1, 1 }; glLineWidth(5); glBegin(GL_LINES); glColor4fv(r); glVertex3i(0, 0, 0); glVertex3i(length, 0, 0); glColor4fv(g); glVertex3i(0, 0, 0); glVertex3i(0, length, 0); glColor4fv(b); glVertex3i(0, 0, 0); glVertex3i(0, 0, length); glEnd(); glutSwapBuffers(); t2 = fast_clock::now(); } auto displayInstructions() -> void { cout << "=== INSTRUCTIONS ===" << endl << "=: Increment current frame index" << endl << "-: Decrement current frame index" << endl << "Enter: Capture current pose and save in current frame" << endl << "n: Switch between Edit/Playback mode" << endl << "p: Play current animation" << endl << "o: Allow animation to loop" << endl << "m: Switch redering modes" << endl << "1: Use slerp" << endl << "2: Use lerp" << endl << "3: Use lerp with matrix" << endl << "4: Use lerp with euler angles" << endl; cout << "Starting in Edit Mode" << endl; cout << "Starting with slerp" << endl; } int main(int argc, char **argv) { glutInit(&argc, argv); //Print context info glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); //double buffer glutInitWindowSize(width, height); glutInitWindowPosition(0, 0); glutCreateWindow("COMP477"); glutDisplayFunc(display); glutReshapeFunc(changeSize); glutTimerFunc(10, timerFunction, 1); glutMouseFunc(mouseEvent); glutMotionFunc(mouseMoveEvent); glutKeyboardFunc(handleKeyPress); glutPassiveMotionFunc(mousePassiveFunc); displayInstructions(); if (argc > 1) { cout << "Attempting to load animation argument" << endl; char* arg1 = argv[0]; string filename{ arg1 }; string filepath = ANIMATIONS_PATH + filename; wstring wfilepath{ begin(filepath), end(filepath) }; BOOL exists = PathFileExists(wfilepath.c_str()); if (!exists) { Animation anim = Animation::loadFromFile(filepath); auto& skel = myDefMesh.mySkeleton; skel.animation = anim; skel.currentFrameIdx = 0; skel.resetAnimParams(); cout << "Animation " << filename << " loaded successfully" << endl; } else { cout << "Tried running with load command on file that does not exist" << endl; } } init(); glutMainLoop(); //delete something return 0; }
23.427988
121
0.635943
aidendeom
7b38e38f837413b6622534a45a79f92246d736f0
18,513
cpp
C++
test/pt-client/test_pt_client.cpp
costanic/mbed-edge
4900e950ff67f8974b7aeef955289ef56606c964
[ "Apache-2.0" ]
24
2018-03-27T16:44:18.000Z
2020-04-28T15:28:34.000Z
test/pt-client/test_pt_client.cpp
costanic/mbed-edge
4900e950ff67f8974b7aeef955289ef56606c964
[ "Apache-2.0" ]
19
2021-01-28T20:14:45.000Z
2021-11-23T13:08:59.000Z
test/pt-client/test_pt_client.cpp
costanic/mbed-edge
4900e950ff67f8974b7aeef955289ef56606c964
[ "Apache-2.0" ]
28
2018-04-02T02:36:48.000Z
2020-10-13T05:37:16.000Z
#include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include "cpputest-custom-types/value_pointer.h" extern "C" { #include "jansson.h" #include <string.h> #include <event2/event.h> #include <event2/bufferevent.h> #include "pt-client/pt_api.h" #include "pt-client/pt_api_internal.h" #include "test-lib/evbase_mock.h" #include "pt-client/client.h" #include "common/edge_mutex.h" #include "common/default_message_id_generator.h" #include "common/websocket_comm.h" #include "libwebsockets.h" #include "libwebsocket-mock/lws_mock.h" #include "cpputest-custom-types/my_json_frame.h" #include "test-lib/json_helper.h" #include "common/edge_trace.h" } #define EXPECTED_EDGE_PROTOCOL_API_VERSION "/1/pt" int dummy_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { return 0; } struct interrupt_parameter; typedef void (*test_func_t)(struct interrupt_parameter *); struct interrupt_parameter { struct event_base *base; struct connection **connection; void *userdata; short events; const char *socket_path; test_func_t test_func; pthread_t *tester_thread; bool connection_fails; bool expect_evthread_use_pthreads_failure; bool expect_cb_failure; }; static struct interrupt_parameter *create_interrupt_parameter(struct event_base *base) { struct interrupt_parameter *parameter = (struct interrupt_parameter *) calloc(1, sizeof(struct interrupt_parameter)); parameter->base = base; parameter->connection = (struct connection**) calloc(1, sizeof(struct connection*)); return parameter; } TEST_GROUP(pt_client) { void setup() { } void teardown() { } }; static void expect_mutex_init_deinit() { mock().expectOneCall("edge_mutex_init") .withPointerParameter("mutex", (void *) &rpc_mutex) .withUnsignedIntParameter("type", PTHREAD_MUTEX_ERRORCHECK) .andReturnValue(0); mock().expectOneCall("edge_mutex_destroy").withPointerParameter("mutex", (void *) &rpc_mutex).andReturnValue(0); } static void expect_mutexing() { mock().expectOneCall("edge_mutex_lock").withPointerParameter("mutex", (void *) &rpc_mutex).andReturnValue(0); mock().expectOneCall("edge_mutex_unlock").withPointerParameter("mutex", (void *) &rpc_mutex).andReturnValue(0); } void test_connection_ready_handler(struct connection *connection, void* userdata) { mock() .actualCall("test_connection_ready_handler") .withPointerParameter("connection", connection) .withPointerParameter("userdata", userdata); } void disconnected_handler(struct connection *connection, void *userdata) { mock().actualCall("disconnected_handler"); } void shutdown_handler(struct connection **connection, void *userdata) { mock().actualCall("shutdown_handler") .withPointerParameter("connection", (void *) connection) .withPointerParameter("userdata", (void *) userdata); } static int write_handler(struct connection *connection, const char *device_id, const uint16_t object_id, const uint16_t instance_id, const uint16_t resource_id, const unsigned int operation, const uint8_t *value, const uint32_t value_size, void *userdata) { ValuePointer *value_pointer = new ValuePointer((uint8_t *) value, value_size); int ret_val = mock().actualCall("write_handler") .withPointerParameter("connnection", connection) .withStringParameter("device_id", device_id) .withIntParameter("object_id", object_id) .withIntParameter("instance_id", instance_id) .withIntParameter("resource_id", resource_id) .withIntParameter("operation", operation) .withParameterOfType("ValuePointer", "value", (void *) value_pointer) .withLongIntParameter("value_size", value_size) .withPointerParameter("userdata", userdata) .returnIntValue(); delete value_pointer; return ret_val; } static void init_pt_cbs_to_null(protocol_translator_callbacks_t *pt_cbs) { pt_cbs->connection_ready_cb = NULL; pt_cbs->received_write_cb = NULL; pt_cbs->connection_shutdown_cb = NULL; } static void init_pt_cbs(protocol_translator_callbacks_t *pt_cbs) { pt_cbs->connection_ready_cb = test_connection_ready_handler; pt_cbs->received_write_cb = write_handler; pt_cbs->connection_shutdown_cb = shutdown_handler; pt_cbs->disconnected_cb = disconnected_handler; } static bool close_condition_check_no_retries(bool close_client) { return 1; // Always close } static void start_client(struct interrupt_parameter *parameter, protocol_translator_callbacks_t *pt_cbs, int dispatch_return_value) { char *name = (char*) "example_client"; pt_init_check_close_condition_function(close_condition_check_no_retries); int evthread_use_pthreads_return_value = parameter->expect_evthread_use_pthreads_failure ? -1 : 0; mock().expectOneCall("evthread_use_pthreads").andReturnValue(evthread_use_pthreads_return_value); if(evthread_use_pthreads_return_value != -1) { mock().expectOneCall("event_base_new") .andReturnValue(parameter->base); } if (!parameter->expect_evthread_use_pthreads_failure && !parameter->expect_cb_failure) { expect_mutexing(); if (parameter->base) { mock().expectOneCall("lws_set_log_level"); mock().expectOneCall("lws_create_context"); if (parameter->connection_fails) { lws_mock_setup_connection_failure(); } mock().expectOneCall("lws_client_connect_via_info") .withStringParameter("path", EXPECTED_EDGE_PROTOCOL_API_VERSION); if (parameter->connection_fails) { mock().expectOneCall("disconnected_handler"); mock().expectOneCall("event_base_loopbreak").withPointerParameter("base", (void *) parameter->base); mock().expectOneCall("shutdown_handler") .withPointerParameter("connection", parameter->connection) .withPointerParameter("userdata", parameter->userdata); } else { mock().expectOneCall("event_base_dispatch") .withPointerParameter("base", parameter->base) .andReturnValue(dispatch_return_value); if (dispatch_return_value != -1) { mock().expectOneCall("event_base_loopbreak").withPointerParameter("base", (void *) parameter->base); mock().expectOneCall("shutdown_handler") .withPointerParameter("connection", parameter->connection) .withPointerParameter("userdata", parameter->userdata); } } mock().expectOneCall("lws_context_destroy"); } } mock().expectOneCall("event_base_free") .withPointerParameter("base", parameter->base); mock().expectOneCall("libevent_global_shutdown"); pt_client_start(parameter->socket_path, name, pt_cbs, parameter->userdata, parameter->connection); } TEST(pt_client, test_initialize_and_destroy_trace_api) { mock().expectOneCall("edge_mutex_init") .withPointerParameter("mutex", &trace_mutex) .withIntParameter("type", PTHREAD_MUTEX_RECURSIVE) .andReturnValue(0); edge_trace_init(1); mock().checkExpectations(); mock().expectOneCall("edge_mutex_destroy").withPointerParameter("mutex", &trace_mutex).andReturnValue(0); edge_trace_destroy(); mock().checkExpectations(); } static void *client_shutdown_test_thread(void * param) { struct interrupt_parameter *parameter = (struct interrupt_parameter *) param; struct event_base *base = parameter->base; evbase_mock_wait_until_event_loop(base); struct lws *wsi = lws_mock_get_wsi(); websocket_connection_t *connection = (websocket_connection_t *) wsi->userdata; struct connection *conn = connection->conn; mock().expectOneCall("test_connection_ready_handler") .withPointerParameter("connection", conn) .withPointerParameter("userdata", conn->userdata); lws_mock_connection_established(lws_mock_get_wsi(), LWS_CALLBACK_CLIENT_ESTABLISHED); if (parameter->test_func) { parameter->test_func(parameter); } mock().expectOneCall("disconnected_handler"); lws_mock_connection_closed(lws_mock_get_wsi()); pt_client_shutdown(*(parameter->connection)); return NULL; } static void clean_interrupt_thread_and_parameter(struct interrupt_parameter *parameter) { if (parameter->base && parameter->base->event_loop_wait_simulation && parameter->tester_thread) { evbase_mock_release_interrupt_thread(parameter->base); pthread_join(*(parameter->tester_thread), NULL); } if (parameter->base) { if (parameter->base->event_loop_wait_simulation) { evbase_mock_release_interrupt_thread(parameter->base); } evbase_mock_delete(parameter->base); } free(parameter->tester_thread); free(*parameter->connection); free(parameter->connection); free(parameter); } static void test_start_and_shutdown_variant_common(const char *socket_path, bool connection_fails, test_func_t test_func) { struct event_base *base = evbase_mock_new(); struct interrupt_parameter *parameter = create_interrupt_parameter(base); parameter->connection_fails = connection_fails; parameter->socket_path = socket_path; parameter->test_func = test_func; expect_mutex_init_deinit(); protocol_translator_callbacks_t pt_cbs; init_pt_cbs(&pt_cbs); if (!connection_fails) { evbase_mock_setup_event_loop_wait(base); parameter->tester_thread = (pthread_t *) calloc(1, sizeof(pthread_t)); pthread_create(parameter->tester_thread, NULL, client_shutdown_test_thread, (void *) parameter); } start_client(parameter, &pt_cbs, 0); clean_interrupt_thread_and_parameter(parameter); } static void test_start_and_shutdown_variant(const char *socket_path, bool connection_fails) { test_start_and_shutdown_variant_common(socket_path, connection_fails, NULL); } static void test_start_and_shutdown_variant_with_test_func(const char *socket_path, test_func_t test_func) { test_start_and_shutdown_variant_common(socket_path, false, test_func); } static void test_callback_combination(pt_connection_ready_cb connection_ready_cb, pt_received_write_handler received_write_cb, pt_connection_shutdown_cb connection_shutdown_cb) { struct interrupt_parameter *parameter = create_interrupt_parameter(NULL); parameter->expect_cb_failure = true; expect_mutex_init_deinit(); expect_mutexing(); protocol_translator_callbacks_t pt_cbs; pt_cbs.connection_ready_cb = connection_ready_cb; pt_cbs.received_write_cb = received_write_cb; pt_cbs.connection_shutdown_cb = connection_shutdown_cb; start_client(parameter, &pt_cbs, -1); clean_interrupt_thread_and_parameter(parameter); } TEST(pt_client, test_start_client_and_shutdown) { test_start_and_shutdown_variant(NULL, false); mock().checkExpectations(); } TEST(pt_client, test_start_client_and_shutdown_with_localhost) { test_start_and_shutdown_variant("default-pt-socket", false); mock().checkExpectations(); } static void test_lws_client_receive_invalid(struct interrupt_parameter *parameter) { (void) parameter; unsigned char *data = (unsigned char *) "{ \"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"id\" : \"1\" }"; size_t len = 54; const char *expected_response = "{\"error\":{\"code\":-32601,\"message\":\"Method not found\"},\"id\":\"1\",\"jsonrpc\":\"2.0\"}"; int32_t response_len = 79; MyJsonFrameComparator comparator; mock().installComparator("MyJsonFrame", comparator); mock().expectOneCall("lws_remaining_packet_payload").andReturnValue(0); mock().expectOneCall("lws_callback_on_writable").andReturnValue(0); MyJsonFrame *frame = new MyJsonFrame((const char *) expected_response, response_len); mock().expectOneCall("lws_write").withParameterOfType("MyJsonFrame", "buf", (const void *) frame).andReturnValue(0); lws_mock_callback_client_receive(data, len, 0); delete frame; } TEST(pt_client, test_lws_client_receive_callback_invalid_message) { test_start_and_shutdown_variant_with_test_func("default-pt-socket", test_lws_client_receive_invalid); mock().checkExpectations(); } static void test_lws_client_receive_protocol_error(struct interrupt_parameter *parameter) { (void) parameter; // Note: following is not valid json. unsigned char *data = (unsigned char *) "[ \"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"id\" : \"1\" }"; size_t len = 54; mock().expectOneCall("lws_remaining_packet_payload").andReturnValue(0); mock().expectOneCall("lws_callback_on_writable").andReturnValue(-1); mock().expectOneCall("lws_close_reason"); lws_mock_callback_client_receive(data, len, 0); } TEST(pt_client, test_lws_client_receive_callback_protocol_error) { test_start_and_shutdown_variant_with_test_func("default-pt-socket", test_lws_client_receive_protocol_error); mock().checkExpectations(); } static void test_lws_client_receive_valid(struct interrupt_parameter *parameter) { #define TEST_WRITE_FROM_EDGE_CORE TEST_DATA_DIR "/write_from_edge_core_test.json" // Load device registration jsonrpc parameters structure from file json_t *request = load_json_params(TEST_WRITE_FROM_EDGE_CORE); // Build device registration jsonrpc structure unsigned char *data = (unsigned char *) json_dumps(request, JSON_COMPACT); size_t len = strlen((char *) data); const char *expected_response = "{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":\"ok\"}"; int32_t response_len = 49; MyJsonFrameComparator comparator; mock().installComparator("MyJsonFrame", comparator); mock().expectOneCall("lws_remaining_packet_payload").andReturnValue(0); mock().expectOneCall("lws_callback_on_writable").andReturnValue(0); struct connection *connection = *parameter->connection; ValuePointer *value_pointer = new ValuePointer((const uint8_t *) "@(=p\243\327\n=", 8); mock().expectOneCall("write_handler") .withPointerParameter("connnection", connection) .withStringParameter("device_id", "device-id-1") .withIntParameter("object_id", 3306) .withIntParameter("instance_id", 0) .withIntParameter("resource_id", 5700) .withIntParameter("operation", 2) .withParameterOfType("ValuePointer", "value", value_pointer) .withLongIntParameter("value_size", 8) .withPointerParameter("userdata", 0) .andReturnValue(0); MyJsonFrame *response_frame = new MyJsonFrame((const char *) expected_response, response_len); mock().expectOneCall("lws_write") .withParameterOfType("MyJsonFrame", "buf", (const void *) response_frame) .andReturnValue(0); lws_mock_callback_client_receive(data, len, 0); free(data); json_decref(request); delete response_frame; delete value_pointer; } TEST(pt_client, test_lws_client_receive_callback_valid_message) { test_start_and_shutdown_variant_with_test_func("default-pt-socket", test_lws_client_receive_valid); mock().checkExpectations(); } TEST(pt_client, test_lws_connection_fails) { test_start_and_shutdown_variant_common("default-pt-socket", true /* connection fails */, NULL); mock().checkExpectations(); } TEST(pt_client, test_start_client_libevent_configuration_fails) { struct interrupt_parameter *parameter = create_interrupt_parameter(NULL); parameter->expect_evthread_use_pthreads_failure = -1; expect_mutex_init_deinit(); protocol_translator_callbacks_t pt_cbs; init_pt_cbs_to_null(&pt_cbs); expect_mutexing(); start_client(parameter, &pt_cbs, -1); clean_interrupt_thread_and_parameter(parameter); mock().checkExpectations(); } TEST(pt_client, test_start_client_incorrect_protocol_translator_callbacks) { test_callback_combination(NULL, NULL, NULL); test_callback_combination(NULL, NULL, shutdown_handler); test_callback_combination(NULL, write_handler, NULL); test_callback_combination(NULL, write_handler, shutdown_handler); test_callback_combination(test_connection_ready_handler, NULL, NULL); test_callback_combination(test_connection_ready_handler, NULL, shutdown_handler); test_callback_combination(test_connection_ready_handler, write_handler, NULL); mock().checkExpectations(); } TEST(pt_client, test_start_client_and_shutdown_base_allocation_fails) { struct interrupt_parameter *parameter = create_interrupt_parameter(NULL); expect_mutex_init_deinit(); protocol_translator_callbacks_t pt_cbs; init_pt_cbs(&pt_cbs); start_client(parameter, &pt_cbs, -1); clean_interrupt_thread_and_parameter(parameter); mock().checkExpectations(); } TEST(pt_client, test_start_client_and_shutdown_with_failing_dispatch) { struct event_base *base = evbase_mock_new(); struct interrupt_parameter *parameter = create_interrupt_parameter(base); expect_mutex_init_deinit(); mock().expectOneCall("shutdown_handler") .withPointerParameter("connection", parameter->connection) .withPointerParameter("userdata", parameter->userdata); protocol_translator_callbacks_t pt_cbs; init_pt_cbs(&pt_cbs); start_client(parameter, &pt_cbs, -1); clean_interrupt_thread_and_parameter(parameter); mock().checkExpectations(); } TEST(pt_client, test_setting_message_id_generator) { pt_client_set_msg_id_generator(edge_default_generate_msg_id); mock().checkExpectations(); } TEST(pt_client, test_setting_default_message_id_generator) { pt_client_set_msg_id_generator(NULL); mock().checkExpectations(); }
39.056962
120
0.708097
costanic
7b3d18818aba67a65bf5dcb69d54fcba1aed292f
21,118
cpp
C++
src/engine/render/Model.cpp
italrr/astro
1c1ac28eacb081eee17a19c833d7866dfb348967
[ "MIT" ]
2
2020-11-30T23:18:12.000Z
2021-10-16T05:26:16.000Z
src/engine/render/Model.cpp
italrr/astro
1c1ac28eacb081eee17a19c833d7866dfb348967
[ "MIT" ]
null
null
null
src/engine/render/Model.cpp
italrr/astro
1c1ac28eacb081eee17a19c833d7866dfb348967
[ "MIT" ]
null
null
null
#include <cmath> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "../common/Type.hpp" #include "../common/Result.hpp" #include "../Core.hpp" #include "Model.hpp" static astro::Mat<4,4, float> aiMat2Astro(const aiMatrix4x4 &mat){ astro::Mat<4,4, float> result; result.mat[0 + 0*4] = mat.a1; result.mat[0 + 1*4] = mat.a2; result.mat[0 + 2*4] = mat.a3; result.mat[0 + 3*4] = mat.a4; result.mat[1 + 0*4] = mat.b1; result.mat[1 + 1*4] = mat.b2; result.mat[1 + 2*4] = mat.b3; result.mat[1 + 3*4] = mat.b4; result.mat[2 + 0*4] = mat.c1; result.mat[2 + 1*4] = mat.c2; result.mat[2 + 2*4] = mat.c3; result.mat[2 + 3*4] = mat.c4; result.mat[3 + 0*4] = mat.d1; result.mat[3 + 1*4] = mat.d2; result.mat[3 + 2*4] = mat.d3; result.mat[3 + 3*4] = mat.d4; return result; } static astro::Mat<4,4, float> aiMat2Astro(const aiMatrix3x3 &mat){ astro::Mat<4,4, float> result; result.mat[0 + 0*4] = mat.a1; result.mat[0 + 1*4] = mat.a2; result.mat[0 + 2*4] = mat.a3; result.mat[0 + 3*4] = 0.0f; result.mat[1 + 0*4] = mat.b1; result.mat[1 + 1*4] = mat.b2; result.mat[1 + 2*4] = mat.b3; result.mat[1 + 3*4] = 0.0f; result.mat[2 + 0*4] = mat.c1; result.mat[2 + 1*4] = mat.c2; result.mat[2 + 2*4] = mat.c3; result.mat[2 + 3*4] = 0.0f; result.mat[3 + 0*4] = 0.0f; result.mat[3 + 1*4] = 0.0f; result.mat[3 + 2*4] = 0.0f; result.mat[3 + 3*4] = 1.0f; return result; } static void initMesh( const unsigned int index, const aiScene* pScene, const aiMesh *mesh, astro::Gfx::Mesh *amesh, astro::Gfx::Model *model, std::vector<astro::Gfx::Vertex> &verts, std::vector<unsigned int> &ind, std::vector<astro::Gfx::TextureDependency> &textures); static void initScene(const aiScene* pScene, astro::Gfx::Model *model); static void initBones(const unsigned int index, const aiMesh *mesh, astro::Gfx::Mesh *amesh, astro::Gfx::Model *model); static void initTexture(const aiScene* scene, const aiMesh *mesh, std::vector<astro::Gfx::TextureDependency> &textures); static void initAnimation(const aiScene* scene, astro::Gfx::Model *model); static void initScene(const aiScene* scene, astro::Gfx::Model *model){ int nmeshes = scene->mNumMeshes; model->meshes.resize(nmeshes); unsigned int nVert = 0; unsigned int nIndices = 0; model->gInvTrans = aiMat2Astro(scene->mRootNode->mTransformation).inverse(); // setup for (unsigned int i = 0; i < nmeshes; ++i) { // create meshes auto mesh = std::make_shared<astro::Gfx::Mesh>(astro::Gfx::Mesh()); model->meshes[i] = mesh; model->meshes[i]->mIndex = scene->mMeshes[i]->mMaterialIndex; // metadata model->meshes[i]->nIndices = scene->mMeshes[i]->mNumFaces * 3; model->meshes[i]->bVertex = nVert; model->meshes[i]->bIndex = nIndices; nVert += scene->mMeshes[i]->mNumVertices; nIndices += model->meshes[i]->nIndices; } // init everything for(unsigned int i = 0; i < nmeshes; ++i){ auto &mesh = model->meshes[i]; initMesh(i, scene, scene->mMeshes[i], mesh.get(), model, mesh->vertices, mesh->indices, model->texDeps); } // init animation initAnimation(scene, model); } static void initBones(const unsigned int index, const aiMesh *mesh, astro::Gfx::Mesh *amesh, astro::Gfx::Model *model){ for(int i = 0; i < mesh->mNumBones; ++i){ auto aiBone = mesh->mBones[i]; std::string name(aiBone->mName.data); int boneIndex = model->boneInfo.size(); if(model->boneMapping.find(name) == model->boneMapping.end()){ // map index model->boneMapping[name] = boneIndex; // add bone info astro::Gfx::BoneInfo boneInfo; model->boneInfo.push_back(boneInfo); }else{ boneIndex = model->boneMapping[name]; } model->boneInfo[boneIndex].offset = aiMat2Astro(aiBone->mOffsetMatrix); model->boneInfo[boneIndex].name = name; // add weights for(int j = 0; j < aiBone->mNumWeights; ++j){ unsigned int vertId = aiBone->mWeights[j].mVertexId; float weight = aiBone->mWeights[j].mWeight; amesh->vertices[vertId].setBoneData(boneIndex, weight); } } } static void initTexture(const aiScene* pScene, const aiMesh *mesh, std::vector<astro::Gfx::TextureDependency> &textures){ auto indexer = astro::Core::getIndexer(); static auto process = [&](aiMaterial *mat, aiTextureType type, int rtypeName){ for(unsigned int i = 0; i < mat->GetTextureCount(type); ++i){ aiString str; mat->GetTexture(type, i, &str); astro::Gfx::TextureDependency dep; dep.role = rtypeName; dep.file = indexer->findByName(str.C_Str()); if(dep.file.get() == NULL){ return; } textures.push_back(dep); } }; aiMaterial* material = pScene->mMaterials[mesh->mMaterialIndex]; process(material, aiTextureType_DIFFUSE, astro::Gfx::TextureRole::DIFFUSE); process(material, aiTextureType_SPECULAR, astro::Gfx::TextureRole::SPECULAR); process(material, aiTextureType_HEIGHT, astro::Gfx::TextureRole::NORMAL); process(material, aiTextureType_AMBIENT, astro::Gfx::TextureRole::HEIGHT); }; static void initMesh( const unsigned int index, const aiScene* pScene, const aiMesh *mesh, astro::Gfx::Mesh *amesh, astro::Gfx::Model *model, std::vector<astro::Gfx::Vertex> &verts, std::vector<unsigned int> &ind, std::vector<astro::Gfx::TextureDependency> &textures){ // TODO: this can be parallelized // vertex data for(unsigned int i = 0; i < mesh->mNumVertices; ++i){ astro::Gfx::Vertex vertex; // positions vertex.position.set(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z); // normals if (mesh->HasNormals()){ vertex.normal.set(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z); } // texture coordinates if(mesh->HasTextureCoords(0)){ vertex.texCoords.set(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y); }else{ vertex.texCoords.set(0.0f, 0.0f); } // tangent and bittangent if(mesh->HasTangentsAndBitangents()){ // tangent vertex.tangent.set(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z); // bitangent vertex.bitangent.set(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z); }else{ // TODO: maybe generate these if not available? vertex.tangent.set(0); vertex.bitangent.set(0); } verts.push_back(vertex); } // indices for(unsigned int i = 0; i < mesh->mNumFaces; ++i){ aiFace face = mesh->mFaces[i]; for(int j = 0; j < face.mNumIndices; ++j){ ind.push_back(face.mIndices[j]); } } // bones if(mesh->HasBones()){ initBones(index, mesh, amesh, model); } // textures initTexture(pScene, mesh, textures); } static void initAnimation(const aiScene* scene, astro::Gfx::Model *model){ auto nanim = scene->mNumAnimations; std::unordered_map<std::string, std::shared_ptr<astro::Gfx::SkeletalHierarchy>> skelHierarchy; typedef std::shared_ptr<astro::Gfx::SkeletalAnimation> asSkAnim; typedef std::shared_ptr<astro::Gfx::SkeletalHierarchy> asSkHier; std::function<asSkHier(const aiNode *node, const asSkHier &parent)> readHierarchy = [&](const aiNode *node, const asSkHier &parent){ std::string nodeName(node->mName.data); // add to hierarchy auto current = std::make_shared<astro::Gfx::SkeletalHierarchy>(astro::Gfx::SkeletalHierarchy()); current->mat = aiMat2Astro(node->mTransformation); current->parent = parent; current->name = nodeName; skelHierarchy[nodeName] = current; // iterate children for(int i = 0; i < node->mNumChildren; ++i){ current->children.push_back(readHierarchy(node->mChildren[i], current)); } return current; }; std::function<void(const aiNode *node, const aiAnimation *aiAnim, asSkAnim &anim)> readAnimations = [&](const aiNode *node, const aiAnimation *aiAnim, asSkAnim &anim){ std::string nodeName(node->mName.data); // find channels for(int i = 0; i < aiAnim->mNumChannels; ++i){ const aiNodeAnim* pNodeAnim = aiAnim->mChannels[i]; if(nodeName != std::string(pNodeAnim->mNodeName.data)){ continue; } auto fbone = anim->bones.find(nodeName); if(fbone == anim->bones.end()){ auto animbone = std::make_shared<astro::Gfx::Bone>(astro::Gfx::Bone()); animbone->name = nodeName; anim->bones[nodeName] = animbone; fbone = anim->bones.find(nodeName); } if(fbone != anim->bones.end()){ // rotation for(unsigned int j = 0; j < pNodeAnim->mNumRotationKeys; ++j){ astro::Gfx::SkeletalFrameRotation rot; auto airot = pNodeAnim->mRotationKeys[j]; rot.time = (float)airot.mTime; rot.rotation = astro::Vec4<float>(airot.mValue.x, airot.mValue.y, airot.mValue.z, airot.mValue.w); fbone->second->rotations.push_back(rot); } // scaling for (unsigned int j = 0; j < pNodeAnim->mNumScalingKeys; ++j) { astro::Gfx::SkeletalFrameScaling scaling; auto aiscaling = pNodeAnim->mScalingKeys[j]; scaling.time = (float)aiscaling.mTime; scaling.scaling = astro::Vec3<float>(aiscaling.mValue.x, aiscaling.mValue.y, aiscaling.mValue.z); fbone->second->scalings.push_back(scaling); } // translation for (unsigned int j = 0; j < pNodeAnim->mNumPositionKeys; ++j) { astro::Gfx::SkeletalFrameTranslation trans; auto aitrans = pNodeAnim->mPositionKeys[j]; trans.time = (float)aitrans.mTime; trans.translation = astro::Vec3<float>(aitrans.mValue.x, aitrans.mValue.y, aitrans.mValue.z); fbone->second->translations.push_back(trans); } } } // iterate children for(int i = 0; i < node->mNumChildren; ++i){ readAnimations(node->mChildren[i], aiAnim, anim); } }; // build hierarchy model->skeletonRoot = readHierarchy(scene->mRootNode, asSkHier(NULL)); model->skeleton = skelHierarchy; // read animations for(unsigned int i = 0; i < nanim; ++i){ auto anim = std::make_shared<astro::Gfx::SkeletalAnimation>(astro::Gfx::SkeletalAnimation()); anim->name = std::string(scene->mAnimations[i]->mName.data); anim->ticksPerSecond = scene->mAnimations[i]->mTicksPerSecond; anim->duration = scene->mAnimations[i]->mDuration; // init bones for this animation for(int i = 0; i < model->boneInfo.size(); ++i){ auto &bi = model->boneInfo[i]; auto bone = std::make_shared<astro::Gfx::Bone>(astro::Gfx::Bone()); bone->name = bi.name; anim->bones[bi.name] = bone; } // read anim keys readAnimations(scene->mRootNode, scene->mAnimations[i], anim); model->animations[anim->name] = anim; } // asign default animation (if any) if(nanim > 0){ model->currentAnim = model->animations.begin()->second; } } std::shared_ptr<astro::Result> astro::Gfx::Model::load(const std::shared_ptr<astro::Indexing::Index> &file){ auto result = astro::makeResult(astro::ResultType::Waiting); // only use diffuse for now this->transform->resetMatMode(); this->transform->enMatMode(Gfx::MaterialMode::DIFFUSE); result->job = astro::spawn([&, file, result](astro::Job &ctx){ Assimp::Importer import; const aiScene *scene = import.ReadFile(file->path.c_str(), aiProcess_JoinIdenticalVertices | aiProcess_SortByPType | aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_LimitBoneWeights); if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode){ result->setFailure(astro::String::format("Model::load: failed to load model '%s': %s\n", file->fname.c_str(), import.GetErrorString())); return; } initScene(scene, this); auto rscmngr = Core::getResourceMngr(); // create expect list std::vector<std::shared_ptr<astro::Result>> results; for(int i = 0; i < this->texDeps.size(); ++i){ auto &tex = this->texDeps[i]; results.push_back(rscmngr->load(tex.file, std::make_shared<astro::Gfx::Texture>(astro::Gfx::Texture()))); } // expect all textures to load astro::expect(results, [&, result,rscmngr, results](astro::Job &ctx){ if(!ctx.succDeps){ std::string messages = ""; for(int i =0; i < ctx.listeners.size(); ++i){ messages += astro::String::format("%s%s ", results[i]->msg.c_str(), (i < ctx.listeners.size()-1 ? "," : "")); } astro::log("Model::load: warning: not all textures were loaded succesfully: %s\n", messages.c_str()); } for(int i = 0; i < this->texDeps.size(); ++i){ auto &tex = this->texDeps[i]; if(tex.file.get() == NULL){ continue; } auto texture = rscmngr->findByName(tex.file->fname); this->transform->textures.push_back(BindTexture(std::static_pointer_cast<astro::Gfx::Texture>(texture), tex.role)); } auto jgfx = astro::findJob({"astro_gfx"}); if(jgfx.get() == NULL){ result->setFailure(astro::String::format("gfx job not found: cannot load model '%s'", file->fname.c_str())); return; } // load meshes to gpu jgfx->addBacklog([&, result](astro::Job &ctx){ auto ren = astro::Gfx::getRenderEngine(); for(int i = 0; i < meshes.size(); ++i){ auto meshres = ren->generateMesh(meshes[i]->vertices, meshes[i]->indices, this->transform->useBones); meshres->payload->reset(); meshres->payload->read(&meshes[i]->vao, sizeof(meshes[i]->vao)); meshres->payload->read(&meshes[i]->vbo, sizeof(meshes[i]->vbo)); meshres->payload->read(&meshes[i]->ebo, sizeof(meshes[i]->ebo)); } result->set(astro::ResultType::Success); }); }, false); }, true, false, true); return result; } std::shared_ptr<astro::Result> astro::Gfx::Model::unload(){ // TODO: unload code return astro::makeResult(astro::ResultType::Success); } void astro::Gfx::Model::updateAnim(float time){ auto &anim = this->currentAnim; float tps = time * anim->ticksPerSecond; float animTime = std::fmod(tps, anim->duration); static auto findRotation = [&](const std::shared_ptr<astro::Gfx::Bone> &bone, float animTime){ for(int i = 0; i < bone->rotations.size() - 1; i++){ if(animTime < bone->rotations[i + 1].time){ return i; } } return 0; }; static auto findTrans = [&](const std::shared_ptr<astro::Gfx::Bone> &bone, float animTime){ for(int i = 0; i < bone->translations.size() - 1; i++){ if(animTime < bone->translations[i + 1].time){ return i; } } return 0; }; static auto interpRotation = [&](const std::shared_ptr<astro::Gfx::Bone> &bone){ if(bone->rotations.size() == 1){ auto start = aiQuaternion(bone->rotations[0].rotation.w, bone->rotations[0].rotation.x, bone->rotations[0].rotation.y, bone->rotations[0].rotation.z); return aiMat2Astro(start.GetMatrix()); } int current = findRotation(bone, animTime); int next = current + 1; float dt = bone->rotations[next].time - bone->rotations[current].time; float factor = (animTime - bone->rotations[current].time) / dt; auto start = aiQuaternion(bone->rotations[current].rotation.w, bone->rotations[current].rotation.x, bone->rotations[current].rotation.y, bone->rotations[current].rotation.z); auto end = aiQuaternion(bone->rotations[next].rotation.w, bone->rotations[next].rotation.x, bone->rotations[next].rotation.y, bone->rotations[next].rotation.z); aiQuaternion result; aiQuaternion::Interpolate(result, start, end, factor); result = result.Normalize(); return aiMat2Astro(result.GetMatrix()); }; static auto interpTrans = [&](const std::shared_ptr<astro::Gfx::Bone> &bone){ if(bone->translations.size() == 1){ return astro::MAT4Identity.translate(bone->translations[0].translation); } int current = findTrans(bone, animTime); int next = current + 1; float dt = bone->translations[next].time - bone->translations[current].time; float factor = (animTime - bone->translations[current].time) / dt; const aiVector3D start = aiVector3D(bone->translations[current].translation.x, bone->translations[current].translation.y, bone->translations[current].translation.z); const aiVector3D end = aiVector3D(bone->translations[next].translation.x, bone->translations[next].translation.y, bone->translations[next].translation.z); aiVector3D delta = end - start; auto result = start + factor * delta; return astro::MAT4Identity.translate(astro::Vec3<float>(result.x, result.y, result.z)); }; // calc std::unordered_map<std::string, astro::Mat<4, 4, float>> builtSkel; typedef std::function<void(const std::shared_ptr<astro::Gfx::SkeletalHierarchy> &top, const astro::Mat<4, 4, float> &parent)> bCHType; static bCHType buildCurrentHirarchy = [&](const std::shared_ptr<astro::Gfx::SkeletalHierarchy> &top, const astro::Mat<4, 4, float> &parent){ auto node = top->mat; auto fbone = anim->bones.find(top->name); if(fbone != anim->bones.end() && fbone->second->rotations.size() > 0 && fbone->second->translations.size() > 0){ auto &bone = fbone->second; auto trans = interpTrans(bone); auto rot = interpRotation(bone); node = trans * rot; } auto transform = parent * node; builtSkel[top->name] = transform; for(int i = 0; i < top->children.size(); ++i){ buildCurrentHirarchy(top->children[i], transform); } }; buildCurrentHirarchy(skeletonRoot, astro::MAT4Identity); for(int i = 0; i < boneInfo.size(); ++i){ auto &bi = boneInfo[i]; // build skeleton based on current animation astro::Mat<4, 4, float> globalTrans = builtSkel[bi.name]; // final transformation bi.transf = gInvTrans * globalTrans * bi.offset; } } void astro::Gfx::Model::render(){ auto ren = astro::Gfx::getRenderEngine(); updateAnim(ren->currentTime); for(int i = 0; i < boneInfo.size(); ++i){ std::string name = astro::String::format("gBones[%i]", i); this->transform->shAttrs[name] = std::make_shared<astro::Gfx::ShaderAttrMat4>(boneInfo[i].transf); } for(int i = 0; i < meshes.size(); ++i){ meshes[i]->transform = this->transform; ren->renderMesh(meshes[i].get()); } } void astro::Gfx::Mesh::render(){ auto ren = astro::Gfx::getRenderEngine(); ren->renderMesh(this); }
42.490946
183
0.564116
italrr
7b414cb0a59aa01e8d876de89b356fdd33d77f8e
5,672
cpp
C++
DialogSystemSolution/DialogSystem/j1DialogSystem.cpp
RoperoIvan/Dialogue-System
f9619decf859c452addc6a5ba37fcc26c892d9ea
[ "MIT" ]
null
null
null
DialogSystemSolution/DialogSystem/j1DialogSystem.cpp
RoperoIvan/Dialogue-System
f9619decf859c452addc6a5ba37fcc26c892d9ea
[ "MIT" ]
null
null
null
DialogSystemSolution/DialogSystem/j1DialogSystem.cpp
RoperoIvan/Dialogue-System
f9619decf859c452addc6a5ba37fcc26c892d9ea
[ "MIT" ]
null
null
null
#include "j1App.h" #include "j1UIManager.h" #include "j1Fonts.h" #include "j1DialogSystem.h" #include "j1Input.h" #include "GUI_Label.h" #include "GUI_Button.h" j1DialogSystem::j1DialogSystem() { } j1DialogSystem::~j1DialogSystem() { } bool j1DialogSystem::Start() { bool ret = true; LoadDialogue("Dialog.xml"); currentNode = dialogTrees[treeid]->dialogNodes[0]; PerformDialogue(treeid); return ret; } bool j1DialogSystem::Update(float dt) { bool ret = true; if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) { App->ui_manager->DeleteAllUIElements(); treeid = 0; currentNode = dialogTrees[treeid]->dialogNodes[0]; input = 7; PerformDialogue(treeid); } if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { App->ui_manager->DeleteAllUIElements(); treeid = 1; currentNode = dialogTrees[treeid]->dialogNodes[0]; input = 7; PerformDialogue(treeid); } if (App->input->GetKey(SDL_SCANCODE_F3) == KEY_DOWN) { App->ui_manager->DeleteAllUIElements(); treeid = 2; currentNode = dialogTrees[treeid]->dialogNodes[0]; input = 7; PerformDialogue(treeid); } if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN) { App->ui_manager->DeleteAllUIElements(); input = 0; PerformDialogue(treeid); } if (App->input->GetKey(SDL_SCANCODE_2) == KEY_DOWN) { App->ui_manager->DeleteAllUIElements(); input = 1; PerformDialogue(treeid); } if (App->input->GetKey(SDL_SCANCODE_3) == KEY_DOWN) { App->ui_manager->DeleteAllUIElements(); input = 2; PerformDialogue(treeid); } if (App->input->GetKey(SDL_SCANCODE_R) == KEY_DOWN) { App->ui_manager->DeleteAllUIElements(); dialogTrees[treeid]->karma = 0; currentNode = dialogTrees[treeid]->dialogNodes[0]; input = 7; PerformDialogue(treeid); } return ret; } bool j1DialogSystem::CleanUp() { bool ret = true; for (int j = 0; j < dialogTrees.size(); j++) { for (int i = 0; i < dialogTrees[j]->dialogNodes.size(); i++) delete dialogTrees[j]->dialogNodes[i]; dialogTrees[j]->dialogNodes.clear(); delete dialogTrees[j]; } dialogTrees.clear(); return ret; } void j1DialogSystem::PerformDialogue(int tr_id) { if (dialogTrees.empty()) LOG("TreeEmpty"); if (CompareKarma() == true) { //Find the next node if (input >= 0 && input < currentNode->dialogOptions.size()) //Only if the input is valid { for (int j = 0; j < dialogTrees[tr_id]->dialogNodes.size(); j++) { if (currentNode->dialogOptions[input]->nextnode == dialogTrees[tr_id]->dialogNodes[j]->id) //If the option id is the same as one of the nodes ids in the tree { CheckForKarma(currentNode); currentNode = dialogTrees[tr_id]->dialogNodes[j]; // we assign our node pointer to the next node in the tree break; } } } } else if (CompareKarma() == false) { for (int i = 0; i < dialogTrees[tr_id]->dialogNodes.size(); i++) { // We search the mood of the bad response bad response = -1 / neutral = 0 if (dialogTrees[tr_id]->karma == dialogTrees[tr_id]->dialogNodes[i]->karma) { currentNode = dialogTrees[tr_id]->dialogNodes[i]; //This node is the bad response from the npc } } } //Put the player's name in the lines of the npc dialog while(currentNode->text.find("PLAYERNAME") != std::string::npos) { currentNode->text.replace(currentNode->text.find("PLAYERNAME"), 10, "Ivan"); } // Print the dialog in the screen BlitDialog(); } void j1DialogSystem::BlitDialog() { App->ui_manager->AddLabel(150, 180, currentNode->text.c_str(), 50, App->ui_manager->screen, WHITE, "fonts/Final_Fantasy_font.ttf", this); int space = 200; for (int i = 0; i < currentNode->dialogOptions.size(); i++) App->ui_manager->AddLabel(150, space += 30, currentNode->dialogOptions[i]->text.c_str(), 45, App->ui_manager->screen, GREEN, "fonts/Final_Fantasy_font.ttf", this); } bool j1DialogSystem::CompareKarma() { bool ret = true; if (dialogTrees[treeid]->karma < 0) ret = false; return ret; } void j1DialogSystem::CheckForKarma(DialogNode* karmaNode) { dialogTrees[treeid]->karma += karmaNode->dialogOptions[input]->karma; } bool j1DialogSystem::LoadDialogue(const char* file) { bool ret = true; pugi::xml_parse_result result = tree_file.load_file(file); if (result == NULL) { LOG("Could not load map xml file %s. pugi error: %s", file, result.description()); ret = false; } else LOG("XML was loaded succesfully!"); for (pugi::xml_node t = tree_file.child("dialogue").child("dialogtree"); t != NULL; t = t.next_sibling("dialogtree")) { DialogTree* tr = new DialogTree; tr->treeid = t.attribute("treeid").as_int(); tr->karma = t.attribute("karma").as_int(); LoadTreeData(t, tr); dialogTrees.push_back(tr); } return ret; } bool j1DialogSystem::LoadTreeData(pugi::xml_node& trees, DialogTree* oak) { bool ret = true; //Filling the dialogue tree information for (pugi::xml_node n = trees.child("node");n != NULL; n = n.next_sibling("node")) { DialogNode* node = new DialogNode; node->text.assign(n.attribute("line").as_string()); node->id = n.attribute("id").as_int(); node->karma = n.attribute("karma").as_int(); LoadNodesDetails(n, node); oak->dialogNodes.push_back(node); } return ret; } bool j1DialogSystem::LoadNodesDetails(pugi::xml_node& text_node, DialogNode* npc) { bool ret = true; for (pugi::xml_node op = text_node.child("option"); op != NULL; op = op.next_sibling("option")) { DialogOption* option = new DialogOption; option->text.assign(op.attribute("line").as_string()); option->nextnode = op.attribute("nextnode").as_int(); option->karma = op.attribute("karma").as_int(); npc->dialogOptions.push_back(option); } return ret; }
24.448276
165
0.681594
RoperoIvan
7b47036661d4b580854a359716405bc723c25137
810
cpp
C++
hackerrank/c++/stl/vector_erase.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
hackerrank/c++/stl/vector_erase.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
hackerrank/c++/stl/vector_erase.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> #include <vector> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int length; cin >> length; vector<unsigned int> sequence(length); for (auto& element : sequence) { cin >> element; } unsigned int index; unsigned int left; unsigned int right; cin >> index >> left >> right; sequence.erase(sequence.cbegin() + index - 1); sequence.erase(sequence.cbegin() + left - 1, sequence.cbegin() + right - 1); cout << sequence.size() << '\n'; for (auto i = sequence.cbegin(); i != sequence.cend(); ++i) { cout << *i << " \n"[i + 1 == sequence.cend()]; } return 0; }
17.608696
63
0.569136
Rkhoiwal
0da2fba5c2f892c74d3f8f0f7cea5fa22c42a8a3
2,703
cpp
C++
Chapter_4_Graph/SSSP/kattis_emptyingbaltic.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
2
2021-12-29T04:12:59.000Z
2022-03-30T09:32:19.000Z
Chapter_4_Graph/SSSP/kattis_emptyingbaltic.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
null
null
null
Chapter_4_Graph/SSSP/kattis_emptyingbaltic.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
1
2022-03-01T06:12:46.000Z
2022-03-01T06:12:46.000Z
/* kattis - emptyingbaltic Observation 1: When considering how much water will eventually be drained from a cell r,c, we realise it is actually drained until the level of the minimum max height along all paths from r,c to the drain. This is actually similar to the SSSP principle but instead of minimising distance, we minimise the maximum height along the path to get to r,c. So our distance values will all be replaced by "minimum max height to get to r,c". And instead the the dist to nr, nc being dist(r,c) + w, instead it will be max(grid(nr,nc), ldu(r,c)). While this problem looks scary cos its some strange variant, once you figure out the observation, the implementation actually isn't that difficult. Time: O(hw log hw), Mem: O(hw) */ #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int h, w, s_r, s_c; vector<vector<int>>grid, ldu; //grid slows elevation, ldu (level drained until) shows how far the water level is drained int dr[] = {-1, -1, 0, 1, 1, 1, 0, -1}; int dc[] = {0, 1, 1, 1, 0, -1, -1, -1}; priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<tuple<int,int,int>>> pq; int main(){ fast_cin(); cin >> h >> w; grid.assign(h, vector<int>(w, 0)); ldu.assign(h, vector<int>(w, 0)); for (int r=0;r<h;r++){ for (int c=0;c<w;c++){ cin >> grid[r][c]; grid[r][c] = min(grid[r][c], 0); // we can more or less ignore all heights above 0 } } cin >> s_r >> s_c; // starting row and column s_r--; s_c--; pq.emplace(grid[s_r][s_c], s_r, s_c); ldu[s_r][s_c] = grid[s_r][s_c]; while (!pq.empty()){ auto [d, r, c] = pq.top(); pq.pop(); //printf("d: %d, r: %d, c:%d\n", d, r, c); if (d > ldu[r][c])continue; // inferior pair for (int i=0;i<8;i++){ int nc = c + dc[i]; int nr = r + dr[i]; if (nc < 0 || nr < 0 || nc >= w || nr >= h)continue; if (max(ldu[r][c], grid[nr][nc]) >= ldu[nr][nc])continue; // relaxing through this node doesn't help ldu[nr][nc] = max(ldu[r][c], grid[nr][nc]); pq.emplace(ldu[nr][nc], nr, nc); } } ll total = 0; for (int r=0;r<h;r++){ for (int c=0;c<w;c++){ //cout << ldu[r][c]<< " "; total -= ldu[r][c]; } //cout << endl; } cout << total << endl; return 0; }
34.653846
120
0.572327
BrandonTang89
0da5bf18e4e0ca7b2684740e13a4964a656c8332
370
cpp
C++
09-Inheritance/06-Gen_Spec.cpp
PronomitaDey/Cpp_Tutorial
a64a10a27d018bf9edf5280505201a1fbfd359ed
[ "MIT" ]
null
null
null
09-Inheritance/06-Gen_Spec.cpp
PronomitaDey/Cpp_Tutorial
a64a10a27d018bf9edf5280505201a1fbfd359ed
[ "MIT" ]
1
2021-10-01T13:35:44.000Z
2021-10-02T03:54:29.000Z
09-Inheritance/06-Gen_Spec.cpp
PronomitaDey/Cpp_Tutorial
a64a10a27d018bf9edf5280505201a1fbfd359ed
[ "MIT" ]
3
2021-10-01T14:07:09.000Z
2021-10-01T18:24:31.000Z
#include <iostream> using namespace std; // Generalization /* Shape is not something real whereas Rectangle, Square and all are so Shape is just a Generalization of those This is also called as Polymorphism */ // Specialization /* Cuboid is an extension of Rectangle So this method is called specialization */ int main() { return 0; }
16.818182
57
0.694595
PronomitaDey
0da642165d7437a4d49fd5224549f9f7b091fadc
2,196
cpp
C++
Jimmy_Core/source/Sys_Init.cpp
nozsavsev/jimmy
0be7a153e9c1a2f14710d072fd172ee1b3402742
[ "Apache-2.0" ]
1
2021-05-17T23:03:14.000Z
2021-05-17T23:03:14.000Z
Jimmy_Core/source/Sys_Init.cpp
nozsavsev/jimmy
0be7a153e9c1a2f14710d072fd172ee1b3402742
[ "Apache-2.0" ]
null
null
null
Jimmy_Core/source/Sys_Init.cpp
nozsavsev/jimmy
0be7a153e9c1a2f14710d072fd172ee1b3402742
[ "Apache-2.0" ]
null
null
null
/*Copyright 2020 Nozdrachev Ilia 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 "Jimmy_Core.h" bool Is_Running_As_Admin() { BOOL is_run_as_admin = FALSE; PSID administrators_group = NULL; SID_IDENTIFIER_AUTHORITY nt_authority = SECURITY_NT_AUTHORITY; if (!AllocateAndInitializeSid(&nt_authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &administrators_group)) { FreeSid(administrators_group); return false; } else CheckTokenMembership(NULL, administrators_group, &is_run_as_admin); FreeSid(administrators_group); return is_run_as_admin ? true : false; } void Sys_Init(int argc, char** argv) { if (!Is_Running_As_Admin()) { MessageBoxW(NULL, L"Jimmy cannot work without administrator privileges\npress Ok to restart winth admin rights", L"Jimmy - accessibility alert", MB_OK | MB_TOPMOST); { wchar_t szPath[MAX_PATH]; GetModuleFileNameW(NULL, szPath, MAX_PATH); SHELLEXECUTEINFO sei = { sizeof(sei) }; sei.lpParameters = L""; sei.lpVerb = L"runas"; sei.lpFile = szPath; sei.hwnd = NULL; sei.nShow = SW_NORMAL; if (ShellExecuteEx(&sei)) exit(0); } } Log("Admin check OK\n"); CreateMutex(NULL, true, L"JYMMY_GLOBAL_START_MUTEX"); if (GetLastError() == ERROR_ALREADY_EXISTS) { Log("Jimmy is alaredy running!\n"); MessageBoxW(NULL, L"Jimmy is alaredy running!", L"Jimmy", MB_OK | MB_TOPMOST); exit(0); } Log("Instance check OK\n"); }
32.776119
174
0.651639
nozsavsev
0da6a82aa2a526dede29cb766c8cc4d129cc92c6
2,513
cpp
C++
CameraCtrl.cpp
neil3d/ShadowMappingD3D
fa5c856ae8fb7ee0afa22e70e84c1dd34fbce52f
[ "MIT" ]
1
2019-11-29T01:19:31.000Z
2019-11-29T01:19:31.000Z
CameraCtrl.cpp
neil3d/ShadowMappingD3D
fa5c856ae8fb7ee0afa22e70e84c1dd34fbce52f
[ "MIT" ]
null
null
null
CameraCtrl.cpp
neil3d/ShadowMappingD3D
fa5c856ae8fb7ee0afa22e70e84c1dd34fbce52f
[ "MIT" ]
null
null
null
#include ".\cameractrl.h" #include "SGITrackBall.h" CameraCtrl g_camera; inline D3DXVECTOR3 operator * (const D3DXVECTOR3& v,const D3DXMATRIX& m) { return D3DXVECTOR3(v.x*m._11+v.y*m._21+v.z*m._31+m._41, v.x*m._12+v.y*m._22+v.z*m._32+m._42, v.x*m._13+v.y*m._23+v.z*m._33+m._43); } CameraCtrl::CameraCtrl(void) { D3DXMatrixIdentity(&m_matPrj); setDefaultView(); m_bDrag = false; } CameraCtrl::~CameraCtrl(void) { } void CameraCtrl::setDefaultView() { m_lookAt = D3DXVECTOR3(0,0,0); m_dist = 400; D3DXQuaternionRotationYawPitchRoll(&m_rotate,0,-D3DX_PI/4,0); updateViewMat(); } void CameraCtrl::setPerspective(float fov, int clientW, int clientH, float zNear, float zFar) { float aspect = float(clientW)/clientH; D3DXMatrixPerspectiveFovLH(&m_matPrj, fov, aspect, zNear, zFar); m_zNear = zNear; m_zFar = zFar; } void CameraCtrl::updateViewMat() { D3DXMATRIX matR; D3DXMatrixRotationQuaternion(&matR,&m_rotate); D3DXVECTOR3 vViewDir = D3DXVECTOR3(0,0,1); D3DXVECTOR3 vUp(0,1,0); vViewDir = vViewDir * matR; vUp = vUp * matR; m_eyePos = vViewDir*m_dist + m_lookAt; D3DXMatrixLookAtLH(&m_matView,&m_eyePos,&m_lookAt,&vUp); } void CameraCtrl::onKeyDown(DWORD vk) { D3DXVECTOR3 vX(m_matView._11,m_matView._21,m_matView._31); D3DXVECTOR3 vY(m_matView._12,m_matView._22,m_matView._32); D3DXVECTOR3 vZ(m_matView._13,m_matView._23,m_matView._33); float s = 10; switch(vk) { case 'W': m_lookAt += vZ*s; break; case 'S': m_lookAt -= vZ*s; break; case 'A': m_lookAt += vX*s; break; case 'D': m_lookAt -= vX*s; break; case 'Z': m_lookAt += vY*s; break; case 'X': m_lookAt -= vY*s; break; default: break; } updateViewMat(); } void CameraCtrl::onLButtonDown(int x,int y) { m_bDrag = true; m_lastDragPt.x = x; m_lastDragPt.y = y; trackball((float*)m_lastRotate,0,0,0,0); } void CameraCtrl::onLbuttonUp() { m_bDrag = false; } D3DXVECTOR2 _normalize(int x, int y) { return D3DXVECTOR2( ( ( 2.0f * x ) / clientWidth ) - 1 , -( ( ( 2.0f * y ) / clientHeight ) - 1 )); } void CameraCtrl::onMouseMove(int x,int y) { if(m_bDrag) { D3DXVECTOR2 lastPt = _normalize(m_lastDragPt.x,m_lastDragPt.y); D3DXVECTOR2 nowPt = _normalize(x,y); trackball((float*)&m_lastRotate,lastPt.x,lastPt.y,nowPt.x,nowPt.y); m_lastDragPt.x = x; m_lastDragPt.y = y; add_quats((float*)&m_lastRotate,(float*)&m_rotate,(float*)&m_rotate); updateViewMat(); } } void CameraCtrl::onMouseWheel(int delta) { m_dist += delta*0.2f; updateViewMat(); }
18.477941
93
0.68842
neil3d
0daa96caab68a09d8f1da30958d5760679e5f0e3
1,938
cpp
C++
graph-source-code/174-D/1509433.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/174-D/1509433.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/174-D/1509433.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <string.h> #define rep(i,n) for(int i=0; i<n; i++) #define reps(i,m,n) for(int i=m; i<n; i++) #define repe(i,m,n) for(int i=m; i<=n; i++) #define repi(it,stl) for(typeof((stl).begin()) it = (stl).begin(); (it)!=stl.end(); ++(it)) #define sz(a) ((int)(a).size()) #define mem(a,n) memset((a), (n), sizeof(a)) #define all(n) (n).begin(),(n).end() #define rall(n) (n).rbegin(),(n).rend() #define mp(a,b) make_pair((a),(b)) #define pii pair<int,int> #define vi vector<int> #define vs vector<string> #define sstr stringstream #define fnd(v,x) (find(all((v)),(x))!=(v).end()) #define itr(A,B) typeof(B) A = B typedef long long ll; using namespace std; const int size = 100002; int states[size]; vi g[size],revg[size]; bool mark1[size],mark2[size]; void DFS(int idx){ mark1[idx] = 1; // if(states[idx]==2) return; rep(i,sz(g[idx])){ if(!mark1[g[idx][i]]) DFS(g[idx][i]); } } void DFS2(int idx){ mark2[idx] = 1; if(states[idx]==1) return; rep(i,sz(revg[idx])){ if(!mark2[revg[idx][i]]) DFS2(revg[idx][i]); } } int main(){ #ifndef ONLINE_JUDGE freopen("in","rt",stdin); freopen("out","wt",stdout); #endif int n,m,a,b; scanf("%d%d",&n,&m); rep(i,n){ scanf("%d",states+i); } rep(i,m){ scanf("%d%d",&a,&b); --a, --b; g[a].push_back(b); revg[b].push_back(a); } rep(i,n){ if(states[i]==1) DFS(i); if(states[i]==2) DFS2(i); } rep(i,n) printf(mark1[i] && mark2[i]?"1\n":"0\n"); }
19.188119
91
0.557276
AmrARaouf
0daba5852d634fb454ef7bfa9bfe9b59927befc4
867
cpp
C++
src/main.cpp
RomainAmuat/apt_project
520281a09756816f6297e3f35b42bce2ab12973b
[ "MIT" ]
null
null
null
src/main.cpp
RomainAmuat/apt_project
520281a09756816f6297e3f35b42bce2ab12973b
[ "MIT" ]
null
null
null
src/main.cpp
RomainAmuat/apt_project
520281a09756816f6297e3f35b42bce2ab12973b
[ "MIT" ]
null
null
null
#include <pistache/http.h> #include <pistache/description.h> #include <pistache/endpoint.h> #include <pistache/serializer/rapidjson.h> #include "view/ServiceManager.h" #include "model/MySQLLink.h" using namespace std; using namespace Pistache; int main(int argc, char *argv[]) { std::string url; if (argc > 1) { url = argv[1]; std::cout << "Using MySQL URL given in command line : " << url << std::endl; } else { url = "tcp://127.0.0.1:3306"; } Port port(9080); ConMySQL * msql = new ConMySQL(url); int thr = 2; Address addr(Ipv4::any(), port); cout << "Cores = " << hardware_concurrency() << endl; cout << "Using " << thr << " threads" << endl; ServiceManager manager(addr, msql); manager.init(thr); manager.start(); auto c = getchar(); manager.shutdown(); }
19.704545
84
0.594002
RomainAmuat
0dabefa1becca43221ab84ce7c3307441bbbeb58
6,550
cpp
C++
src/vm/appdomainstack.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
10
2015-11-03T16:35:25.000Z
2021-07-31T16:36:29.000Z
src/vm/appdomainstack.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
1
2019-03-05T18:50:09.000Z
2019-03-05T18:50:09.000Z
src/vm/appdomainstack.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
4
2015-10-28T12:26:26.000Z
2021-09-04T11:36:04.000Z
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // #include "common.h" #include "appdomainstack.h" #include "appdomainstack.inl" #include "security.h" #include "securitypolicy.h" #include "appdomain.inl" #ifdef FEATURE_REMOTING #include "crossdomaincalls.h" #else #include "callhelpers.h" #endif #ifdef _DEBUG void AppDomainStack::CheckOverridesAssertCounts() { LIMITED_METHOD_CONTRACT; DWORD dwAppDomainIndex = 0; DWORD dwOverrides = 0; DWORD dwAsserts = 0; AppDomainStackEntry *pEntry = NULL; for(dwAppDomainIndex=0;dwAppDomainIndex<m_numEntries;dwAppDomainIndex++) { pEntry = __GetEntryPtr(dwAppDomainIndex); dwOverrides += pEntry->m_dwOverridesCount; dwAsserts += pEntry->m_dwAsserts; } _ASSERTE(dwOverrides == m_dwOverridesCount); _ASSERTE(dwAsserts == m_dwAsserts); } #endif BOOL AppDomainStackEntry::IsFullyTrustedWithNoStackModifiers(void) { LIMITED_METHOD_CONTRACT; if (m_domainID.m_dwId == INVALID_APPDOMAIN_ID || m_dwOverridesCount != 0 || m_dwAsserts != 0) return FALSE; AppDomainFromIDHolder pDomain(m_domainID, FALSE); if (pDomain.IsUnloaded()) return FALSE; IApplicationSecurityDescriptor *currAppSecDesc = pDomain->GetSecurityDescriptor(); if (currAppSecDesc == NULL) return FALSE; return Security::CheckDomainWideSpecialFlag(currAppSecDesc, 1 << SECURITY_FULL_TRUST); } BOOL AppDomainStackEntry::IsHomogeneousWithNoStackModifiers(void) { LIMITED_METHOD_CONTRACT; if (m_domainID.m_dwId == INVALID_APPDOMAIN_ID || m_dwOverridesCount != 0 || m_dwAsserts != 0) return FALSE; AppDomainFromIDHolder pDomain(m_domainID, FALSE); if (pDomain.IsUnloaded()) return FALSE; IApplicationSecurityDescriptor *currAppSecDesc = pDomain->GetSecurityDescriptor(); if (currAppSecDesc == NULL) return FALSE; return (currAppSecDesc->IsHomogeneous() && !currAppSecDesc->ContainsAnyRefusedPermissions()); } BOOL AppDomainStackEntry::HasFlagsOrFullyTrustedWithNoStackModifiers(DWORD flags) { LIMITED_METHOD_CONTRACT; if (m_domainID.m_dwId == INVALID_APPDOMAIN_ID || m_dwOverridesCount != 0 || m_dwAsserts != 0) return FALSE; AppDomainFromIDHolder pDomain(m_domainID, FALSE); if (pDomain.IsUnloaded()) return FALSE; IApplicationSecurityDescriptor *currAppSecDesc = pDomain->GetSecurityDescriptor(); if (currAppSecDesc == NULL) return FALSE; // either the desired flag (often 0) or fully trusted will do flags |= (1<<SECURITY_FULL_TRUST); return Security::CheckDomainWideSpecialFlag(currAppSecDesc, flags); } void AppDomainStackEntry::UpdateHomogeneousPLS(OBJECTREF* homogeneousPLS) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; AppDomainFromIDHolder domain(m_domainID, TRUE); if (domain.IsUnloaded()) return; IApplicationSecurityDescriptor *thisAppSecDesc = domain->GetSecurityDescriptor(); if (thisAppSecDesc->IsHomogeneous()) { // update the intersection with the current grant set NewArrayHolder<BYTE> pbtmpSerializedObject(NULL); struct gc { OBJECTREF refGrantSet; } gc; ZeroMemory( &gc, sizeof( gc ) ); AppDomain* pCurrentDomain; pCurrentDomain = GetAppDomain(); GCPROTECT_BEGIN( gc ); #ifdef FEATURE_REMOTING // should not be possible without remoting DWORD cbtmpSerializedObject = 0; if (pCurrentDomain->GetId() != m_domainID) { // Unlikely scenario where we have another homogeneous AD on the callstack that's different from // the current one. If there's another AD on the callstack, it's likely to be FT. ENTER_DOMAIN_ID(m_domainID) { // Release the holder to allow GCs. This is safe because we've entered the AD, so it won't go away. domain.Release(); gc.refGrantSet = thisAppSecDesc->GetGrantedPermissionSet(NULL); AppDomainHelper::MarshalObject(GetAppDomain(), &gc.refGrantSet, &pbtmpSerializedObject, &cbtmpSerializedObject); if (pbtmpSerializedObject == NULL) { // this is an error: possibly an OOM prevented the blob from getting created. // We could return null and let the managed code use a fully restricted object or throw here. // Let's throw here... COMPlusThrow(kSecurityException); } gc.refGrantSet = NULL; } END_DOMAIN_TRANSITION AppDomainHelper::UnmarshalObject(pCurrentDomain,pbtmpSerializedObject, cbtmpSerializedObject, &gc.refGrantSet); } else #else _ASSERTE(pCurrentDomain->GetId() == m_domainID); #endif //!FEATURE_CORECLR { // Release the holder to allow GCs. This is safe because we're running in this AD, so it won't go away. domain.Release(); gc.refGrantSet = thisAppSecDesc->GetGrantedPermissionSet(NULL); } // At this point gc.refGrantSet has the grantSet of pDomain (thisAppSecDesc) in the current domain. // We don't care about refused perms since we established there were // none earlier for this call stack. // Let's intersect with what we've already got. PREPARE_NONVIRTUAL_CALLSITE(METHOD__PERMISSION_LIST_SET__UPDATE); DECLARE_ARGHOLDER_ARRAY(args, 2); args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(*homogeneousPLS); // arg 0 args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(gc.refGrantSet); // arg 1 CALL_MANAGED_METHOD_NORET(args); GCPROTECT_END(); } } BOOL AppDomainStack::AllDomainsHomogeneousWithNoStackModifiers() { WRAPPER_NO_CONTRACT; // Used primarily by CompressedStack code to decide if a CS has to be constructed DWORD dwAppDomainIndex = 0; InitDomainIteration(&dwAppDomainIndex); while (dwAppDomainIndex != 0) { AppDomainStackEntry* pEntry = GetNextDomainEntryOnStack(&dwAppDomainIndex); _ASSERTE(pEntry != NULL); if (!pEntry->IsHomogeneousWithNoStackModifiers() && !pEntry->IsFullyTrustedWithNoStackModifiers()) return FALSE; } return TRUE; }
33.248731
128
0.671145
CyberSys
0daec77a627b03e2bc4ead844c9bc8c9c0e152ff
1,535
cpp
C++
FindMissingNumber.cpp
Cuncis/codeWith-hacktoberfest
9cd5059e4d90b42fa9e12ba5ec8bf3f49c9e6c63
[ "MIT" ]
null
null
null
FindMissingNumber.cpp
Cuncis/codeWith-hacktoberfest
9cd5059e4d90b42fa9e12ba5ec8bf3f49c9e6c63
[ "MIT" ]
null
null
null
FindMissingNumber.cpp
Cuncis/codeWith-hacktoberfest
9cd5059e4d90b42fa9e12ba5ec8bf3f49c9e6c63
[ "MIT" ]
null
null
null
/* Problem-Task : Create a function that takes an array of numbers between 1 and 10 (excluding one number) and returns the missing number. * Problem Link : https://edabit.com/challenge/7YaJhC4terApw5DFa */ //C++ Program to find the Missing Number /*The logic we are using is: Sum of n integer elements is: n(n+1)/2. Here we are missing one element which means we should replace n with n+1 so the total of elements in our case becomes: (n+1)(n+2)/2. Once we have the total, we are removing all the elements that user has entered from the total, this way the remaining value is our missing number.*/ CODE:- #include <iostream> using namespace std; int findMissingNo (int arr[], int len){ int temp; temp = ((len+1)*(len+2))/2; for (int i = 0; i<len; i++) temp -= arr[i]; return temp; } int main() { int n; cout<<"Enter the size of array: "; cin>>n; int arr[n-1]; cout<<"Enter array elements: "; for(int i=0; i<n; i++){ cin>>arr[i]; } int missingNo = findMissingNo(arr , 10 ); cout<<"Missing Number is: "<<missingNo; return 0; } Output: Example 1:- Enter the size of array: 10 Enter array elements: 1 2 3 5 6 7 8 9 10 Missing Number is: 4 Example 2:- Enter the size of array: 10 Enter array elements: 1 3 4 5 6 7 8 9 10 Missing Number is: 2 Example 3:- Enter the size of array: 10 Enter array elements: 1 2 3 4 5 7 8 9 10 Missing Number is: 6
18.058824
88
0.614332
Cuncis
0db0ca1c31bf042834d85629285d51b66d9a2362
352
hpp
C++
include/cuda_dl.hpp
jetd1/kuafu
819d338682f3e889710731cf7ca16f790b54568f
[ "MIT" ]
17
2021-09-03T03:06:48.000Z
2022-03-27T04:02:14.000Z
include/cuda_dl.hpp
jetd1/kuafu
819d338682f3e889710731cf7ca16f790b54568f
[ "MIT" ]
null
null
null
include/cuda_dl.hpp
jetd1/kuafu
819d338682f3e889710731cf7ca16f790b54568f
[ "MIT" ]
null
null
null
// // Created by jet on 9/17/21. // #pragma once #include <cuda.h> namespace kuafu { void kfCuDlOpen(); void kfCuDlClose(); CUresult kfCuInit(unsigned int Flags); CUresult kfCuStreamCreate(CUstream* phStream, unsigned int Flags); CUresult kfCuCtxCreate(CUcontext* pctx, unsigned int flags, CUdevice dev); CUresult kfCuCtxDestroy(CUcontext ctx); }
18.526316
74
0.758523
jetd1
0db79073d01f6a5e7dc7459f93003d3937f68c78
3,819
cpp
C++
Lab4/src/CircleHough.cpp
DavidePistilli173/Computer-Vision
4066a99f6f6fdc941829d3cd3015565ec0046a2f
[ "Apache-2.0" ]
null
null
null
Lab4/src/CircleHough.cpp
DavidePistilli173/Computer-Vision
4066a99f6f6fdc941829d3cd3015565ec0046a2f
[ "Apache-2.0" ]
null
null
null
Lab4/src/CircleHough.cpp
DavidePistilli173/Computer-Vision
4066a99f6f6fdc941829d3cd3015565ec0046a2f
[ "Apache-2.0" ]
null
null
null
#include "CircleHough.hpp" #include <opencv2/imgproc.hpp> using namespace lab4; CircleHough::CircleHough(const cv::Mat& img, std::string_view winName) : ImgProcessor(img, winName, CV_8UC3) { bool success{ true }; /* Add trackbars for parameters of type double. */ for (int i = 0; i < static_cast<int>(DoubleParam::tot); ++i) { success = success && win_.addTrackBar(double_param_names[i], double_param_start_vals[i], double_param_max[i]); } /* Add trackbars for parameters of type int. */ for (int i = 0; i < static_cast<int>(IntParam::tot); ++i) { success = success && win_.addTrackBar(int_param_names[i], int_param_start_vals[i], int_param_max[i]); } if (!success) Log::error("Failed to create enough trackbars for all parameters."); } std::optional<cv::Vec3f> CircleHough::getRelevantCircle() { if (circles_.empty()) return std::optional<cv::Vec3f>(); return std::optional(circles_[0]); } bool CircleHough::update(bool force) { /* If the update is not forced and if no trackbars were changed don't perform any computation. */ if (!force && !win_.modified()) return false; /* Convert the input image to greyscale. */ cv::cvtColor(srcImg_, greyScaleImg_, cv::COLOR_BGR2GRAY); fetchNormalisedParams_(); // Get the current parameter values. circles_.clear(); // Clear the result from previous computations. Log::info("Computing HoughCircles..."); cv::HoughCircles( greyScaleImg_, circles_, cv::HOUGH_GRADIENT, double_params_[static_cast<int>(DoubleParam::res)], double_params_[static_cast<int>(DoubleParam::dist)], double_params_[static_cast<int>(DoubleParam::th1)], double_params_[static_cast<int>(DoubleParam::th2)], int_params_[static_cast<int>(IntParam::min_r)], int_params_[static_cast<int>(IntParam::max_r)] ); Log::info("SUCCESS"); resultImg_ = srcImg_.clone(); Log::info("Drawing circles..."); drawCircles_(); // Draw detected circles. Log::info("SUCCESS"); win_.showImg(resultImg_); return true; } void CircleHough::drawCircles_() { for (const auto& circle : circles_) { cv::circle( resultImg_, cv::Point { cvRound(circle[static_cast<int>(CircleParam::x)]), cvRound(circle[static_cast<int>(CircleParam::y)]) }, cvRound(circle[static_cast<int>(CircleParam::r)]), cv::Scalar{ 0, circle_intensity, 0 }, circle_thickness, cv::LINE_AA ); } } void CircleHough::fetchNormalisedParams_() { Log::info("Normalising CirleHough parameters."); if ( std::vector<int> params = win_.fetchTrckVals(); params.size() >= static_cast<int>(DoubleParam::tot) + static_cast<int>(IntParam::tot) ) { /* Normalise parameters of type double. */ for (int i = 0; i < double_param_num; ++i) { double_params_[i] = scale( double_param_limits[i].first, double_param_limits[i].second, scaling_coeff(params[i], double_param_max[i]) ); Log::info("Parameter %d = %f.", i, double_params_[i]); } /* Normalise parameters of type int. */ for (int i = 0; i < int_param_num; ++i) { int_params_[i] = scale( int_param_limits[i].first, int_param_limits[i].second, scaling_coeff(params[i + double_param_num], int_param_max[i]) ); Log::info("Parameter %d = %d.", i + double_param_num, int_params_[i]); } } else { Log::error("Not enough parameters available."); } }
32.092437
112
0.59911
DavidePistilli173
0dbf9b4c39ae19b637977f9af9789b6e31d8d519
29,310
cpp
C++
sketchup_converter/main.cpp
jhhsia/sketchup_converter
7d8daffd61c8d8f6c214640672e38c7817e37788
[ "MIT" ]
1
2020-09-27T10:55:07.000Z
2020-09-27T10:55:07.000Z
sketchup_converter/main.cpp
jhhsia/sketchup_converter
7d8daffd61c8d8f6c214640672e38c7817e37788
[ "MIT" ]
null
null
null
sketchup_converter/main.cpp
jhhsia/sketchup_converter
7d8daffd61c8d8f6c214640672e38c7817e37788
[ "MIT" ]
null
null
null
// // main.cpp // sketchup_converter // // Created by jahsia on 10/26/18. // Copyright © 2018 trisetra. All rights reserved. // #include <iostream> #include <SketchUpAPI/common.h> #include <SketchUpAPI/geometry.h> #include <SketchUpAPI/geometry/vector3d.h> #include <SketchUpAPI/initialize.h> #include <SketchUpAPI/model/component_definition.h> #include <SketchUpAPI/model/component_instance.h> #include <SketchUpAPI/model/drawing_element.h> #include <SketchUpAPI/model/edge.h> #include <SketchUpAPI/model/entities.h> #include <SketchUpAPI/model/entity.h> #include <SketchUpAPI/model/face.h> #include <SketchUpAPI/model/group.h> #include <SketchUpAPI/model/image_rep.h> #include <SketchUpAPI/model/layer.h> #include <SketchUpAPI/model/loop.h> #include <SketchUpAPI/model/material.h> #include <SketchUpAPI/model/mesh_helper.h> #include <SketchUpAPI/model/model.h> #include <SketchUpAPI/model/texture.h> #include <SketchUpAPI/model/texture_writer.h> #include <SketchUpAPI/model/uv_helper.h> #include <SketchUpAPI/model/vertex.h> #include <SketchUpAPI/unicodestring.h> #include <Eigen/Dense> #include "MeshImporter.hpp" #include <map> #include <vector> #include <unordered_set> #define SU_CALL(func) \ if ((func) != SU_ERROR_NONE) \ throw std::exception() #define Y_UP false using namespace trisetra; class CSUString { public: CSUString() { SUSetInvalid(su_str_); SUStringCreate(&su_str_); } ~CSUString() { SUStringRelease(&su_str_); } operator SUStringRef*() { return &su_str_; } std::string utf8() { size_t length; SUStringGetUTF8Length(su_str_, &length); std::string string; string.resize(length + 1); size_t returned_length; SUStringGetUTF8(su_str_, length, &string[0], &returned_length); string.erase(length, 1); return string; } private: // Disallow copying for simplicity CSUString(const CSUString& copy); CSUString& operator=(const CSUString& copy); SUStringRef su_str_; }; static std::string GetComponentDefinitionName(SUComponentDefinitionRef comp_def) { CSUString name; SU_CALL(SUComponentDefinitionGetName(comp_def, name)); return name.utf8(); } struct SUImportInfo { std::vector<SUMaterialRef> mats; std::vector<std::string> names; std::vector<SUImageRepRef> textures; std::vector<SUPoint2D> texST; std::map<void*, MeshSource*> def_map; std::map<void*, std::vector<SUMaterialRef>> mat_map; }; struct SUPolyInfo { std::vector<float> vertex_positions; // The vertex's position (x,y,z) std::vector<uint32_t> vertex_indices; std::vector<float> vertex_normals; // The vertex's surface normal (x,y,z) std::vector<float> uvs; // The vertex's texture coordinates (u,v) std::vector<int32_t> material_ids; std::vector<int32_t> face_material; }; static std::vector<float> EigenToVector(const Eigen::Affine3f& t) { std::vector<float> local_transformations(12); local_transformations[0] = t(0, 0); local_transformations[1] = t(1, 0); local_transformations[2] = t(2, 0); local_transformations[3] = t(0, 1); local_transformations[4] = t(1, 1); local_transformations[5] = t(2, 1); local_transformations[6] = t(0, 2); local_transformations[7] = t(1, 2); local_transformations[8] = t(2, 2); local_transformations[9] = t(0, 3); local_transformations[10] = t(1, 3); local_transformations[11] = t(2, 3); return local_transformations; } static Eigen::Affine3f ToEigenAffine(const double* raw_data) { Eigen::Affine3f t; float scale = 1.0f / (float)(raw_data[15]); t(0, 0) = (float)(raw_data[0]) * scale; t(1, 0) = (float)(raw_data[1]) * scale; t(2, 0) = (float)(raw_data[2]) * scale; t(3, 0) = 0.0f; t(0, 1) = (float)(raw_data[4]) * scale; t(1, 1) = (float)(raw_data[5]) * scale; t(2, 1) = (float)(raw_data[6]) * scale; t(3, 1) = 0.0f; t(0, 2) = (float)(raw_data[8]) * scale; t(1, 2) = (float)(raw_data[9]) * scale; t(2, 2) = (float)(raw_data[10]) * scale; t(3, 2) = 0.0f; t(0, 3) = (float)(raw_data[12]) * scale; t(1, 3) = (float)(raw_data[13]) * scale; t(2, 3) = (float)(raw_data[14]) * scale; t(3, 3) = 1.0f; return t; } static void InitMaterialData(std::shared_ptr<MaterialData>& material, const SUImportInfo& su_mats, int src_idx) { SUColor color; double opt = 1.0; bool use_opacity; SUMaterialGetColor(su_mats.mats[src_idx], &color); SUMaterialGetOpacity(su_mats.mats[src_idx], &opt); SUMaterialGetUseOpacity(su_mats.mats[src_idx], &use_opacity); material->name = su_mats.names[src_idx]; material->base_color[0] = color.red / 255.0f; material->base_color[1] = color.green / 255.0f; material->base_color[2] = color.blue / 255.0f; material->base_color[3] = color.alpha / 255.0f; if (use_opacity) material->opacity = opt; } static void AddTextrueToMat(SUImageRepRef& img_rep, std::shared_ptr<MaterialData>& material, const std::string& composed_name) { if (SUIsValid(img_rep)) { size_t width, height, data_size, bits_per_pixel; SUImageRepGetPixelDimensions(img_rep, &width, &height); SUImageRepGetDataSize(img_rep, &data_size, &bits_per_pixel); std::string file_path = "./" +composed_name+".png"; SUImageRepSaveToFile(img_rep, file_path.c_str()); material->base_color_map = file_path; } } // returns first the transform to store for the node3d // the second transform (might cointains negtive scale) to be baked into vertecies static std::tuple<Eigen::Affine3f, Eigen::Affine3f> DecomposeTransform(Eigen::Affine3f t) { Eigen::Affine3f original_t = t; Eigen::Matrix3f rotation_scale_part(original_t.linear()); if (rotation_scale_part.determinant() > 0.0f) { Eigen::Affine3f identity = Eigen::Affine3f::Identity(); return std::make_tuple(original_t, identity); } else { t.translation() = Eigen::Vector3f(0.0f, 0.0f, 0.0f); Eigen::Matrix3f M = t.linear(); Eigen::Matrix3f rotation_matrix = t.rotation(); Eigen::Matrix3f scaling_matrix = rotation_matrix.transpose() * M; // sanitize non rotational component (only scaling > 0) scaling_matrix(0, 0) = std::abs(scaling_matrix(0, 0)); scaling_matrix(1, 1) = std::abs(scaling_matrix(1, 1)); scaling_matrix(2, 2) = std::abs(scaling_matrix(2, 2)); scaling_matrix(0, 1) = scaling_matrix(0, 2) = scaling_matrix(1, 0) = scaling_matrix(1, 2) = scaling_matrix(2, 0) = scaling_matrix(2, 1) = 0.0f; t.linear() = rotation_matrix * scaling_matrix; t.translation() = original_t.translation(); Eigen::Affine3f inverse_t = t.inverse(); Eigen::Affine3f bake_t = inverse_t * original_t; return std::make_tuple(t, bake_t); } } static void WriteFace(SUFaceRef face, SUTextureWriterRef texture_writer, SUPolyInfo& m_data, SUImportInfo& mat_info, int parent_idx, bool front, SUMaterialRef assigned, bool instanced, MeshImport* mesh_import, MeshSource* mesh, const Eigen::Affine3f& transform, const Eigen::Matrix3f& normal_transform) { if (SUIsInvalid(face)) return; SUMaterialRef face_material = SU_INVALID; // sort of hack as may face expect back face to be front facing due to material assignment. // so we use a key here to be smart about back/front face selection bool prefer_back_face = false; bool has_face_material = true; { SUMaterialRef bface_material = SU_INVALID; SUTextureRef ftexture_ref = SU_INVALID; SUFaceGetFrontMaterial(face, &face_material); if (SUIsValid(face_material)) { SUMaterialGetTexture(face_material, &ftexture_ref); } SUFaceGetBackMaterial(face, &bface_material); if (SUIsValid(bface_material)) { SUTextureRef texture_ref = SU_INVALID; SUMaterialGetTexture(bface_material, &texture_ref); if (SUIsValid(texture_ref) && SUIsInvalid(ftexture_ref)) { SUFaceReverse(face); face_material = bface_material; prefer_back_face = true; } } } SUVector3D fnorm; SUFaceGetNormal(face, &fnorm); // Get the current front and back materials off of our stack if (SUIsInvalid(face_material)) { face_material = assigned; has_face_material = false; } long mat_idx = 0; auto find_mat_it = std::find_if( mat_info.mats.begin(), mat_info.mats.end(), [face_material](const SUMaterialRef& in) { return face_material.ptr == in.ptr; }); if (find_mat_it != mat_info.mats.end()) { mat_idx = find_mat_it - mat_info.mats.begin(); } bool has_texture = SUIsValid(mat_info.textures[mat_idx]); // info.has_front_texture_ || info.has_back_texture_; if (has_texture && has_face_material) { long textureId = 0; SUTextureWriterGetTextureIdForFace(texture_writer, face, true, &textureId); } size_t local_mat_id = std::distance(m_data.material_ids.begin(), find(m_data.material_ids.begin(), m_data.material_ids.end(), mat_idx)); if (local_mat_id == m_data.material_ids.size()) { m_data.material_ids.push_back((int)mat_idx); } if (mesh) { // 0 is defefault material auto eu_material = mesh_import->get_material((int)mat_idx); mesh_import->apply_material(mesh, eu_material.get()); } // Get a uv helper float inv_ss = 1.0f; float inv_tt = 1.0f; if (!has_face_material) { inv_ss = mat_info.texST[mat_idx].x; inv_tt = mat_info.texST[mat_idx].y; } // Find out how many loops the face has size_t num_loops = 0; SU_CALL(SUFaceGetNumInnerLoops(face, &num_loops)); num_loops++; // add the outer loop // If this is a complex face with one or more holes in it // we tessellate it into triangles using the polygon mesh class, then // export each triangle as a face. // info.has_single_loop_ = false; // Create a mesh from face. SUMeshHelperRef mesh_ref = SU_INVALID; SU_CALL(SUMeshHelperCreateWithTextureWriter(&mesh_ref, face, texture_writer)); // Get the vertices size_t num_vertices = 0; SU_CALL(SUMeshHelperGetNumVertices(mesh_ref, &num_vertices)); if (num_vertices == 0) return; std::vector<SUPoint3D> vertices(num_vertices); SU_CALL(SUMeshHelperGetVertices(mesh_ref, num_vertices, &vertices[0], &num_vertices)); std::vector<SUVector3D> normals(num_vertices); SU_CALL(SUMeshHelperGetNormals(mesh_ref, num_vertices, &normals[0], &num_vertices)); std::vector<SUPoint3D> stq_coords(num_vertices); size_t uv_size = 0; if (!prefer_back_face) { SUMeshHelperGetFrontSTQCoords(mesh_ref, num_vertices, &stq_coords[0], &uv_size); } else { SUMeshHelperGetBackSTQCoords(mesh_ref, num_vertices, &stq_coords[0], &uv_size); } std::vector<float> vertex_positions(num_vertices * 3); std::vector<float> vertex_normal(num_vertices * 3); // dimension is Y up for (size_t i = 0; i < num_vertices; ++i) { Eigen::Vector3f pos(vertices[i].x, vertices[i].y, vertices[i].z); Eigen::Vector3f norm(normals[i].x, normals[i].y, normals[i].z); Eigen::Vector3f post_trans = transform * pos; Eigen::Vector3f norm_trans = normal_transform * norm; norm_trans.normalize(); vertex_positions[i * 3 + 0] = post_trans.x(); vertex_positions[i * 3 + 1] = post_trans.y(); vertex_positions[i * 3 + 2] = post_trans.z(); vertex_normal[i * 3 + 0] = norm_trans.x(); vertex_normal[i * 3 + 1] = norm_trans.y(); vertex_normal[i * 3 + 2] = norm_trans.z(); } // Get triangle indices. size_t num_triangles = 0; SU_CALL(SUMeshHelperGetNumTriangles(mesh_ref, &num_triangles)); const size_t num_indices = 3 * num_triangles; size_t num_retrieved = 0; std::vector<size_t> indices(num_indices); SU_CALL(SUMeshHelperGetVertexIndices(mesh_ref, num_indices, &indices[0], &num_retrieved)); std::vector<uint32_t> dst_idx(num_indices); std::vector<float> uv_coord; if (uv_size > 0) { uv_coord.resize(num_vertices * 2); for (size_t i = 0; i < num_vertices; ++i) { uv_coord[i * 2 + 0] = inv_ss * stq_coords[i].x / stq_coords[i].z; uv_coord[i * 2 + 1] = inv_tt * stq_coords[i].y / stq_coords[i].z; } } size_t base_idx = m_data.vertex_positions.size() / 3; std::vector<int32_t> face_materials(num_triangles); front = !prefer_back_face; for (size_t i_triangle = 0; i_triangle < num_triangles; i_triangle++) { face_materials[i_triangle] = (int)local_mat_id; // Three points in each triangle if (front) { for (size_t i = 0; i < 3; i++) { size_t index = indices[i_triangle * 3 + i]; dst_idx[i_triangle * 3 + i] = (int)(index + base_idx); } } else { // back face size_t index0 = indices[i_triangle * 3 + 0]; size_t index1 = indices[i_triangle * 3 + 1]; size_t index2 = indices[i_triangle * 3 + 2]; dst_idx[i_triangle * 3 + 0] = (int)(index2 + base_idx); dst_idx[i_triangle * 3 + 1] = (int)(index1 + base_idx); dst_idx[i_triangle * 3 + 2] = (int)(index0 + base_idx); } } // combine to original array m_data.vertex_positions.insert(m_data.vertex_positions.end(), vertex_positions.begin(), vertex_positions.end()); m_data.vertex_normals.insert(m_data.vertex_normals.end(), vertex_normal.begin(), vertex_normal.end()); m_data.vertex_indices.insert(m_data.vertex_indices.end(), dst_idx.begin(), dst_idx.end()); m_data.face_material.insert(m_data.face_material.end(), face_materials.begin(), face_materials.end()); if (uv_size > 0) { m_data.uvs.insert(m_data.uvs.end(), uv_coord.begin(), uv_coord.end()); } } static void WriteEntities(SUEntitiesRef entities, SUTextureWriterRef texture_writer, SUGroupRef group, SUImportInfo& mat_info, int parent_idx, SUMaterialRef parent_mat, MeshImport* mesh_import, const Node* parent, Eigen::Affine3f bake_transform) { #if 1 size_t num_instances = 0; SU_CALL(SUEntitiesGetNumInstances(entities, &num_instances)); if (num_instances > 0) { std::vector<SUComponentInstanceRef> instances(num_instances); SU_CALL(SUEntitiesGetInstances(entities, num_instances, &instances[0], &num_instances)); for (size_t c = 0; c < num_instances; c++) { SUComponentInstanceRef instance = instances[c]; SUComponentDefinitionRef definition = SU_INVALID; SU_CALL(SUComponentInstanceGetDefinition(instance, &definition)); size_t attached_instance = 0; SUComponentInstanceGetNumAttachedInstances(instance, &attached_instance); SUEntitiesRef entity_from_def; SUComponentDefinitionGetEntities(definition, &entity_from_def); size_t num_faces; SUEntitiesGetNumFaces(entity_from_def, &num_faces); SUTransformation transform; SU_CALL(SUComponentInstanceGetTransform(instance, &transform)); const double* raw_data = (const double*)transform.values; //---- checking if matrix has neg scal term, if so, we need to bake into vertecies auto src_affine = ToEigenAffine(raw_data); auto stacked = src_affine; Eigen::Affine3f to_transform; Eigen::Affine3f to_bake; std::tie(to_transform, to_bake) = DecomposeTransform(src_affine); bool need_baking = !to_bake.matrix().isIdentity(); auto sanitized_transform = EigenToVector(bake_transform * to_transform); //----------------------------------------------------------------------------- std::string def_name = GetComponentDefinitionName(definition); // add transformation info auto instance_node = mesh_import->create_node(parent, def_name); mesh_import->add_tranform3x4(instance_node.get(), std::move(sanitized_transform)); SUMaterialRef material = SU_INVALID; SUDrawingElementGetMaterial(SUComponentInstanceToDrawingElement(instance), &material); if (num_faces > 0) { MeshSource* mesh_node = nullptr; auto eu_mesh = mat_info.def_map.find(definition.ptr); if ((eu_mesh == mat_info.def_map.end()) || need_baking) { auto mesh = mesh_import->create_mesh(def_name); // only sotre into map if we dont need baking if (!need_baking) mat_info.def_map[definition.ptr] = mesh.get(); mesh_node = mesh.get(); mesh_import->add_face_descriptor(mesh_node, {3}); mesh_import->add_mesh_to_node(instance_node.get(), mesh_node); } else { // hook up instance. mesh_import->add_mesh_to_node(instance_node.get(), eu_mesh->second); } std::vector<SUFaceRef> faces(num_faces); SU_CALL(SUEntitiesGetFaces(entity_from_def, num_faces, &faces[0], &num_faces)); if (SUIsValid(material) == false) { material = parent_mat; } SUPolyInfo front_mesh; auto normal_transform = ((to_bake.linear()).inverse()).transpose(); for (size_t i = 0; i < num_faces; i++) { WriteFace(faces[i], texture_writer, front_mesh, mat_info, parent_idx, true, material, true, mesh_import, mesh_node, to_bake, normal_transform); } if (mesh_node) { mesh_import->add_positions(mesh_node, std::move(front_mesh.vertex_positions), std::move(front_mesh.vertex_indices)); mesh_import->add_normals(mesh_node, std::move(front_mesh.vertex_normals), {}); mesh_import->add_uv(mesh_node, 0, std::move(front_mesh.uvs), {}); mesh_import->add_face_material_idx(mesh_node, std::move(front_mesh.face_material)); } } WriteEntities(entity_from_def, texture_writer, group, mat_info, -1, material, mesh_import, instance_node.get(), to_bake); } } #endif // Groups size_t num_groups = 0; SU_CALL(SUEntitiesGetNumGroups(entities, &num_groups)); if (num_groups > 0) { std::vector<SUGroupRef> groups(num_groups); SU_CALL(SUEntitiesGetGroups(entities, num_groups, &groups[0], &num_groups)); for (size_t g = 0; g < num_groups; g++) { SUGroupRef group = groups[g]; if (!SUIsValid(group)) { continue; } // SUComponentDefinitionRef group_component = SU_INVALID; SUEntitiesRef group_entities = SU_INVALID; SU_CALL(SUGroupGetEntities(group, &group_entities)); int my_idx = parent_idx; size_t num_faces = 0; SUTransformation transform; SU_CALL(SUGroupGetTransform(group, &transform)); // FbxAMatrix& lLocalTransform = pNode->EvaluateLocalTransform(); const double* raw_data = (const double*)transform.values; //---- checking if matrix has neg scal term, if so, we need to bake into vertecies auto src_affine = ToEigenAffine(raw_data); auto stacked = src_affine; Eigen::Affine3f to_transform; Eigen::Affine3f to_bake; std::tie(to_transform, to_bake) = DecomposeTransform(src_affine); auto sanitized_transform = EigenToVector(bake_transform * to_transform); //----------------------------------------------------------------------------- CSUString name; SUGroupGetName(group, name); auto def_name = "group_" + name.utf8(); //------ add transformation info auto instance_node = mesh_import->create_node(parent, def_name); mesh_import->add_tranform3x4(instance_node.get(), std::move(sanitized_transform)); SU_CALL(SUEntitiesGetNumFaces(group_entities, &num_faces)); SUDrawingElementRef dwrf = SUGroupToDrawingElement(group); SUMaterialRef material = SU_INVALID; if (SUIsValid(dwrf)) { SUDrawingElementGetMaterial(dwrf, &material); if (SUIsValid(material)) parent_mat = material; } if (num_faces > 0) { auto mesh = mesh_import->create_mesh(name.utf8()); mesh_import->add_face_descriptor(mesh.get(), {3}); mesh_import->add_mesh_to_node(instance_node.get(), mesh.get()); std::vector<SUFaceRef> faces(num_faces); SU_CALL(SUEntitiesGetFaces(group_entities, num_faces, &faces[0], &num_faces)); if (SUIsInvalid(material)) material = parent_mat; SUPolyInfo front_mesh; auto normal_transform = ((to_bake.linear()).inverse()).transpose(); for (size_t i = 0; i < num_faces; i++) { WriteFace(faces[i], texture_writer, front_mesh, mat_info, parent_idx, true, material, false, mesh_import, mesh.get(), to_bake, normal_transform); } if (mesh.get()) { mesh_import->add_positions(mesh.get(), std::move(front_mesh.vertex_positions), std::move(front_mesh.vertex_indices)); mesh_import->add_normals(mesh.get(), std::move(front_mesh.vertex_normals), {}); mesh_import->add_uv(mesh.get(), 0, std::move(front_mesh.uvs), {}); mesh_import->add_face_material_idx(mesh.get(), std::move(front_mesh.face_material)); } } // Write entities WriteEntities(group_entities, texture_writer, group, mat_info, my_idx, parent_mat, mesh_import, instance_node.get(), to_bake); } } } void load_skp(const std::string& path, MeshImport* mesh_import) { // Always initialize the API before using it SUInitialize(); // Load the model from a file SUModelRef model = SU_INVALID; SUResult res = SUModelCreateFromFile(&model, path.c_str()); // It's best to always check the return code from each SU function call. // Only showing this check once to keep this example short. if (res != SU_ERROR_NONE) throw std::runtime_error("SUModelCreateFromFile failed to open: " + path); SUTextureWriterRef texture_writer; SU_CALL(SUTextureWriterCreate(&texture_writer)); // Get the entity container of the model. SUEntitiesRef entities = SU_INVALID; SUModelGetEntities(model, &entities); //---------------- material ------------------------ size_t material_count = 0; SUModelGetNumMaterials(model, &material_count); SUImportInfo su_mats; su_mats.mats.resize(material_count + 1); su_mats.textures.resize(material_count + 1); su_mats.names.resize(material_count + 1); su_mats.texST.resize(material_count + 1); // with default material std::vector<std::shared_ptr<MaterialData>> materials(material_count + 1); ; for (int i = 0; i < material_count + 1; ++i) { materials[i] = std::make_shared<MaterialData>(); } // material creation... { SUModelGetMaterials(model, material_count, &su_mats.mats[1], &material_count); // set 0 to default material // su_mats.names[0] = "default"; materials[0]->name = "default"; su_mats.textures[0] = SU_INVALID; su_mats.mats[0] = SU_INVALID; for (int i = 1; i < material_count + 1; ++i) { CSUString name; SUMaterialGetNameLegacyBehavior(su_mats.mats[i], name); SUTextureRef texture_ref = SU_INVALID; SUMaterialGetTexture(su_mats.mats[i], &texture_ref); su_mats.names[i] = name.utf8(); InitMaterialData(materials[i], su_mats, i); if (SUIsValid(texture_ref)) { size_t width, height; double ss, st; SUTextureGetDimensions(texture_ref, &width, &height, &ss, &st); SUImageRepRef img_rep = SU_INVALID; SUImageRepCreate(&img_rep); su_mats.textures[i] = img_rep; SUTextureGetImageRep(texture_ref, &img_rep); CSUString tex_name; SUTextureGetFileName(texture_ref, tex_name); std::string composed_name = tex_name.utf8() + "_" + name.utf8(); su_mats.texST[i].x = (float)ss; su_mats.texST[i].y = (float)st; AddTextrueToMat(img_rep, materials[i], composed_name ); SUImageRepRelease(&img_rep); } } } mesh_import->add_materials(materials); // Get model name CSUString name; SUModelGetName(model, name); std::vector<float> local_transformations(12); { local_transformations[0] = 1; local_transformations[1] = 0; local_transformations[2] = 0; local_transformations[3] = 0; local_transformations[4] = 1; local_transformations[5] = 0; local_transformations[6] = 0; local_transformations[7] = 0; local_transformations[8] = 1; local_transformations[9] = 0; local_transformations[10] = 0; local_transformations[11] = 0; } auto root_node = mesh_import->create_node(nullptr, "y_up_convert" + name.utf8()); { mesh_import->add_tranform3x4(root_node.get(), std::move(local_transformations)); } size_t num_faces = 0; Eigen::Affine3f identity; identity.setIdentity(); SU_CALL(SUEntitiesGetNumFaces(entities, &num_faces)); if (num_faces > 0) { auto en_mesh = mesh_import->create_mesh("entity"); mesh_import->add_face_descriptor(en_mesh.get(), {3}); mesh_import->add_mesh_to_node(root_node.get(), en_mesh.get()); std::vector<SUFaceRef> faces(num_faces); SU_CALL(SUEntitiesGetFaces(entities, num_faces, &faces[0], &num_faces)); SUPolyInfo front_mesh; for (size_t i = 0; i < num_faces; i++) { WriteFace(faces[i], texture_writer, front_mesh, su_mats, 0, true, SU_INVALID, false, mesh_import, en_mesh.get(), identity, identity.linear()); } if (en_mesh.get()) { mesh_import->add_positions(en_mesh.get(), std::move(front_mesh.vertex_positions), std::move(front_mesh.vertex_indices)); mesh_import->add_normals(en_mesh.get(), std::move(front_mesh.vertex_normals), {}); mesh_import->add_uv(en_mesh.get(), 0, std::move(front_mesh.uvs), {}); mesh_import->add_face_material_idx(en_mesh.get(), std::move(front_mesh.face_material)); } } // material gathering // GetEntitiesMaterial(entities, texture_writer, SU_INVALID, model_data_ptr, su_mats, 0); // Groups SUMaterialRef material = SU_INVALID; WriteEntities(entities, texture_writer, SU_INVALID, su_mats, 0, material, mesh_import, root_node.get(), identity); // Must release the model or there will be memory leaks SUModelRelease(&model); // Always terminate the API when done using it SUTerminate(); } int main(int argc, const char * argv[]) { // insert code here... MeshImporter mi; if( argc > 1){ float rotate = 0.0f; std::string file_name = std::string(argv[1]); if(argc > 2) rotate = std::stof( std::string(argv[2])); load_skp(file_name, &mi ); size_t lastindex = file_name.find_last_of("."); std::string rawname = file_name.substr(0, lastindex); rawname = rawname + ".tri"; //mi.serialize_to_file(rawname, true, Y_UP, -1.571f); mi.serialize_to_file(rawname, true, Y_UP, rotate); } return 0; }
38.872679
162
0.608393
jhhsia
0dbff02f2d2ddc13d3713e7691ed49c0ee996e42
1,028
cpp
C++
Luogu/P3805/manacher.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
Luogu/P3805/manacher.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
Luogu/P3805/manacher.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <bits/stdc++.h> using namespace std; #define SIZE 11000010 int radius[SIZE << 1]; string man; void init(const string & str) { memset(radius, 0, sizeof(radius)); man.clear(); man.push_back('#'); for (auto ch : str) { man.push_back(ch); man.push_back('#'); } } void manacher() { int rightPt = -1, midPt = -1, len = man.size(); for (int i = 0; i < len; i++) { radius[i] = i < rightPt ? min(radius[(midPt << 1) - i], radius[midPt] + midPt - i) : 1; while (radius[i] < min(len - i, i + 1) && man[i + radius[i]] == man[i - radius[i]]) radius[i]++; if (radius[i] + i > rightPt) { rightPt = radius[i] + i; midPt = i; } } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); string str; cin >> str; init(str); manacher(); int ans = 0; for (int i = 0; i < (int)man.size(); i++) ans = max(ans, radius[i]); cout << ans - 1 << '\n'; return 0; }
21.87234
95
0.488327
codgician
0dc05ff01b6e68b3e8529d0234a5cd5841eee709
6,156
cc
C++
src/App.cc
ElChapos/BlockWorld
9fcd224682ef52a1ca82d7f4ff6c1b39afe97b94
[ "BSD-2-Clause" ]
1
2016-05-24T17:25:51.000Z
2016-05-24T17:25:51.000Z
src/App.cc
ElChapos/BlockWorld
9fcd224682ef52a1ca82d7f4ff6c1b39afe97b94
[ "BSD-2-Clause" ]
null
null
null
src/App.cc
ElChapos/BlockWorld
9fcd224682ef52a1ca82d7f4ff6c1b39afe97b94
[ "BSD-2-Clause" ]
null
null
null
#define GLEW_STATIC // Easier debugging #define RUN_GRAPHICS_DISPLAY 0x00; #include <GL/glew.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #include <SDL2/SDL.h> #include <iostream> #include <memory> #include <boost/program_options.hpp> #include "common.h" #include "App.h" #include "GameWorld.h" /** * SDL timers run in separate threads. In the timer thread * push an event onto the event queue. This event signifies * to call display() from the thread in which the OpenGL * context was created. */ Uint32 tick(Uint32 interval, void *param) { SDL_Event event; event.type = SDL_USEREVENT; event.user.code = RUN_GRAPHICS_DISPLAY; event.user.data1 = 0; event.user.data2 = 0; SDL_PushEvent(&event); return interval; } /** * Destroys the game SDL_Window */ struct SDLWindowDeleter { inline void operator()(SDL_Window* window) { SDL_DestroyWindow(window); } }; /** * Handles global input from mouse and keyboard */ void App::HandleInput(const std::shared_ptr<GameWorld> &game_world) { int mouse_x; int mouse_y; const Uint8 * keyboard_state; Input input_direction = NILL; // For camera pitch/yaw SDL_GetRelativeMouseState(&mouse_x, &mouse_y); // Slow down the mouse_x and mouse_y mouse_x = mouse_x*0.2; mouse_y = mouse_y*0.2; game_world->UpdateCameraPosition(input_direction, mouse_x, mouse_y); // For keyboard presses keyboard_state = SDL_GetKeyboardState(NULL); if(keyboard_state[SDL_SCANCODE_W]) { game_world->UpdateCameraPosition(UP, mouse_x, mouse_y); } if(keyboard_state[SDL_SCANCODE_A]) { game_world->UpdateCameraPosition(LEFT, mouse_x, mouse_y); } if(keyboard_state[SDL_SCANCODE_S]) { game_world->UpdateCameraPosition(DOWN, mouse_x, mouse_y); } if(keyboard_state[SDL_SCANCODE_D]) { game_world->UpdateCameraPosition(RIGHT, mouse_x, mouse_y); } if(keyboard_state[SDL_SCANCODE_SPACE]) { game_world->UpdateCameraPosition(SPACE, mouse_x, mouse_y); } if(keyboard_state[SDL_SCANCODE_LCTRL]) { game_world->UpdateCameraPosition(CTRL, mouse_x, mouse_y); } if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT)) { game_world->BlockAction(true); } if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT)) { game_world->BlockAction(false); } if(keyboard_state[SDL_SCANCODE_ESCAPE]) { SDL_Quit(); } if(keyboard_state[SDL_SCANCODE_1]) { game_world->BlockType(BW_CUBE); } if(keyboard_state[SDL_SCANCODE_2]) { game_world->BlockType(BW_STAR); } if(keyboard_state[SDL_SCANCODE_3]) { game_world->BlockType(BW_DIAMOND); } } /** * Draws the colour and calls to GameWorld for Drawing */ void App::Draw(const std::shared_ptr<SDL_Window> &window, const std::shared_ptr<GameWorld> &game_world) { // Background glClearColor(0.0f, 0.2f, 0.2f, 0.3f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); game_world->Draw(); // Don't forget to swap the buffers SDL_GL_SwapWindow(window.get()); } /** * Initialises the SDL_Window and OpenGL 3.0 */ std::shared_ptr<SDL_Window> App::InitWorld() { Uint32 width = 1027; Uint32 height = 768; SDL_Window * _window; std::shared_ptr<SDL_Window> window; // Glew will later ensure that OpenGL 3 *is* supported SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); // Do double buffering in GL SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); // Initialise SDL - when using C/C++ it's common to have to // initialise libraries by calling a function within them. if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER)<0) { std::cout << "Failed to initialise SDL: " << SDL_GetError() << std::endl; return nullptr; } // When we close a window quit the SDL application atexit(SDL_Quit); SDL_ShowCursor(0); // Create a new window with an OpenGL surface _window = SDL_CreateWindow("BlockWorld", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN ); if (!_window) { std::cout << "Failed to create SDL window: " << SDL_GetError() << std::endl; return nullptr; } SDL_GLContext glContext = SDL_GL_CreateContext(_window); if (!glContext) { std::cout << "Failed to create OpenGL context: " << SDL_GetError() << std::endl; return nullptr; } // Initialise GLEW - an easy way to ensure OpenGl 3.0+ // The *must* be done after we have set the video mode - otherwise we have no // OpenGL context to test. glewInit(); if (!glewIsSupported("GL_VERSION_3_0")) { std::cerr << "OpenGL 3.0 not available" << std::endl; return nullptr; } // OpenGL settings glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); window.reset(_window, SDL_DestroyWindow); return window; } /** * Starts our game loop, called via Python or Main */ void App::Run() { Uint32 delay = 1000/60; // in milliseconds auto window = InitWorld(); auto game_world = std::make_shared<GameWorld>(); if(!window) { SDL_Quit(); } // Call the function "tick" every delay milliseconds SDL_AddTimer(delay, tick, NULL); SDL_SetRelativeMouseMode(SDL_TRUE); // Add the main event loop SDL_Event event; while (SDL_WaitEvent(&event)) { switch (event.type) { case SDL_QUIT: { SDL_Quit(); break; } case SDL_USEREVENT: { HandleInput(game_world); Draw(window, game_world); break; } default: break; } } }
24.722892
103
0.647336
ElChapos
0dc5ef8e54d12820990e9e15b07f85e89723a40d
900
cpp
C++
src/util/function.cpp
keszocze/abo
2d59ac20832b308ef5f90744fc98752797a4f4ba
[ "MIT" ]
null
null
null
src/util/function.cpp
keszocze/abo
2d59ac20832b308ef5f90744fc98752797a4f4ba
[ "MIT" ]
null
null
null
src/util/function.cpp
keszocze/abo
2d59ac20832b308ef5f90744fc98752797a4f4ba
[ "MIT" ]
1
2020-03-11T14:50:31.000Z
2020-03-11T14:50:31.000Z
#include "function.hpp" #include <algorithm> #include <cassert> namespace abo::util { Function::Function(const Cudd &mgr, const std::vector<BDD> &value, NumberRepresentation representation) : mgr(mgr), value(value), representation(representation) { assert(value.size() > 0); } BDD& Function::operator[](std::size_t index) { return value.at(index); } const BDD& Function::operator[](std::size_t index) const { return value.at(index); } Function Function::operator&(const BDD& b) const { Function result = *this; result &= b; return result; } Function Function::operator|(const BDD& b) const { Function result = *this; result |= b; return result; } void Function::operator&=(const BDD& b) { for (BDD& own : value) { own &= b; } } void Function::operator|=(const BDD& b) { for (BDD& own : value) { own |= b; } } }
18.75
105
0.626667
keszocze
0dc78a607390e1fcc4c43afa5600113d3d44d7c2
22,062
hpp
C++
src/algorithms/bfs.hpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
112
2016-04-26T05:54:30.000Z
2022-03-27T05:56:16.000Z
src/algorithms/bfs.hpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
21
2016-03-22T19:06:46.000Z
2021-10-07T15:40:18.000Z
src/algorithms/bfs.hpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
22
2016-04-26T05:54:35.000Z
2021-12-21T03:33:20.000Z
/* * GraphBLAS Template Library (GBTL), Version 3.0 * * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and * Authors. * * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF * THE UNITED STATES GOVERNMENT. NEITHER THE UNITED STATES GOVERNMENT NOR THE * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED * RIGHTS. * * Released under a BSD-style license, please see LICENSE file or contact * permission@sei.cmu.edu for full terms. * * [DISTRIBUTION STATEMENT A] This material has been approved for public release * and unlimited distribution. Please see Copyright notice for non-US * Government use and distribution. * * DM20-0442 */ #pragma once #include <limits> #include <tuple> #include <graphblas/graphblas.hpp> //**************************************************************************** namespace algorithms { //************************************************************************ /** * @brief Perform a single "parent" breadth first search (BFS) traversal * on the given graph. * * @param[in] graph N x N adjacency matrix of the graph on which to * perform a BFS. (NOT the transpose). The value * 1 should indicate an edge. * @param[in] source Index of the root vertex to use in the * calculation. * @param[out] parent_list The list of parents for each traversal (row) * specified in the roots array. */ template <typename MatrixT, typename ParentListVectorT> void bfs(MatrixT const &graph, grb::IndexType source, ParentListVectorT &parent_list) { grb::IndexType const N(graph.nrows()); // assert parent_list is N-vector // assert source is in proper range // assert parent_list ScalarType is grb::IndexType // create index ramp for index_of() functionality grb::Vector<grb::IndexType> index_ramp(N); for (grb::IndexType i = 0; i < N; ++i) { index_ramp.setElement(i, i); } // initialize wavefront to source node. grb::Vector<grb::IndexType> wavefront(N); wavefront.setElement(source, 1UL); // set root parent to self; parent_list.clear(); parent_list.setElement(source, source); while (wavefront.nvals() > 0) { // convert all stored values to their column index grb::eWiseMult(wavefront, grb::NoMask(), grb::NoAccumulate(), grb::First<grb::IndexType>(), index_ramp, wavefront); // First because we are left multiplying wavefront rows // Masking out the parent list ensures wavefront values do not // overlap values already stored in the parent list grb::vxm(wavefront, grb::complement(grb::structure(parent_list)), grb::NoAccumulate(), grb::MinFirstSemiring<grb::IndexType>(), wavefront, graph, grb::REPLACE); // We don't need to mask here since we did it in mxm. // Merges new parents in current wavefront with existing parents // parent_list<!parent_list,merge> += wavefront grb::apply(parent_list, grb::NoMask(), grb::Plus<grb::IndexType>(), grb::Identity<grb::IndexType>(), wavefront, grb::MERGE); } } //************************************************************************ /** * @brief Perform a single "parent" breadth first search (BFS) traversal * on the given graph. * * @param[in] graph N x N adjacency matrix of the graph on which to * perform a BFS. (NOT the transpose). The value * 1 should indicate an edge. * @param[in] wavefront N-vector, initial wavefront/root to use in the * calculation. It should have a * single value set to '1' corresponding to the * root. * @param[out] parent_list The list of parents for each traversal (row) * specified in the roots array. */ template <typename MatrixT, typename WavefrontVectorT, typename ParentListVectorT> void bfs(MatrixT const &graph, WavefrontVectorT wavefront, // copy is intentional ParentListVectorT &parent_list) { using T = typename MatrixT::ScalarType; grb::IndexType const N(graph.nrows()); // assert parent_list is N-vector // assert wavefront is N-vector // assert parent_list ScalarType is grb::IndexType // create index ramp for index_of() functionality grb::Vector<grb::IndexType> index_ramp(N); for (grb::IndexType i = 0; i < N; ++i) { index_ramp.setElement(i, i); } // Set the roots parents to themselves using indices grb::eWiseMult(parent_list, grb::NoMask(), grb::NoAccumulate(), grb::First<grb::IndexType>(), index_ramp, wavefront); // convert all stored values to their column index grb::eWiseMult(parent_list, grb::NoMask(), grb::NoAccumulate(), grb::First<grb::IndexType>(), index_ramp, parent_list); while (wavefront.nvals() > 0) { // convert all stored values to their column index grb::eWiseMult(wavefront, grb::NoMask(), grb::NoAccumulate(), grb::First<grb::IndexType>(), index_ramp, wavefront); // First because we are left multiplying wavefront rows // Masking out the parent list ensures wavefront values do not // overlap values already stored in the parent list grb::vxm(wavefront, grb::complement(grb::structure(parent_list)), grb::NoAccumulate(), grb::MinFirstSemiring<T>(), wavefront, graph, grb::REPLACE); // We don't need to mask here since we did it in mxm. // Merges new parents in current wavefront with existing parents // parent_list<!parent_list,merge> += wavefront grb::apply(parent_list, grb::NoMask(), grb::Plus<T>(), grb::Identity<T>(), wavefront, grb::MERGE); } } //************************************************************************ /** * @brief Perform a set of breadth first search (BFS) traversals on the * given graph. * * @param[in] graph N x N adjacency matrix of the graph on which to * perform a BFS. (NOT the transpose). The value * 1 should indicate an edge, * @param[in] wavefronts R x N, initial wavefront(s)/root(s) to use in the * calculation. Each row (1) corresponds to a * different BFS traversal and (2) should have a * single value set to '1' corresponding to the * root. * @param[out] parent_list The list of parents for each traversal (row) * specified in the roots array. */ template <typename MatrixT, typename WavefrontMatrixT, typename ParentListMatrixT> void bfs_batch(MatrixT const &graph, WavefrontMatrixT wavefronts, // copy is intentional ParentListMatrixT &parent_list) { using T = typename MatrixT::ScalarType; grb::IndexType const N(graph.nrows()); // assert parent_list is RxN // assert wavefront is RxN // assert parent_list ScalarType is grb::IndexType // create index ramp for index_of() functionality grb::Matrix<grb::IndexType> index_ramp(N, N); for (grb::IndexType idx = 0; idx < N; ++idx) { index_ramp.setElement(idx, idx, idx); } // Set the roots parents to themselves. grb::mxm(parent_list, grb::NoMask(), grb::NoAccumulate(), grb::MinSecondSemiring<T>(), wavefronts, index_ramp); while (wavefronts.nvals() > 0) { // convert all stored values to their column index grb::mxm(wavefronts, grb::NoMask(), grb::NoAccumulate(), grb::MinSecondSemiring<T>(), wavefronts, index_ramp); // First because we are left multiplying wavefront rows // Masking out the parent list ensures wavefronts values do not // overlap values already stored in the parent list grb::mxm(wavefronts, grb::complement(grb::structure(parent_list)), grb::NoAccumulate(), grb::MinFirstSemiring<T>(), wavefronts, graph, grb::REPLACE); // We don't need to mask here since we did it in mxm. // Merges new parents in current wavefront with existing parents // parent_list<!parent_list,merge> += wavefronts grb::apply(parent_list, grb::NoMask(), grb::Plus<T>(), grb::Identity<T>(), wavefronts, grb::MERGE); } } //************************************************************************ /** * @brief Perform a single "level" breadth first search (BFS) traversal * on the given graph. * * @param[in] graph N x N adjacency matrix of the graph on which to * perform a BFS. (NOT the transpose). The value * 1 should indicate an edge. * @param[in] source Index of the root vertex to use in the * calculation. * @param[out] levels The level (distance in unweighted graphs) from * the source (root) of the BFS. */ template <typename MatrixT, typename LevelsVectorT> void bfs_level(MatrixT const &graph, grb::IndexType source, LevelsVectorT &levels) { grb::IndexType const N(graph.nrows()); /// @todo Assert graph is square grb::Vector<bool> wavefront(N); wavefront.setElement(source, true); grb::IndexType depth(0); while (wavefront.nvals() > 0) { // Increment the level ++depth; // Apply the level to all newly visited nodes grb::apply(levels, grb::NoMask(), grb::Plus<grb::IndexType>(), //[depth](auto arg) { return arg * depth; }, std::bind(grb::Times<grb::IndexType>(), depth, std::placeholders::_1), wavefront); grb::mxv(wavefront, complement(levels), grb::NoAccumulate(), grb::LogicalSemiring<bool>(), transpose(graph), wavefront, grb::REPLACE); } } //************************************************************************ /** * @brief Perform a breadth first search (BFS) on the given graph. * * @param[in] graph The graph to perform a BFS on. NOT built from * the transpose of the adjacency matrix. * (1 indicates edge, structural zero = 0). * @param[in] wavefront The initial wavefront to use in the calculation. * (1 indicates root, structural zero = 0). * @param[out] levels The level (distance in unweighted graphs) from * the corresponding root of that BFS * * @deprecated Use batched_bfs_level_masked */ template <typename MatrixT, typename WavefrontMatrixT, typename LevelListMatrixT> void bfs_level(MatrixT const &graph, WavefrontMatrixT wavefront, //row vectors, copy made LevelListMatrixT &levels) { /// @todo Assert graph is square /// @todo Assert graph has a compatible shape with wavefront? unsigned int depth = 0; while (wavefront.nvals() > 0) { // Increment the level ++depth; // Apply the level to all newly visited nodes grb::apply(levels, grb::NoMask(), grb::Plus<unsigned int>(), std::bind(grb::Times<unsigned int>(), depth, std::placeholders::_1), wavefront, grb::REPLACE); grb::mxm(wavefront, grb::NoMask(), grb::NoAccumulate(), grb::LogicalSemiring<unsigned int>(), wavefront, graph, grb::REPLACE); // Cull previously visited nodes from the wavefront grb::apply( wavefront, grb::complement(levels), grb::NoAccumulate(), grb::Identity<typename WavefrontMatrixT::ScalarType>(), wavefront, grb::REPLACE); } } //************************************************************************ /** * @brief Perform a single breadth first searches (BFS) on the given graph. * * @param[in] graph NxN adjacency matrix of the graph on which to * perform a BFS (not the transpose). A value of * 1 indicates an edge (structural zero = 0). * @param[in] wavefront N-vector initial wavefront to use in the calculation * of R simultaneous traversals. A value of 1 in a * given position indicates a root for the * traversal.. * @param[out] levels The level (distance in unweighted graphs) from * the corresponding root of that BFS. Roots are * assigned a value of 1. (a value of 0 implies not * reachable. */ template <typename MatrixT, typename WavefrontT, typename LevelListT> void bfs_level_masked(MatrixT const &graph, WavefrontT wavefront, //row vector, copy made LevelListT &levels) { /// Assert graph is square/have a compatible shape with wavefront grb::IndexType grows(graph.nrows()); grb::IndexType gcols(graph.ncols()); grb::IndexType wsize(wavefront.size()); if ((grows != gcols) || (wsize != grows)) { throw grb::DimensionException(); } grb::IndexType depth = 0; while (wavefront.nvals() > 0) { // Increment the level ++depth; // Apply the level to all newly visited nodes grb::apply(levels, grb::NoMask(), grb::Plus<unsigned int>(), std::bind(grb::Times<grb::IndexType>(), depth, std::placeholders::_1), wavefront, grb::REPLACE); // Advance the wavefront and mask out nodes already assigned levels grb::vxm(wavefront, grb::complement(levels), grb::NoAccumulate(), grb::LogicalSemiring<grb::IndexType>(), wavefront, graph, grb::REPLACE); } } //************************************************************************ /** * @brief Perform multiple breadth first searches (BFS) on the given graph. * * @param[in] graph NxN adjacency matrix of the graph on which to * perform a BFS (not the transpose). A value of * 1 indicates an edge (structural zero = 0). * @param[in] wavefronts RxN initial wavefronts to use in the calculation * of R simultaneous traversals. A value of 1 in a * given row indicates a root for the corresponding * traversal. (structural zero = 0). * @param[out] levels The level (distance in unweighted graphs) from * the corresponding root of that BFS. Roots are * assigned a value of 1. (a value of 0 implies not * reachable. */ template <typename MatrixT, typename WavefrontsMatrixT, typename LevelListMatrixT> void batch_bfs_level_masked(MatrixT const &graph, WavefrontsMatrixT wavefronts, //row vectors, copy LevelListMatrixT &levels) { /// Assert graph is square/have a compatible shape with wavefronts grb::IndexType grows(graph.nrows()); grb::IndexType gcols(graph.ncols()); grb::IndexType cols(wavefronts.ncols()); if ((grows != gcols) || (cols != grows)) { throw grb::DimensionException(); } grb::IndexType depth = 0; while (wavefronts.nvals() > 0) { // Increment the level ++depth; // Apply the level to all newly visited nodes grb::apply(levels, grb::NoMask(), grb::Plus<unsigned int>(), std::bind(grb::Times<grb::IndexType>(), depth, std::placeholders::_1), wavefronts, grb::REPLACE); // Advance the wavefronts and mask out nodes already assigned levels grb::mxm(wavefronts, grb::complement(levels), grb::NoAccumulate(), grb::LogicalSemiring<grb::IndexType>(), wavefronts, graph, grb::REPLACE); } } //************************************************************************ /** * @brief Perform a single breadth first searches (BFS) on the given graph. * * @param[in] graph NxN adjacency matrix of the graph on which to * perform a BFS (not the transpose). A value of * 1 indicates an edge (structural zero = 0). * @param[in] wavefront N-vector initial wavefront to use in the calculation * of R simultaneous traversals. A value of 1 in a * given position indicates a root for the * traversal.. * @param[out] levels The level (distance in unweighted graphs) from * the corresponding root of that BFS. Roots are * assigned a value of 1. (a value of 0 implies not * reachable. */ template <typename MatrixT, typename WavefrontT, typename LevelListT> void bfs_level_masked_v2(MatrixT const &graph, WavefrontT wavefront, //row vector, copy made LevelListT &levels) { /// Assert graph is square/have a compatible shape with wavefront grb::IndexType grows(graph.nrows()); grb::IndexType gcols(graph.ncols()); grb::IndexType wsize(wavefront.size()); if ((grows != gcols) || (wsize != grows)) { throw grb::DimensionException(); } grb::IndexType depth = 0; while (wavefront.nvals() > 0) { // Increment the level ++depth; grb::assign(levels, wavefront, grb::NoAccumulate(), depth, grb::AllIndices(), grb::MERGE); // Advance the wavefront and mask out nodes already assigned levels grb::vxm(wavefront, grb::complement(levels), grb::NoAccumulate(), grb::LogicalSemiring<grb::IndexType>(), wavefront, graph, grb::REPLACE); } } }
40.780037
82
0.493382
KIwabuchi
0dcfca94ba8ea1a603a51334ea8cc925cdc8cc88
26,336
cpp
C++
Engine/Src/SFEngine/Graphics/Vulkan/SFVulkanLibrary.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
1
2020-06-20T07:35:25.000Z
2020-06-20T07:35:25.000Z
Engine/Src/SFEngine/Graphics/Vulkan/SFVulkanLibrary.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
Engine/Src/SFEngine/Graphics/Vulkan/SFVulkanLibrary.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // CopyRight (c) 2017 Kyungkun Ko // // Author : KyungKun Ko // // Description : Vulkan library // //////////////////////////////////////////////////////////////////////////////// #include "SFEnginePCH.h" #include "SFVulkanLibrary.h" #if HAVE_VULKAN #if SF_PLATFORM == SF_PLATFORM_ANDROID #include <dlfcn.h> #define LOAD_VULKAN_LIBRARY() dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL) namespace SF { template<class FunctionType> FunctionType GetDLLProcAddress(void* dllInstance, const char* procName) { return reinterpret_cast<FunctionType>(dlsym(dllInstance, procName)); } } #elif SF_PLATFORM == SF_PLATFORM_WINDOWS #define LOAD_VULKAN_LIBRARY() LoadLibraryA("vulkan-1.dll") namespace SF { template<class FunctionType> FunctionType GetDLLProcAddress(HMODULE dllInstance, const char* procName) { return reinterpret_cast<FunctionType>(GetProcAddress(dllInstance, procName)); } } #else #error "Not supported platform" #endif #define GET_PROCADDRESS(libvulkan, procName) GetDLLProcAddress<PFN_##procName>(libvulkan, #procName) namespace SF { bool SFVulkanLibrary_Initialize() { #if SF_VULKAN_DYNAMIC_LIBRARY if (vkCreateInstance != nullptr) return true; auto libvulkan = LOAD_VULKAN_LIBRARY(); if (!libvulkan) { assert(false); return false; } // Vulkan supported, set function addresses vkCreateInstance = GET_PROCADDRESS(libvulkan, vkCreateInstance); vkDestroyInstance = GET_PROCADDRESS(libvulkan, vkDestroyInstance); vkEnumeratePhysicalDevices = GET_PROCADDRESS(libvulkan, vkEnumeratePhysicalDevices); vkGetPhysicalDeviceFeatures = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceFeatures); vkGetPhysicalDeviceFormatProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceFormatProperties); vkGetPhysicalDeviceImageFormatProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceImageFormatProperties); vkGetPhysicalDeviceProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceProperties); vkGetPhysicalDeviceQueueFamilyProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceQueueFamilyProperties); vkGetPhysicalDeviceMemoryProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceMemoryProperties); vkGetInstanceProcAddr = GET_PROCADDRESS(libvulkan, vkGetInstanceProcAddr); vkGetDeviceProcAddr = GET_PROCADDRESS(libvulkan, vkGetDeviceProcAddr); vkCreateDevice = GET_PROCADDRESS(libvulkan, vkCreateDevice); vkDestroyDevice = GET_PROCADDRESS(libvulkan, vkDestroyDevice); vkEnumerateInstanceExtensionProperties = GET_PROCADDRESS(libvulkan, vkEnumerateInstanceExtensionProperties); vkEnumerateDeviceExtensionProperties = GET_PROCADDRESS(libvulkan, vkEnumerateDeviceExtensionProperties); vkEnumerateInstanceLayerProperties = GET_PROCADDRESS(libvulkan, vkEnumerateInstanceLayerProperties); vkEnumerateDeviceLayerProperties = GET_PROCADDRESS(libvulkan, vkEnumerateDeviceLayerProperties); vkGetDeviceQueue = GET_PROCADDRESS(libvulkan, vkGetDeviceQueue); vkQueueSubmit = GET_PROCADDRESS(libvulkan, vkQueueSubmit); vkQueueWaitIdle = GET_PROCADDRESS(libvulkan, vkQueueWaitIdle); vkDeviceWaitIdle = GET_PROCADDRESS(libvulkan, vkDeviceWaitIdle); vkAllocateMemory = GET_PROCADDRESS(libvulkan, vkAllocateMemory); vkFreeMemory = GET_PROCADDRESS(libvulkan, vkFreeMemory); vkMapMemory = GET_PROCADDRESS(libvulkan, vkMapMemory); vkUnmapMemory = GET_PROCADDRESS(libvulkan, vkUnmapMemory); vkFlushMappedMemoryRanges = GET_PROCADDRESS(libvulkan, vkFlushMappedMemoryRanges); vkInvalidateMappedMemoryRanges = GET_PROCADDRESS(libvulkan, vkInvalidateMappedMemoryRanges); vkGetDeviceMemoryCommitment = GET_PROCADDRESS(libvulkan, vkGetDeviceMemoryCommitment); vkBindBufferMemory = GET_PROCADDRESS(libvulkan, vkBindBufferMemory); vkBindImageMemory = GET_PROCADDRESS(libvulkan, vkBindImageMemory); vkGetBufferMemoryRequirements = GET_PROCADDRESS(libvulkan, vkGetBufferMemoryRequirements); vkGetImageMemoryRequirements = GET_PROCADDRESS(libvulkan, vkGetImageMemoryRequirements); vkGetImageSparseMemoryRequirements = GET_PROCADDRESS(libvulkan, vkGetImageSparseMemoryRequirements); vkGetPhysicalDeviceSparseImageFormatProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSparseImageFormatProperties); vkQueueBindSparse = GET_PROCADDRESS(libvulkan, vkQueueBindSparse); vkCreateFence = GET_PROCADDRESS(libvulkan, vkCreateFence); vkDestroyFence = GET_PROCADDRESS(libvulkan, vkDestroyFence); vkResetFences = GET_PROCADDRESS(libvulkan, vkResetFences); vkGetFenceStatus = GET_PROCADDRESS(libvulkan, vkGetFenceStatus); vkWaitForFences = GET_PROCADDRESS(libvulkan, vkWaitForFences); vkCreateSemaphore = GET_PROCADDRESS(libvulkan, vkCreateSemaphore); vkDestroySemaphore = GET_PROCADDRESS(libvulkan, vkDestroySemaphore); vkCreateEvent = GET_PROCADDRESS(libvulkan, vkCreateEvent); vkDestroyEvent = GET_PROCADDRESS(libvulkan, vkDestroyEvent); vkGetEventStatus = GET_PROCADDRESS(libvulkan, vkGetEventStatus); vkSetEvent = GET_PROCADDRESS(libvulkan, vkSetEvent); vkResetEvent = GET_PROCADDRESS(libvulkan, vkResetEvent); vkCreateQueryPool = GET_PROCADDRESS(libvulkan, vkCreateQueryPool); vkDestroyQueryPool = GET_PROCADDRESS(libvulkan, vkDestroyQueryPool); vkGetQueryPoolResults = GET_PROCADDRESS(libvulkan, vkGetQueryPoolResults); vkCreateBuffer = GET_PROCADDRESS(libvulkan, vkCreateBuffer); vkDestroyBuffer = GET_PROCADDRESS(libvulkan, vkDestroyBuffer); vkCreateBufferView = GET_PROCADDRESS(libvulkan, vkCreateBufferView); vkDestroyBufferView = GET_PROCADDRESS(libvulkan, vkDestroyBufferView); vkCreateImage = GET_PROCADDRESS(libvulkan, vkCreateImage); vkDestroyImage = GET_PROCADDRESS(libvulkan, vkDestroyImage); vkGetImageSubresourceLayout = GET_PROCADDRESS(libvulkan, vkGetImageSubresourceLayout); vkCreateImageView = GET_PROCADDRESS(libvulkan, vkCreateImageView); vkDestroyImageView = GET_PROCADDRESS(libvulkan, vkDestroyImageView); vkCreateShaderModule = GET_PROCADDRESS(libvulkan, vkCreateShaderModule); vkDestroyShaderModule = GET_PROCADDRESS(libvulkan, vkDestroyShaderModule); vkCreatePipelineCache = GET_PROCADDRESS(libvulkan, vkCreatePipelineCache); vkDestroyPipelineCache = GET_PROCADDRESS(libvulkan, vkDestroyPipelineCache); vkGetPipelineCacheData = GET_PROCADDRESS(libvulkan, vkGetPipelineCacheData); vkMergePipelineCaches = GET_PROCADDRESS(libvulkan, vkMergePipelineCaches); vkCreateGraphicsPipelines = GET_PROCADDRESS(libvulkan, vkCreateGraphicsPipelines); vkCreateComputePipelines = GET_PROCADDRESS(libvulkan, vkCreateComputePipelines); vkDestroyPipeline = GET_PROCADDRESS(libvulkan, vkDestroyPipeline); vkCreatePipelineLayout = GET_PROCADDRESS(libvulkan, vkCreatePipelineLayout); vkDestroyPipelineLayout = GET_PROCADDRESS(libvulkan, vkDestroyPipelineLayout); vkCreateSampler = GET_PROCADDRESS(libvulkan, vkCreateSampler); vkDestroySampler = GET_PROCADDRESS(libvulkan, vkDestroySampler); vkCreateDescriptorSetLayout = GET_PROCADDRESS(libvulkan, vkCreateDescriptorSetLayout); vkDestroyDescriptorSetLayout = GET_PROCADDRESS(libvulkan, vkDestroyDescriptorSetLayout); vkCreateDescriptorPool = GET_PROCADDRESS(libvulkan, vkCreateDescriptorPool); vkDestroyDescriptorPool = GET_PROCADDRESS(libvulkan, vkDestroyDescriptorPool); vkResetDescriptorPool = GET_PROCADDRESS(libvulkan, vkResetDescriptorPool); vkAllocateDescriptorSets = GET_PROCADDRESS(libvulkan, vkAllocateDescriptorSets); vkFreeDescriptorSets = GET_PROCADDRESS(libvulkan, vkFreeDescriptorSets); vkUpdateDescriptorSets = GET_PROCADDRESS(libvulkan, vkUpdateDescriptorSets); vkCreateFramebuffer = GET_PROCADDRESS(libvulkan, vkCreateFramebuffer); vkDestroyFramebuffer = GET_PROCADDRESS(libvulkan, vkDestroyFramebuffer); vkCreateRenderPass = GET_PROCADDRESS(libvulkan, vkCreateRenderPass); vkDestroyRenderPass = GET_PROCADDRESS(libvulkan, vkDestroyRenderPass); vkGetRenderAreaGranularity = GET_PROCADDRESS(libvulkan, vkGetRenderAreaGranularity); vkCreateCommandPool = GET_PROCADDRESS(libvulkan, vkCreateCommandPool); vkDestroyCommandPool = GET_PROCADDRESS(libvulkan, vkDestroyCommandPool); vkResetCommandPool = GET_PROCADDRESS(libvulkan, vkResetCommandPool); vkAllocateCommandBuffers = GET_PROCADDRESS(libvulkan, vkAllocateCommandBuffers); vkFreeCommandBuffers = GET_PROCADDRESS(libvulkan, vkFreeCommandBuffers); vkBeginCommandBuffer = GET_PROCADDRESS(libvulkan, vkBeginCommandBuffer); vkEndCommandBuffer = GET_PROCADDRESS(libvulkan, vkEndCommandBuffer); vkResetCommandBuffer = GET_PROCADDRESS(libvulkan, vkResetCommandBuffer); vkCmdBindPipeline = GET_PROCADDRESS(libvulkan, vkCmdBindPipeline); vkCmdSetViewport = GET_PROCADDRESS(libvulkan, vkCmdSetViewport); vkCmdSetScissor = GET_PROCADDRESS(libvulkan, vkCmdSetScissor); vkCmdSetLineWidth = GET_PROCADDRESS(libvulkan, vkCmdSetLineWidth); vkCmdSetDepthBias = GET_PROCADDRESS(libvulkan, vkCmdSetDepthBias); vkCmdSetBlendConstants = GET_PROCADDRESS(libvulkan, vkCmdSetBlendConstants); vkCmdSetDepthBounds = GET_PROCADDRESS(libvulkan, vkCmdSetDepthBounds); vkCmdSetStencilCompareMask = GET_PROCADDRESS(libvulkan, vkCmdSetStencilCompareMask); vkCmdSetStencilWriteMask = GET_PROCADDRESS(libvulkan, vkCmdSetStencilWriteMask); vkCmdSetStencilReference = GET_PROCADDRESS(libvulkan, vkCmdSetStencilReference); vkCmdBindDescriptorSets = GET_PROCADDRESS(libvulkan, vkCmdBindDescriptorSets); vkCmdBindIndexBuffer = GET_PROCADDRESS(libvulkan, vkCmdBindIndexBuffer); vkCmdBindVertexBuffers = GET_PROCADDRESS(libvulkan, vkCmdBindVertexBuffers); vkCmdDraw = GET_PROCADDRESS(libvulkan, vkCmdDraw); vkCmdDrawIndexed = GET_PROCADDRESS(libvulkan, vkCmdDrawIndexed); vkCmdDrawIndirect = GET_PROCADDRESS(libvulkan, vkCmdDrawIndirect); vkCmdDrawIndexedIndirect = GET_PROCADDRESS(libvulkan, vkCmdDrawIndexedIndirect); vkCmdDispatch = GET_PROCADDRESS(libvulkan, vkCmdDispatch); vkCmdDispatchIndirect = GET_PROCADDRESS(libvulkan, vkCmdDispatchIndirect); vkCmdCopyBuffer = GET_PROCADDRESS(libvulkan, vkCmdCopyBuffer); vkCmdCopyImage = GET_PROCADDRESS(libvulkan, vkCmdCopyImage); vkCmdBlitImage = GET_PROCADDRESS(libvulkan, vkCmdBlitImage); vkCmdCopyBufferToImage = GET_PROCADDRESS(libvulkan, vkCmdCopyBufferToImage); vkCmdCopyImageToBuffer = GET_PROCADDRESS(libvulkan, vkCmdCopyImageToBuffer); vkCmdUpdateBuffer = GET_PROCADDRESS(libvulkan, vkCmdUpdateBuffer); vkCmdFillBuffer = GET_PROCADDRESS(libvulkan, vkCmdFillBuffer); vkCmdClearColorImage = GET_PROCADDRESS(libvulkan, vkCmdClearColorImage); vkCmdClearDepthStencilImage = GET_PROCADDRESS(libvulkan, vkCmdClearDepthStencilImage); vkCmdClearAttachments = GET_PROCADDRESS(libvulkan, vkCmdClearAttachments); vkCmdResolveImage = GET_PROCADDRESS(libvulkan, vkCmdResolveImage); vkCmdSetEvent = GET_PROCADDRESS(libvulkan, vkCmdSetEvent); vkCmdResetEvent = GET_PROCADDRESS(libvulkan, vkCmdResetEvent); vkCmdWaitEvents = GET_PROCADDRESS(libvulkan, vkCmdWaitEvents); vkCmdPipelineBarrier = GET_PROCADDRESS(libvulkan, vkCmdPipelineBarrier); vkCmdBeginQuery = GET_PROCADDRESS(libvulkan, vkCmdBeginQuery); vkCmdEndQuery = GET_PROCADDRESS(libvulkan, vkCmdEndQuery); vkCmdResetQueryPool = GET_PROCADDRESS(libvulkan, vkCmdResetQueryPool); vkCmdWriteTimestamp = GET_PROCADDRESS(libvulkan, vkCmdWriteTimestamp); vkCmdCopyQueryPoolResults = GET_PROCADDRESS(libvulkan, vkCmdCopyQueryPoolResults); vkCmdPushConstants = GET_PROCADDRESS(libvulkan, vkCmdPushConstants); vkCmdBeginRenderPass = GET_PROCADDRESS(libvulkan, vkCmdBeginRenderPass); vkCmdNextSubpass = GET_PROCADDRESS(libvulkan, vkCmdNextSubpass); vkCmdEndRenderPass = GET_PROCADDRESS(libvulkan, vkCmdEndRenderPass); vkCmdExecuteCommands = GET_PROCADDRESS(libvulkan, vkCmdExecuteCommands); vkDestroySurfaceKHR = GET_PROCADDRESS(libvulkan, vkDestroySurfaceKHR); vkGetPhysicalDeviceSurfaceSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSurfaceSupportKHR); vkGetPhysicalDeviceSurfaceCapabilitiesKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSurfaceCapabilitiesKHR); vkGetPhysicalDeviceSurfaceFormatsKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSurfaceFormatsKHR); vkGetPhysicalDeviceSurfacePresentModesKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSurfacePresentModesKHR); vkCreateSwapchainKHR = GET_PROCADDRESS(libvulkan, vkCreateSwapchainKHR); vkDestroySwapchainKHR = GET_PROCADDRESS(libvulkan, vkDestroySwapchainKHR); vkGetSwapchainImagesKHR = GET_PROCADDRESS(libvulkan, vkGetSwapchainImagesKHR); vkAcquireNextImageKHR = GET_PROCADDRESS(libvulkan, vkAcquireNextImageKHR); vkQueuePresentKHR = GET_PROCADDRESS(libvulkan, vkQueuePresentKHR); vkGetPhysicalDeviceDisplayPropertiesKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceDisplayPropertiesKHR); vkGetPhysicalDeviceDisplayPlanePropertiesKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceDisplayPlanePropertiesKHR); vkGetDisplayPlaneSupportedDisplaysKHR = GET_PROCADDRESS(libvulkan, vkGetDisplayPlaneSupportedDisplaysKHR); vkGetDisplayModePropertiesKHR = GET_PROCADDRESS(libvulkan, vkGetDisplayModePropertiesKHR); vkCreateDisplayModeKHR = GET_PROCADDRESS(libvulkan, vkCreateDisplayModeKHR); vkGetDisplayPlaneCapabilitiesKHR = GET_PROCADDRESS(libvulkan, vkGetDisplayPlaneCapabilitiesKHR); vkCreateDisplayPlaneSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateDisplayPlaneSurfaceKHR); vkCreateSharedSwapchainsKHR = GET_PROCADDRESS(libvulkan, vkCreateSharedSwapchainsKHR); #ifdef VK_USE_PLATFORM_XLIB_KHR vkCreateXlibSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateXlibSurfaceKHR); vkGetPhysicalDeviceXlibPresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceXlibPresentationSupportKHR); #endif #ifdef VK_USE_PLATFORM_XCB_KHR vkCreateXcbSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateXcbSurfaceKHR); vkGetPhysicalDeviceXcbPresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceXcbPresentationSupportKHR); #endif #ifdef VK_USE_PLATFORM_WAYLAND_KHR vkCreateWaylandSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateWaylandSurfaceKHR); vkGetPhysicalDeviceWaylandPresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceWaylandPresentationSupportKHR); #endif #ifdef VK_USE_PLATFORM_MIR_KHR vkCreateMirSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateMirSurfaceKHR); vkGetPhysicalDeviceMirPresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceMirPresentationSupportKHR); #endif #ifdef VK_USE_PLATFORM_ANDROID_KHR vkCreateAndroidSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateAndroidSurfaceKHR); #endif #ifdef VK_USE_PLATFORM_WIN32_KHR vkCreateWin32SurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateWin32SurfaceKHR); vkGetPhysicalDeviceWin32PresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceWin32PresentationSupportKHR); #endif #ifdef USE_DEBUG_EXTENTIONS vkCreateDebugReportCallbackEXT = GET_PROCADDRESS(libvulkan, vkCreateDebugReportCallbackEXT); vkDestroyDebugReportCallbackEXT = GET_PROCADDRESS(libvulkan, vkDestroyDebugReportCallbackEXT); vkDebugReportMessageEXT = GET_PROCADDRESS(libvulkan, vkDebugReportMessageEXT); #endif #endif return true; } } #if SF_VULKAN_DYNAMIC_LIBRARY // No Vulkan support, do not set function addresses PFN_vkCreateInstance vkCreateInstance = nullptr; PFN_vkDestroyInstance vkDestroyInstance = nullptr; PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices = nullptr; PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures = nullptr; PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties = nullptr; PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties = nullptr; PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties = nullptr; PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties = nullptr; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = nullptr; PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr = nullptr; PFN_vkCreateDevice vkCreateDevice = nullptr; PFN_vkDestroyDevice vkDestroyDevice = nullptr; PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties = nullptr; PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties = nullptr; PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties = nullptr; PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties = nullptr; PFN_vkGetDeviceQueue vkGetDeviceQueue = nullptr; PFN_vkQueueSubmit vkQueueSubmit = nullptr; PFN_vkQueueWaitIdle vkQueueWaitIdle = nullptr; PFN_vkDeviceWaitIdle vkDeviceWaitIdle = nullptr; PFN_vkAllocateMemory vkAllocateMemory = nullptr; PFN_vkFreeMemory vkFreeMemory = nullptr; PFN_vkMapMemory vkMapMemory = nullptr; PFN_vkUnmapMemory vkUnmapMemory = nullptr; PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges = nullptr; PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges = nullptr; PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment = nullptr; PFN_vkBindBufferMemory vkBindBufferMemory = nullptr; PFN_vkBindImageMemory vkBindImageMemory = nullptr; PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements = nullptr; PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements = nullptr; PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements = nullptr; PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties = nullptr; PFN_vkQueueBindSparse vkQueueBindSparse = nullptr; PFN_vkCreateFence vkCreateFence = nullptr; PFN_vkDestroyFence vkDestroyFence = nullptr; PFN_vkResetFences vkResetFences = nullptr; PFN_vkGetFenceStatus vkGetFenceStatus = nullptr; PFN_vkWaitForFences vkWaitForFences = nullptr; PFN_vkCreateSemaphore vkCreateSemaphore = nullptr; PFN_vkDestroySemaphore vkDestroySemaphore = nullptr; PFN_vkCreateEvent vkCreateEvent = nullptr; PFN_vkDestroyEvent vkDestroyEvent = nullptr; PFN_vkGetEventStatus vkGetEventStatus = nullptr; PFN_vkSetEvent vkSetEvent = nullptr; PFN_vkResetEvent vkResetEvent = nullptr; PFN_vkCreateQueryPool vkCreateQueryPool = nullptr; PFN_vkDestroyQueryPool vkDestroyQueryPool = nullptr; PFN_vkGetQueryPoolResults vkGetQueryPoolResults = nullptr; PFN_vkCreateBuffer vkCreateBuffer = nullptr; PFN_vkDestroyBuffer vkDestroyBuffer = nullptr; PFN_vkCreateBufferView vkCreateBufferView = nullptr; PFN_vkDestroyBufferView vkDestroyBufferView = nullptr; PFN_vkCreateImage vkCreateImage = nullptr; PFN_vkDestroyImage vkDestroyImage = nullptr; PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout = nullptr; PFN_vkCreateImageView vkCreateImageView = nullptr; PFN_vkDestroyImageView vkDestroyImageView = nullptr; PFN_vkCreateShaderModule vkCreateShaderModule = nullptr; PFN_vkDestroyShaderModule vkDestroyShaderModule = nullptr; PFN_vkCreatePipelineCache vkCreatePipelineCache = nullptr; PFN_vkDestroyPipelineCache vkDestroyPipelineCache = nullptr; PFN_vkGetPipelineCacheData vkGetPipelineCacheData = nullptr; PFN_vkMergePipelineCaches vkMergePipelineCaches = nullptr; PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines = nullptr; PFN_vkCreateComputePipelines vkCreateComputePipelines = nullptr; PFN_vkDestroyPipeline vkDestroyPipeline = nullptr; PFN_vkCreatePipelineLayout vkCreatePipelineLayout = nullptr; PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout = nullptr; PFN_vkCreateSampler vkCreateSampler = nullptr; PFN_vkDestroySampler vkDestroySampler = nullptr; PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout = nullptr; PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout = nullptr; PFN_vkCreateDescriptorPool vkCreateDescriptorPool = nullptr; PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool = nullptr; PFN_vkResetDescriptorPool vkResetDescriptorPool = nullptr; PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets = nullptr; PFN_vkFreeDescriptorSets vkFreeDescriptorSets = nullptr; PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets = nullptr; PFN_vkCreateFramebuffer vkCreateFramebuffer = nullptr; PFN_vkDestroyFramebuffer vkDestroyFramebuffer = nullptr; PFN_vkCreateRenderPass vkCreateRenderPass = nullptr; PFN_vkDestroyRenderPass vkDestroyRenderPass = nullptr; PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity = nullptr; PFN_vkCreateCommandPool vkCreateCommandPool = nullptr; PFN_vkDestroyCommandPool vkDestroyCommandPool = nullptr; PFN_vkResetCommandPool vkResetCommandPool = nullptr; PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers = nullptr; PFN_vkFreeCommandBuffers vkFreeCommandBuffers = nullptr; PFN_vkBeginCommandBuffer vkBeginCommandBuffer = nullptr; PFN_vkEndCommandBuffer vkEndCommandBuffer = nullptr; PFN_vkResetCommandBuffer vkResetCommandBuffer = nullptr; PFN_vkCmdBindPipeline vkCmdBindPipeline = nullptr; PFN_vkCmdSetViewport vkCmdSetViewport = nullptr; PFN_vkCmdSetScissor vkCmdSetScissor = nullptr; PFN_vkCmdSetLineWidth vkCmdSetLineWidth = nullptr; PFN_vkCmdSetDepthBias vkCmdSetDepthBias = nullptr; PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants = nullptr; PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds = nullptr; PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask = nullptr; PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask = nullptr; PFN_vkCmdSetStencilReference vkCmdSetStencilReference = nullptr; PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets = nullptr; PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer = nullptr; PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers = nullptr; PFN_vkCmdDraw vkCmdDraw = nullptr; PFN_vkCmdDrawIndexed vkCmdDrawIndexed = nullptr; PFN_vkCmdDrawIndirect vkCmdDrawIndirect = nullptr; PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect = nullptr; PFN_vkCmdDispatch vkCmdDispatch = nullptr; PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect = nullptr; PFN_vkCmdCopyBuffer vkCmdCopyBuffer = nullptr; PFN_vkCmdCopyImage vkCmdCopyImage = nullptr; PFN_vkCmdBlitImage vkCmdBlitImage = nullptr; PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage = nullptr; PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer = nullptr; PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer = nullptr; PFN_vkCmdFillBuffer vkCmdFillBuffer = nullptr; PFN_vkCmdClearColorImage vkCmdClearColorImage = nullptr; PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage = nullptr; PFN_vkCmdClearAttachments vkCmdClearAttachments = nullptr; PFN_vkCmdResolveImage vkCmdResolveImage = nullptr; PFN_vkCmdSetEvent vkCmdSetEvent = nullptr; PFN_vkCmdResetEvent vkCmdResetEvent = nullptr; PFN_vkCmdWaitEvents vkCmdWaitEvents = nullptr; PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier = nullptr; PFN_vkCmdBeginQuery vkCmdBeginQuery = nullptr; PFN_vkCmdEndQuery vkCmdEndQuery = nullptr; PFN_vkCmdResetQueryPool vkCmdResetQueryPool = nullptr; PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp = nullptr; PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults = nullptr; PFN_vkCmdPushConstants vkCmdPushConstants = nullptr; PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass = nullptr; PFN_vkCmdNextSubpass vkCmdNextSubpass = nullptr; PFN_vkCmdEndRenderPass vkCmdEndRenderPass = nullptr; PFN_vkCmdExecuteCommands vkCmdExecuteCommands = nullptr; PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR = nullptr; PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR = nullptr; PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr; PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR = nullptr; PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR = nullptr; PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR = nullptr; PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR = nullptr; PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR = nullptr; PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR = nullptr; PFN_vkQueuePresentKHR vkQueuePresentKHR = nullptr; PFN_vkGetPhysicalDeviceDisplayPropertiesKHR vkGetPhysicalDeviceDisplayPropertiesKHR = nullptr; PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR vkGetPhysicalDeviceDisplayPlanePropertiesKHR = nullptr; PFN_vkGetDisplayPlaneSupportedDisplaysKHR vkGetDisplayPlaneSupportedDisplaysKHR = nullptr; PFN_vkGetDisplayModePropertiesKHR vkGetDisplayModePropertiesKHR = nullptr; PFN_vkCreateDisplayModeKHR vkCreateDisplayModeKHR = nullptr; PFN_vkGetDisplayPlaneCapabilitiesKHR vkGetDisplayPlaneCapabilitiesKHR = nullptr; PFN_vkCreateDisplayPlaneSurfaceKHR vkCreateDisplayPlaneSurfaceKHR = nullptr; PFN_vkCreateSharedSwapchainsKHR vkCreateSharedSwapchainsKHR = nullptr; #ifdef VK_USE_PLATFORM_XLIB_KHR PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR = nullptr; PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR vkGetPhysicalDeviceXlibPresentationSupportKHR = nullptr; #endif #ifdef VK_USE_PLATFORM_XCB_KHR PFN_vkCreateXcbSurfaceKHR vkCreateXcbSurfaceKHR = nullptr; PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR vkGetPhysicalDeviceXcbPresentationSupportKHR = nullptr; #endif #ifdef VK_USE_PLATFORM_WAYLAND_KHR PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR = nullptr; PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR vkGetPhysicalDeviceWaylandPresentationSupportKHR = nullptr; #endif #ifdef VK_USE_PLATFORM_MIR_KHR PFN_vkCreateMirSurfaceKHR vkCreateMirSurfaceKHR = nullptr; PFN_vkGetPhysicalDeviceMirPresentationSupportKHR vkGetPhysicalDeviceMirPresentationSupportKHR = nullptr; #endif #ifdef VK_USE_PLATFORM_ANDROID_KHR PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR = nullptr; #endif #ifdef VK_USE_PLATFORM_WIN32_KHR PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR = nullptr; PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR vkGetPhysicalDeviceWin32PresentationSupportKHR = nullptr; #endif PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT = nullptr; PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT = nullptr; PFN_vkDebugReportMessageEXT vkDebugReportMessageEXT = nullptr; #endif #endif // #if HAVE_VULKAN
57.881319
131
0.851306
blue3k
0dd1418522f97a08080e378c45d316b27f9933c8
2,610
cpp
C++
src/qt/orphandownloader.cpp
Mart1250/biblepay
d53d04f74242596b104d360187268a50b845b82e
[ "MIT" ]
null
null
null
src/qt/orphandownloader.cpp
Mart1250/biblepay
d53d04f74242596b104d360187268a50b845b82e
[ "MIT" ]
null
null
null
src/qt/orphandownloader.cpp
Mart1250/biblepay
d53d04f74242596b104d360187268a50b845b82e
[ "MIT" ]
null
null
null
#include "orphandownloader.h" #include <univalue.h> #include "rpcipfs.h" #include "guiutil.h" #include "rpcpog.h" #include "timedata.h" #include <QUrl> #include <boost/algorithm/string/case_conv.hpp> #include <QDir> #include <QTimer> #include <QString> OrphanDownloader::OrphanDownloader(QString xURL, QString xDestName, int xTimeout) : sURL(xURL), sDestName(xDestName), iTimeout(xTimeout) { } void OrphanDownloader::Get() { if (sURL == "" || sDestName == "") return; int64_t nFileSize = GetFileSize(GUIUtil::FROMQS(sDestName)); bDownloadFinished = false; if (nFileSize > 0) { return; } // We must call out using an HTTPS request here - to pull down the Orphan's picture locally (otherwise QT won't display the image) manager = new QNetworkAccessManager; QNetworkRequest request; request.setUrl(QUrl(sURL)); reply = manager->get(request); file = new QFile; file->setFileName(sDestName); file->open(QIODevice::WriteOnly); connect(reply,SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(onDownloadProgress(qint64,qint64))); connect(reply,SIGNAL(readyRead()), this, SLOT(onReadyRead())); connect(reply,SIGNAL(finished()), this, SLOT(onReplyFinished())); connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*))); QTimer::singleShot(iTimeout, this, SLOT(DownloadFailure())); } void OrphanDownloader::BusyWait() { int iBroken = 0; while (1==1) { int64_t nFileSize = GetFileSize(GUIUtil::FROMQS(sDestName)); if (nFileSize > 0 || bDownloadFinished) break; MilliSleep(250); iBroken++; if (iBroken > (iTimeout/500)) break; } } void OrphanDownloader::DownloadFailure() { LogPrintf("Download failed\n"); bDownloadFinished = true; } void OrphanDownloader::onDownloadProgress(qint64 bytesRead,qint64 bytesTotal) { printf("OnDownloadProgress %f ", (double)bytesRead); } void OrphanDownloader::onFinished(QNetworkReply * reply) { switch(reply->error()) { case QNetworkReply::NoError: { printf(" \n Downloaded successfully. "); } break; default: { printf(" BioDownloadError %s ", GUIUtil::FROMQS(reply->errorString()).c_str()); }; } if(file->isOpen()) { file->close(); file->deleteLater(); } bDownloadFinished = true; } void OrphanDownloader::onReadyRead() { file->write(reply->readAll()); } void OrphanDownloader::onReplyFinished() { if(file->isOpen()) { file->close(); file->deleteLater(); } } OrphanDownloader::~OrphanDownloader() { // Note - there is no UI to delete }
23.097345
136
0.67931
Mart1250
0dd1f5ec98aef716956bd127f9d70e50b8adfc43
1,254
hpp
C++
ufora/core/UnitTest.hpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
ufora/core/UnitTest.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
ufora/core/UnitTest.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2015 Ufora 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 "Platform.hpp" #ifdef BSA_PLATFORM_WINDOWS #define BOOST_TEST_DYN_LINK #endif #include <boost/test/unit_test.hpp> #define BOOST_TEST_USE_CPPML_PRINTER( T ) \ namespace boost { namespace test_tools { \ template<> \ struct print_log_value<T> { \ void operator()( std::ostream& os, T const& t ) \ { \ os << prettyPrintString(t); \ } \ }; \ }} // End of macro.
35.828571
77
0.555821
ufora
0dd7bc5f047c985bf90a901d7f732c8482e23cff
1,204
cpp
C++
pc_code/Serial/SerialTestMFC/AboutDlg.cpp
johnenrickplenos/water_level_monitoring
3e0628daea5eb1caba1fb69efdd2691590ce6c32
[ "MIT" ]
null
null
null
pc_code/Serial/SerialTestMFC/AboutDlg.cpp
johnenrickplenos/water_level_monitoring
3e0628daea5eb1caba1fb69efdd2691590ce6c32
[ "MIT" ]
null
null
null
pc_code/Serial/SerialTestMFC/AboutDlg.cpp
johnenrickplenos/water_level_monitoring
3e0628daea5eb1caba1fb69efdd2691590ce6c32
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "SerialTestMFC.h" #include "AboutDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAboutDlg methods CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BOOL CAboutDlg::OnInitDialog() { // Call base class CDialog::OnInitDialog(); LOGFONT logFont = {0}; logFont.lfCharSet = DEFAULT_CHARSET; logFont.lfHeight = 24; logFont.lfWeight = FW_BOLD; lstrcpy(logFont.lfFaceName, _T("Arial")); HFONT hFont = ::CreateFontIndirect(&logFont); SendDlgItemMessage(IDC_ABOUT_TITLE, WM_SETFONT, LPARAM(hFont), FALSE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
21.122807
77
0.63206
johnenrickplenos
0dd8861e56ff759a80a345bc27736ff4ef253114
2,796
hpp
C++
include/musycl/midi/midi_out.hpp
keryell/muSYCL
130e4b29c3a4daf4c908b08263b53910acb13787
[ "Apache-2.0" ]
16
2021-05-07T11:33:59.000Z
2022-03-05T02:36:06.000Z
include/musycl/midi/midi_out.hpp
keryell/muSYCL
130e4b29c3a4daf4c908b08263b53910acb13787
[ "Apache-2.0" ]
null
null
null
include/musycl/midi/midi_out.hpp
keryell/muSYCL
130e4b29c3a4daf4c908b08263b53910acb13787
[ "Apache-2.0" ]
null
null
null
#ifndef MUSYCL_MIDI_MIDI_OUT_HPP #define MUSYCL_MIDI_MIDI_OUT_HPP /** \file SYCL abstraction for a MIDI output pipe Based on RtMidi library. */ #include <cstdlib> #include <functional> #include <iostream> #include <memory> #include <string> #include <vector> #include "rtmidi/RtMidi.h" #include "musycl/midi.hpp" namespace musycl { // To use time unit literals directly using namespace std::chrono_literals; /** A MIDI output interface exposed as a SYCL pipe. In SYCL the type is used to synthesize the connection between kernels, so there can be only 1 instance of a MIDI input interface. */ class midi_out { /** The handlers to control the MIDI output interfaces Use a pointer because RtMidiOut is a broken type and is neither copyable nor movable */ static inline std::vector<std::unique_ptr<RtMidiOut>> interfaces; /// Check for RtMidi errors static auto constexpr check_error = [] (auto&& function) { try { return function(); } catch (const RtMidiError &error) { error.printMessage(); std::exit(EXIT_FAILURE); } }; public: /// Open all the IMID input ports available void open(const std::string& application_name, const std::string& port_name, RtMidi::Api backend) { std::cout << "RtMidi version " << RtMidi::getVersion() << std::endl; // Create a throwable MIDI output just to get later the number of port auto midi_out = check_error([&] { return RtMidiOut { backend, "muSYCLtest" }; }); auto n_out_ports = midi_out.getPortCount(); std::cout << "\nThere are " << n_out_ports << " MIDI output ports available." << std::endl;; for (auto i = 0; i < n_out_ports; ++i) { interfaces.push_back(check_error([&] { return std::make_unique<RtMidiOut>(backend, application_name); })); auto port_name = check_error([&] { return midi_out.getPortName(i); }); std::cout << " Output Port #" << i << ": " << port_name << std::endl; // Open the port and give it a fancy name check_error([&] { interfaces[i]->openPort(i, port_name); }); } } /// The sycl::pipe::write-like interface to write a MIDI message static void write(const std::vector<std::uint8_t>& v) { #if 0 for (int e : v) std::cout << std::hex << e << ' '; std::cout << std::endl; for (int e : v) std::cout << std::dec << e << ' '; std::cout << std::endl; #endif // Hard-code now for KeyLab Essential interfaces[1]->sendMessage(&v); } /// The non-blocking sycl::pipe::write-like interface to write a MIDI message static void try_write(const std::vector<std::uint8_t>& v) { write(v); } }; } #endif // MUSYCL_MIDI_MIDI_OUT_HPP
27.145631
79
0.628755
keryell
0ddfb804bf0e44a86e59569681b9e4f64d988f9e
13,615
cpp
C++
ObjGroupTree.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
1
2020-07-19T10:19:18.000Z
2020-07-19T10:19:18.000Z
ObjGroupTree.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
null
null
null
ObjGroupTree.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // ObjGroupTree.cpp /////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Joe Riedel // 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 <ORGANIZATION> nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Tread.h" #include "ObjGroupTree.h" #include "System.h" #include "TreadDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define EYE_ICON 3 #define BLANK_ICON 2 ///////////////////////////////////////////////////////////////////////////// // CObjGroupTree CObjGroupTree::CObjGroupTree() { m_pDoc = 0; } CObjGroupTree::~CObjGroupTree() { } void CObjGroupTree::ShowGroup( CObjectGroup* obj ) { if( obj->GetTreeItem() ) { EnsureVisible( obj->GetTreeItem() ); Expand( obj->GetTreeItem(), TVE_COLLAPSE ); } } void CObjGroupTree::SetDoc( CTreadDoc* pDoc ) { m_pDoc = pDoc; } void CObjGroupTree::SelectItemUID( int uid ) { HTREEITEM item = FindItemByUID( uid, TVI_ROOT ); if( item ) { //Select( item, TVGN_CARET|TVGN_FIRSTVISIBLE ); SelectItem( item ); //if( GetChildItem( item ) != 0 ) // Expand( item, TVE_EXPAND ); } } int CObjGroupTree::AddObjectProc( CMapObject* obj, void* p, void* p2 ) { if( !obj->CanAddToTree() ) return 0; CObjGroupTree* tree = (CObjGroupTree*)p; HTREEITEM item; int icon; item = 0; // // find the parent? // if( obj->GetGroupUID() != -1 ) { CObjectGroup* gr = tree->m_pDoc->GroupForUID( obj->GetGroupUID() ); if( gr ) item = gr->GetTreeItem(); } if( !item ) item = tree->m_pRoot; icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON; item = tree->InsertItem( obj->GetName(), icon, icon, item ); tree->SetItemData( item, obj->GetUID() ); obj->SetTreeItem( item ); return 0; } int CObjGroupTree::ClearObjectTreeItemProc( CMapObject* obj, void* p, void* p2 ) { obj->SetTreeItem( 0 ); return 0; } int CObjGroupTree::ClearGroupTreeItemProc( CObjectGroup* gr, void* p, void* p2 ) { gr->SetTreeItem( 0 ); return 0; } void CObjGroupTree::AddObject( CMapObject* obj ) { HTREEITEM item; int icon; item = 0; // // find the parent? // if( obj->GetGroupUID() != -1 ) { CObjectGroup* gr = m_pDoc->GroupForUID( obj->GetGroupUID() ); if( gr ) item = gr->GetTreeItem(); } if( !item ) item = m_pRoot; icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON; item = InsertItem( obj->GetName(), icon, icon, item ); SetItemData( item, obj->GetUID() ); obj->SetTreeItem( item ); //Expand( m_pRoot, TVE_EXPAND ); SelectSetFirstVisible( item ); } void CObjGroupTree::RemoveObject( CMapObject* obj ) { if( obj->GetTreeItem() ) { DeleteItem( obj->GetTreeItem() ); obj->SetTreeItem( 0 ); } } void CObjGroupTree::AddGroup( CObjectGroup* gr ) { HTREEITEM item; int icon; icon = (gr->IsVisible())?EYE_ICON:BLANK_ICON; item = InsertItem( gr->GetName(), icon, icon, m_pRoot ); SetItemData( item, gr->GetUID() ); gr->SetTreeItem( item ); Expand( item, TVE_COLLAPSE ); } void CObjGroupTree::RemoveGroup( CObjectGroup* gr ) { if( gr->GetTreeItem() ) { DeleteItem( gr->GetTreeItem() ); gr->SetTreeItem( 0 ); } } void CObjGroupTree::ObjectStateChange( CMapObject* obj ) { if( !obj->GetTreeItem() ) return; int icon; icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON; SetItemImage( obj->GetTreeItem(), icon, icon ); SetItemText( obj->GetTreeItem(), obj->GetName() ); } void CObjGroupTree::GroupStateChange( CObjectGroup* obj ) { if( !obj->GetTreeItem() ) return; int icon; icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON; SetItemImage( obj->GetTreeItem(), icon, icon ); SetItemText( obj->GetTreeItem(), obj->GetName() ); } void CObjGroupTree::BuildTree() { DeleteItem( TVI_ROOT ); // // create the root. // m_pRoot = InsertItem( "Objects/Groups", 4, 4 ); // // clear all objects. // m_pDoc->GetObjectGroupList()->WalkList( ClearGroupTreeItemProc ); m_pDoc->GetObjectList()->WalkList( ClearObjectTreeItemProc ); m_pDoc->GetSelectedObjectList()->WalkList( ClearObjectTreeItemProc ); // // add all groups. // int icon; HTREEITEM item; CObjectGroup* gr; for( gr = m_pDoc->GetObjectGroupList()->ResetPos(); gr; gr = m_pDoc->GetObjectGroupList()->GetNextItem() ) { icon = (gr->IsVisible())?EYE_ICON:BLANK_ICON; item = InsertItem( gr->GetName(), icon, icon, m_pRoot ); SetItemData( item, gr->GetUID() ); gr->SetTreeItem( item ); } m_pDoc->GetObjectList()->WalkList( AddObjectProc, this ); m_pDoc->GetSelectedObjectList()->WalkList( AddObjectProc, this ); Expand( m_pRoot, TVE_EXPAND ); //SortList( TVI_ROOT ); } HTREEITEM CObjGroupTree::FindItemByUID( int uid, HTREEITEM pRoot ) { HTREEITEM item = GetChildItem( pRoot ); HTREEITEM child; while( item != 0 ) { if( item != m_pRoot && GetItemData( item ) == (DWORD)uid ) return item; child = FindItemByUID( uid, item ); // search children. if( child ) return child; item = GetNextSiblingItem( item ); } return 0; } BEGIN_MESSAGE_MAP(CObjGroupTree, CTreeCtrl) //{{AFX_MSG_MAP(CObjGroupTree) ON_WM_LBUTTONDOWN() ON_NOTIFY_REFLECT(TVN_BEGINLABELEDIT, OnBeginlabeledit) ON_NOTIFY_REFLECT(TVN_ENDLABELEDIT, OnEndlabeledit) ON_WM_LBUTTONDBLCLK() ON_WM_MOUSEMOVE() ON_WM_RBUTTONDOWN() ON_WM_RBUTTONDBLCLK() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CObjGroupTree message handlers void CObjGroupTree::OnBeginlabeledit(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; // TODO: Add your control notification handler code here if( pTVDispInfo->item.hItem == TVI_ROOT || pTVDispInfo->item.hItem == m_pRoot ) { *pResult = 1; return; } *pResult = 0; } void CObjGroupTree::OnEndlabeledit(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; // TODO: Add your control notification handler code here if( pTVDispInfo->item.pszText == 0 || pTVDispInfo->item.pszText[0] == 0 ) return; CString s = pTVDispInfo->item.pszText; HTREEITEM item = pTVDispInfo->item.hItem; int uid = (int)GetItemData( item ); CMapObject* obj = m_pDoc->ObjectForUID( uid ); if( obj ) { obj->SetName( s ); m_pDoc->Prop_UpdateObjectState( obj ); m_pDoc->Prop_UpdateSelection(); } else { CObjectGroup* gr = m_pDoc->GroupForUID( uid ); if( gr ) { gr->SetName( s ); m_pDoc->Prop_UpdateGroupState( gr ); } } *pResult = 0; } void CObjGroupTree::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default // // modify visibility. // TVHITTESTINFO hitTest; hitTest.pt = point; HitTest( &hitTest ); if( hitTest.hItem == TVI_ROOT || hitTest.hItem == m_pRoot || hitTest.hItem == 0 ) return; if( (hitTest.flags&TVHT_ONITEMICON) ) { // // toggle the object. // CMapObject* obj; CObjectGroup* gr; int uid, icon; uid = GetItemData( hitTest.hItem ); obj = m_pDoc->ObjectForUID( uid ); if( obj ) { bool deselect = obj->IsSelected(); if( deselect ) m_pDoc->MakeUndoDeselectAction(); obj->SetVisible( m_pDoc, !obj->IsVisible() ); if( deselect ) obj->Deselect( m_pDoc ); icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON; } else { gr = m_pDoc->GroupForUID( uid ); if( gr ) { gr->SetVisible( m_pDoc, !gr->IsVisible() ); icon = (gr->IsVisible())?EYE_ICON:BLANK_ICON; } } SetItemImage( hitTest.hItem, icon, icon ); m_pDoc->UpdateSelectionInterface(); m_pDoc->Prop_UpdateSelection(); Sys_RedrawWindows(); return; } CTreeCtrl::OnLButtonDown(nFlags, point); } void CObjGroupTree::OnLButtonDblClk(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default // // modify visibility. // TVHITTESTINFO hitTest; hitTest.pt = point; HitTest( &hitTest ); if( hitTest.hItem == TVI_ROOT || hitTest.hItem == m_pRoot || hitTest.hItem == 0 ) return; if( (hitTest.flags&TVHT_ONITEMICON) ) { // // toggle the object. // CMapObject* obj; CObjectGroup* gr; int uid, icon; uid = GetItemData( hitTest.hItem ); obj = m_pDoc->ObjectForUID( uid ); if( obj ) { bool deselect = obj->IsSelected(); if( deselect ) m_pDoc->MakeUndoDeselectAction(); obj->SetVisible( m_pDoc, !obj->IsVisible() ); if( deselect ) obj->Deselect( m_pDoc ); icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON; } else { gr = m_pDoc->GroupForUID( uid ); if( gr ) { gr->SetVisible( m_pDoc, !gr->IsVisible() ); icon = (gr->IsVisible())?EYE_ICON:BLANK_ICON; } } SetItemImage( hitTest.hItem, icon, icon ); m_pDoc->UpdateSelectionInterface(); m_pDoc->Prop_UpdateSelection(); Sys_RedrawWindows(); return; } CTreeCtrl::OnLButtonDblClk(nFlags, point); } void CObjGroupTree::OnMouseMove(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CTreeCtrl::OnMouseMove(nFlags, point); } void CObjGroupTree::DeleteGroup() { HTREEITEM item = GetSelectedItem(); if( !item ) return; int uid = (int)GetItemData( item ); CObjectGroup* gr; gr = m_pDoc->GroupForUID( uid ); if( gr ) { // // orhpan all the objects. // gr->OrphanObjects( m_pDoc ); RemoveGroup( gr ); m_pDoc->GetObjectGroupList()->RemoveItem( gr ); delete gr; } } BOOL CObjGroupTree::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class if( pMsg->message == WM_KEYDOWN ) { // When an item is being edited make sure the edit control // receives certain important key strokes if( GetEditControl() && (pMsg->wParam == VK_RETURN || pMsg->wParam == VK_DELETE || pMsg->wParam == VK_ESCAPE || GetKeyState( VK_CONTROL) ) ) { ::TranslateMessage(pMsg); ::DispatchMessage(pMsg); return TRUE; // DO NOT process further } else if( pMsg->wParam == VK_DELETE ) { DeleteGroup(); return TRUE; } } return CTreeCtrl::PreTranslateMessage(pMsg); } void CObjGroupTree::OnRButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default TVHITTESTINFO hitTest; hitTest.pt = point; HitTest( &hitTest ); if( hitTest.hItem == TVI_ROOT || hitTest.hItem == m_pRoot || hitTest.hItem == 0 ) return; // // select the object/group. // CMapObject* obj; int uid; bool deselect = (nFlags&MS_CONTROL)?false:true; bool jump = (nFlags&MS_SHIFT)?true:false; uid = GetItemData( hitTest.hItem ); obj = m_pDoc->ObjectForUID( uid ); if( obj ) { obj->SetVisible( m_pDoc, true ); m_pDoc->Prop_UpdateObjectState( obj ); bool wassel = obj->IsSelected(); if( deselect ) { m_pDoc->MakeUndoDeselectAction(); m_pDoc->ClearSelection(); } if( wassel && !deselect ) { obj->Deselect( m_pDoc ); } else if( !wassel ) { obj->Select( m_pDoc ); } } else { CObjectGroup* gr = m_pDoc->GroupForUID( uid ); if( gr ) { bool wassel = gr->IsSelected( m_pDoc ); if( deselect ) { m_pDoc->MakeUndoDeselectAction(); m_pDoc->ClearSelection(); } gr->SetVisible( m_pDoc, true ); m_pDoc->Prop_UpdateGroupState( gr ); if( wassel && !deselect ) { gr->DeselectObjects( m_pDoc ); } else if( !wassel ) { gr->SelectObjects( m_pDoc ); } } } m_pDoc->UpdateSelectionInterface(); m_pDoc->Prop_UpdateSelection(); Sys_RedrawWindows(); //Select( hitTest.hItem, TVGN_CARET|TVGN_FIRSTVISIBLE ); SelectItem( hitTest.hItem ); //CTreeCtrl::OnRButtonDown(nFlags, point); } void CObjGroupTree::OnRButtonDblClk(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default OnRButtonDown(nFlags, point); //CTreeCtrl::OnRButtonDblClk(nFlags, point); }
22.541391
107
0.644142
joeriedel
0de65532cb5c29f81f26e0e4af0b35029675c23d
605
cpp
C++
qmessagebox/mainwindow.cpp
orthoWitch/gosha-dudar-qt
6ec073a2bd1e6bd13f9084d84b6340d60753b978
[ "Apache-2.0" ]
null
null
null
qmessagebox/mainwindow.cpp
orthoWitch/gosha-dudar-qt
6ec073a2bd1e6bd13f9084d84b6340d60753b978
[ "Apache-2.0" ]
null
null
null
qmessagebox/mainwindow.cpp
orthoWitch/gosha-dudar-qt
6ec073a2bd1e6bd13f9084d84b6340d60753b978
[ "Apache-2.0" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QMessageBox::StandardButton reply = QMessageBox::question(this, "Заголовок", "Просто текст внутри", QMessageBox::Yes | QMessageBox::No); if(reply == QMessageBox::Yes) { QApplication::quit(); } else { qDebug() << "Кнопка нет была нажата"; } }
20.862069
103
0.636364
orthoWitch
df0438c6e92f5a896f8a86d411d0dd99d5462aff
910
hpp
C++
shared_model/backend/plain/domain.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
shared_model/backend/plain/domain.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
shared_model/backend/plain/domain.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_SHARED_MODEL_PLAIN_DOMAIN_HPP #define IROHA_SHARED_MODEL_PLAIN_DOMAIN_HPP #include "interfaces/common_objects/domain.hpp" #include "interfaces/common_objects/types.hpp" namespace shared_model { namespace plain { class Domain final : public interface::Domain { public: Domain(const interface::types::DomainIdType &domain_id, const interface::types::RoleIdType &default_role_id); const interface::types::DomainIdType &domainId() const override; const interface::types::RoleIdType &defaultRole() const override; private: const interface::types::DomainIdType domain_id_; const interface::types::RoleIdType default_role_id_; }; } // namespace plain } // namespace shared_model #endif // IROHA_SHARED_MODEL_PLAIN_DOMAIN_HPP
27.575758
71
0.737363
akshatkarani
df06417639a31e1dfee729a0b26871250a217391
856
cc
C++
type_traits/remove_cvref.cc
pycpp/stl-test
cbae1e77a16c102715c1c0c64ba3f929f78aadef
[ "MIT" ]
null
null
null
type_traits/remove_cvref.cc
pycpp/stl-test
cbae1e77a16c102715c1c0c64ba3f929f78aadef
[ "MIT" ]
null
null
null
type_traits/remove_cvref.cc
pycpp/stl-test
cbae1e77a16c102715c1c0c64ba3f929f78aadef
[ "MIT" ]
null
null
null
// :copyright: (c) 2017-2018 Alex Huszagh. // :license: MIT, see LICENSE.md for more details. /* * \addtogroup Tests * \brief `remove_cvref` unittests. */ #include <pycpp/stl/type_traits/remove_cvref.h> #include <gtest/gtest.h> PYCPP_USING_NAMESPACE // TESTS // ----- TEST(remove_cvref, remove_cvref) { static_assert(std::is_same<typename remove_cvref<int>::type, int>::value, ""); static_assert(std::is_same<remove_cvref_t<int>, int>::value, ""); static_assert(std::is_same<remove_cvref_t<int&>, int>::value, ""); static_assert(std::is_same<remove_cvref_t<const int&>, int>::value, ""); static_assert(std::is_same<remove_cvref_t<volatile int&>, int>::value, ""); static_assert(std::is_same<remove_cvref_t<const volatile int&>, int>::value, ""); static_assert(!std::is_same<remove_cvref_t<float>, int>::value, ""); }
32.923077
85
0.690421
pycpp
df0964fdde61703a0a7213b88824e398666942fb
899
cpp
C++
leet_code/binary_tree/rightView.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
leet_code/binary_tree/rightView.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
leet_code/binary_tree/rightView.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(): val(0), left(nullptr), right(nullptr) {} TreeNode(int x): val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode* left, TreeNode* right): val(x), left(left), right(right) {} }; class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int> ans; if (!root) return ans; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { TreeNode* temp = q.front(); q.pop(); if (i == n - 1) ans.push_back(temp->val); if (temp->left) q.push(temp->left); if (temp->right) q.push(temp->right); } } return ans; } };
25.685714
89
0.498331
sahilduhan
df0cc0584c20635ed0c1bf551cb33223da674d80
30
cpp
C++
benchmarks/include/mpl11.min.erb.cpp
ldionne/benchcc
87cd508b47b39c9da5fb2152ec3f07de62297771
[ "BSL-1.0" ]
1
2017-10-12T11:54:43.000Z
2017-10-12T11:54:43.000Z
benchmarks/include/mpl11.min.erb.cpp
ldionne/benchcc
87cd508b47b39c9da5fb2152ec3f07de62297771
[ "BSL-1.0" ]
null
null
null
benchmarks/include/mpl11.min.erb.cpp
ldionne/benchcc
87cd508b47b39c9da5fb2152ec3f07de62297771
[ "BSL-1.0" ]
null
null
null
#include <boost/mpl11.min.hpp>
30
30
0.766667
ldionne
df11c53fdd1dc265f1bd7528a8245261b1dbc2a1
8,640
cpp
C++
src/backtester/TickGenerator.cpp
paps/Open-Trading
b62f85f391be9975a161713f87aeff0cae0a1e37
[ "BSD-2-Clause" ]
23
2015-07-24T15:45:36.000Z
2021-11-23T15:35:33.000Z
src/backtester/TickGenerator.cpp
paps/Open-Trading
b62f85f391be9975a161713f87aeff0cae0a1e37
[ "BSD-2-Clause" ]
null
null
null
src/backtester/TickGenerator.cpp
paps/Open-Trading
b62f85f391be9975a161713f87aeff0cae0a1e37
[ "BSD-2-Clause" ]
21
2015-07-12T16:42:01.000Z
2020-08-23T22:56:50.000Z
// The Open Trading Project - open-trading.org // // Copyright (c) 2011 Martin Tapia - martin.tapia@open-trading.org // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // 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 <cmath> #include "TickGenerator.hpp" #include "core/History.hpp" #include "core/strategy/Strategy.hpp" #include "Conf.hpp" #include "Logger.hpp" #define CLASS "[Backtester/TickGenerator] " namespace Backtester { TickGenerator::TickGenerator(Core::History const& history, Logger const& logger, Conf const& conf) : _history(history), _conf(conf), _logger(logger), _barPos(0) { this->_historyPos = this->_history.GetFirstBarPosOfPeriod(this->_conf.period); } TickGenerator::GenerationResult TickGenerator::GenerateNextTick(Core::Strategy::Strategy const& strategy, std::pair<float, float>& tick, Core::Bar& bar) { if (this->_tickBuffer.empty()) { Core::Bar minuteBar; Core::History::FetchType fetch = this->_history.FetchBar(minuteBar, this->_historyPos, 1); if (fetch == Core::History::FetchError) return NoMoreTicks; else if (fetch == Core::History::FetchGap) { this->_NextBar(); return Interruption; } this->_currentBar.time = minuteBar.time; if (this->_conf.fewerTicks) this->_GenerateFewerTicks(strategy, minuteBar); else this->_GenerateTicks(strategy, minuteBar); } float value = this->_tickBuffer.front(); this->_tickBuffer.pop(); GenerationResult ret; if (this->_currentBar.valid) { if (this->_currentBar.h < value) this->_currentBar.h = value; if (this->_currentBar.l > value) this->_currentBar.l = value; this->_currentBar.c = value; ret = NormalTick; } else { this->_currentBar.valid = true; this->_currentBar.o = value; this->_currentBar.h = value; this->_currentBar.l = value; this->_currentBar.c = value; ret = NewBarTick; } bar = this->_currentBar; ++this->_currentBar.time; // adds 1 second so that the next tick is not a multiple of 60 tick.first = value + strategy.PipsToOffset(this->_conf.spread); tick.second = value; if (this->_tickBuffer.empty()) this->_NextBar(); return ret; } void TickGenerator::_NextBar() { ++this->_historyPos; ++this->_barPos; if (this->_barPos >= this->_conf.period) { this->_barPos = 0; this->_currentBar.valid = false; } } void TickGenerator::_GenerateFewerTicks(Core::Strategy::Strategy const&, Core::Bar const& bar) { this->_tickBuffer.push(bar.o); if (bar.o == bar.c) { if (bar.h == bar.l) return; else if (bar.l == bar.o) this->_tickBuffer.push(bar.h); else if (bar.h == bar.o) this->_tickBuffer.push(bar.l); else { this->_tickBuffer.push(bar.l); this->_tickBuffer.push(bar.h); } } else if (bar.l == bar.c && bar.h != bar.o) this->_tickBuffer.push(bar.h); else if (bar.h == bar.c && bar.l != bar.o) this->_tickBuffer.push(bar.l); else if (bar.o == bar.l) this->_tickBuffer.push(bar.h); else if (bar.o == bar.h) this->_tickBuffer.push(bar.l); else { if (bar.c > bar.o) { this->_tickBuffer.push(bar.l); this->_tickBuffer.push(bar.h); } else { this->_tickBuffer.push(bar.h); this->_tickBuffer.push(bar.l); } } this->_tickBuffer.push(bar.c); } void TickGenerator::_GenerateTicks(Core::Strategy::Strategy const& strategy, Core::Bar const& bar) { this->_tickBuffer.push(bar.o); if (bar.o == bar.c) { if (bar.h == bar.l) // l | h ~ return; else if (bar.l == bar.o) // l |- h ~ this->_tickBuffer.push(bar.h); else if (bar.h == bar.o) // l -| h ~ this->_tickBuffer.push(bar.l); else // l -|- h ~ { this->_tickBuffer.push(bar.l); this->_tickBuffer.push(bar.h); } } else if (bar.l == bar.c) { if (bar.h == bar.o) // l | | h < this->_tickBuffer.push(strategy.FloorPrice(bar.c + 0.5 * (bar.o - bar.c))); else // l | |- h < this->_tickBuffer.push(bar.h); } else if (bar.h == bar.c) { if (bar.l == bar.o) // l | | h > this->_tickBuffer.push(strategy.CeilPrice(bar.o + 0.5 * (bar.c - bar.o))); else // l -| | h > this->_tickBuffer.push(bar.l); } else if (bar.o == bar.l) // l | |- h > this->_tickBuffer.push(bar.h); else if (bar.o == bar.h) // l -| | h < this->_tickBuffer.push(bar.l); else { float unit = fabs(bar.c - bar.o) > strategy.GetPriceUnit() ? strategy.GetPriceUnit() : 0; if (bar.c > bar.o) // l -| |- h > { this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.25 * (bar.o - bar.l))); this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.5 * (bar.o - bar.l))); this->_tickBuffer.push(bar.l); this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.33 * (bar.h - bar.l))); this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.33 * (bar.h - bar.l) - unit)); this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.66 * (bar.h - bar.l))); this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.66 * (bar.h - bar.l) - unit)); this->_tickBuffer.push(bar.h); this->_tickBuffer.push(strategy.CeilPrice(bar.h - 0.75 * (bar.h - bar.c))); this->_tickBuffer.push(strategy.CeilPrice(bar.h - 0.5 * (bar.h - bar.c))); } else // l -| |- h < { this->_tickBuffer.push(strategy.FloorPrice(bar.h - 0.25 * (bar.h - bar.o))); this->_tickBuffer.push(strategy.FloorPrice(bar.h - 0.5 * (bar.h - bar.o))); this->_tickBuffer.push(bar.h); this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.66 * (bar.h - bar.l))); this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.66 * (bar.h - bar.l) + unit)); this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.33 * (bar.h - bar.l))); this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.33 * (bar.h - bar.l) + unit)); this->_tickBuffer.push(bar.l); this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.75 * (bar.c - bar.l))); this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.5 * (bar.c - bar.l))); } } this->_tickBuffer.push(bar.c); } }
40
156
0.544792
paps
df1411ccbf54ff4c863292ddc46e2123e034a1cd
1,114
cc
C++
src/114_flatten-binary-tree-to-linked-list.cc
q191201771/yoko_leetcode
a29b163169f409856e9c9808890bcb25ca976f78
[ "MIT" ]
2
2018-07-28T06:11:30.000Z
2019-01-15T15:16:54.000Z
src/114_flatten-binary-tree-to-linked-list.cc
q191201771/yoko_leetcode
a29b163169f409856e9c9808890bcb25ca976f78
[ "MIT" ]
null
null
null
src/114_flatten-binary-tree-to-linked-list.cc
q191201771/yoko_leetcode
a29b163169f409856e9c9808890bcb25ca976f78
[ "MIT" ]
null
null
null
// Given a binary tree, flatten it to a linked list in-place. // // For example, given the following tree: // // 1 // / \ // 2 5 // / \ \ // 3 4 6 // The flattened tree should look like: // // 1 // \ // 2 // \ // 3 // \ // 4 // \ // 5 // \ // 6 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: void help(TreeNode *root, TreeNode **ret, TreeNode **prev) { if (!root) { return; } if (*prev == NULL) { *prev = new TreeNode(root->val); *ret = *prev; } else { (*prev)->right = new TreeNode(root->val); *prev = (*prev)->right; } help(root->left, ret, prev); help(root->right, ret, prev); } public: void flatten(TreeNode* root) { if (!root) { return; } TreeNode *ret = NULL; TreeNode *prev = NULL; help(root, &ret, &prev); root->val = ret->val; root->left = NULL; root->right = ret->right; } };
19.206897
78
0.493716
q191201771
df16cfbc43d6c923158fd70b144f1c999c74c0d9
4,039
cpp
C++
Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp
TheKeaver/o3de
3791149c6bb18d007ee375f592bdd031871f793d
[ "Apache-2.0", "MIT" ]
1
2021-08-11T02:20:46.000Z
2021-08-11T02:20:46.000Z
Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzTest/AzTest.h> #include <Atom/Utils/TestUtils/AssetSystemStub.h> #include <AtomToolsFramework/Util/MaterialPropertyUtil.h> namespace UnitTest { class AtomToolsFrameworkTest : public ::testing::Test { protected: void SetUp() override { if (!AZ::AllocatorInstance<AZ::SystemAllocator>::IsReady()) { AZ::AllocatorInstance<AZ::SystemAllocator>::Create(AZ::SystemAllocator::Descriptor()); } m_assetSystemStub.Activate(); RegisterSourceAsset("objects/upgrades/materials/supercondor.material"); RegisterSourceAsset("materials/condor.material"); RegisterSourceAsset("materials/talisman.material"); RegisterSourceAsset("materials/city.material"); RegisterSourceAsset("materials/totem.material"); RegisterSourceAsset("textures/orange.png"); RegisterSourceAsset("textures/red.png"); RegisterSourceAsset("textures/gold.png"); RegisterSourceAsset("textures/fuzz.png"); } void TearDown() override { m_assetSystemStub.Deactivate(); if (AZ::AllocatorInstance<AZ::SystemAllocator>::IsReady()) { AZ::AllocatorInstance<AZ::SystemAllocator>::Destroy(); } } void RegisterSourceAsset(const AZStd::string& path) { const AZ::IO::BasicPath assetRootPath = AZ::IO::PathView(m_assetRoot).LexicallyNormal(); const AZ::IO::BasicPath normalizedPath = AZ::IO::BasicPath(assetRootPath).Append(path).LexicallyNormal(); AZ::Data::AssetInfo assetInfo = {}; assetInfo.m_assetId = AZ::Uuid::CreateRandom(); assetInfo.m_relativePath = normalizedPath.LexicallyRelative(assetRootPath).StringAsPosix(); m_assetSystemStub.RegisterSourceInfo(normalizedPath.StringAsPosix().c_str(), assetInfo, assetRootPath.StringAsPosix().c_str()); } static constexpr const char* m_assetRoot = "d:/project/assets/"; AssetSystemStub m_assetSystemStub; }; TEST_F(AtomToolsFrameworkTest, GetExteralReferencePath_Succeeds) { ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("", "", 2), ""); ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/materials/condor.material", "", 2), ""); ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/materials/talisman.material", "", 2), ""); ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/materials/talisman.material", "d:/project/assets/textures/gold.png", 2), "../textures/gold.png"); ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/materials/talisman.material", "d:/project/assets/textures/gold.png", 0), "textures/gold.png"); ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 3), "../../../materials/condor.material"); ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 2), "materials/condor.material"); ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 1), "materials/condor.material"); ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 0), "materials/condor.material"); } AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); } // namespace UnitTest
51.782051
220
0.694726
TheKeaver
df17e6d56363be3e65b1829713daf59c85f5d89c
729
cpp
C++
LeetCode/687.Longest_Univalue_Path.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
9
2017-10-08T16:22:03.000Z
2021-08-20T09:32:17.000Z
LeetCode/687.Longest_Univalue_Path.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
null
null
null
LeetCode/687.Longest_Univalue_Path.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
2
2018-01-15T16:35:44.000Z
2019-03-21T18:30:04.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int longestUnivaluePath(TreeNode* root) { int ans = 0; find(root, ans); return max(ans - 1, 0); } int find(TreeNode *root, int &ans) { if(root == NULL) return 0; int l = 0, r = 0; l = find(root->left, ans); r = find(root->right, ans); if(root->left && root->left->val != root->val) l = 0; if(root->right && root->right->val != root->val) r = 0; ans = max(ans, l + r + 1); return max(l, r) + 1; } };
25.137931
63
0.492455
w181496
df1fd94d698e594f2648c6836684b55cfa8e3785
3,506
cc
C++
src/app/main.cc
JeanTracker/qt-qml-project-template-with-ci
022992af4bd4e4df006a3125fe124a56a25c23a5
[ "BSD-2-Clause" ]
null
null
null
src/app/main.cc
JeanTracker/qt-qml-project-template-with-ci
022992af4bd4e4df006a3125fe124a56a25c23a5
[ "BSD-2-Clause" ]
null
null
null
src/app/main.cc
JeanTracker/qt-qml-project-template-with-ci
022992af4bd4e4df006a3125fe124a56a25c23a5
[ "BSD-2-Clause" ]
null
null
null
// // Copyright (c) 2020, 219 Design, LLC // See LICENSE.txt // // https://www.219design.com // Software | Electrical | Mechanical | Product Design // #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickStyle> #include "autogenerated/version.h" // USE THIS INCLUDE SPARINGLY. IT CAN TRIGGER REBUILDS. #include "src/app/view_model_collection.h" #include "src/lib_app/cli_options.h" #include "src/lib_app/ios/ios_log_redirect.h" #include "src/minutil/logger.h" // <--- included for DEMONSTRATION. Prefer Qt logging where available. #include "src/util/am_i_inside_debugger.h" #include "util-assert.h" int main( int argc, char* argv[] ) { project::SetAppVersionStringForLogging( project::GIT_HASH_WHEN_BUILT ); project::WhenOnIos_RerouteStdoutStderrToDeviceFilesystem(); qSetMessagePattern( QString( "%{time yyyy-MM-dd hh:mm:ss.zzz} [QT-%{type}][v-" ) + project::GIT_HASH_WHEN_BUILT + "][thr:%{threadid}]%{if-category}%{category}: %{endif}%{file}(%{line}): %{message}" ); if( !project::OkToEnableAssertions() ) { // In production mobile apps, disable our assertions Suppress_All_Assertions(); } // project::log used for DEMONSTRATION. Prefer Qt logging where available. project::log( "main.cc starting now %d", static_cast<int>( __LINE__ ) ); QGuiApplication app( argc, argv ); // ... note next line... // QQuickStyle::setStyle( "Fusion" ); // <-- call setStyle after creating app (if style is needed) // ViewModels must OUTLIVE the qml engine, so create them first: project::ViewModelCollection vms( app, false /*cliArgsOnlyParseThenSkipErrorHandling*/ ); // For antialiasing: https://stackoverflow.com/a/49576756/10278 // QSurfaceFormat format; // format.setSamples( 8 ); // LEAVING THIS HERE AS A "WARNING". This gave us good antialiasing on // the QML ShapePath that it was intended to help. It DID help where we // wanted it to help. But it also caused weird tiny lines to intermittently // appear around some of our SVG icons. // So now we use a different, QML-only tactic in the ShapePath. // QSurfaceFormat::setDefaultFormat( format ); // // Instead, do this in the QML of your ShapePath: // layer.enabled: true // Without this, the edges look "jaggy" and pixelated // layer.samples: 4 // Without this, the edges look "jaggy" and pixelated // Created after vms, so that we avoid null vm qml warnings upon vm dtors QQmlApplicationEngine engine; vms.ExportContextPropertiesToQml( &engine ); engine.addImportPath( "qrc:///" ); // needed for finding qml in our plugins engine.load( QUrl( QStringLiteral( "qrc:///qml/main.qml" ) ) ); if( vms.Options().ShowColorPalette() ) { // This second app window will cause the FASSERT about root objects // count to trigger below, but just choose 'c' to continue beyond the // failed assert prompt. (It's ok to keep the assertion as-is, because // this color palette option is not meant be used in production.) engine.load( QUrl( QStringLiteral( "qrc:///qml/viewColorPalette.qml" ) ) ); } const QList<QObject*> objs = engine.rootObjects(); FASSERT( objs.size() == 1, "if the app starts creating more than one root window, " "please reevaluate the logic of SetRootObject and our global event filter" ); vms.SetRootObject( objs[ 0 ] ); return app.exec(); }
43.283951
115
0.67741
JeanTracker
b3018ed8c9a08a6736a0df27939557770c4f67bb
1,161
cc
C++
samples/06-looping/do_while_loop/main.cc
brockus/the_cpp_tutorial
87d73fa7111dd6fe22299b01edc5663bfd192782
[ "Apache-2.0" ]
null
null
null
samples/06-looping/do_while_loop/main.cc
brockus/the_cpp_tutorial
87d73fa7111dd6fe22299b01edc5663bfd192782
[ "Apache-2.0" ]
null
null
null
samples/06-looping/do_while_loop/main.cc
brockus/the_cpp_tutorial
87d73fa7111dd6fe22299b01edc5663bfd192782
[ "Apache-2.0" ]
null
null
null
// // author: Michael Brockus // gmail : <michaelbrockus@gmail.com> // #include <iostream> #include <cstdlib> int main() { // // To run a block of code repeatedly in a predetermined // time, you use the for loop statement. In cases you // want to run a block of code repeatedly based on a // given condition with a check at the end of each // iteration, you use the do while loop statement. // // The do while loop statement consists of execution // statements and a Boolean condition. First, the execute // statements are executed, and then the condition is // checked. If the condition evaluates to true, the execute // statements are executed again until the condition evaluates // to false. // // Unlike the while loop, the execute statements inside the // do while loop execute at least one time because the condition // is checked at the end of each iteration. // int x = 5; int i = 0; // // using do while loop statement // do { i++; std::cout << i << std::endl; } while (i < x); return EXIT_SUCCESS; } // end of function main
27.642857
68
0.63652
brockus
b305adef83ef8dcb74344a6b7039844e1bc9def9
1,778
cpp
C++
CastleDoctrine/gameSource/FastBoxBlurFilter.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
1
2020-01-16T00:07:11.000Z
2020-01-16T00:07:11.000Z
CastleDoctrine/gameSource/FastBoxBlurFilter.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
null
null
null
CastleDoctrine/gameSource/FastBoxBlurFilter.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
2
2019-09-17T12:08:20.000Z
2020-09-26T00:54:48.000Z
#include "FastBoxBlurFilter.h" #include <string.h> FastBoxBlurFilter::FastBoxBlurFilter() { } void FastBoxBlurFilter::applySubRegion( unsigned char *inChannel, int *inTouchPixelIndices, int inNumTouchPixels, int inWidth, int inHeight ) { // use pointer tricks to walk through neighbor box of each pixel // four "corners" around box in accumulation table used to compute // box total // these are offsets to current accumulation pointer int cornerOffsetA = inWidth + 1; int cornerOffsetB = -inWidth + 1; int cornerOffsetC = inWidth - 1; int cornerOffsetD = -inWidth - 1; // sides around box int sideOffsetA = inWidth; int sideOffsetB = -inWidth; int sideOffsetC = 1; int sideOffsetD = -1; unsigned char *sourceData = new unsigned char[ inWidth * inHeight ]; memcpy( sourceData, inChannel, inWidth * inHeight ); // sum boxes right into passed-in channel for( int i=0; i<inNumTouchPixels; i++ ) { int pixelIndex = inTouchPixelIndices[ i ]; unsigned char *sourcePointer = &( sourceData[ pixelIndex ] ); inChannel[ pixelIndex ] = ( sourcePointer[ 0 ] + sourcePointer[ cornerOffsetA ] + sourcePointer[ cornerOffsetB ] + sourcePointer[ cornerOffsetC ] + sourcePointer[ cornerOffsetD ] + sourcePointer[ sideOffsetA ] + sourcePointer[ sideOffsetB ] + sourcePointer[ sideOffsetC ] + sourcePointer[ sideOffsetD ] ) / 9; } delete [] sourceData; return; }
24.694444
72
0.568616
PhilipLudington
b30a3afe090e14054c69844fa0888371e872001c
844
cpp
C++
Dynamic Programming/0-1 Knapsack/(6)CountOfSubsetDiff.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
53
2020-09-26T19:44:33.000Z
2021-09-30T20:38:52.000Z
Dynamic Programming/0-1 Knapsack/(6)CountOfSubsetDiff.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
197
2020-08-25T18:13:56.000Z
2021-06-19T07:26:19.000Z
Dynamic Programming/0-1 Knapsack/(6)CountOfSubsetDiff.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
204
2020-08-24T09:21:02.000Z
2022-02-13T06:13:42.000Z
#include<bits/stdc++.h> using namespace std; int t[100][100]; // LeetCode Target sum ques int CountSubsetGivenSum(int *wt, int Sum, int n) { for (int i = 0; i <= Sum; i++) t[0][i] = 0; for (int i = 0; i <= n; i++) t[i][0] = 1; //empty set for (int i = 1; i <= n; i++) { for (int j = 1; j <= Sum; j++) { if (wt[i - 1] <= j) { t[i][j] = (t[i - 1][j - wt[i - 1]] + t[i - 1][j]); } else { t[i][j] = t[i - 1][j]; } } } return t[n][Sum]; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int wt[] = {1, 2, 4}; int diff = 3; int range = 0; int n = sizeof(wt) / sizeof(int); for (int i = 0; i < n; i++) range += wt[i]; int S1 = (diff + range) / 2; // diff+range should be even else ans=0 cout << CountSubsetGivenSum(wt, S1, n) << endl; }
18.347826
69
0.50237
jaydulera
b30ed7b2523b1e1d820217fed82ab8f66189698e
363
cpp
C++
09_lambda/09_07_generic_lambda_capture_expressions/09_07_00_generic_lambda_capture_expressions.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
13
2020-09-01T14:57:21.000Z
2021-11-24T06:00:26.000Z
09_lambda/09_07_generic_lambda_capture_expressions/09_07_00_generic_lambda_capture_expressions.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
5
2020-06-11T14:13:00.000Z
2021-07-14T05:27:53.000Z
09_lambda/09_07_generic_lambda_capture_expressions/09_07_00_generic_lambda_capture_expressions.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
10
2021-03-22T07:54:36.000Z
2021-09-15T04:03:32.000Z
// Generic lambda // Capture expressions #include <iostream> #include <vector> class move_only { public: move_only() = default; move_only(move_only&& other) = default; }; int main() { [](auto x){}; move_only mo; [mo](){}(); // how to fix int a{}; int b{}; // capture sum // type of sum // return back to example 6 }
12.964286
43
0.564738
pAbogn
b310c32bc0bc1ed676d6841e2f40f15979ad8fc3
1,180
cpp
C++
src/main.cpp
int08h/SumoJam-Line-Sensors-Example
b5c5cfd15e7deb5446b3097f9dee31c796685c65
[ "Unlicense" ]
null
null
null
src/main.cpp
int08h/SumoJam-Line-Sensors-Example
b5c5cfd15e7deb5446b3097f9dee31c796685c65
[ "Unlicense" ]
null
null
null
src/main.cpp
int08h/SumoJam-Line-Sensors-Example
b5c5cfd15e7deb5446b3097f9dee31c796685c65
[ "Unlicense" ]
null
null
null
// // Example how to read the Zumo32U4 line sensors // #include <Zumo32U4.h> namespace { // Delay between loop()s in milliseconds constexpr unsigned long DELAY_MS = 100; // Line sensors interface Zumo32U4LineSensors lineSensors = Zumo32U4LineSensors{}; // Enable the LCD Screen Zumo32U4LCD lcd = Zumo32U4LCD{}; // Sensor values will go in this array // array indicies Left = 0, Center = 1, Right = 2 unsigned int lineSensorValues[3] = {}; // Constants for the accessing sensor values array indicies enum Position { LEFT = 0, CENTER = 1, RIGHT = 2 }; } void setup() { // Initialize the sensors lineSensors.initThreeSensors(); // Initialize the LCD display lcd.init(); } void loop() { // Read in the values lineSensors.read(lineSensorValues); // Display the values divided by 10 (to fit on LCD) // L R // C lcd.clear(); // Left sensor lcd.gotoXY(0, 0); lcd.print(lineSensorValues[Position::LEFT] / 10); // Right sensor lcd.gotoXY(5, 0); lcd.print(lineSensorValues[Position::RIGHT] / 10); // Center sensor lcd.gotoXY(3, 1); lcd.print(lineSensorValues[Position::CENTER] / 10); delay(DELAY_MS); }
21.454545
61
0.668644
int08h
b314b54045963787d616d62b053d379759f5fb49
283
hpp
C++
src/tests/functional/plugin/shared/include/single_layer_tests/einsum.hpp
wood-ghost/openvino
0babf20bd2f4cd3f0be3c025d91ea55526b36fb2
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/tests/functional/plugin/shared/include/single_layer_tests/einsum.hpp
wood-ghost/openvino
0babf20bd2f4cd3f0be3c025d91ea55526b36fb2
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/tests/functional/plugin/shared/include/single_layer_tests/einsum.hpp
tuxedcat/openvino
5939cb1b363ebb56b73c2ad95d8899961a084677
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "shared_test_classes/single_layer/einsum.hpp" namespace LayerTestsDefinitions { TEST_P(EinsumLayerTest, CompareWithRefs) { Run(); } } // namespace LayerTestsDefinitions
17.6875
54
0.759717
wood-ghost
b31636287ed68f8f3b2037eb8d1dfc484fece7b2
869
cpp
C++
Leetcode/Day023/string_to_int_atoi.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day023/string_to_int_atoi.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day023/string_to_int_atoi.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
/* Imp to remember: erasing string mechanism | isdigit() | str.erase() */ class Solution { public: int myAtoi(string str) { long long int ans=0; string temp=str; bool pos=true; while(temp[0]==' ') temp.erase(temp.begin()); if(temp[0]=='-' || temp[0]=='+') { if(temp[0]=='-') pos=false; temp.erase(temp.begin()); } for(char ch:temp) { if(!isdigit(ch)) break; ans=ans*10+(ch-'0'); if(ans>INT_MAX) { if(!pos) return INT_MIN; else return INT_MAX; } } if(!pos) ans=-ans; return ans; } };
18.891304
67
0.352129
SujalAhrodia
b3169991554b43dcb993a85a054ccb07c974c53c
8,881
cpp
C++
src/state/StateVector.cpp
neophack/steam
28f0637e3ae4ff2c21ad12b2331c535e9873c997
[ "BSD-3-Clause" ]
null
null
null
src/state/StateVector.cpp
neophack/steam
28f0637e3ae4ff2c21ad12b2331c535e9873c997
[ "BSD-3-Clause" ]
null
null
null
src/state/StateVector.cpp
neophack/steam
28f0637e3ae4ff2c21ad12b2331c535e9873c997
[ "BSD-3-Clause" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////////////////// /// \file StateVector.cpp /// /// \author Sean Anderson, ASRL ////////////////////////////////////////////////////////////////////////////////////////////// #include <steam/state/StateVector.hpp> #include <steam/blockmat/BlockVector.hpp> #include <iostream> namespace steam { ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Default constructor ////////////////////////////////////////////////////////////////////////////////////////////// StateVector::StateVector() : numBlockEntries_(0) {} ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Copy constructor -- deep copy ////////////////////////////////////////////////////////////////////////////////////////////// StateVector::StateVector(const StateVector& other) : states_(other.states_), numBlockEntries_(other.numBlockEntries_) { // Map is copied in initialization list to avoid re-hashing all the entries, // now we go through the entries and perform a deep copy boost::unordered_map<StateID, StateContainer>::iterator it = states_.begin(); for(; it != states_.end(); ++it) { it->second.state = it->second.state->clone(); } } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Assignment operator -- deep copy ////////////////////////////////////////////////////////////////////////////////////////////// StateVector& StateVector::operator= (const StateVector& other) { // Copy-swap idiom StateVector tmp(other); // note, copy constructor makes a deep copy std::swap(states_, tmp.states_); std::swap(numBlockEntries_, tmp.numBlockEntries_); return *this; } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Copy the values of 'other' into 'this' (states must already align, typically /// this means that one is already a deep copy of the other) ////////////////////////////////////////////////////////////////////////////////////////////// void StateVector::copyValues(const StateVector& other) { // Check state vector are the same size if (this->states_.empty() || this->numBlockEntries_ != other.numBlockEntries_ || this->states_.size() != other.states_.size()) { throw std::invalid_argument("StateVector size was not the same in copyValues()"); } // Iterate over the state vectors and perform a "deep" copy without allocation new memory. // Keeping the original pointers is important as they are shared in other places, and we // want to update the shared memory. // todo: can we avoid a 'find' here? boost::unordered_map<StateID, StateContainer>::iterator it = states_.begin(); for(; it != states_.end(); ++it) { // Find matching state by ID boost::unordered_map<StateID, StateContainer>::const_iterator itOther = other.states_.find(it->second.state->getKey().getID()); // Check that matching state was found and has the same structure if (itOther == other.states_.end() || it->second.state->getKey().getID() != itOther->second.state->getKey().getID() || it->second.localBlockIndex != itOther->second.localBlockIndex) { throw std::runtime_error("StateVector was missing an entry in copyValues(), " "or structure of StateVector did not match."); } // Copy it->second.state->setFromCopy(itOther->second.state); } } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Add state variable ////////////////////////////////////////////////////////////////////////////////////////////// void StateVector::addStateVariable(const StateVariableBase::Ptr& state) { // Verify that state is not locked if (state->isLocked()) { throw std::invalid_argument("Tried to add locked state variable to " "an optimizable state vector"); } // Verify we don't already have this state StateKey key = state->getKey(); if (this->hasStateVariable(key)) { throw std::runtime_error("StateVector already contains the state being added."); } // Create new container StateContainer newEntry; newEntry.state = state; // copy the shared_ptr (increases ref count) newEntry.localBlockIndex = numBlockEntries_; states_[key.getID()] = newEntry; // Increment number of entries numBlockEntries_++; } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Check if a state variable exists in the vector ////////////////////////////////////////////////////////////////////////////////////////////// bool StateVector::hasStateVariable(const StateKey& key) const { // Find the StateContainer for key boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.find(key.getID()); // Return if found return it != states_.end(); } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get a state variable using a key ////////////////////////////////////////////////////////////////////////////////////////////// StateVariableBase::ConstPtr StateVector::getStateVariable(const StateKey& key) const { // Find the StateContainer for key boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.find(key.getID()); // Check that it was found if (it == states_.end()) { throw std::runtime_error("State variable was not found in call to getStateVariable()"); } // Return state variable reference return it->second.state; } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get number of state variables ////////////////////////////////////////////////////////////////////////////////////////////// unsigned int StateVector::getNumberOfStates() const { return states_.size(); } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get the block index of a state ////////////////////////////////////////////////////////////////////////////////////////////// int StateVector::getStateBlockIndex(const StateKey& key) const { // Find the StateContainer for key boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.find(key.getID()); // Check that the state exists in the state vector // **Note the likely causes that this occurs: // 1) A cost term includes a state that is not added to the problem // 2) A cost term is not checking whether states are locked, and adding a Jacobian for a locked state variable if (it == states_.end()) { std::stringstream ss; ss << "Tried to find a state that does not exist " "in the state vector (ID: " << key.getID() << ")."; throw std::runtime_error(ss.str()); } // Return block index return it->second.localBlockIndex; } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get an ordered list of the sizes of the 'block' state variables ////////////////////////////////////////////////////////////////////////////////////////////// std::vector<unsigned int> StateVector::getStateBlockSizes() const { // Init return std::vector<unsigned int> result; result.resize(states_.size()); // Iterate over states and populate result for (boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.begin(); it != states_.end(); ++it ) { // Check that the local block index is in a valid range if (it->second.localBlockIndex < 0 || it->second.localBlockIndex >= (int)result.size()) { throw std::logic_error("localBlockIndex is not a valid range"); } // Populate return vector result[it->second.localBlockIndex] = it->second.state->getPerturbDim(); } return result; } ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Update the state vector ////////////////////////////////////////////////////////////////////////////////////////////// void StateVector::update(const Eigen::VectorXd& perturbation) { // Convert single vector to a block-vector of perturbations (this checks sizes) BlockVector blkPerturb(this->getStateBlockSizes(), perturbation); // Iterate over states and update each for ( boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.begin(); it != states_.end(); ++it ) { // Check for valid index if (it->second.localBlockIndex < 0) { throw std::runtime_error("localBlockIndex is not initialized"); } // Update state it->second.state->update(blkPerturb.at(it->second.localBlockIndex)); } } } // steam
41.306977
131
0.515145
neophack
b319184ac9b6fc21959e9ad978f1b468791faacd
1,431
cpp
C++
leetcode/problems/hard/115-distinct-subsequences.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/hard/115-distinct-subsequences.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/hard/115-distinct-subsequences.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Distinct Subsequences https://leetcode.com/problems/distinct-subsequences/ Given two strings s and t, return the number of distinct subsequences of s which equals t. A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not). It is guaranteed the answer fits on a 32-bit signed integer. Example 1: Input: s = "rabbbit", t = "rabbit" Output: 3 Explanation: As shown below, there are 3 ways you can generate "rabbit" from S. rabbbit rabbbit rabbbit Example 2: Input: s = "babgbag", t = "bag" Output: 5 Explanation: As shown below, there are 5 ways you can generate "bag" from S. babgbag babgbag babgbag babgbag babgbag Constraints: 1 <= s.length, t.length <= 1000 s and t consist of English letters. */ class Solution { public: int numDistinct(string s, string t) { int n = s.size(), m = t.size(); unsigned long long dp[n + 1][m + 1]; memset(dp, 0, sizeof(dp)); for(int i = 0; i <= n; i++) dp[i][0] = 1; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { dp[i][j] = dp[i - 1][j]; if(s[i - 1] == t[j - 1]) { dp[i][j] += dp[i - 1][j - 1]; } } } return dp[n][m]; } };
24.672414
246
0.594689
wingkwong
b31a116dfe80be72926d7f7dfe00938e3c20b5db
21,701
hpp
C++
Project/include/lak/transform.hpp
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
Project/include/lak/transform.hpp
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
Project/include/lak/transform.hpp
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2018 Lucas Kleiss (LAK132) 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. */ /* Dual Quaternion concepts from "A Beginners Guide to Dual-Quaternions" (Ben Kenwright) https://cs.gmu.edu/~jmlien/teaching/cs451/uploads/Main/dual-quaternion.pdf https://web.archive.org/web/20180622093933/https://cs.gmu.edu/~jmlien/teaching/cs451/uploads/Main/dual-quaternion.pdf */ #include <cmath> #include <type_traits> // #include <lak/mstream.hpp> #ifndef DEBUG # ifdef NDEBUG # define DEBUG(x) # else # include <iostream> # define DEBUG(x) std::cout << __FILE__ << "(" << std::dec << __LINE__ << ") " << x # endif #endif #ifndef LAK_TRANSFORM_MAT4 #include <glm/mat4x4.hpp> #define LAK_TRANSFORM_MAT4 glm::mat4 #endif #ifndef LAK_TRANSFORM_VEC3 #include <glm/vec3.hpp> #define LAK_TRANSFORM_VEC3 glm::vec3 #endif #ifndef LAK_TRANSFORM_VEC2 #include <glm/vec2.hpp> #define LAK_TRANSFORM_VEC2 glm::vec2 #endif #ifndef LAK_TRANSFORM_H #define LAK_TRANSFORM_H namespace lak { using mat4_t = LAK_TRANSFORM_MAT4; using vec3_t = LAK_TRANSFORM_VEC3; using vec2_t = LAK_TRANSFORM_VEC2; // template <> // mstream &operator>><vec3_t &>(mstream &strm, vec3_t &obj) // { // strm >> obj.x >> obj.y >> obj.z; // return strm; // } // template <> // mstream &operator<<<vec3_t &>(mstream &strm, vec3_t &obj) // { // strm << obj.x << obj.y << obj.z; // return strm; // } // template <> // mstream &operator>><vec2_t &>(mstream &strm, vec2_t &obj) // { // strm >> obj.x >> obj.y; // return strm; // } // template <> // mstream &operator<<<vec2_t &>(mstream &strm, vec2_t &obj) // { // strm << obj.x << obj.y; // return strm; // } #if defined(LAK_TRANSFORM_BIGGER_TYPE_ADD) template<typename L, typename R> using biggerType = decltype(L(0) + R(0)); #elif defined(LAK_TRANSFORM_BIGGER_TYPE_SUB) template<typename L, typename R> using biggerType = decltype(L(0) - R(0)); #else template<typename L, typename R> using biggerType = decltype(L(0) * R(0)); #endif template<typename T> struct quaternion_t; template<typename T> struct quaternion_t { typedef typename std::decay<T>::type _value_type; typedef quaternion_t<_value_type> _type; _value_type x; _value_type y; _value_type z; _value_type w; quaternion_t() : x(_value_type(0)), y(_value_type(0)), z(_value_type(0)), w(_value_type(1)) {} // quaternion_t(const _value_type& X, const _value_type& Y, const _value_type& Z, const _value_type& W) : x(X), y(Y), z(Z), w(W) {} // quaternion_t(_value_type&& X, _value_type&& Y, _value_type&& Z, _value_type&& W) : x(X), y(Y), z(Z), w(W) {} quaternion_t(_value_type X, _value_type Y, _value_type Z, _value_type W) : x(X), y(Y), z(Z), w(W) {} quaternion_t(const _value_type XYZW[4]) : x(XYZW[0]), y(XYZW[1]), z(XYZW[2]), w(XYZW[3]) {} template<typename R> quaternion_t(const quaternion_t<R>& other) { *this = other; } template<typename R> quaternion_t(quaternion_t<R>&& other) { *this = other; } template<typename R> _type& operator=(const quaternion_t<R>& rhs) { x = rhs.x; y = rhs.y; z = rhs.z; w = rhs.w; return *this; } template<typename R> _type& operator=(quaternion_t<R>&& rhs) { x = rhs.x; y = rhs.y; z = rhs.z; w = rhs.w; return *this; } _type operator*() // abuse the derefernce operator for conjugate operation { return _type(-x, -y, -z, w); } _type conjugate() { return _type(-x, -y, -z, w); } _value_type operator~() // magnitude { // sqrt(this->dot(*this)) // overkill // sqrt((*this * this->conjugate()).w) // overkill return sqrt((x*x)+(y*y)+(z*z)+(w*w)); } _value_type magnitude() { return sqrt((x*x)+(y*y)+(z*z)+(w*w)); } _type norm() { return *this * (_value_type(1) / magnitude()); } _type& normalize() { return *this *= _value_type(1) / magnitude(); } _value_type& operator[](const size_t& index) // useful for &(qrtn[0]) { return *((&x)+index); } _value_type& operator[](size_t&& index) // useful for &(qrtn[0]) { return *((&x)+index); } _value_type* operator[](const char& index) { switch(index) { case 'x': return &x; case 'y': return &y; case 'z': return &z; case 'w': return &w; } return nullptr; } template<typename R> bool operator==(const quaternion_t<R>& rhs) { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; } template<typename R> bool operator==(quaternion_t<R>&& rhs) { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; } template<typename R> bool operator!=(const quaternion_t<R>& rhs) { return x != rhs.x && y != rhs.y && z != rhs.z && w != rhs.w; } template<typename R> bool operator!=(quaternion_t<R>&& rhs) { return x != rhs.x && y != rhs.y && z != rhs.z && w != rhs.w; } template<typename R> biggerType<_value_type, typename std::decay<R>::type> dot(const quaternion_t<R>& rhs) { return (x * rhs.x) + (y * rhs.y) + (z * rhs.z) + (w * rhs.w); } template<typename R> biggerType<_value_type, typename std::decay<R>::type> dot(quaternion_t<R>&& rhs) { return (x * rhs.x) + (y * rhs.y) + (z * rhs.z) + (w * rhs.w); } template<typename R> _type& operator+=(const quaternion_t<R>& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; w += rhs.w; return *this; } template<typename R> _type& operator+=(quaternion_t<R>&& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; w += rhs.w; return *this; } template<typename R> quaternion_t<biggerType<_value_type, R>> operator+(const quaternion_t<R>& rhs) { return quaternion_t<biggerType<_value_type, R>>(x+rhs.x, y+rhs.y, z+rhs.z, z+rhs.z); } template<typename R> quaternion_t<biggerType<_value_type, R>> operator+(quaternion_t<R>&& rhs) { return quaternion_t<biggerType<_value_type, R>>(x+rhs.x, y+rhs.y, z+rhs.z, z+rhs.z); } template<typename R> _type& operator*=(R rhs) // scalar mult { x *= rhs; y *= rhs; z *= rhs; w *= rhs; return *this; } template<typename R> _type& operator*=(const quaternion_t<R>& rhs) { _value_type _x = ((y * rhs.z) - (z * rhs.y)) + (w * rhs.x) + (x * rhs.w); _value_type _y = ((z * rhs.x) - (x * rhs.z)) + (w * rhs.y) + (y * rhs.w); _value_type _z = ((x * rhs.y) - (y * rhs.x)) + (w * rhs.z) + (z * rhs.w); _value_type _w = (w * rhs.w) - ((x * rhs.x) + (y * rhs.y) + (z * rhs.z)); x = _x; y = _y; z = _z; w = _w; return *this; } template<typename R> _type& operator*=(quaternion_t<R>&& rhs) { _value_type _x = ((y * rhs.z) - (z * rhs.y)) + (w * rhs.x) + (x * rhs.w); _value_type _y = ((z * rhs.x) - (x * rhs.z)) + (w * rhs.y) + (y * rhs.w); _value_type _z = ((x * rhs.y) - (y * rhs.x)) + (w * rhs.z) + (z * rhs.w); _value_type _w = (w * rhs.w) - ((x * rhs.x) + (y * rhs.y) + (z * rhs.z)); x = _x; y = _y; z = _z; w = _w; return *this; } template<typename R> quaternion_t<biggerType<_value_type, typename std::decay<R>::type>> operator*(R rhs) { quaternion_t<biggerType<_value_type, typename std::decay<R>::type>> rtn = *this; return rtn *= rhs; } template<typename R> quaternion_t<biggerType<_value_type, R>> operator*(const quaternion_t<R>& rhs) { quaternion_t<biggerType<_value_type, R>> rtn = *this; return rtn *= rhs; } template<typename R> quaternion_t<biggerType<_value_type, R>> operator*(quaternion_t<R>&& rhs) { quaternion_t<biggerType<_value_type, R>> rtn = *this; return rtn *= rhs; } template<typename L> friend quaternion_t<biggerType<_value_type, typename std::decay<L>::type>> operator*(L lhs, quaternion_t<_value_type> rhs) { quaternion_t<biggerType<_value_type, typename std::decay<L>::type>> rtn = rhs; return rtn *= lhs; } }; // template <typename T> // mstream &operator>><quaternion_t<T>>(mstream &strm, quaternion_t<T> &obj) // { // strm >> obj.x >> obj.y >> obj.z >> obj.w; // return strm; // } // template <typename T> // mstream &operator<<<quaternion_t<T>>(mstream &strm, quaternion_t<T> &obj) // { // strm << obj.x << obj.y << obj.z << obj.w; // return strm; // } typedef quaternion_t<float> quaternionf_t; typedef quaternion_t<double> quaterniond_t; template<typename T> struct dualquaternion_t { typedef typename std::decay<T>::type _value_type; typedef quaternion_t<_value_type> _qtrn_type; typedef dualquaternion_t<_value_type> _type; _qtrn_type real; _qtrn_type dual; dualquaternion_t() : real(_value_type(0), _value_type(0), _value_type(0), _value_type(1)), dual(_value_type(0), _value_type(0), _value_type(0), _value_type(0)) {} // dualquaternion_t(const _qtrn_type& R, const _qtrn_type& D) : real(R), dual(D) {} // dualquaternion_t(_qtrn_type&& R, _qtrn_type&& D) : real(R), dual(D) {} dualquaternion_t(_qtrn_type R, _qtrn_type D) : real(R), dual(D) {} dualquaternion_t(const _qtrn_type RD[2]) : real(RD[0]), dual(RD[1]) {} // dualquaternion_t( // const _value_type& rX, const _value_type& rY, const _value_type& rZ, const _value_type& rW, // const _value_type& dX, const _value_type& dY, const _value_type& dZ, const _value_type& dW // ) : real(rX, rY, rZ, rW), dual(dX, dY, dZ, dW) {} // dualquaternion_t( // _value_type&& rX, _value_type&& rY, _value_type&& rZ, _value_type&& rW, // _value_type&& dX, _value_type&& dY, _value_type&& dZ, _value_type&& dW // ) : real(rX, rY, rZ, rW), dual(dX, dY, dZ, dW) {} dualquaternion_t( _value_type rX, _value_type rY, _value_type rZ, _value_type rW, _value_type dX, _value_type dY, _value_type dZ, _value_type dW ) : real(rX, rY, rZ, rW), dual(dX, dY, dZ, dW) {} dualquaternion_t(const _value_type vals[8]) : real(vals[0], vals[1], vals[2], vals[3]), dual(vals[4], vals[5], vals[6], vals[7]) {} _type& fromRotTrans(const _qtrn_type& rot, _qtrn_type trans) { real = rot; trans.w = _value_type(0); dual = _value_type(0.5) * trans * rot; return *this; } _type& fromRotTrans(_qtrn_type&& rot, _qtrn_type&& trans) { real = rot; trans.w = _value_type(0); dual = _value_type(0.5) * trans * rot; return *this; } _type& fromEuler(const _qtrn_type& rot, _qtrn_type trans) { real.w = cos(rot.w / 2); _value_type srw2 = sin(rot.w / 2);// / sqrt((rot.x*rot.x) + (rot.y*rot.y) + (rot.z*rot.z)); real.x = rot.x * srw2; real.y = rot.y * srw2; real.z = rot.z * srw2; trans.w = _value_type(0); dual = _value_type(0.5) * trans * real; return *this; } _type& fromEuler(_qtrn_type&& rot, _qtrn_type&& trans) { real.w = cos(rot.w / 2); _value_type srw2 = sin(rot.w / 2); real.x = rot.x * srw2; real.y = rot.y * srw2; real.z = rot.z * srw2; trans.w = _value_type(0); dual = _value_type(0.5) * trans * real; return *this; } _qtrn_type rotation() { return real; } _qtrn_type eulerRotation() { _qtrn_type rtn; rtn.w = acos(real.w) * 2; _value_type srw2 = sin(rtn.w / 2); if(srw2 == 0.0f) { rtn.x = 0.0f; rtn.y = 0.0f; rtn.z = 0.0f; } else { rtn.x = real.x / srw2; rtn.y = real.y / srw2; rtn.z = real.z / srw2; } return rtn; } _qtrn_type translation() { _qtrn_type& trans = (dual * _value_type(2)) * *real; trans.w = _value_type(0); return trans; } mat4_t transform() { normalize(); _qtrn_type& trans = translation(); _value_type &x = real.x, &y = real.y, &z = real.z, &w = real.w; const _value_type t = 2; return mat4_t { (w*w) + (x*x) - (y*y) - (z*z), (t*x*y) + (t*w*z), (t*x*z) - (t*w*y), _value_type(0), (t*x*y) - (t*w*z), (w*w) + (y*y) - (x*x) - (z*z), (t*y*z) + (t*w*x), _value_type(0), (t*x*z) + (t*w*y), (t*y*z) - (t*w*x), (w*w) + (z*z) - (x*x) - (y*y), _value_type(0), trans.x, trans.y, trans.z, _value_type(1) }; } _type operator*() // abuse the derefernce operator for conjugate operation { return _type(*real, *dual); } _type conjugate() { return _type(*real, *dual); } _value_type operator~() // magnitude { // ||dq|| = sqrt(dq*(*dq)) // dq1*dq2 = dq1.r*dq2.r + (dq1.r*dq2.d + dq1.d*dq2.r)ε // dq*(*dq) = dq.r*(*dq.r) + (dq.r*(*dq.d) + dq.d*(*dq.r))ε // dq*(*dq) = dq.r*(*dq.r) + (0)ε // ||dq|| = ||dq.r|| return ~real; } _value_type magnitude() { return ~real; } _type norm() { return *this * (_value_type(1) / magnitude()); } _type& normalize() { return *this *= _value_type(1) / magnitude(); } _value_type& operator[](const size_t& index) // useful for &(qrtn[0]) { return *((&real)+index); } _value_type& operator[](size_t&& index) // useful for &(qrtn[0]) { return *((&real)+index); } _value_type* operator[](const char& index) { switch(index) { case 'r': return &real; case 'd': return &dual; } return nullptr; } template<typename R> bool operator==(const dualquaternion_t<R>& rhs) { return real == rhs.real && dual == rhs.dual; } template<typename R> bool operator==(dualquaternion_t<R>&& rhs) { return real == rhs.real && dual == rhs.dual; } template<typename R> bool operator!=(const dualquaternion_t<R>& rhs) { return real != rhs.real && dual != rhs.dual; } template<typename R> bool operator!=(dualquaternion_t<R>&& rhs) { return real != rhs.real && dual != rhs.dual; } template<typename R> quaternion_t<biggerType<_value_type, typename std::decay<R>::type>> dot(const dualquaternion_t<R>& rhs) { return real.dot(rhs.real); } template<typename R> quaternion_t<biggerType<_value_type, typename std::decay<R>::type>> dot(dualquaternion_t<R>&& rhs) { return real.dot(rhs.real); } template<typename R> _type& operator=(const dualquaternion_t<R>& rhs) { real = rhs.real; dual = rhs.dual; return *this; } template<typename R> _type& operator=(dualquaternion_t<R>&& rhs) { real = rhs.real; dual = rhs.dual; return *this; } template<typename R> _type& operator+=(const dualquaternion_t<R>& rhs) { real += rhs.real; dual += rhs.dual; return *this; } template<typename R> _type& operator+=(dualquaternion_t<R>&& rhs) { real += rhs.real; dual += rhs.dual; return *this; } template<typename R> dualquaternion_t<biggerType<_value_type, R>> operator+(const dualquaternion_t<R>& rhs) { return dualquaternion_t<biggerType<_value_type, R>>(real+rhs.real, dual+rhs.dual); } template<typename R> dualquaternion_t<biggerType<_value_type, R>> operator+(dualquaternion_t<R>&& rhs) { return dualquaternion_t<biggerType<_value_type, R>>(real+rhs.real, dual+rhs.dual); } template<typename R> _type& operator*=(R rhs) // scalar mult { real *= rhs; dual *= rhs; return *this; } template<typename R> _type& operator*=(const dualquaternion_t<R>& rhs) { // NOTE: current real is needed to calculate new dual! beware of order! dual = (real * rhs.dual) + (dual * rhs.real); real *= rhs.real; return *this; } template<typename R> _type& operator*=(dualquaternion_t<R>&& rhs) { dual = (real * rhs.dual) + (dual * rhs.real); real *= rhs.real; return *this; } template<typename R> dualquaternion_t<biggerType<_value_type, typename std::decay<R>::type>> operator*(R rhs) { dualquaternion_t<biggerType<_value_type, typename std::decay<R>::type>> rtn = *this; return rtn *= rhs; } template<typename R> dualquaternion_t<biggerType<_value_type, R>> operator*(const dualquaternion_t<R>& rhs) { dualquaternion_t<biggerType<_value_type, R>> rtn = *this; return rtn *= rhs; } template<typename R> dualquaternion_t<biggerType<_value_type, R>> operator*(dualquaternion_t<R>&& rhs) { dualquaternion_t<biggerType<_value_type, R>> rtn = *this; return rtn *= rhs; } template<typename L> friend dualquaternion_t<biggerType<_value_type, typename std::decay<L>::type>> operator*(L lhs, dualquaternion_t<_value_type> rhs) { dualquaternion_t<biggerType<_value_type, typename std::decay<L>::type>> rtn = rhs; return rtn *= lhs; } }; // template <typename T> // mstream &operator>><dualquaternion_t<T>>(mstream &strm, dualquaternion_t<T> &obj) // { // strm >> obj.real >> obj.dual; // return strm; // } // template <typename T> // mstream &operator<<<dualquaternion_t<T>>(mstream &strm, dualquaternion_t<T> &obj) // { // strm << obj.real << obj.dual; // return strm; // } typedef dualquaternion_t<float> dualquaternionf_t; typedef dualquaternion_t<double> dualquaterniond_t; } #endif // LAK_TRANSFORM_H // #define LAK_TRANSFORM_IMPLEM #ifdef LAK_TRANSFORM_IMPLEM #ifndef LAK_TRANSFORM_HAS_IMPLEM #define LAK_TRANSFORM_HAS_IMPLEM namespace lak { } #endif // LAK_TRANSFORM_HAS_IMPLEM #endif // LAK_TRANSFORM_IMPLEM
33.592879
170
0.516059
LAK132
b31e07989aeebeb61c6c758cbd2368a8c67891dc
8,707
cpp
C++
ze_imu/src/imu_buffer.cpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
30
2016-09-27T07:41:28.000Z
2021-12-03T20:44:28.000Z
ze_imu/src/imu_buffer.cpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
1
2018-12-18T15:53:06.000Z
2018-12-21T03:10:06.000Z
ze_imu/src/imu_buffer.cpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
12
2016-11-05T07:51:29.000Z
2020-07-13T02:26:08.000Z
// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye // 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 <ze/imu/imu_buffer.hpp> namespace ze { template<int BufferSize, typename GyroInterp, typename AccelInterp> ImuBuffer<BufferSize, GyroInterp, AccelInterp>::ImuBuffer(ImuModel::Ptr imu_model) : imu_model_(imu_model) , gyro_delay_(secToNanosec(imu_model->gyroscopeModel()->intrinsicModel()->delay())) , accel_delay_(secToNanosec(imu_model->accelerometerModel()->intrinsicModel()->delay())) { } template<int BufferSize, typename GyroInterp, typename AccelInterp> void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertImuMeasurement( int64_t time, const ImuAccGyr value) { acc_buffer_.insert(correctStampAccel(time), value.head<3>(3)); gyr_buffer_.insert(correctStampGyro(time), value.tail<3>(3)); } template<int BufferSize, typename GyroInterp, typename AccelInterp> void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertGyroscopeMeasurement( int64_t time, const Vector3 value) { gyr_buffer_.insert(correctStampGyro(time), value); } template<int BufferSize, typename GyroInterp, typename AccelInterp> void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertAccelerometerMeasurement( int64_t time, const Vector3 value) { acc_buffer_.insert(correctStampAccel(time), value); } template<int BufferSize, typename GyroInterp, typename AccelInterp> bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::get(int64_t time, Eigen::Ref<ImuAccGyr> out) { std::lock_guard<std::mutex> gyr_lock(gyr_buffer_.mutex()); std::lock_guard<std::mutex> acc_lock(acc_buffer_.mutex()); if (time > gyr_buffer_.times().back() || time > acc_buffer_.times().back()) { return false; } const auto gyro_before = gyr_buffer_.iterator_equal_or_before(time); const auto acc_before = acc_buffer_.iterator_equal_or_before(time); if (gyro_before == gyr_buffer_.times().end() || acc_before == acc_buffer_.times().end()) { return false; } VectorX w = GyroInterp::interpolate(&gyr_buffer_, time, gyro_before); VectorX a = AccelInterp::interpolate(&acc_buffer_, time, acc_before); out = imu_model_->undistort(a, w); return true; } template<int BufferSize, typename GyroInterp, typename AccelInterp> bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getAccelerometerDistorted( int64_t time, Eigen::Ref<Vector3> out) { return acc_buffer_.getValueInterpolated(time, out); } template<int BufferSize, typename GyroInterp, typename AccelInterp> bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getGyroscopeDistorted( int64_t time, Eigen::Ref<Vector3> out) { return gyr_buffer_.getValueInterpolated(time, out); } template<int BufferSize, typename GyroInterp, typename AccelInterp> std::pair<ImuStamps, ImuAccGyrContainer> ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getBetweenValuesInterpolated( int64_t stamp_from, int64_t stamp_to) { //Takes gyroscope timestamps and interpolates accelerometer measurements at // same times. Rectifies all measurements. CHECK_GE(stamp_from, 0u); CHECK_LT(stamp_from, stamp_to); ImuAccGyrContainer rectified_measurements; ImuStamps stamps; std::lock_guard<std::mutex> gyr_lock(gyr_buffer_.mutex()); std::lock_guard<std::mutex> acc_lock(acc_buffer_.mutex()); if(gyr_buffer_.times().size() < 2) { LOG(WARNING) << "Buffer has less than 2 entries."; // return empty means unsuccessful. return std::make_pair(stamps, rectified_measurements); } const time_t oldest_stamp = gyr_buffer_.times().front(); const time_t newest_stamp = gyr_buffer_.times().back(); if (stamp_from < oldest_stamp) { LOG(WARNING) << "Requests older timestamp than in buffer."; // return empty means unsuccessful. return std::make_pair(stamps, rectified_measurements); } if (stamp_to > newest_stamp) { LOG(WARNING) << "Requests newer timestamp than in buffer."; // return empty means unsuccessful. return std::make_pair(stamps, rectified_measurements); } const auto it_from_before = gyr_buffer_.iterator_equal_or_before(stamp_from); const auto it_to_after = gyr_buffer_.iterator_equal_or_after(stamp_to); CHECK(it_from_before != gyr_buffer_.times().end()); CHECK(it_to_after != gyr_buffer_.times().end()); const auto it_from_after = it_from_before + 1; const auto it_to_before = it_to_after - 1; if (it_from_after == it_to_before) { LOG(WARNING) << "Not enough data for interpolation"; // return empty means unsuccessful. return std::make_pair(stamps, rectified_measurements); } // resize containers const size_t range = it_to_before.index() - it_from_after.index() + 3; rectified_measurements.resize(Eigen::NoChange, range); stamps.resize(range); // first element VectorX w = GyroInterp::interpolate(&gyr_buffer_, stamp_from, it_from_before); VectorX a = AccelInterp::interpolate(&acc_buffer_, stamp_from); stamps(0) = stamp_from; rectified_measurements.col(0) = imu_model_->undistort(a, w); // this is a real edge case where we hit the two consecutive timestamps // with from and to. size_t col = 1; if (range > 2) { for (auto it=it_from_before+1; it!=it_to_after; ++it) { w = GyroInterp::interpolate(&gyr_buffer_, (*it), it); a = AccelInterp::interpolate(&acc_buffer_, (*it)); stamps(col) = (*it); rectified_measurements.col(col) = imu_model_->undistort(a, w); ++col; } } // last element w = GyroInterp::interpolate(&gyr_buffer_, stamp_to, it_to_before); a = AccelInterp::interpolate(&acc_buffer_, stamp_to); stamps(range - 1) = stamp_to; rectified_measurements.col(range - 1) = imu_model_->undistort(a, w); return std::make_pair(stamps, rectified_measurements); } template<int BufferSize, typename GyroInterp, typename AccelInterp> std::tuple<int64_t, int64_t, bool> ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getOldestAndNewestStamp() const { std::tuple<int64_t, int64_t, bool> accel = acc_buffer_.getOldestAndNewestStamp(); std::tuple<int64_t, int64_t, bool> gyro = gyr_buffer_.getOldestAndNewestStamp(); if (!std::get<2>(accel) || !std::get<2>(gyro)) { return std::make_tuple(-1, -1, false); } int64_t oldest = std::get<0>(accel) < std::get<0>(gyro) ? std::get<0>(gyro) : std::get<0>(accel); int64_t newest = std::get<1>(accel) < std::get<1>(gyro) ? std::get<1>(accel) : std::get<1>(gyro); // This is an extreme edge case where the accel and gyro measurements // do not overlap at all. if (oldest > newest) { return std::make_tuple(-1, -1, false); } return std::make_tuple(oldest, newest, true); } // A set of explicit declarations template class ImuBuffer<2000, InterpolatorLinear>; template class ImuBuffer<5000, InterpolatorLinear>; template class ImuBuffer<2000, InterpolatorNearest>; template class ImuBuffer<5000, InterpolatorNearest>; template class ImuBuffer<2000, InterpolatorDifferentiatorLinear, InterpolatorLinear>; template class ImuBuffer<5000, InterpolatorDifferentiatorLinear, InterpolatorLinear>; } // namespace ze
37.856522
90
0.733892
rockenbf
b31f20b37b5ecdb9921dbc8412cce7adb328b677
3,034
hpp
C++
core/injector/block_producing_node_injector.hpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
core/injector/block_producing_node_injector.hpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
core/injector/block_producing_node_injector.hpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CORE_INJECTOR_BLOCK_PRODUCING_NODE_INJECTOR_HPP #define KAGOME_CORE_INJECTOR_BLOCK_PRODUCING_NODE_INJECTOR_HPP #include "application/app_config.hpp" #include "application/impl/local_key_storage.hpp" #include "consensus/babe/impl/babe_impl.hpp" #include "consensus/babe/impl/syncing_babe_observer.hpp" #include "consensus/grandpa/impl/syncing_round_observer.hpp" #include "injector/application_injector.hpp" #include "injector/validating_node_injector.hpp" #include "runtime/dummy/grandpa_api_dummy.hpp" #include "storage/in_memory/in_memory_storage.hpp" namespace kagome::injector { namespace di = boost::di; template <typename... Ts> auto makeBlockProducingNodeInjector( const application::AppConfigPtr &app_config, Ts &&... args) { using namespace boost; // NOLINT; assert(app_config); return di::make_injector( // inherit application injector makeApplicationInjector(app_config->genesis_path(), app_config->leveldb_path(), app_config->rpc_http_endpoint(), app_config->rpc_ws_endpoint()), // bind sr25519 keypair di::bind<crypto::SR25519Keypair>.to( [](auto const &inj) { return get_sr25519_keypair(inj); }), // bind ed25519 keypair di::bind<crypto::ED25519Keypair>.to( [](auto const &inj) { return get_ed25519_keypair(inj); }), // compose peer keypair di::bind<libp2p::crypto::KeyPair>.to([](auto const &inj) { return get_peer_keypair(inj); })[boost::di::override], // peer info di::bind<network::OwnPeerInfo>.to( [p2p_port{app_config->p2p_port()}](const auto &injector) { return get_peer_info(injector, p2p_port); }), di::bind<consensus::Babe>.to( [](auto const &inj) { return get_babe(inj); }), di::bind<consensus::BabeLottery>.template to<consensus::BabeLotteryImpl>(), di::bind<network::BabeObserver>.to( [](auto const &inj) { return get_babe(inj); }), di::bind<consensus::grandpa::RoundObserver>.template to<consensus::grandpa::SyncingRoundObserver>(), di::bind<application::KeyStorage>.to( [app_config](const auto &injector) { return get_key_storage(app_config->keystore_path(), injector); }), di::bind<runtime::GrandpaApi>.template to<runtime::dummy::GrandpaApiDummy>() [boost::di::override], di::bind<crypto::CryptoStore>.template to( [app_config](const auto &injector) { return get_crypto_store(app_config->keystore_path(), injector); })[boost::di::override], // user-defined overrides... std::forward<decltype(args)>(args)...); } } // namespace kagome::injector #endif // KAGOME_CORE_INJECTOR_BLOCK_PRODUCING_NODE_INJECTOR_HPP
41
108
0.649637
FlorianFranzen
b320f1f2824b2938836eba833807f18832e371eb
5,423
cpp
C++
src/CourseContentsList.cpp
Midiman/stepmania
a55d5d614c4caa8b035b9b7cdca94017baba026b
[ "MIT" ]
1
2019-02-13T07:01:27.000Z
2019-02-13T07:01:27.000Z
src/CourseContentsList.cpp
Tatsh/stepmania
bff04ba72e9d578e922fd830819515559b535c45
[ "MIT" ]
null
null
null
src/CourseContentsList.cpp
Tatsh/stepmania
bff04ba72e9d578e922fd830819515559b535c45
[ "MIT" ]
null
null
null
#include "global.h" #include "CourseContentsList.h" #include "GameConstantsAndTypes.h" #include "RageLog.h" #include "Course.h" #include "Trail.h" #include "GameState.h" #include "XmlFile.h" #include "ActorUtil.h" #include "RageUtil.h" #include "Steps.h" REGISTER_ACTOR_CLASS( CourseContentsList ); CourseContentsList::~CourseContentsList() { FOREACH( Actor *, m_vpDisplay, d ) delete *d; m_vpDisplay.clear(); } void CourseContentsList::LoadFromNode( const XNode* pNode ) { int iMaxSongs = 5; pNode->GetAttrValue( "MaxSongs", iMaxSongs ); const XNode *pDisplayNode = pNode->GetChild( "Display" ); if( pDisplayNode == NULL ) { LuaHelpers::ReportScriptErrorFmt("%s: CourseContentsList: missing the Display child", ActorUtil::GetWhere(pNode).c_str()); return; } for( int i=0; i<iMaxSongs; i++ ) { Actor *pDisplay = ActorUtil::LoadFromNode( pDisplayNode, this ); pDisplay->SetUseZBuffer( true ); m_vpDisplay.push_back( pDisplay ); } ActorScroller::LoadFromNode( pNode ); } void CourseContentsList::SetFromGameState() { RemoveAllChildren(); if( GAMESTATE->GetMasterPlayerNumber() == PlayerNumber_Invalid ) return; const Trail *pMasterTrail = GAMESTATE->m_pCurTrail[GAMESTATE->GetMasterPlayerNumber()]; if( pMasterTrail == NULL ) return; unsigned uNumEntriesToShow = pMasterTrail->m_vEntries.size(); CLAMP( uNumEntriesToShow, 0, m_vpDisplay.size() ); for( int i=0; i<(int)uNumEntriesToShow; i++ ) { Actor *pDisplay = m_vpDisplay[i]; SetItemFromGameState( pDisplay, i ); this->AddChild( pDisplay ); } bool bLoop = pMasterTrail->m_vEntries.size() > uNumEntriesToShow; this->SetLoop( bLoop ); this->Load2(); this->SetTransformFromHeight( m_vpDisplay[0]->GetUnzoomedHeight() ); this->EnableMask( m_vpDisplay[0]->GetUnzoomedWidth(), m_vpDisplay[0]->GetUnzoomedHeight() ); if( bLoop ) { SetPauseCountdownSeconds( 1.5f ); this->SetDestinationItem( m_vpDisplay.size()+1 ); // loop forever } } void CourseContentsList::SetItemFromGameState( Actor *pActor, int iCourseEntryIndex ) { const Course *pCourse = GAMESTATE->m_pCurCourse; FOREACH_HumanPlayer(pn) { const Trail *pTrail = GAMESTATE->m_pCurTrail[pn]; if( pTrail == NULL || iCourseEntryIndex >= (int) pTrail->m_vEntries.size() || iCourseEntryIndex >= (int) pCourse->m_vEntries.size() ) continue; const TrailEntry *te = &pTrail->m_vEntries[iCourseEntryIndex]; const CourseEntry *ce = &pCourse->m_vEntries[iCourseEntryIndex]; if( te == NULL ) continue; RString s; Difficulty dc; if( te->bSecret ) { if( ce == NULL ) continue; int iLow = ce->stepsCriteria.m_iLowMeter; int iHigh = ce->stepsCriteria.m_iHighMeter; bool bLowIsSet = iLow != -1; bool bHighIsSet = iHigh != -1; if( !bLowIsSet && !bHighIsSet ) { s = "?"; } if( !bLowIsSet && bHighIsSet ) { s = ssprintf( ">=%d", iHigh ); } else if( bLowIsSet && !bHighIsSet ) { s = ssprintf( "<=%d", iLow ); } else if( bLowIsSet && bHighIsSet ) { if( iLow == iHigh ) s = ssprintf( "%d", iLow ); else s = ssprintf( "%d-%d", iLow, iHigh ); } dc = te->dc; if( dc == Difficulty_Invalid ) dc = Difficulty_Edit; } else { s = ssprintf("%d", te->pSteps->GetMeter()); dc = te->pSteps->GetDifficulty(); } Message msg("SetSong"); msg.SetParam( "PlayerNumber", pn ); msg.SetParam( "Song", te->pSong ); msg.SetParam( "Steps", te->pSteps ); msg.SetParam( "Difficulty", dc ); msg.SetParam( "Meter", s ); msg.SetParam( "Number", iCourseEntryIndex+1 ); msg.SetParam( "Modifiers", te->Modifiers ); msg.SetParam( "Secret", te->bSecret ); pActor->HandleMessage( msg ); } } // lua start #include "LuaBinding.h" /** @brief Allow Lua to have access to the CourseContentsList. */ class LunaCourseContentsList: public Luna<CourseContentsList> { public: static int SetFromGameState( T* p, lua_State *L ) { p->SetFromGameState(); COMMON_RETURN_SELF; } LunaCourseContentsList() { ADD_METHOD( SetFromGameState ); } }; LUA_REGISTER_DERIVED_CLASS( CourseContentsList, ActorScroller ) // lua end /* * (c) 2001-2004 Chris Danford * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL 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. */
28.244792
124
0.698506
Midiman
b32cbaa75e3a7496f340f5d835fafde175b5877c
1,233
cpp
C++
DSA/Graphs/Topological_Sort.cpp
ShrishtiAgarwal/DSA
8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df
[ "MIT" ]
null
null
null
DSA/Graphs/Topological_Sort.cpp
ShrishtiAgarwal/DSA
8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df
[ "MIT" ]
null
null
null
DSA/Graphs/Topological_Sort.cpp
ShrishtiAgarwal/DSA
8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df
[ "MIT" ]
null
null
null
/* Topological sort using bfs */ class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { int in_degree[numCourses]; for(int i=0;i<numCourses;i++) in_degree[i]=0; vector<int>q[numCourses]; vector<int>t; for(int i=0;i<prerequisites.size();i++) { int u=prerequisites[i][0]; int v=prerequisites[i][1]; in_degree[u]++; q[v].push_back(u); } queue<int>qp; for(int i=0;i<numCourses;i++) { if(in_degree[i]==0) qp.push(i); } if(qp.empty()==true) { vector<int>o; return o; } while(!qp.empty()) { int j=qp.front(); qp.pop(); t.push_back(j); for(int i=0;i<q[j].size();i++) { in_degree[q[j][i]]--; if(in_degree[q[j][i]]==0) qp.push(q[j][i]); } } if(t.size()==numCourses) return t; else { vector<int>o; return o; } } };
22.418182
79
0.394972
ShrishtiAgarwal
b333b03b2917ac62ad74a0bfaa214bb113a85ef3
430
cc
C++
P10-FundamentalAlgorithms&AdvancedExercises/P98179.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
P10-FundamentalAlgorithms&AdvancedExercises/P98179.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
P10-FundamentalAlgorithms&AdvancedExercises/P98179.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
//Inserció en taula ordenada #include <iostream> #include <vector> using namespace std; void insereix(vector<double>& v) { int tam = v.size(); for (int i = 1; i < tam; ++i) { double x = v[i]; int j = i; while (j > 0 && x < v[j - 1]) { v[j] = v[j - 1]; --j; } v[j] = x; } }
22.631579
47
0.351163
srmeeseeks
b3342d81ae0cdb7f677a1ecf5c5ca693c503cd90
1,224
cpp
C++
tests/categorytest.cpp
jgcoded/UVA-Arena-Qt
084cb5031e5faa8a9bfe5256959584a9cb0cf82b
[ "MIT" ]
1
2020-03-02T09:25:44.000Z
2020-03-02T09:25:44.000Z
tests/categorytest.cpp
jgcoded/UVA-Arena-Qt
084cb5031e5faa8a9bfe5256959584a9cb0cf82b
[ "MIT" ]
null
null
null
tests/categorytest.cpp
jgcoded/UVA-Arena-Qt
084cb5031e5faa8a9bfe5256959584a9cb0cf82b
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <memory> #include <QList> #include <QNetworkAccessManager> #include <QApplication> #include <QFrame> #include <QPushButton> #include <QVBoxLayout> #include <QFile> #include "mainwindow.h" #include "uhunt/uhunt.h" #include "uhunt/category.h" using namespace std; using namespace uva; int main(int argc, char* argv[]) { QApplication app(argc, argv); /* Category data file Download link: https://raw.githubusercontent.com/dipu-bd/uva-problem-category/master/data/CP%20Book3.cat */ QString file = "CP-Book-3.cat"; if (!QFile::exists(file)) { cout << "File does not exist." << endl; getchar(); return 0; } //Get category node QFile f(file); if (!f.open(QFile::ReadOnly | QFile::Text)) qDebug() << "Error while reading the file"; const QJsonDocument& jdoc = QJsonDocument::fromJson(f.readAll()); std::shared_ptr<Category> node(Category::fromJsonObject(jdoc.object())); cout << node->Name.toStdString() << endl; cout << node->Note.toStdString() << endl; cout << node->Problems.count() << endl; cout << node->Branches.count() << endl; return app.exec(); }
23.538462
110
0.640523
jgcoded
b33907f967ff49758d5a1f84e421620393fb82e4
66,803
hpp
C++
include/SSDK/Archive/Json/json.hpp
djc80s/c-cpp_study
3ea8289c358a2b732524ab391aa87c4a8fc0b6a7
[ "BSD-2-Clause" ]
null
null
null
include/SSDK/Archive/Json/json.hpp
djc80s/c-cpp_study
3ea8289c358a2b732524ab391aa87c4a8fc0b6a7
[ "BSD-2-Clause" ]
null
null
null
include/SSDK/Archive/Json/json.hpp
djc80s/c-cpp_study
3ea8289c358a2b732524ab391aa87c4a8fc0b6a7
[ "BSD-2-Clause" ]
null
null
null
#ifndef JSONHELPER_H #define JSONHELPER_H #include <string> #include <type_traits> #include <map> #include <iostream> #include <fstream> #include <memory> #include <stdio.h> #include <math.h> #include <boost/variant/variant.hpp> #include <boost/variant.hpp> #include <rapidjson/writer.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/document.h> //#include <rapidjson/filestream.h> #include <rapidjson/prettywriter.h> #include "Exception/customexception.hpp" #include "TypeTraits/typetraits.hpp" namespace SSDK { namespace Archive { /** * @brief This class is used to wrap Json operation * 参考: * 1.refer to <<深入应用c++11>> P310 “rapidjson的基本用法” * 2.rapidjson首页说明:http://rapidjson.org/zh-cn/ * * rapidjson基本操作: * 1.读操作: 从文件,从字符串,从对象(反序列化) * 2.创建一个Json对象 * 3.写文件: 到文件, 序列化 * 4.查询Object, 查询Array * 5.修改成员的值 * 6.删除/增加成员 * 7.删除/增加/清空Array的成员 * * @author rime * @version 1.00 2017-04-06 rime * note:create it */ class Json { public: //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //enum & unsing using JsonWriter = rapidjson::PrettyWriter<rapidjson::StringBuffer>; /** *RapidJson的数据类型分为以下几种: * union Data { * String s;(可以为null) * Number n;(bool,int,uint,int64,uint64,double) * Object o;(复杂对象, 可以包含各种类型的Value,所以它是老大,可以为null) * Array a; * }; * * 这4种类型都成为Value * */ /** * @brief The ValueType enum * Value的类型 * 对于最上层Value的类型(也就是doc), 对于Json只可能是Object和Array */ enum ValueType { NUMBER, STRING, ARRAY, OBJECT }; //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //constructor & deconstructor /** * 仅仅是创建一个对象,没有任何数据 */ Json(); /** * @brief Json * 创建Json对象后进行读取操作 * @param str * 1.当从文件读取时,str表示文件路径 * 2.当从字符串读取时,str表示读取的字符串 * @param isFromString * true:从字符串读取 * false:从文件读取 */ Json(const std::string& str, bool isFromString); Json(const QString &str,bool isFromString); virtual ~Json(); //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //get & set functions rapidjson::Value& doc(){return this->m_doc;} JsonWriter& write(){return this->m_writer;} //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //read functions /** * @brief loadFromFile * 读取一个Json文件 * @param filePath * 文件路径 * 如果文件不存在或者打开失败,该函数不进行任何操作 */ void loadFromFile(const std::string& filePath); void loadFromFile(const QString& filePath); // void loadFromDoc(const rapidjson::Document& doc); /** * @brief parseFromString * 从字符串解析得到一个Json对象 * @param JsonString * 对应Json的字符串 */ void parseFromString(const std::string& jsonString); void parseFromString(const QString& jsonString); void parseFromString(const char* jsonStr); /** * 返回对象序列化后端的json字符串 */ const char* toString() ; /** * @brief docType * @return * 获取Doc的类型, 只可能是Object或者Array */ ValueType docType(); //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //write functions //>>>------------------------------------------------------------------------------------------------------------------------------------- //1. write string for json creation /** *writeValue 创建一个Json对象的时候通过writeValue写键值对 */ template<typename V>//int typename std::enable_if<std::is_same<V, int>::value>::type writeValue(const V& value); template<typename V>//int typename std::enable_if<std::is_same<V, uint>::value>::type writeValue(const V& value); template<typename V>//long unsigned int(uint64) typename std::enable_if<std::is_same<V,uint64_t>::value>::type writeValue(const V& value); template<typename V>//int64 typename std::enable_if<std::is_same<V, int64_t>::value>::type writeValue(const V& value); template<typename V>//float or double typename std::enable_if<std::is_floating_point<V>::value>::type writeValue(const V& value); template<typename V>//bool typename std::enable_if<std::is_same<V, bool>::value>::type writeValue(const V& value); void writeValue(const char* value); template<typename V>//null typename std::enable_if<std::is_same<V, std::nullptr_t>::value>::type writeValue(const V& value); template<typename T> void writeValue(const char* key, const T& value); /** * 序列化结构体数组之前需要调用此接口,然后再循环去序列化 */ void startArray(); void endArray(); /** *每次写一个对象都要调用startObject函数,结束调用endObject */ void startObject(); void endObject(); //>>>------------------------------------------------------------------------------------------------------------------------------------- //2. serialization /** * @brief writeToFile * 写一个Json对象到文件 * @param filePath * 文件保存路径 */ void writeToFile(const QString& filePath); void writeToFile(const std::string& filePath); //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //query function //>>>------------------------------------------------------------------------------------------------------------------------------------- //0.Value /** * @brief queryValue * 在obj查找指定key的Value * @param parentKey * 父Value的Name * @param childKey * 子Value的Name * @param isFound * 是否找到对应的Value, 如果找到返回true,否则返回false * @return * 返回查找到的Value */ rapidjson::Value& queryValue( const char* parentKey, const char* childKey, bool& isFound); /** * @brief queryValue * 在obj查找指定key的对象. * @param key * 查找的起始value * @param isFound * 输入参数:是否已经到对对象, 找到设置为true, 否则设置为false * @return * 返回查找到的Value */ rapidjson::Value& queryValue(const char* key, bool& isFound); /** * @brief queryValue * 在obj查找指定key的Value. * @param obj * 查找的起始value * @param key * 需要查找的对象的name * @param isFound * 输入参数:是否已经到对对象, 找到设置为true, 否则设置为false * @return * 输出参数:是否已经找到对象 * * 注意: * 1.该函数能够遍历json树, * 如果找到对象key的对象,返回第一个满足条件的对象,返回true * 如果没有任何满足条件的对象,返回false * * 2.该函数只支持在Object中查找, 无法搜索在Array中的对象, rapid中FindMember本身就不支持查找Array对象 */ static rapidjson::Value& queryValue( rapidjson::Value& obj, const char* key, bool& isFound); //>>>------------------------------------------------------------------------------------------------------------------------------------- //1.Number /** * @brief queryNumber * 查询指定key的Number, 包含了多个重载函数 * @param parentKey * Number所在的上一层Value的Name * @param childKey * Number所在的Value的Name * @return * 返回查找到的Number * * 注意: * 1.childKey任意一个为key都会抛出异常, parentKey为null时默认从最上层开始查找 * 2.没有key的成员或者key的类型和T的类型不匹配时,会抛出异常 * 3.当key的成员类型为数组时, 会被忽略掉, 最终还是会触发没有找到的异常 * 4.当key的成员存在并类型匹配时,返回该成员 * 5.使用enable_if进行函数的重载时,能够实现仅仅返回参数类型不同的重载(其它方式做不到) * */ template<typename T> T queryNumber(const char* parentKey, const char* childKey); /** *和上面的重载函数类似,只不过没有parentKey参数,那么默认就是从json的最上层开始检索 * 这样可能存在Json文件中不同的Object中含有相同Name的Value, 这种情况下类型不一致就会引发异常 */ template<typename T> T queryNumber(const char* key); /** * @brief queryNumber * 查询指定key的Number * @param value * 查找Number所在的父Value * @param key * Number所在的Value的Name * @param isFound * 是否已经找到, 找到返回true, 没找到的话返回false * @return * 查找到的Number, isFound为false, 请忽略该值 */ template<typename T> static T queryNumber(rapidjson::Value& value,const char* key,bool& isFound); //>>>------------------------------------------------------------------------------------------------------------------------------------- //2.String /** * @brief queryString * 查询指定key的Number, 包含了多个重载函数 * @param parentKey * String所在的上一层Value的Name * @param childKey * String所在的Value的Name * @return * 返回查找到的String * * 注意: * 1.childKey任意一个为key都会抛出异常, parentKey为null时默认从最上层开始查找 * 2.没有key的成员或者key的类型和T的类型不匹配时,会抛出异常 * 3.当key的成员类型为数组时, 会被忽略掉, 最终还是会触发没有找到的异常 * 4.当key的成员存在并类型匹配时,返回该成员 * */ const char* queryString(const char* parentKey, const char* childKey); /** *和上面的重载函数类似,只不过没有parentKey参数,那么默认就是从json的最上层开始检索 * 这样可能存在Json文件中不同的Object中含有相同Name的Value, 这种情况下类型不一致就会引发异常 */ const char* queryString(const char* key); static const char* queryString(rapidjson::Value& value,bool& isTypeMatched); static const char* queryString(rapidjson::Value& value, const char* key, bool& isFound); //>>>------------------------------------------------------------------------------------------------------------------------------------- //3.Array /** * 查询指定key的Array, 包含了多个重载函数 * * 注意: * 1.对于数组来说 * 返回Value, 因为Array中可能包含不同的类型, 由调用方进一步解析 * 当Array的所有成员都属于同一类型的话,那么可以直接返回一个vector, 但是需要进行类型验证 * 2.支持嵌套在一个Object层级结构中的数组对象的查询, 即Array并不是在Object的最上层 * 3.rapidjson不支持数组嵌套数组的情况(包括最新的版本) */ /** * @brief querryArray * 查询指定key的Array * @param parentObjKey * 父Object的Name * @param arrayName * Array的Name * @param isFound * 输入参数:是否已经到对对象, 找到设置为true, 否则设置为false * @return * 找到的Array类型的Value */ rapidjson::Value& queryArray(const char* parentObjKey, const char* arrayName, bool& isFound); /** *和上面的重载函数类似,只不过没有parentObjKey参数,那么默认就是从json的最上层开始检索 * 这样可能存在Json文件中不同的Object中含有相同Name的Value, 这种情况下类型不一致就会引发异常 */ rapidjson::Value& queryArray(const char* arrayName, bool& isFound); /** * @brief queryArray * 查询指定key的Array * @param parentObjKey * 父Object的Name * @param arrayName * 需要查找的数组的arrayName * @param vector * 输出参数, 查找到的对象放置在这个vector容器中 * @return * 查询成功返回true, 否则返回false * * 注意: * 只有当Array的成员类型完全一样时才生效, 否则返回false */ template<typename T> bool queryArray(const char* parentObjKey,const char* arrayName, std::vector<T>& vector); /** * @brief queryArray * 查询指定key的Array * @param arrayName * 需要查找的数组的arrayName * @param vector * 输出参数, 查找到的对象放置在这个vector容器中 * @return * 查询成功返回true, 否则返回false * * 注意: * 只有当Array的成员类型完全一样时才生效, 否则返回false */ template<typename T> bool queryArray(const char* arrayName, std::vector<T>& vector); /** * @brief queryDocArrayBasedOnIndex * 当doc为array类型时, 根据返回对象的值 * @param index * Array的索引 * @param elementName * 数组成员的名称 * @return * 返回的值 * * 注意: * 1.只有当doc为Array类型时,才能调用该方法, 否则会抛出异常 * 2.doc为Array时, elememt一般为简单类型, 即Number和String * 3.elementName不能为null, 否则会抛出异常 */ template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T,uint64_t>::value)|| (std::is_same<T, double>::value),T>::type queryNumberOfDocArray( int index, const char* elementName); const char* queryStringOfDocArray( int index, const char* elementName); // template<typename T> // T queryDocArrayBasedOnIndex( int objIndex , int elementIndex); /** * @brief queryEmbededArrayElementBasedOnIndex * 当doc不是array类型时, 即array作为doc的一个嵌入数组, 根据索引返回对象的值 * @param parentObjKey * array对象所在的父对象的Key * @param arrayName * 嵌入对象的Name * @param index * 访问对象的索引 * @return * 返回的值 * * 注意: * 该函数只有在数组中所有成员的类型一致时才能时候, 否则将抛出异常 */ template<typename T> T queryEmbededArrayBasedOnIndex(const char* parentObjKey,const char* arrayName, uint index); template<typename T> T queryEmbededArrayBasedOnIndex(const char* arrayName, uint index); template<typename T> T queryLastElementOfEmbededArray(const char* parentObjKey,const char* arrayName); template<typename T> T queryLastElementOfEmbededArray(const char* arrayName); template<typename T> T queryFirstElementOfEmbededArray(const char* parentObjKey,const char* arrayName); template<typename T> T queryFirstElementOfEmbededArray(const char* arrayName); /** * @brief getArrayCount * 获取到Array成员的数量 * @param parentObjKey * Array所在的父Value * @param arrayName * Array的名称 * @return * Array成员的数量 * * 当获取失败时, 返回-1 */ int getArrayCount(const char* parentObjKey, const char* arrayName); /** *和上面的重载函数类似,只不过没有parentObjKey参数,那么默认就是从json的最上层开始检索 * 这样可能存在Json文件中不同的Object中含有相同Name的Value, 这种情况下类型不一致就会引发异常 */ int getArrayCount(const char* arrayName); /** * @brief getArrayCount * 当Doc为Array类型时,返回其长度 * @return * Doc为数组的长度, 当Doc不是数组时,返回-1 */ int getArrayCount(); //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //modify functions //>>>------------------------------------------------------------------------------------------------------------------------------------- //1.Number /** * @brief modifyNumber * 修正指定key的value, 包含如下行为 * 对于Number, 具体是bool, int, uint, int64, uint64, double * @param parentKey * 父对象的name * @param childKey * 子对象的name * @param value * 需要修正的值 * * * 注意: * 1.没有key的成员或者key的类型和T的类型不匹配时,会抛出异常 * 2.当key的成员存在并类型匹配时,会修正该值 * 3.虽然下面几个函数都是模板函数, 可以支持任何类型的输入, 但是内部调用的modify模板函数都是有类型收窄的, 一旦都不支持的类型输入,编译将报错 * 4.不支持原来是Number类型的成员对象设置为指定类型( 官方文档没有类似的set函数 ) */ template<typename T> void modifyNumber(const char* parentKey, const char* childKey, const T& value); template<typename T> void modifyNumber(const char* key, const T& value);//主要用于const char*/char* ,这2中类型不会调用上面的重载 //>>>------------------------------------------------------------------------------------------------------------------------------------- //2.String /** * @brief modifyString * 修正指定key的value, 包含如下行为 * 对于String类型, 原来是null类型的对象可以设置为string * @param parentKey * 父Value的name * @param childKey * 需要修改的value的name * * @param value * 需要查找的值 * * * 注意: * 1.没有key的成员或者key的类型和T的类型不匹配时,会抛出异常 * 2.当key的成员存在并类型匹配时,会修正该值 * 3.虽然下面几个函数都是模板函数, 可以支持任何类型的输入, 但是内部调用的modify模板函数都是有类型收窄的, 一旦都不支持的类型输入,编译将报错 * 4.不支持原来是null类型的成员对象设置为指定类型( 官方文档没有类似的set函数 ) * 5.不支持直接修正一个Value类型的成员(即需要指定到基础类型,如Number和String的修改,大对象的修改需要分解到小对象, 官方文档没有类似的set函数) */ void modifyString(const char* parentKey, const char* childKey, const char* value); void modifyString(const char* key, const char* value); //>>>------------------------------------------------------------------------------------------------------------------------------------- //3.Array /** * 修改指定key的Array, 包含如下行为 * 1. 增加成员 * 2. 删除成员 * 3. 清空Array * 4. 修改成员 */ /** * @brief pushValBackToArray * 在Array末尾插入Value成员 * @param parentKey * 父对象的Key * @param childkey * Array的Key * @param newElementVal * 待插入的Value * @return * 插入成功返回true, 插入失败返回false * * 注意: * 1.当没有找到指定Key的Array,抛出异常 * 2.当插入的Val类型无法匹配Array中现有成员的类型,抛出异常 */ bool pushValBackToArray(const char* parentKey, const char* childkey, rapidjson::Value& newElementVal); bool pushValBackToArray(const char* key, rapidjson::Value& newElementVal); /** * @brief pushNumberBackToArray * 在Array末尾插入一个Number成员 * @param parentKey * 父对象的Key * @param childkey * Array的Key * @param newElementVal * 待插入的Value * @return * 插入成功返回true, 插入失败返回false * * 注意: * 1.当没有找到指定Key的Array,抛出异常 * 2.当插入的Val类型无法匹配Array中现有成员的类型,抛出异常 */ template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T, double>::value), bool>::type pushNumberBackToArray(const char* parentKey,const char* childkey, const T& newElementVal); template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T, double>::value), bool>::type pushNumberBackToArray(const char* key, const T& newElementVal); /** * @brief pushStringBackToArray * 在Array末尾插入Value成员 * @param parentkey * 父对象的Key * @param childkey * Array的Key * @param newElementVal * 待插入的Value * @return * 插入成功返回true, 插入失败返回false */ bool pushStringBackToArray(const char *parentkey,const char *childkey, const char *newElementVal); bool pushStringBackToArray(const char* key, const char* newElementVal); /** * @brief popBackFromArray * 移除Array末尾的成员 * @param parentkey * 父对象的Key * @param childKey * Array的Key * @return * 插入成功返回true, 插入失败返回false */ bool popBackFromArray(const char *parentkey,const char* childKey); bool popBackFromArray(const char* key); bool clearArray(const char *parentkey,const char *childKey); bool clearArray(const char* key); /** * @brief modifyElementOfArrayBasedOnIndex * 修改Array指定index的值 * @param parentKey * Array的父对象的Key * @param childKey * Array的Key * @param index * 修改Array的Index * @param value * 待修改的值 * * 注意 * 涉及到修改单个成员: * 1.如果Array的成员是复杂类型, 即成员由不同类型的Object组成,请使用queryArray得到数组的Array, 然后再手动修改 * 2.如果Array的成员是简单类型, 请使用modifyArrayElementBasedOnIndex修改 */ template<typename T> bool modifyNumberElementOfArrayBasedOnIndex(const char* parentKey,const char* childKey, uint index, const T& value); template<typename T> bool modifyNumberElementOfArrayBasedOnIndex(const char* key, uint index, const T& value); bool modifyStringElementOfArrayBasedOnIndex(const char* parentKey,const char* childKey, uint index, const char* value); bool modifyStringElementOfArrayBasedOnIndex(const char* key, uint index, const char* value); //>>>------------------------------------------------------------------------------------------------------------------------------------- //4.Object /** * 添加删除成员操作, * 1.这里的操作是指针对Object类型的Value, 可以添加和删除成员, 不包括基础类型(Number&String)和Array * 2.不同于查询, add/remove 的成员可能是复杂的对象,如果再进一步拆解成基础类型会很不方便,同时官网API也只是支持到Value */ /** * @brief addValueToObject * 增加一个Value到Object * @param parentKey * 需要被添加的Object的value * @param childKey * 需要添加的子Value的name * @param childValue * 需要添加的Value * */ void addValueToObject(const char* parentKey, const char* childKey, const char* memName, rapidjson::Value& childValue); void addValueToObject(const char *key,const char* memName, rapidjson::Value &childValue); /** * @brief Json::addStringToObject * 增加一个String到Object * @param parentKey * Object所在的父Object的name * @param childKey * Object的name * @param memName * 待添加的Object的name * @param memVal * 待添加的Object的value */ void addStringToObject(const char *parentKey, const char *childKey, const char *memName, const char* memVal); void addStringToObject(const char *key, const char *memName, const char* memVal); /** * @brief addNumberToObject * 增加一个Number到Object * @paramt T * 待添加Number的类型,这里可以为bool,int,uint,int64,uint64和double * @param parentKey * Object所在的父Object的name * @param childKey * Object的name * @param memName * 待添加的Object的name * @param memVal * 待添加的Object的value */ template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T,uint64_t>::value)|| (std::is_same<T, double>::value)>::type addNumberToObject(const char *parentKey, const char *childKey, const char *memName, const T& memVal); template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T,uint64_t>::value)|| (std::is_same<T, double>::value)>::type addNumberToObject(const char *key, const char *memName, const T& memVal); /** * @brief removeMemberFromObject * 从Object中移除成员 * @param parentKey * Object所在的父Object的name * @param childKey * Object的name * @param memName * 待添加的Object的name */ void removeMemberFromObject(const char *parentKey, const char *childKey,const char *memName); void removeMemberFromObject(const char *key,const char *memName); private: //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //member variant rapidjson::StringBuffer m_buf; JsonWriter m_writer; rapidjson::Document m_doc; //是否需要重新accept, 默认不需要, 但是当发生修改时,需要重写accept bool m_isReAccept{false}; //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //query functions //>>>------------------------------------------------------------------------------------------------------------------------------------- //1.Number /** *queryNumber 在Value查询不同类型的Number */ template<typename T> typename std::enable_if<std::is_same<T, bool>::value, T>::type//bool static queryNumber(rapidjson::Value& value, bool& isTypeMatched); template<typename T> typename std::enable_if<std::is_same<T, int>::value, T>::type//int static queryNumber(rapidjson::Value& value, bool& isTypeMatched); template<typename T> typename std::enable_if<std::is_same<T, uint>::value, T>::type//uint static queryNumber(rapidjson::Value& value, bool& isTypeMatched); template<typename T> typename std::enable_if<std::is_same<T, int64_t>::value, T>::type//int64 static queryNumber(rapidjson::Value& value, bool& isTypeMatched); template<typename T> typename std::enable_if<std::is_same<T, uint64_t>::value, T>::type//uint64 static queryNumber(rapidjson::Value& value, bool& isTypeMatched); template<typename T> typename std::enable_if<std::is_same<T,double>::value, T>::type//double or float static queryNumber(rapidjson::Value& value, bool& isTypeMatched); //>>>------------------------------------------------------------------------------------------------------------------------------------- //2.string //... //>>>------------------------------------------------------------------------------------------------------------------------------------- //3.Array /** * @brief queryArray * 查询指定key的Array * @param parentObj * 查找数组的起始Object * @param arrayName * 需要查找的数组的name * @param resVal * 输出参数, 查找到的对象 * @return * 是否已经找到对象, 找到的话返回true;否则返回false * */ rapidjson::Value& queryArray( rapidjson::Value& parentObj, const char* arrayName, bool& isFound); //>>>------------------------------------------------------------------------------------------------------------------------------------- //4.Object //... //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //modify functions //>>>------------------------------------------------------------------------------------------------------------------------------------- //1.Number /** *以下的重载modify函数都是用于按照类型modify对应的key值 * 1.当输入的模板类型不支持或者模板类型与key值类型不符合时,返回false * 2.设置成功返回true */ template<typename T> typename std::enable_if<std::is_same<T, bool>::value, bool>::type//bool modifyNumber( rapidjson::Value& val, const T& value); template<typename T> typename std::enable_if<std::is_same<T, int>::value, bool>::type//int modifyNumber( rapidjson::Value& val, const T& value); template<typename T> typename std::enable_if<std::is_same<T, uint>::value, bool>::type//uint modifyNumber( rapidjson::Value& val, const T& value); template<typename T> typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type//int64_t modifyNumber( rapidjson::Value& val, const T& value); template<typename T> typename std::enable_if<std::is_same<T, uint64_t>::value, bool>::type//uint64_t modifyNumber( rapidjson::Value& val, const T& value); template<typename T> typename std::enable_if<std::is_same<T, double>::value, bool>::type//double modifyNumber( rapidjson::Value& val, const T& value); //>>>------------------------------------------------------------------------------------------------------------------------------------- //2.String bool modifyString( rapidjson::Value& val, const char* value); //>>>------------------------------------------------------------------------------------------------------------------------------------- //3.Array /** *以下几个重载函数:pushElementToVector * 在Array所有成员类型全部一致,并且为简单类型(string, number, nullptr)的情况下封装到一个外部传入的vector中 */ template<typename T> typename std::enable_if<std::is_same<T, bool>::value, bool>::type//bool pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const; template<typename T> typename std::enable_if<std::is_same<T, int>::value, bool>::type//int pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const; template<typename T> typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type//int64_t pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const; template<typename T> typename std::enable_if<std::is_same<T, uint64_t>::value, bool>::type//uint64_t pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const; template<typename T> typename std::enable_if<std::is_same<T, double>::value, bool>::type//double pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const; template<typename T> typename std::enable_if<std::is_same<T, std::string>::value, bool>::type//string pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const; template<typename T> typename std::enable_if<std::is_same<char*, T>::value || std::is_same<const char*,T>::value, bool>::type//char* or const char* pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const; //>>>------------------------------------------------------------------------------------------------------------------------------------- //4.Object //... //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- };//End of Json }//End of namespace Archive }//End of namespace SSDK //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //write functions template<typename V>//int typename std::enable_if<std::is_same<V, int>::value>::type SSDK::Archive::Json::writeValue(const V& value) { m_writer.Int(value); } template<typename V>//int typename std::enable_if<std::is_same<V, uint>::value>::type SSDK::Archive::Json::writeValue(const V& value) { m_writer.Uint(value); } template<typename V>//long unsigned int(uint64) typename std::enable_if<std::is_same<V,uint64_t>::value>::type SSDK::Archive::Json::writeValue(const V& value) { m_writer.Uint64(value); } template<typename V>//int64 typename std::enable_if<std::is_same<V, int64_t>::value>::type SSDK::Archive::Json::writeValue(const V& value) { m_writer.Int64(value); } template<typename V>//float or double typename std::enable_if<std::is_floating_point<V>::value>::type SSDK::Archive::Json::writeValue(const V& value) { m_writer.Double(value); } template<typename V>//bool typename std::enable_if<std::is_same<V, bool>::value>::type SSDK::Archive::Json::writeValue(const V& value) { m_writer.Bool(value); } template<typename V>//null typename std::enable_if<std::is_same<V, std::nullptr_t>::value>::type SSDK::Archive::Json::writeValue(const V& value) { m_writer.Null(); } template<typename T> void SSDK::Archive::Json::writeValue(const char* key, const T& value) { m_writer.String(key); writeValue(value); } //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //query functions //>>>------------------------------------------------------------------------------------------------------------------------------------- //1.Number template<typename T> T SSDK::Archive::Json::queryNumber(const char* key) { return queryNumber<T>(nullptr, key); } template<typename T> T SSDK::Archive::Json::queryNumber(const char* parentKey, const char* childKey) { using namespace rapidjson; bool isFound = false; auto& childVal = queryValue(parentKey,childKey,isFound);//找出子Value if(isFound) { bool isTypeMatched = false; auto val = queryNumber<T>(childVal,isTypeMatched); if(!isTypeMatched) { THROW_EXCEPTION_WITH_OBJ("Type of Member["+std::string(childKey)+"] is not matched!"); } else { return val; } } else { THROW_EXCEPTION_WITH_OBJ("Member["+std::string(childKey)+"] is not found!"); } } template<typename T> typename std::enable_if<std::is_same<T, bool>::value, T>::type//bool SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched) { isTypeMatched = false; if(value.IsBool()) { isTypeMatched = true; return value.GetBool(); } else { return false; } } template<typename T> T SSDK::Archive::Json::queryNumber(rapidjson::Value& value,const char* key,bool& isFound) { isFound = false; auto& val = queryValue(value,key, isFound); return queryNumber<T>(val,isFound); } template<typename T> typename std::enable_if<std::is_same<T, int>::value, T>::type//int SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched) { isTypeMatched = false; if(value.IsInt()) { isTypeMatched = true; return value.GetInt(); } else { return 0; } } template<typename T> typename std::enable_if<std::is_same<T, uint>::value, T>::type//uint SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched) { isTypeMatched = false; if(value.IsUint()) { isTypeMatched = true; return value.GetUint(); } else { return 0; } } template<typename T> typename std::enable_if<std::is_same<T, int64_t>::value, T>::type//int64 SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched) { isTypeMatched = false; if(value.IsInt64()) { isTypeMatched = true; return value.GetInt64(); } else { return 0; } } template<typename T> typename std::enable_if<std::is_same<T, uint64_t>::value, T>::type//uint64 SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched) { isTypeMatched = false; if(value.IsUint64()) { isTypeMatched = true; return value.GetUint64(); } else { return 0; } } template<typename T> typename std::enable_if<std::is_same<T,double>::value, T>::type//double or float SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched) { isTypeMatched = false; if(value.IsDouble()) { isTypeMatched = true; return value.GetDouble(); } else { return 0.0; } } //>>>------------------------------------------------------------------------------------------------------------------------------------- //2.String //>>>------------------------------------------------------------------------------------------------------------------------------------- //3.Array template<typename T> bool SSDK::Archive::Json::queryArray(const char* arrayName, std::vector<T>& vector) { using namespace rapidjson; bool isFound = false; auto& val = queryArray(this->m_doc, arrayName, isFound);; if(isFound && val.IsArray()) { //注意,这里要使用Begin(), 而不是MemberBegin for (auto itr = val.Begin(); itr != val.End(); ++itr) { pushElementOfArrayToVector(itr,vector); } return true; } else { return false; } } template<typename T> bool SSDK::Archive::Json::queryArray(const char* parentObjKey,const char* arrayName, std::vector<T>& vector) { using namespace rapidjson; bool isFound = false; auto& val = queryValue(parentObjKey, arrayName, isFound);; if(isFound && val.IsArray()) { //注意,这里要使用Begin(), 而不是MemberBegin for (auto itr = val.Begin(); itr != val.End(); ++itr) { pushElementOfArrayToVector(itr,vector); } return true; } else { return false; } } template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T,uint64_t>::value)|| (std::is_same<T, double>::value),T>::type SSDK::Archive::Json::queryNumberOfDocArray( int index, const char* elementName) { if(nullptr == elementName) { THROW_EXCEPTION_WITH_OBJ("Element Name can not be nullptr"); } if(this->m_doc.IsArray()) { int elementCnt = this->m_doc.Size(); if(index<0 || index>elementCnt-1) { std::ostringstream stream; stream<<"Index["<<index<<"] is invaild, it must be in[0,"<<elementCnt - 1<<"]"; THROW_EXCEPTION_WITH_OBJ( stream.str()); } else { bool isFound {false}; auto& value = queryValue( this->m_doc[index],elementName,isFound); if(!isFound) { THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(elementName)+"] is not found!" ); } else { bool isMatched {false}; return queryNumber<T>(value,isMatched); } } } else { THROW_EXCEPTION_WITH_OBJ("Doc must be array type"); } } template<typename T> T SSDK::Archive::Json::queryEmbededArrayBasedOnIndex(const char* parentObjKey,const char* arrayName, uint index) { using namespace rapidjson; std::vector<T> vector; bool isFound = queryArray(parentObjKey,arrayName,vector); if(!isFound) { THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(arrayName)+"] is not found!" ); } else { if(index > vector.size()) { std::ostringstream stream; stream<<"Index["<<index<<"] is invaild, it must be in[0,"<<vector.size()<<"]"; THROW_EXCEPTION_WITH_OBJ( stream.str() ); } else { return vector[index]; } } return true; } template<typename T> T SSDK::Archive::Json::queryEmbededArrayBasedOnIndex(const char* arrayName, uint index) { return queryEmbededArrayBasedOnIndex<T>(nullptr,arrayName,index); } template<typename T> T SSDK::Archive::Json::queryLastElementOfEmbededArray(const char* parentObjKey,const char* arrayName) { using namespace rapidjson; std::vector<T> vector; bool isFound = queryArray(parentObjKey,arrayName,vector); if(!isFound) { THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(arrayName)+"] is not found!" ); } else { if(vector.size()==0) { return vector[0]; } else { return vector[vector.size()-1]; } } } template<typename T> T SSDK::Archive::Json::queryLastElementOfEmbededArray(const char* arrayName) { return queryLastElementOfEmbededArray<T>(nullptr,arrayName); } template<typename T> T SSDK::Archive::Json::queryFirstElementOfEmbededArray(const char* parentObjKey,const char* arrayName) { using namespace rapidjson; std::vector<T> vector; bool isFound = queryArray(parentObjKey,arrayName,vector); if(!isFound) { THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(arrayName)+"] is not found!" ); } else { if(!isFound) { THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(arrayName)+"] is not found!" ); } else { return vector[0]; } } // return true; } template<typename T> T SSDK::Archive::Json::queryFirstElementOfEmbededArray(const char* arrayName) { return queryFirstElementOfEmbededArray<T>(nullptr, arrayName); } //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //>>>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //modify functions //>>>------------------------------------------------------------------------------------------------------------------------------------- //1.Number template<typename T> void SSDK::Archive::Json::modifyNumber(const char* parentKey, const char* childKey, const T& value) { using namespace rapidjson; bool isFound{false}; auto& val = queryValue(parentKey,childKey,isFound); if(isFound)//对于rapidjson v1.0 需要判断是否为0, 对于最新的v1.1 要判断是否为EndMember { if(!modifyNumber<T>(val, value)) { THROW_EXCEPTION_WITH_OBJ("Member["+std::string(parentKey)+"] is bool type!"); } this->m_isReAccept = true; } else { THROW_EXCEPTION_WITH_OBJ("Member["+std::string(parentKey)+"] is not found!"); } } template<typename T> void SSDK::Archive::Json::modifyNumber(const char* key, const T& value)//主要用于const char*/char* ,这2中类型不会调用上面的重载 { modifyNumber(nullptr,key,value); } template<typename T> typename std::enable_if<std::is_same<T, bool>::value, bool>::type//bool SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value) { if(val.IsBool()) { val.SetBool(value); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, int>::value, bool>::type//int SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value) { if(val.IsInt()) { val.SetInt(value); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, uint>::value, bool>::type//uint SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value) { if(val.IsUint()) { val.SetUint(value); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type//int64_t SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value) { if(val.IsInt64()) { val.SetInt64(value); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, uint64_t>::value, bool>::type//uint64_t SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value) { if(val.IsUint64()) { val.SetUint64(value); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, double>::value, bool>::type//double SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value) { if(val.IsDouble()) { val.SetDouble(value); return true; } else { return false; } } //>>>------------------------------------------------------------------------------------------------------------------------------------- //3.Array /** * @brief modifyElementOfArrayBasedOnIndex * 修改Array指定index的值 * @param parentKey * Array的父对象的Key * @param childKey * Array的Key * @param index * 修改Array的Index * @param value * 待修改的值 * * 注意 * 涉及到修改单个成员: * 1.如果Array的成员是复杂类型, 即成员由不同类型的Object组成,请使用queryArray得到数组的Array, 然后再手动修改 * 2.如果Array的成员是简单类型, 请使用modifyArrayElementBasedOnIndex修改 */ template<typename T> bool SSDK::Archive::Json::modifyNumberElementOfArrayBasedOnIndex(const char* parentKey,const char* childKey, uint index, const T& value) { using namespace rapidjson; bool isFound = false; auto& val = queryValue(parentKey,childKey,isFound); if(isFound && val.IsArray()) { if(index<0 || index > val.Size()) { std::ostringstream stream; stream<<"Index["<<index<<"] is invaild, it must be in[0,"<<val.Size()<<"]"; THROW_EXCEPTION_WITH_OBJ( stream.str() ); } else { modifyNumber(val[index], value); } } else { THROW_EXCEPTION_WITH_OBJ("Member["+std::string(childKey)+"] is not found!"); } } template<typename T> bool SSDK::Archive::Json::modifyNumberElementOfArrayBasedOnIndex(const char* key, uint index, const T& value) { using namespace rapidjson; bool isSuccessful{false}; bool isFound {false}; auto& val = queryValue(this->m_doc,key,isFound); if(isFound && val.IsArray()) { if( index > val.Size()) { std::ostringstream stream; stream<<"Index["<<index<<"] is invaild, it must be in[0,"<<val.Size()<<"]"; THROW_EXCEPTION_WITH_OBJ( stream.str() ); } else { isSuccessful = modifyNumber(val[index], value); } } else { THROW_EXCEPTION_WITH_OBJ("Member["+std::string(key)+"] is not found!"); } return isSuccessful; } template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T, double>::value), bool>::type SSDK::Archive::Json::pushNumberBackToArray(const char* parentKey,const char* childkey, const T& newElementVal) { rapidjson::Value val(newElementVal); return pushValBackToArray(parentKey,childkey,val); } template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T, double>::value), bool>::type SSDK::Archive::Json::pushNumberBackToArray(const char* key, const T& newElementVal) { return pushNumberBackToArray(nullptr,key,newElementVal); } template<typename T> typename std::enable_if<std::is_same<T, bool>::value, bool>::type//bool SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const { if(arrayElementVal->IsBool()) { vector.push_back(arrayElementVal->GetBool()); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, int>::value, bool>::type//int SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const { if(arrayElementVal->IsInt()) { vector.push_back(arrayElementVal->GetInt()); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type//int64_t SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const { if(arrayElementVal->IsInt64()) { vector.push_back(arrayElementVal->GetInt64()); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, uint64_t>::value, bool>::type//uint64_t SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const { if(arrayElementVal->IsUint64()) { vector.push_back(arrayElementVal->GetUint64()); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, double>::value, bool>::type//double SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const { if(arrayElementVal->IsDouble()) { vector.push_back(arrayElementVal->GetDouble()); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<T, std::string>::value, bool>::type//string SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const { if(arrayElementVal->IsString()) { vector.emplace_back(std::string(arrayElementVal->GetString())); return true; } else { return false; } } template<typename T> typename std::enable_if<std::is_same<char*, T>::value || std::is_same<const char*,T>::value, bool>::type//char* or const char* SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const { if(arrayElementVal->IsString()) { vector.push_back((T)arrayElementVal->GetString()); return true; } else { return false; } } //>>>------------------------------------------------------------------------------------------------------------------------------------- //4.Object /** * @brief addNumberToObject * 增加一个Number到Object * @paramt T * 待添加Number的类型,这里可以为bool,int,uint,int64,uint64和double * @param parentKey * Object所在的父Object的name * @param childKey * Object的name * @param memName * 待添加的Object的name * @param memVal * 待添加的Object的value */ template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T,uint64_t>::value)|| (std::is_same<T, double>::value)>::type SSDK::Archive::Json::addNumberToObject(const char *parentKey, const char *childKey, const char *memName, const T& memVal) { bool isFound{false}; auto& parentObj = queryValue(parentKey, childKey,isFound); if(!isFound && !parentObj.IsObject()) { THROW_EXCEPTION_WITH_OBJ("Object["+std::string(childKey)+"] is not found!"); } else { parentObj.AddMember(rapidjson::Value::StringRefType(memName),memVal,this->m_doc.GetAllocator()); this->m_isReAccept = true; } } template<typename T> typename std::enable_if< (std::is_same<T, bool>::value)|| (std::is_same<T, int>::value)|| (std::is_same<T, uint>::value)|| (std::is_same<T, int64_t>::value)|| (std::is_same<T,uint64_t>::value)|| (std::is_same<T, double>::value)>::type SSDK::Archive::Json::addNumberToObject(const char *key, const char *memName, const T& memVal) { addNumberToObject(nullptr,key,memName,memVal); } //<<<---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #endif // JSONHELPER_H
38.74884
229
0.416613
djc80s
b33ea83d066a38090cfc443fe727b5b3e5879ecc
9,226
cpp
C++
historyView.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
historyView.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
historyView.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2018-06-20T21:55:11.000Z
2020-10-21T19:04:54.000Z
/************************************************************************ * * * Copyright (C) 2007 Christina Warrender and Drew Levin * * * * This file is part of QtCyCells. * * * * QtCyCells 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. * * * * QtCyCells 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 QtCyCells; if not, write to the Free Software Foundation, * * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * ************************************************************************/ /************************************************************************ * file historyView.cc * * render() routine for HistoryView * * Graphs cell populations and molecular concentrations over time * * This version plots with wx/GTK instead of openGL - can use text * ************************************************************************/ #include "historyView.h" #include <GL/gl.h> #include "history.h" /************************************************************************ * HistoryView() * * Constructor * * * * Parameters * * int x, y, w, h: position (x,y) and size (w,h) of view * * * * Returns - nothing * ************************************************************************/ HistoryView::HistoryView(QWidget *parent, int x, int y, int w, int h, const History *hist) : SimView(parent, x, y, w, h), history(hist), m_first(true) { m_border = 100; QRect geo = geometry(); m_height = geo.height(); m_width = geo.width(); } void HistoryView::paintEvent(QPaintEvent * /* event */) { QPainter painter(this); // get number of samples taken and max value for each axis const vector<double> times = history->getTimes(); int numsamples = times.size(); double maxTime = times[numsamples-1]; int maxCells = history->getMaxCount(); double maxConc = history->getMaxConc(); // Set Painter Properties painter.setPen(Qt::black); painter.setFont(QFont("Modern", 10)); // Draw the graph's axes drawAxes(painter, maxTime, maxCells, maxConc); // Only plot if there are two more more data points if (numsamples > 1) { // Get the data History::CellHistory counts; History::ConcHistory concs; int t0 = m_border; int tmax = m_width-m_border; double tscale = (tmax-t0)/maxTime; int y0 = m_height-m_border; int ymax = m_border; // Cell counts first - scale according to max count so far if (maxCells == 0) { if (int last = history->getNumCellTypes()) { // just draw one line (last color) along x axis painter.setPen(QColor(cell_palette[last].red(), cell_palette[last].green(), cell_palette[last].blue())); painter.drawLine(t0, y0, tmax, y0); } } else { double yscale = (y0-ymax)/double(maxCells); // Each loop handles drawing one cell type for (int i=0; i<history->getNumCellTypes(); i++) { counts = history->getCounts(i); // Set color according to palette painter.setPen(QColor(cell_palette[i].red(), cell_palette[i].green(), cell_palette[i].blue())); for (int j=0; j<numsamples-1; j++) painter.drawLine(int(tscale*times[j]+t0), y0-int(yscale*counts[j]), int(tscale*times[j+1] + t0), y0 - int(yscale*counts[j+1])); } // end for loop } // end if maxCells not 0 // Rescale for molecular concentrations if (maxConc == 0) { if (int last = history->getNumMolTypes()) { // Just draw one line (last color) along the x-axis painter.setPen(QColor(mol_palette[last].red(), mol_palette[last].green(), mol_palette[last].blue())); painter.drawLine(t0, y0, tmax, y0); } } else { double yscale = (y0-ymax)/maxConc; // Each loop handles drawing one molecule type for (int i=0; i<history->getNumMolTypes(); i++) { concs = history->getConc(i); // Set color according to palette painter.setPen(QColor(mol_palette[i].red(), mol_palette[i].green(), mol_palette[i].blue())); for (int j=0; j<numsamples-1; j++) painter.drawLine(int(tscale*times[j] + t0), y0 - int(yscale*concs[j]), int(tscale*times[j+1] + t0), y0 - int(yscale*concs[j+1])); } // end for loop } // end if maxConc not 0 } // end if more than one sample } /************************************************************************ * render() * * Qt code to draw history of sim * * * * Returns - nothing * ************************************************************************/ void HistoryView::render() { } /************************************************************************ * drawAxes() * * Sets up xaxis (time) and 2 yaxes (one for cells and one for * * molecules) * * * * Parameters - * * double maxTime: max value on y axis * * int maxCells: max value on left y axis * * double maxConc: max value on right y axis * * * \ * Returns - nothing * ************************************************************************/ void HistoryView::drawAxes(QPainter &painter, double maxTime, int maxCells, double maxConc) { QString str; // Draw lines for axes painter.drawLine(m_border, m_border, m_border, m_height - m_border); painter.drawLine(m_border, m_height - m_border, m_width - m_border, m_height - m_border); painter.drawLine(m_width - m_border, m_height - m_border, m_width - m_border, m_border); // X-Axis Label painter.drawText(m_width/2-100, m_height-(3*m_border/4)-25, 200, 50, Qt::AlignCenter, tr("Time (sec)")); painter.save(); painter.rotate(-90); // Left Y-Axis Label painter.drawText(-m_height/2-100, (3*m_border)/4-25, 200, 50, Qt::AlignCenter, tr("# of Cells")); // Right Y-Axis Label painter.drawText(-m_height/2-100, m_width-(3*m_border)/4-25, 200, 50, Qt::AlignCenter, tr("Concentration (Moles/ml)")); painter.restore(); // X-Axis Max Value str.sprintf("%.1f", maxTime); painter.drawText(m_width-m_border-100, height-4*m_border/5-25, 200, 50, Qt::AlignCenter, str); // Left Y-Axis Max Value str.sprintf("%d", maxCells); painter.drawText(m_border/2-100, m_border-25, 200, 50, Qt::AlignCenter, str); // Right Y-Axis Max Value str.sprintf("%.1e", maxConc); painter.drawText(m_width-m_border/2-100, m_border-25, 200, 50, Qt::AlignCenter, str); }
39.939394
82
0.423911
neelsoumya
b33f308ad5284b295bc1aa8c12a524b657fb5637
531
hpp
C++
libraries/plugins/chain/include/steem/plugins/chain/abstract_block_producer.hpp
reactivespace/Steemit-Fork-2.0
1bf860963f5715309bda6f77e362e09e9d3ccf8a
[ "MIT" ]
null
null
null
libraries/plugins/chain/include/steem/plugins/chain/abstract_block_producer.hpp
reactivespace/Steemit-Fork-2.0
1bf860963f5715309bda6f77e362e09e9d3ccf8a
[ "MIT" ]
null
null
null
libraries/plugins/chain/include/steem/plugins/chain/abstract_block_producer.hpp
reactivespace/Steemit-Fork-2.0
1bf860963f5715309bda6f77e362e09e9d3ccf8a
[ "MIT" ]
null
null
null
#pragma once #include <fc/time.hpp> #include <clout/chain/database.hpp> namespace clout { namespace plugins { namespace chain { class abstract_block_producer { public: virtual ~abstract_block_producer() = default; virtual clout::chain::signed_block generate_block( fc::time_point_sec when, const clout::chain::account_name_type& witness_owner, const fc::ecc::private_key& block_signing_private_key, uint32_t skip = clout::chain::database::skip_nothing) = 0; }; } } } // clout::plugins::chain
25.285714
64
0.721281
reactivespace
b3406b533c5cc030f01da5fc7a49f8ad453a7bb6
4,815
hpp
C++
sandbox/core/system.hpp
KabelitzJ/sandbox
fe870387e634e101a63398409966c61088e1384b
[ "MIT" ]
null
null
null
sandbox/core/system.hpp
KabelitzJ/sandbox
fe870387e634e101a63398409966c61088e1384b
[ "MIT" ]
null
null
null
sandbox/core/system.hpp
KabelitzJ/sandbox
fe870387e634e101a63398409966c61088e1384b
[ "MIT" ]
null
null
null
#ifndef SBX_ECS_SYSTEM_HPP_ #define SBX_ECS_SYSTEM_HPP_ #include <type_traits> #include <utility> #include <iostream> #include <memory> #include <string> #include <types/primitives.hpp> #include <types/transform.hpp> #include "resource_cache.hpp" #include "scene.hpp" #include "event_queue.hpp" #include "input.hpp" #include "key.hpp" #include "mouse_button.hpp" namespace sbx { class system { public: system(); virtual ~system() = default; virtual void initialize() = 0; virtual void update(const time delta_time) = 0; virtual void terminate() = 0; [[nodiscard]] bool is_running() const noexcept; protected: void exit() noexcept { _terminate(); } entity create_entity(const transform& transform = transform{}, const entity parent = null_entity); void destroy_entity(const entity entity); template<typename Component, typename... Args> decltype(auto) add_component(const entity entity, Args&&... args) { assert(_scene); // Scene is uninitialized return _scene->add_component<Component>(entity, std::forward<Args>(args)...); } template<typename... Components> decltype(auto) get_components(const entity entity) const { assert(_scene); // Scene is uninitialized return _scene->get_components<Components...>(entity); } template<typename... Components> decltype(auto) get_components(const entity entity) { assert(_scene); // Scene is uninitialized return _scene->get_components<Components...>(entity); } template<typename... Components> void remove_components(const entity entity) { assert(_scene); // Scene is uninitialized return _scene->remove_components<Components...>(entity); } template<typename... Components> [[nodiscard]] bool has_components(const entity entity) const { assert(_scene); // Scene is uninitialized return _scene->has_components<Components...>(entity); } template<typename... Components, typename... Excludes> [[nodiscard]] decltype(auto) create_view(exclude_t<Excludes...> = {}) const { assert(_scene); // Scene is uninitialized return _scene->create_view<Components..., Excludes...>(); } template<typename... Components, typename... Excludes> [[nodiscard]] decltype(auto) create_view(exclude_t<Excludes...> = {}) { assert(_scene); // Scene is uninitialized return _scene->create_view<Components..., Excludes...>(); } template<typename Event, typename Listener> void add_listener(Listener&& listener) { assert(_event_queue); // Event queue is uninitialized _event_queue->add_listener<Event>(std::move(listener)); } template<typename Event, typename... Args> void dispatch_event(Args&&... args) { assert(_event_queue); // Event queue is uninitialized _event_queue->dispatch_event<Event>(std::forward<Args>(args)...); } template<typename Resource, typename... Args> void load_resource(const std::string& name, Args&&... args) { assert(_resource_cache); // Resource cache is uninitialized _resource_cache->load<Resource>(name, std::forward<Args>(args)...); } template<typename Resource> std::shared_ptr<Resource> get_resource(const std::string& name) { assert(_resource_cache); // Resource cache is uninitialized return _resource_cache->get<Resource>(name); } bool is_key_down(const key key) const; bool is_key_up(const key key) const; bool is_mouse_button_down(const mouse_button button) const; bool is_mouse_button_up(const mouse_button button) const; scene* get_scene() noexcept { assert(_scene); // Scene is uninitialized return _scene; } event_queue* get_event_queue() noexcept { assert(_event_queue); // Event queue is uninitialized return _event_queue; } resource_cache* get_resource_cache() noexcept { assert(_resource_cache); // Resource cache is uninitialized return _resource_cache; } input* get_input() noexcept { assert(_input); // Input is uninitialized return _input; } private: friend class scheduler; friend class engine; inline static scene* _scene{nullptr}; inline static event_queue* _event_queue{nullptr}; inline static resource_cache* _resource_cache{nullptr}; inline static input* _input{nullptr}; void _initialize(); void _update(const time delta_time); void _terminate(); bool _is_running{false}; }; // class system template<typename Function> class system_adaptor : public system, private Function { public: template<typename... Args> system_adaptor(Args&&... args) : Function{std::forward<Args>(args)...} { } void initialize() override { } void update(const time delta_time) override { Function::operator()(delta_time, [this](){ exit(); }); } void terminate() override { } }; // class system_adaptor } // namespace sbx #endif // SBX_ECS_SYSTEM_HPP_
26.75
100
0.71298
KabelitzJ
b3474ba95efadd131a0fca3e23e2f99058671c84
22,454
cpp
C++
qikkDB_test/DispatcherTestsRegression.cpp
veselyja/qikkdb-community
680f62632ba85e468beee672624b80a61ed40f55
[ "Apache-2.0" ]
15
2020-06-30T13:43:42.000Z
2022-02-02T12:52:33.000Z
qikkDB_test/DispatcherTestsRegression.cpp
veselyja/qikkdb-community
680f62632ba85e468beee672624b80a61ed40f55
[ "Apache-2.0" ]
1
2020-11-28T22:29:35.000Z
2020-12-22T10:28:25.000Z
qikkDB_test/DispatcherTestsRegression.cpp
qikkDB/qikkdb
4ee657c7d2bfccd460d2f0d2c84a0bbe72d9a80a
[ "Apache-2.0" ]
1
2020-06-30T12:41:37.000Z
2020-06-30T12:41:37.000Z
#include <cmath> #include "gtest/gtest.h" #include "../qikkDB/DatabaseGenerator.h" #include "../qikkDB/ColumnBase.h" #include "../qikkDB/BlockBase.h" #include "../qikkDB/PointFactory.h" #include "../qikkDB/ComplexPolygonFactory.h" #include "../qikkDB/Database.h" #include "../qikkDB/Table.h" #include "../qikkDB/QueryEngine/Context.h" #include "../qikkDB/GpuSqlParser/GpuSqlCustomParser.h" #include "../qikkDB/messages/QueryResponseMessage.pb.h" #include "../qikkDB/GpuSqlParser/ParserExceptions.h" #include "DispatcherObjs.h" TEST(DispatcherTestsRegression, EmptyResultFromGtColConst) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1 FROM TableA WHERE colInteger1 > 4096;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->payloads().size(), 0); // Check if the result size is also 0 } TEST(DispatcherTestsRegression, EmptyResultFromGroupByOrderBy) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1 FROM TableA WHERE colInteger1 > 4096 " "GROUP BY colInteger1 ORDER BY colInteger1;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->payloads().size(), 0); } TEST(DispatcherTestsRegression, EmptyResultFromGroupByCount) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT COUNT(colInteger1) FROM TableA WHERE colInteger1 > 4096 " "GROUP BY colInteger1;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->payloads().size(), 0); } TEST(DispatcherTestsRegression, EmptyResultFromGroupByAvg) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT AVG(colInteger1) FROM TableA WHERE colInteger1 > 4096 GROUP " "BY colInteger1;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->payloads().size(), 0); } TEST(DispatcherTestsRegression, EmptyResultFromGroupBySum) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT SUM(colInteger1) FROM TableA WHERE colInteger1 > 4096 GROUP " "BY colInteger1;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->payloads().size(), 0); } TEST(DispatcherTestsRegression, EmptySetAggregationCount) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT COUNT(colInteger1) FROM TableA WHERE colInteger1 > 4096;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->payloads().size(), Configuration::GetInstance().IsUsingWhereEvaluationSpeedup() ? 0 : 1); // TODO fix this test when COUNT returns "0" when there is empty result set // ASSERT_EQ(result->payloads().size(), 1); // ASSERT_EQ(result->payloads().at("COUNT(colInteger1)").int64payload().int64data()[0], 0); } TEST(DispatcherTestsRegression, EmptySetAggregationSum) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT SUM(colInteger1) FROM TableA WHERE colInteger1 > 4096;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->payloads().size(), Configuration::GetInstance().IsUsingWhereEvaluationSpeedup() ? 0 : 1); // TODO fix this test when SUM returns no rows when there is empty result set // ASSERT_EQ(result->payloads().size(), 0); } TEST(DispatcherTestsRegression, EmptySetAggregationMin) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT MIN(colInteger1) FROM TableA WHERE colInteger1 > 4096;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->payloads().size(), Configuration::GetInstance().IsUsingWhereEvaluationSpeedup() ? 0 : 1); // TODO fix this test when MIN returns no rows when there is empty result set // ASSERT_EQ(result->payloads().size(), 0); } TEST(DispatcherTestsRegression, PointAggregationCount) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT COUNT(colPoint1) FROM TableA;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payloads = result->payloads().at("COUNT(colPoint1)"); ASSERT_EQ(payloads.int64payload().int64data_size(), 1); ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); } TEST(DispatcherTestsRegression, AggregationCountAsteriskNoGroupBy) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT COUNT(*) FROM TableA;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payloads = result->payloads().at("COUNT(*)"); ASSERT_EQ(payloads.int64payload().int64data_size(), 1); ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); } TEST(DispatcherTestsRegression, PointAggregationCountWithWhere) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT COUNT(colPoint1) FROM TableA WHERE colInteger1 > 0;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payloads = result->payloads().at("COUNT(colPoint1)"); ASSERT_EQ(payloads.int64payload().int64data_size(), 1); // Count sufficient row on CPU auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance() .database->GetTables() .at("TableA") .GetColumns() .at("colInteger1") .get()); int32_t expectedCount = 0; for (int i = 0; i < TEST_BLOCK_COUNT; i++) { auto blockInt = columnInt->GetBlocksList()[i]; for (int k = 0; k < TEST_BLOCK_SIZE; k++) { if (blockInt->GetData()[k] > 0) { expectedCount++; } } } ASSERT_EQ(payloads.int64payload().int64data()[0], expectedCount); } TEST(DispatcherTestsRegression, Int32AggregationCount) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT COUNT(colInteger1) FROM TableA;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payloads = result->payloads().at("COUNT(colInteger1)"); ASSERT_EQ(payloads.int64payload().int64data_size(), 1); ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); } TEST(DispatcherTestsRegression, GroupByKeyOpCorrectSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT (colInteger1 + 2) * 10, COUNT(colFloat1) FROM TableA GROUP " "BY colInteger1 + 2;"); ASSERT_NO_THROW(parser.Parse()); } TEST(DispatcherTestsRegression, GroupByKeyOpWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT (10 * colInteger1) + 2, COUNT(colFloat1) FROM TableA GROUP " "BY colInteger1 + 2;"); ASSERT_THROW(parser.Parse(), ColumnGroupByException); GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database, "SELECT colInteger1 + 3, COUNT(colFloat1) FROM TableA GROUP BY " "colInteger1 + 2;"); ASSERT_THROW(parser2.Parse(), ColumnGroupByException); } TEST(DispatcherTestsRegression, NonGroupByAggWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1, SUM(colInteger2) FROM TableA;"); ASSERT_THROW(parser.Parse(), ColumnGroupByException); } TEST(DispatcherTestsRegression, NonGroupByAggCorrectSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT MIN(colInteger1), SUM(colInteger2) FROM TableA;"); ASSERT_NO_THROW(parser.Parse()); } TEST(DispatcherTestsRegression, AggInWhereWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1, SUM(colInteger2) FROM TableA WHERE " "SUM(colInteger2) > 2;"); ASSERT_THROW(parser.Parse(), AggregationWhereException); } TEST(DispatcherTestsRegression, AggInGroupByWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT SUM(colInteger2) FROM TableA GROUP BY SUM(colInteger2);"); ASSERT_THROW(parser.Parse(), AggregationGroupByException); } TEST(DispatcherTestsRegression, AggInGroupByAliasWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT SUM(colInteger2) FROM TableA GROUP BY 1;"); ASSERT_THROW(parser.Parse(), AggregationGroupByException); } TEST(DispatcherTestsRegression, GroupByAliasDataTypeWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1, SUM(colInteger2) FROM TableA GROUP BY 1.1;"); ASSERT_THROW(parser.Parse(), GroupByInvalidColumnException); } TEST(DispatcherTestsRegression, GroupByAliasOutOfRangeWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1, SUM(colInteger2) FROM TableA GROUP BY 100;"); ASSERT_THROW(parser.Parse(), GroupByInvalidColumnException); } TEST(DispatcherTestsRegression, OrderByAliasDataTypeWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1 FROM TableA ORDER BY 1.1;"); ASSERT_THROW(parser.Parse(), OrderByInvalidColumnException); } TEST(DispatcherTestsRegression, OrderByAliasOutOfRangeWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1 FROM TableA ORDER BY 100;"); ASSERT_THROW(parser.Parse(), OrderByInvalidColumnException); } TEST(DispatcherTestsRegression, ConstOpOnMultiGPU) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT ABS(1) FROM TableA;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payloads = result->payloads().at("ABS(1)"); ASSERT_EQ(payloads.intpayload().intdata_size(), DispatcherObjs::GetInstance() .database->GetTables() .at("TableA") .GetColumns() .at("colInteger1") ->GetSize()); ASSERT_EQ(payloads.intpayload().intdata()[0], 1); } TEST(DispatcherTestsRegression, SameAliasAsColumn) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1 as colInteger1 FROM TableA WHERE colInteger1 > " "20;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); } // == JOIN == /* // TODO Fix empty results of JOIN TEST(DispatcherTestsRegression, JoinEmptyResult) { Context::getInstance(); const std::string dbName = "JoinTestDb"; const std::string tableAName = "TableA"; const std::string tableBName = "TableB"; const int32_t blockSize = 32; // length of a block std::vector<int32_t> idsA = {1}; std::vector<int32_t> valuesA = {50}; std::vector<int32_t> idsB = {1, 1}; std::vector<int32_t> valuesB = {32, 33}; std::shared_ptr<Database> joinDatabase = std::make_shared<Database>(dbName.c_str(), blockSize); Database::AddToInMemoryDatabaseList(joinDatabase); auto columnsA = std::unordered_map<std::string, DataType>(); columnsA.insert(std::make_pair<std::string, DataType>("id", DataType::COLUMN_INT)); columnsA.insert(std::make_pair<std::string, DataType>("value", DataType::COLUMN_INT)); joinDatabase->CreateTable(columnsA, tableAName.c_str()); auto columnsB = std::unordered_map<std::string, DataType>(); columnsB.insert(std::make_pair<std::string, DataType>("id", DataType::COLUMN_INT)); columnsB.insert(std::make_pair<std::string, DataType>("value", DataType::COLUMN_INT)); joinDatabase->CreateTable(columnsB, tableBName.c_str()); reinterpret_cast<ColumnBase<int32_t>*>( joinDatabase->GetTables().at(tableAName).GetColumns().at("id").get()) ->InsertData(idsA); reinterpret_cast<ColumnBase<int32_t>*>( joinDatabase->GetTables().at(tableAName).GetColumns().at("value").get()) ->InsertData(valuesA); reinterpret_cast<ColumnBase<int32_t>*>( joinDatabase->GetTables().at(tableBName).GetColumns().at("id").get()) ->InsertData(idsB); reinterpret_cast<ColumnBase<int32_t>*>( joinDatabase->GetTables().at(tableBName).GetColumns().at("value").get()) ->InsertData(valuesB); GpuSqlCustomParser parser(joinDatabase, "SELECT TableA.value, TableB.value FROM TableA JOIN " "TableB ON TableA.id = TableB.id;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payloadA = result->payloads().at("TableA.value"); auto& payloadB = result->payloads().at("TableB.value"); ASSERT_EQ(2, payloadA.intpayload().intdata_size()); ASSERT_EQ(2, payloadB.intpayload().intdata_size()); // TODO assert values Database::RemoveFromInMemoryDatabaseList(dbName.c_str()); } // == JOIN == TEST(DispatcherTestsRegression, JoinTableAliasResult) { Context::getInstance(); const std::string dbName = "JoinTestDb"; const std::string tableAName = "TableA"; const std::string tableBName = "TableB"; const int32_t blockSize = 32; // length of a block std::vector<int32_t> idsA = {1}; std::vector<int32_t> valuesA = {50}; std::vector<int32_t> idsB = {1, 1}; std::vector<int32_t> valuesB = {32, 33}; std::shared_ptr<Database> joinDatabase = std::make_shared<Database>(dbName.c_str(), blockSize); Database::AddToInMemoryDatabaseList(joinDatabase); auto columnsA = std::unordered_map<std::string, DataType>(); columnsA.insert(std::make_pair<std::string, DataType>("id", DataType::COLUMN_INT)); columnsA.insert(std::make_pair<std::string, DataType>("value", DataType::COLUMN_INT)); joinDatabase->CreateTable(columnsA, tableAName.c_str()); auto columnsB = std::unordered_map<std::string, DataType>(); columnsB.insert(std::make_pair<std::string, DataType>("id", DataType::COLUMN_INT)); columnsB.insert(std::make_pair<std::string, DataType>("value", DataType::COLUMN_INT)); joinDatabase->CreateTable(columnsB, tableBName.c_str()); reinterpret_cast<ColumnBase<int32_t>*>( joinDatabase->GetTables().at(tableAName).GetColumns().at("id").get()) ->InsertData(idsA); reinterpret_cast<ColumnBase<int32_t>*>( joinDatabase->GetTables().at(tableAName).GetColumns().at("value").get()) ->InsertData(valuesA); reinterpret_cast<ColumnBase<int32_t>*>( joinDatabase->GetTables().at(tableBName).GetColumns().at("id").get()) ->InsertData(idsB); reinterpret_cast<ColumnBase<int32_t>*>( joinDatabase->GetTables().at(tableBName).GetColumns().at("value").get()) ->InsertData(valuesB); GpuSqlCustomParser parser(joinDatabase, "SELECT ta.value, tb.value FROM TableA AS ta JOIN " "TableB AS tb ON ta.id = tb.id;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payloadA = result->payloads().at("TableA.value"); auto& payloadB = result->payloads().at("TableB.value"); ASSERT_EQ(2, payloadA.intpayload().intdata_size()); ASSERT_EQ(2, payloadB.intpayload().intdata_size()); Database::RemoveFromInMemoryDatabaseList(dbName.c_str()); } */ TEST(DispatcherTestsRegression, AggregationInWhereWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1, COUNT(colInteger2) FROM TableA WHERE " "COUNT(colInteger2) > 10 GROUP " "BY colInteger1;"); ASSERT_THROW(parser.Parse(), AggregationWhereException); } TEST(DispatcherTestsRegression, CreateIndexWrongSemantic) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "CREATE TABLE tblA (colA GEO_POINT, INDEX ind (colA));"); ASSERT_THROW(parser.Parse(), IndexColumnDataTypeException); GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database, "CREATE TABLE tblA (colA GEO_POLYGON, INDEX ind (colA));"); ASSERT_THROW(parser2.Parse(), IndexColumnDataTypeException); } TEST(DispatcherTestsRegression, FixedColumnOrdering) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colInteger1, SUM(colInteger2) FROM TableA GROUP BY " "colInteger1;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); ASSERT_EQ(result->columnorder().Get(0), "TableA.colInteger1"); ASSERT_EQ(result->columnorder().Get(1), "SUM(colInteger2)"); } TEST(DispatcherTestsRegression, MultiBlockAggWithAlias) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT COUNT(colInteger2) as alias FROM TableA;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payloadAlias = result->payloads().at("alias"); ASSERT_EQ(1, payloadAlias.int64payload().int64data_size()); } TEST(DispatcherTestsRegression, ConstantWithWhere) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT 1 FROM TableA WHERE colInteger1 > 0;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payload = result->payloads().at("1"); ASSERT_EQ(2048, payload.intpayload().intdata_size()); for (size_t i = 0; i < payload.intpayload().intdata_size(); i++) { ASSERT_EQ(1, payload.intpayload().intdata()[i]) << " at resrow " << i; } } TEST(DispatcherTestsRegression, FunctionWithWhere) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT POW(2,2) FROM TableA WHERE colInteger1 > 0;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payload = result->payloads().at("POW(2,2)"); ASSERT_EQ(2048, payload.intpayload().intdata_size()); for (size_t i = 0; i < payload.intpayload().intdata_size(); i++) { ASSERT_EQ(4, payload.intpayload().intdata()[i]) << " at resrow " << i; } } TEST(DispatcherTestsRegression, FunctionWithWhereAndLimit) { Context::getInstance(); GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT POW(2,2) FROM TableA WHERE ABS(colInteger1) >= 512 LIMIT 1536;"); auto resultPtr = parser.Parse(); auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get()); auto& payload = result->payloads().at("POW(2,2)"); ASSERT_EQ(1536, payload.intpayload().intdata_size()); for (size_t i = 0; i < payload.intpayload().intdata_size(); i++) { ASSERT_EQ(4, payload.intpayload().intdata()[i]) << " at resrow " << i; } }
40.457658
111
0.659927
veselyja
b34a5a6353725e2d7b35c78dd8471fecee5c3bb4
363
cc
C++
jax/training/21-03/21-03-22-night/a.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
2
2022-01-01T16:55:02.000Z
2022-03-16T14:47:29.000Z
jax/training/21-03/21-03-22-night/a.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
null
null
null
jax/training/21-03/21-03-22-night/a.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; const int maxn = 1005; int arr[maxn]; int main() { int n, a, b, c, t; scanf("%d%d%d%d%d", &n, &a, &b, &c, &t); for (int i = 0; i < n; ++i) scanf("%d", arr + i); int ans = n * a; int k = c - b; if (k > 0) { for (int i = 0; i < n; ++i) ans += (t - arr[i]) * k; } printf("%d", ans); }
22.6875
60
0.432507
JaxVanYang
b34b3c8a71724c473ca5e182ca4726b0963d46bf
822
cc
C++
libDatabase/variant.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
libDatabase/variant.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
libDatabase/variant.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
#include "variant.h" #include <iostream> #include <string> const std::string Variant::toString() const { std::string result = ""; switch (type) { case CHAR: result += data.c; break; case SHORT: result = std::to_string(data.sh); break; case INT: result = std::to_string(data.i); break; case LONG: result = std::to_string(data.l); break; case FLOAT: result = std::to_string(data.f); break; case DOUBLE:result = std::to_string(data.d); break; case TIME: { char buffer[128] = {0}; size_t len = strftime(buffer, sizeof(buffer), "%F %T", &data.t); result = std::string(buffer); } break; case STRING: default: result = s; break; } return result; }
29.357143
80
0.536496
marcbejerano
b357869e3e23b1f62d8e822acd60b6e6e79393fa
76,249
hpp
C++
tm_kit/infra/RealTimeApp_TimeChecker_Piece.hpp
cd606/tm_infra
27f93cc3cf4344a962aa5faeb4105be8458d34f0
[ "Apache-2.0" ]
1
2020-05-22T08:47:05.000Z
2020-05-22T08:47:05.000Z
tm_kit/infra/RealTimeApp_TimeChecker_Piece.hpp
cd606/tm_infra
27f93cc3cf4344a962aa5faeb4105be8458d34f0
[ "Apache-2.0" ]
null
null
null
tm_kit/infra/RealTimeApp_TimeChecker_Piece.hpp
cd606/tm_infra
27f93cc3cf4344a962aa5faeb4105be8458d34f0
[ "Apache-2.0" ]
null
null
null
template <class A0, class A1> class TimeChecker<false, std::variant<A0,A1>> { private: std::bitset<2> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1> class TimeChecker<true, std::variant<A0,A1>> { private: std::bitset<2> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } }; template <class A0, class A1, class A2> class TimeChecker<false, std::variant<A0,A1,A2>> { private: std::bitset<3> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1, class A2> class TimeChecker<true, std::variant<A0,A1,A2>> { private: std::bitset<3> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3> class TimeChecker<false, std::variant<A0,A1,A2,A3>> { private: std::bitset<4> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3> class TimeChecker<true, std::variant<A0,A1,A2,A3>> { private: std::bitset<4> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4> class TimeChecker<false, std::variant<A0,A1,A2,A3,A4>> { private: std::bitset<5> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4> class TimeChecker<true, std::variant<A0,A1,A2,A3,A4>> { private: std::bitset<5> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5> class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5>> { private: std::bitset<6> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5> class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5>> { private: std::bitset<6> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5, class A6> class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5,A6>> { private: std::bitset<7> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; std::optional<typename StateT::TimePointType> tp6_; VersionChecker<A6> versionChecker6_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; case 6: if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp6_ && data.timedData.timePoint < *tp6_) { return false; } } tp6_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(6); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5, class A6> class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5,A6>> { private: std::bitset<7> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; std::optional<typename StateT::TimePointType> tp6_; VersionChecker<A6> versionChecker6_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; case 6: if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp6_ && data.timedData.timePoint < *tp6_) { return false; } } tp6_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(6); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7> class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5,A6,A7>> { private: std::bitset<8> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; std::optional<typename StateT::TimePointType> tp6_; VersionChecker<A6> versionChecker6_; std::optional<typename StateT::TimePointType> tp7_; VersionChecker<A7> versionChecker7_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; case 6: if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp6_ && data.timedData.timePoint < *tp6_) { return false; } } tp6_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(6); } break; case 7: if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp7_ && data.timedData.timePoint < *tp7_) { return false; } } tp7_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(7); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7> class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5,A6,A7>> { private: std::bitset<8> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; std::optional<typename StateT::TimePointType> tp6_; VersionChecker<A6> versionChecker6_; std::optional<typename StateT::TimePointType> tp7_; VersionChecker<A7> versionChecker7_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; case 6: if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp6_ && data.timedData.timePoint < *tp6_) { return false; } } tp6_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(6); } break; case 7: if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp7_ && data.timedData.timePoint < *tp7_) { return false; } } tp7_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(7); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8>> { private: std::bitset<9> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; std::optional<typename StateT::TimePointType> tp6_; VersionChecker<A6> versionChecker6_; std::optional<typename StateT::TimePointType> tp7_; VersionChecker<A7> versionChecker7_; std::optional<typename StateT::TimePointType> tp8_; VersionChecker<A8> versionChecker8_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), tp8_(std::nullopt), versionChecker8_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; case 6: if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp6_ && data.timedData.timePoint < *tp6_) { return false; } } tp6_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(6); } break; case 7: if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp7_ && data.timedData.timePoint < *tp7_) { return false; } } tp7_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(7); } break; case 8: if (!versionChecker8_.checkVersion(std::get<8>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp8_ && data.timedData.timePoint < *tp8_) { return false; } } tp8_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(8); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8>> { private: std::bitset<9> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; std::optional<typename StateT::TimePointType> tp6_; VersionChecker<A6> versionChecker6_; std::optional<typename StateT::TimePointType> tp7_; VersionChecker<A7> versionChecker7_; std::optional<typename StateT::TimePointType> tp8_; VersionChecker<A8> versionChecker8_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), tp8_(std::nullopt), versionChecker8_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; case 6: if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp6_ && data.timedData.timePoint < *tp6_) { return false; } } tp6_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(6); } break; case 7: if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp7_ && data.timedData.timePoint < *tp7_) { return false; } } tp7_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(7); } break; case 8: if (!versionChecker8_.checkVersion(std::get<8>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp8_ && data.timedData.timePoint < *tp8_) { return false; } } tp8_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(8); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8,A9>> { private: std::bitset<10> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; std::optional<typename StateT::TimePointType> tp6_; VersionChecker<A6> versionChecker6_; std::optional<typename StateT::TimePointType> tp7_; VersionChecker<A7> versionChecker7_; std::optional<typename StateT::TimePointType> tp8_; VersionChecker<A8> versionChecker8_; std::optional<typename StateT::TimePointType> tp9_; VersionChecker<A9> versionChecker9_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), tp8_(std::nullopt), versionChecker8_(), tp9_(std::nullopt), versionChecker9_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8,A9>, StateT, typename StateT::TimePointType> const &data) { switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; case 6: if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp6_ && data.timedData.timePoint < *tp6_) { return false; } } tp6_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(6); } break; case 7: if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp7_ && data.timedData.timePoint < *tp7_) { return false; } } tp7_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(7); } break; case 8: if (!versionChecker8_.checkVersion(std::get<8>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp8_ && data.timedData.timePoint < *tp8_) { return false; } } tp8_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(8); } break; case 9: if (!versionChecker9_.checkVersion(std::get<9>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp9_ && data.timedData.timePoint < *tp9_) { return false; } } tp9_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(9); } break; } return true; } inline bool isFinalUpdate() const { return finalMask_.all(); } }; template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8,A9>> { private: std::bitset<10> finalMask_; std::optional<typename StateT::TimePointType> tp0_; VersionChecker<A0> versionChecker0_; std::optional<typename StateT::TimePointType> tp1_; VersionChecker<A1> versionChecker1_; std::optional<typename StateT::TimePointType> tp2_; VersionChecker<A2> versionChecker2_; std::optional<typename StateT::TimePointType> tp3_; VersionChecker<A3> versionChecker3_; std::optional<typename StateT::TimePointType> tp4_; VersionChecker<A4> versionChecker4_; std::optional<typename StateT::TimePointType> tp5_; VersionChecker<A5> versionChecker5_; std::optional<typename StateT::TimePointType> tp6_; VersionChecker<A6> versionChecker6_; std::optional<typename StateT::TimePointType> tp7_; VersionChecker<A7> versionChecker7_; std::optional<typename StateT::TimePointType> tp8_; VersionChecker<A8> versionChecker8_; std::optional<typename StateT::TimePointType> tp9_; VersionChecker<A9> versionChecker9_; mutable std::mutex mutex_; public: TimeChecker() : finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), tp8_(std::nullopt), versionChecker8_(), tp9_(std::nullopt), versionChecker9_(), mutex_() {} inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8,A9>, StateT, typename StateT::TimePointType> const &data) { std::lock_guard<std::mutex> _(mutex_); switch (data.timedData.value.index()) { case 0: if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp0_ && data.timedData.timePoint < *tp0_) { return false; } } tp0_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(0); } break; case 1: if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp1_ && data.timedData.timePoint < *tp1_) { return false; } } tp1_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(1); } break; case 2: if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp2_ && data.timedData.timePoint < *tp2_) { return false; } } tp2_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(2); } break; case 3: if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp3_ && data.timedData.timePoint < *tp3_) { return false; } } tp3_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(3); } break; case 4: if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp4_ && data.timedData.timePoint < *tp4_) { return false; } } tp4_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(4); } break; case 5: if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp5_ && data.timedData.timePoint < *tp5_) { return false; } } tp5_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(5); } break; case 6: if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp6_ && data.timedData.timePoint < *tp6_) { return false; } } tp6_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(6); } break; case 7: if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp7_ && data.timedData.timePoint < *tp7_) { return false; } } tp7_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(7); } break; case 8: if (!versionChecker8_.checkVersion(std::get<8>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp8_ && data.timedData.timePoint < *tp8_) { return false; } } tp8_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(8); } break; case 9: if (!versionChecker9_.checkVersion(std::get<9>(data.timedData.value))) { return false; } if (StateT::CheckTime) { if (tp9_ && data.timedData.timePoint < *tp9_) { return false; } } tp9_ = data.timedData.timePoint; if (data.timedData.finalFlag) { finalMask_.set(9); } break; } return true; } inline bool isFinalUpdate() const { std::lock_guard<std::mutex> _(mutex_); return finalMask_.all(); } };
36.996118
430
0.520322
cd606
b35bd95e3401934078a1539df76ca686a32eff47
271
cpp
C++
atcoder/abc195/A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
atcoder/abc195/A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
atcoder/abc195/A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
#include <bits/stdc++.h> using namespace std; using ll = int64_t; using ff = long double; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int M, H; cin >> M >> H; cout << (H % M == 0 ? "Yes" : "No") << endl; return 0; }
16.9375
48
0.542435
xirc
b3612b67874f5d112db450aa7efd49bf06b6016d
1,841
cpp
C++
computer-networks/udp-agenda/server1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
computer-networks/udp-agenda/server1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
computer-networks/udp-agenda/server1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> using namespace std; #define PORT 8080 #define MAX_SIZE 100 int sockfd; char msg[MAX_SIZE]; string ok = "Server 1 updated successfully"; struct sockaddr_in servaddr, cliaddr; int len = sizeof(cliaddr); map<string, string> tel_of; string name, tel; void take_input(string in){ name.clear(), tel.clear(); int cond = 0; for(auto x : in){ if(x == ' ') { cond = 1; continue; } cond ? tel += x : name += x; } } void assemble(){ tel_of.clear(); ifstream readFile("agenda1"); string name, tel; while(readFile >> name >> tel){ tel_of[name] = tel; } readFile.close(); } void update(){ ofstream writeFile("agenda1"); for(auto x : tel_of){ writeFile << x.first << " " << x.second << endl; } writeFile.close(); } int main() { sockfd = socket(AF_INET, SOCK_DGRAM, 0); memset(&servaddr, 0, sizeof(servaddr)); memset(&cliaddr, 0, sizeof(cliaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_port = htons(PORT); bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)); while(1){ recvfrom(sockfd, (char*) msg, MAX_SIZE, 0, (struct sockaddr*) &cliaddr, (socklen_t *) &len); if(msg[0] == '#') break; string aux(msg); cout << "Received request: " << aux << endl; cout << "Processing..." << endl; take_input(aux); assemble(); tel_of[name] = tel; update(); cout << "Updated" << endl; //memset(&cliaddr, 0, sizeof(cliaddr). sendto(sockfd, ok.c_str(), ok.size(), 0, (struct sockaddr*) &cliaddr, len); cout << "Sended" << endl; } close(sockfd); return 0; }
23.602564
99
0.593156
hsnavarro
b367ee59d5f312c4f9bd67540c9725b2c2e5b863
796
cc
C++
src/Parser/AST/TFPDefStatementNode.cc
stenbror/PythonCoreNative
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
[ "BSL-1.0" ]
null
null
null
src/Parser/AST/TFPDefStatementNode.cc
stenbror/PythonCoreNative
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
[ "BSL-1.0" ]
null
null
null
src/Parser/AST/TFPDefStatementNode.cc
stenbror/PythonCoreNative
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
[ "BSL-1.0" ]
1
2021-05-24T11:18:32.000Z
2021-05-24T11:18:32.000Z
#include <ast/TFPDefStatementNode.h> using namespace PythonCoreNative::RunTime::Parser::AST; using namespace PythonCoreNative::RunTime::Parser; TFPDefStatementNode::TFPDefStatementNode( unsigned int start, unsigned int end, std::shared_ptr<Token> op1, std::shared_ptr<Token> op2, std::shared_ptr<ExpressionNode> right ) : StatementNode(start, end) { mOp1 = op1; mOp2 = op2; mRight = right; } std::shared_ptr<Token> TFPDefStatementNode::GetOperator1() { return mOp1; } std::shared_ptr<Token> TFPDefStatementNode::GetOperator2() { return mOp2; } std::shared_ptr<ExpressionNode> TFPDefStatementNode::GetRight() { return mRight; }
24.121212
66
0.616834
stenbror
b3710a42b03d33f32ae14ddb7236e8ec1853db92
893
cpp
C++
C++/sentence-similarity-iii.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/sentence-similarity-iii.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/sentence-similarity-iii.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) // Space: O(1) class Solution { public: bool areSentencesSimilar(string sentence1, string sentence2) { if (size(sentence1) > size(sentence2)) { swap(sentence1, sentence2); } int count = 0; for (int step = 0; step < 2; ++step) { for (int i = 0; i <= size(sentence1); ++i) { char c1 = i != size(sentence1) ? sentence1[step == 0 ? i : size(sentence1) - 1 - i] : ' '; char c2 = i != size(sentence2) ? sentence2[step == 0 ? i : size(sentence2) - 1 - i] : ' '; if (c1 != c2) { break; } if (c1 == ' ') { ++count; } } } return count >= count_if(cbegin(sentence1), cend(sentence1), [](char x) { return x == ' '; }) + 1; } };
33.074074
106
0.410974
Priyansh2
b3722316be7a68ed15c4e0fc6f2c0b18809bd1c6
9,135
cpp
C++
foedus_code/foedus-core/src/foedus/memory/shared_memory.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/src/foedus/memory/shared_memory.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/src/foedus/memory/shared_memory.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * 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 * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #include "foedus/memory/shared_memory.hpp" #include <fcntl.h> #include <numa.h> #include <numaif.h> #include <unistd.h> #include <valgrind.h> // just for RUNNING_ON_VALGRIND macro. #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <cstdio> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <string> #include "foedus/assert_nd.hpp" #include "foedus/assorted/assorted_func.hpp" #include "foedus/debugging/rdtsc.hpp" #include "foedus/fs/filesystem.hpp" #include "foedus/memory/memory_id.hpp" namespace foedus { namespace memory { // Note, we can't use glog in this file because shared memory is used before glog is initialized. SharedMemory::SharedMemory(SharedMemory &&other) noexcept : block_(nullptr) { *this = std::move(other); } SharedMemory& SharedMemory::operator=(SharedMemory &&other) noexcept { release_block(); meta_path_ = other.meta_path_; size_ = other.size_; numa_node_ = other.numa_node_; shmid_ = other.shmid_; shmkey_ = other.shmkey_; owner_pid_ = other.owner_pid_; block_ = other.block_; other.block_ = nullptr; return *this; } bool SharedMemory::is_owned() const { return owner_pid_ != 0 && owner_pid_ == ::getpid(); } ErrorStack SharedMemory::alloc( const std::string& meta_path, uint64_t size, int numa_node, bool use_hugepages) { release_block(); if (size % (1ULL << 21) != 0) { size = ((size >> 21) + 1ULL) << 21; } // create a meta file. we must first create it then generate key. // shmkey will change whenever we modify the file. if (fs::exists(fs::Path(meta_path))) { std::string msg = std::string("Shared memory meta file already exists:") + meta_path; return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, msg.c_str()); } std::ofstream file(meta_path, std::ofstream::binary); if (!file.is_open()) { std::string msg = std::string("Failed to create shared memory meta file:") + meta_path; return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, msg.c_str()); } // randomly generate shmkey. We initially used ftok(), but it occasionally gives lots of // conflicts for some reason, esp on aarch64. we just need some random number, so here // we use pid and CPU cycle. pid_t the_pid = ::getpid(); uint64_t key64 = debugging::get_rdtsc() ^ the_pid; key_t the_key = (key64 >> 32) ^ key64; if (the_key == 0) { // rdtsc and getpid not working?? std::string msg = std::string("Dubious shmkey"); return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, msg.c_str()); } // Write out the size/node/shmkey of the shared memory in the meta file file.write(reinterpret_cast<char*>(&size), sizeof(size)); file.write(reinterpret_cast<char*>(&numa_node), sizeof(numa_node)); file.write(reinterpret_cast<char*>(&the_key), sizeof(key_t)); file.flush(); file.close(); size_ = size; numa_node_ = numa_node; owner_pid_ = the_pid; meta_path_ = meta_path; shmkey_ = the_key; // if this is running under valgrind, we have to avoid using hugepages due to a bug in valgrind. // When we are running on valgrind, we don't care performance anyway. So shouldn't matter. if (RUNNING_ON_VALGRIND) { use_hugepages = false; } // see https://bugs.kde.org/show_bug.cgi?id=338995 // Use libnuma's numa_set_preferred to initialize the NUMA node of the memory. // This is the only way to control numa allocation for shared memory. // mbind does nothing for shared memory. ScopedNumaPreferred numa_scope(numa_node, true); shmid_ = ::shmget( shmkey_, size_, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR | (use_hugepages ? SHM_HUGETLB : 0)); if (shmid_ == -1) { std::string msg = std::string("shmget() failed! size=") + std::to_string(size_) + std::string(", os_error=") + assorted::os_error() + std::string(", meta_path=") + meta_path; return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, msg.c_str()); } block_ = reinterpret_cast<char*>(::shmat(shmid_, nullptr, 0)); if (block_ == reinterpret_cast<void*>(-1)) { ::shmctl(shmid_, IPC_RMID, nullptr); // first thing. release it! before everything else. block_ = nullptr; std::stringstream msg; msg << "shmat alloc failed!" << *this << ", error=" << assorted::os_error(); release_block(); std::string str = msg.str(); return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, str.c_str()); } std::memset(block_, 0, size_); // see class comment for why we do this immediately // This memset takes a very long time due to the issue in linux kernel: // https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=8382d914ebf72092aa15cdc2a5dcedb2daa0209d // In linux 3.15 and later, this problem gets resolved and highly parallelizable. return kRetOk; } void SharedMemory::attach(const std::string& meta_path, bool use_hugepages) { release_block(); if (!fs::exists(fs::Path(meta_path))) { std::cerr << "Shared memory meta file does not exist:" << meta_path << std::endl; return; } // the meta file contains the size of the shared memory std::ifstream file(meta_path, std::ifstream::binary); if (!file.is_open()) { std::cerr << "Failed to open shared memory meta file:" << meta_path << std::endl; return; } uint64_t shared_size = 0; int numa_node = 0; key_t the_key = 0; file.read(reinterpret_cast<char*>(&shared_size), sizeof(shared_size)); file.read(reinterpret_cast<char*>(&numa_node), sizeof(numa_node)); file.read(reinterpret_cast<char*>(&the_key), sizeof(key_t)); file.close(); // we always use hugepages, so it's at least 2MB if (shared_size < (1ULL << 21)) { std::cerr << "Failed to read size of shared memory from meta file:" << meta_path << ". It looks like:" << shared_size << std::endl; return; } if (the_key == 0) { std::cerr << "Failed to read shmkey from meta file:" << meta_path << std::endl; return; } size_ = shared_size; numa_node_ = numa_node; meta_path_ = meta_path; shmkey_ = the_key; owner_pid_ = 0; if (RUNNING_ON_VALGRIND) { use_hugepages = false; } shmid_ = ::shmget(shmkey_, size_, use_hugepages ? SHM_HUGETLB : 0); if (shmid_ == -1) { std::cerr << "shmget() attach failed! size=" << size_ << ", error=" << assorted::os_error() << std::endl; return; } block_ = reinterpret_cast<char*>(::shmat(shmid_, nullptr, 0)); if (block_ == reinterpret_cast<void*>(-1)) { block_ = nullptr; std::cerr << "shmat attach failed!" << *this << ", error=" << assorted::os_error() << std::endl; release_block(); return; } } void SharedMemory::mark_for_release() { if (block_ != nullptr && shmid_ != 0) { // Some material says that Linux allows shmget even after shmctl(IPC_RMID), but it doesn't. // It allows shmat() after shmctl(IPC_RMID), but not shmget(). // So we have to invoke IPC_RMID after all child processes acked. ::shmctl(shmid_, IPC_RMID, nullptr); } } void SharedMemory::release_block() { if (block_ != nullptr) { // mark the memory to be reclaimed if (is_owned()) { mark_for_release(); } // Just detach it. as we already invoked shmctl(IPC_RMID) at beginning, linux will // automatically release it once the reference count reaches zero. int dt_ret = ::shmdt(block_); if (dt_ret == -1) { std::cerr << "shmdt() failed." << *this << ", error=" << assorted::os_error() << std::endl; } block_ = nullptr; // clean up meta file. if (is_owned()) { std::remove(meta_path_.c_str()); } } } std::ostream& operator<<(std::ostream& o, const SharedMemory& v) { o << "<SharedMemory>"; o << "<meta_path>" << v.get_meta_path() << "</meta_path>"; o << "<size>" << v.get_size() << "</size>"; o << "<owned>" << v.is_owned() << "</owned>"; o << "<owner_pid>" << v.get_owner_pid() << "</owner_pid>"; o << "<numa_node>" << v.get_numa_node() << "</numa_node>"; o << "<shmid>" << v.get_shmid() << "</shmid>"; o << "<shmkey>" << v.get_shmkey() << "</shmkey>"; o << "<address>" << reinterpret_cast<uintptr_t>(v.get_block()) << "</address>"; o << "</SharedMemory>"; return o; } } // namespace memory } // namespace foedus
34.866412
120
0.673454
sam1016yu
b37c72cbae3ff5e65c7d2ebd2b7416791da0980a
3,606
cpp
C++
test/src/gpu.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
1
2020-02-19T13:13:10.000Z
2020-02-19T13:13:10.000Z
test/src/gpu.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
null
null
null
test/src/gpu.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
null
null
null
//======================================================================= // Copyright (c) 2014-2018 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * Suite of tests to make sure that CPU and GPU are correctly * updated when operations are mixed. * * It is necessary to use large matrices in orders to ensure that * GPU is used. */ #include "test.hpp" #include "etl/stop.hpp" #include "mmul_test.hpp" #ifdef ETL_CUDA #ifdef ETL_EGBLAS_MODE TEMPLATE_TEST_CASE_2("gpu/status/0", "[gpu]", T, float, double) { etl::fast_matrix<T, 75, 75> a; etl::fast_matrix<T, 75, 75> b; etl::fast_matrix<T, 75, 75> c; a.ensure_gpu_up_to_date(); b.ensure_gpu_up_to_date(); c = -(a + b); REQUIRE(c.is_gpu_up_to_date()); } TEMPLATE_TEST_CASE_2("gpu/status/1", "[gpu]", T, float, double) { etl::fast_matrix<T, 75, 75> a; etl::fast_matrix<T, 75, 75> b; etl::fast_matrix<T, 75, 75> c; a.ensure_gpu_up_to_date(); b.ensure_gpu_up_to_date(); c = exp(a + b) >> log(a - b); REQUIRE(c.is_gpu_up_to_date()); } #endif TEMPLATE_TEST_CASE_2("gpu/1", "[gpu]", T, float, double) { etl::fast_matrix<T, 200, 200> a; etl::fast_matrix<T, 200, 200> b; a = 1; b = 2; etl::fast_matrix<T, 200, 200> c1; etl::fast_matrix<T, 200, 200> c2; c1 = a * b; c2 = c1; REQUIRE_EQUALS(c1(0, 0), 400); REQUIRE_EQUALS(c1(0, 1), 400); REQUIRE_EQUALS(c1(0, 2), 400); REQUIRE_EQUALS(c1(1, 0), 400); REQUIRE_EQUALS(c1(1, 1), 400); REQUIRE_EQUALS(c1(1, 2), 400); REQUIRE_EQUALS(c1(2, 0), 400); REQUIRE_EQUALS(c1(2, 1), 400); REQUIRE_EQUALS(c1(2, 2), 400); REQUIRE_EQUALS(c2(0, 0), 400); REQUIRE_EQUALS(c2(0, 1), 400); REQUIRE_EQUALS(c2(0, 2), 400); REQUIRE_EQUALS(c2(1, 0), 400); REQUIRE_EQUALS(c2(1, 1), 400); REQUIRE_EQUALS(c2(1, 2), 400); REQUIRE_EQUALS(c2(2, 0), 400); REQUIRE_EQUALS(c2(2, 1), 400); REQUIRE_EQUALS(c2(2, 2), 400); } TEMPLATE_TEST_CASE_2("gpu/2", "[gpu]", T, float, double) { etl::fast_matrix<T, 200, 200> a; etl::fast_matrix<T, 200, 200> b; a = 1; b = 2; etl::fast_matrix<T, 200, 200> c1; etl::fast_matrix<T, 200, 200> c2; c2 = 1; c1 = a * b; c2 += c1; REQUIRE_EQUALS(c1(0, 0), 400); REQUIRE_EQUALS(c1(0, 1), 400); REQUIRE_EQUALS(c1(0, 2), 400); REQUIRE_EQUALS(c1(1, 0), 400); REQUIRE_EQUALS(c1(1, 1), 400); REQUIRE_EQUALS(c1(1, 2), 400); REQUIRE_EQUALS(c1(2, 0), 400); REQUIRE_EQUALS(c1(2, 1), 400); REQUIRE_EQUALS(c1(2, 2), 400); REQUIRE_EQUALS(c2(0, 0), 401); REQUIRE_EQUALS(c2(0, 1), 401); REQUIRE_EQUALS(c2(0, 2), 401); REQUIRE_EQUALS(c2(1, 0), 401); REQUIRE_EQUALS(c2(1, 1), 401); REQUIRE_EQUALS(c2(1, 2), 401); REQUIRE_EQUALS(c2(2, 0), 401); REQUIRE_EQUALS(c2(2, 1), 401); REQUIRE_EQUALS(c2(2, 2), 401); } TEMPLATE_TEST_CASE_2("gpu/3", "[gpu]", T, float, double) { etl::fast_matrix<T, 200, 200> a; etl::fast_matrix<T, 200, 200> b; a = 1; b = 2; etl::fast_matrix<T, 200, 200> c1; c1 = a * b; c1 *= 2.0; REQUIRE_EQUALS(c1(0, 0), 800); REQUIRE_EQUALS(c1(0, 1), 800); REQUIRE_EQUALS(c1(0, 2), 800); REQUIRE_EQUALS(c1(1, 0), 800); REQUIRE_EQUALS(c1(1, 1), 800); REQUIRE_EQUALS(c1(1, 2), 800); REQUIRE_EQUALS(c1(2, 0), 800); REQUIRE_EQUALS(c1(2, 1), 800); REQUIRE_EQUALS(c1(2, 2), 800); } #endif
24.530612
73
0.574321
BeatWolf
b37d2c02d5c873483dba449319dee844fcc4e7aa
13,774
cpp
C++
src/ops/cdl/CDLOpCPU.cpp
omi-lab/lib_opencolorio
a2457657353b5081ca24b5b9b11dd708451c05ba
[ "BSD-3-Clause" ]
null
null
null
src/ops/cdl/CDLOpCPU.cpp
omi-lab/lib_opencolorio
a2457657353b5081ca24b5b9b11dd708451c05ba
[ "BSD-3-Clause" ]
null
null
null
src/ops/cdl/CDLOpCPU.cpp
omi-lab/lib_opencolorio
a2457657353b5081ca24b5b9b11dd708451c05ba
[ "BSD-3-Clause" ]
1
2022-01-27T17:21:42.000Z
2022-01-27T17:21:42.000Z
// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #include <algorithm> #include <cmath> #include <string.h> #include <OpenColorIO/OpenColorIO.h> #include "BitDepthUtils.h" #include "CDLOpCPU.h" #include "SSE.h" namespace OCIO_NAMESPACE { const float RcpMinValue = 1e-2f; inline float Reciprocal(float x) { return 1.0f / std::max(x, RcpMinValue); } RenderParams::RenderParams() { setSlope (1.0f, 1.0f, 1.0f); setOffset(0.0f, 0.0f, 0.0f); setPower (1.0f, 1.0f, 1.0f); setSaturation(1.0f); } void RenderParams::setSlope(float r, float g, float b) { m_slope[0] = r; m_slope[1] = g; m_slope[2] = b; m_slope[3] = 1.f; } void RenderParams::setOffset(float r, float g, float b) { m_offset[0] = r; m_offset[1] = g; m_offset[2] = b; m_offset[3] = 0.f; } void RenderParams::setPower(float r, float g, float b) { m_power[0] = r; m_power[1] = g; m_power[2] = b; m_power[3] = 1.f; } void RenderParams::setSaturation(float sat) { m_saturation = sat; } void RenderParams::update(ConstCDLOpDataRcPtr & cdl) { double slope[3], offset[3], power[3]; cdl->getSlopeParams().getRGB(slope); cdl->getOffsetParams().getRGB(offset); cdl->getPowerParams().getRGB(power); const float saturation = float(cdl->getSaturation()); const CDLOpData::Style style = cdl->getStyle(); m_isReverse = (style == CDLOpData::CDL_V1_2_REV) || (style == CDLOpData::CDL_NO_CLAMP_REV); m_isNoClamp = (style == CDLOpData::CDL_NO_CLAMP_FWD) || (style == CDLOpData::CDL_NO_CLAMP_REV); if (isReverse()) { // Reverse render parameters setSlope(Reciprocal(float(slope[0])), Reciprocal(float(slope[1])), Reciprocal(float(slope[2]))); setOffset(float(-offset[0]), float(-offset[1]), float(-offset[2])); setPower(Reciprocal(float(power[0])), Reciprocal(float(power[1])), Reciprocal(float(power[2]))); setSaturation(Reciprocal(saturation)); } else { // Forward render parameters setSlope(float(slope[0]), float(slope[1]), float(slope[2])); setOffset(float(offset[0]), float(offset[1]), float(offset[2])); setPower(float(power[0]), float(power[1]), float(power[2])); setSaturation(saturation); } } #ifdef USE_SSE static const __m128 LumaWeights = _mm_setr_ps(0.2126f, 0.7152f, 0.0722f, 0.0); // Load a given pixel from the pixel list into a SSE register inline __m128 LoadPixel(const float * rgbaBuffer, float & inAlpha) { inAlpha = rgbaBuffer[3]; return _mm_loadu_ps(rgbaBuffer); } // Store the pixel's values into a given pixel list's position inline void StorePixel(float * rgbaBuffer, const __m128 pix, const float outAlpha) { _mm_storeu_ps(rgbaBuffer, pix); rgbaBuffer[3] = outAlpha; } // Conditionally clamp the pixel's values to the range [0, 1] // When the template argument is true, the clamp mode is used, // and the values in pix are clamped to the range [0,1]. When // the argument is false, nothing is done. template<bool> inline void ApplyClamp(__m128& pix) { pix = _mm_min_ps(_mm_max_ps(pix, EZERO), EONE); } template<> inline void ApplyClamp<false>(__m128&) { } // Apply the power component to the the pixel's values. // When the template argument is true, the values in pix // are clamped to the range [0,1] and the power operation is // applied. When the argument is false, the values in pix are // not clamped before the power operation is applied. When the // base is negative in this mode, pixel values are just passed // through. template<bool CLAMP> inline void ApplyPower(__m128& pix, const __m128& power) { ApplyClamp<CLAMP>(pix); pix = ssePower(pix, power); } template<> inline void ApplyPower<false>(__m128& pix, const __m128& power) { __m128 negMask = _mm_cmplt_ps(pix, EZERO); __m128 pixPower = ssePower(pix, power); pix = sseSelect(negMask, pix, pixPower); } // Apply the saturation component to the the pixel's values inline void ApplySaturation(__m128& pix, const __m128 saturation) { // Compute luma: dot product of pixel values and the luma weights __m128 luma = _mm_mul_ps(pix, LumaWeights); // luma = [ x+y , y+x , z+w , w+z ] luma = _mm_add_ps(luma, _mm_shuffle_ps(luma, luma, _MM_SHUFFLE(2,3,0,1))); // luma = [ x+y+z+w , y+x+w+z , z+w+x+y , w+z+y+x ] luma = _mm_add_ps(luma, _mm_shuffle_ps(luma, luma, _MM_SHUFFLE(1,0,3,2))); // Apply saturation pix = _mm_add_ps(luma, _mm_mul_ps(saturation, _mm_sub_ps(pix, luma))); } #endif // USE_SSE inline void ApplyScale(float * pix, const float scale) { pix[0] = pix[0] * scale; pix[1] = pix[1] * scale; pix[2] = pix[2] * scale; } // Apply the slope component to the the pixel's values inline void ApplySlope(float * pix, const float * slope) { pix[0] = pix[0] * slope[0]; pix[1] = pix[1] * slope[1]; pix[2] = pix[2] * slope[2]; } // Apply the offset component to the the pixel's values inline void ApplyOffset(float * pix, const float * offset) { pix[0] = pix[0] + offset[0]; pix[1] = pix[1] + offset[1]; pix[2] = pix[2] + offset[2]; } // Apply the saturation component to the the pixel's values inline void ApplySaturation(float * pix, const float saturation) { const float srcpix[3] = { pix[0], pix[1], pix[2] }; static const float LumaWeights[3] = { 0.2126f, 0.7152f, 0.0722f }; // Compute luma: dot product of pixel values and the luma weights ApplySlope(pix, LumaWeights); // luma = x+y+z+w const float luma = pix[0] + pix[1] + pix[2]; // Apply saturation pix[0] = luma + saturation * (srcpix[0] - luma); pix[1] = luma + saturation * (srcpix[1] - luma); pix[2] = luma + saturation * (srcpix[2] - luma); } // Conditionally clamp the pixel's values to the range [0, 1] // When the template argument is true, the clamp mode is used, // and the values in pix are clamped to the range [0,1]. When // the argument is false, nothing is done. template<bool> inline void ApplyClamp(float * pix) { // NaNs become 0. pix[0] = Clamp(pix[0], 0.f, 1.f); pix[1] = Clamp(pix[1], 0.f, 1.f); pix[2] = Clamp(pix[2], 0.f, 1.f); } template<> inline void ApplyClamp<false>(float *) { } // Apply the power component to the the pixel's values. // When the template argument is true, the values in pix // are clamped to the range [0,1] and the power operation is // applied. When the argument is false, the values in pix are // not clamped before the power operation is applied. When the // base is negative in this mode, pixel values are just passed // through. template<bool> inline void ApplyPower(float * pix, const float * power) { ApplyClamp<true>(pix); pix[0] = powf(pix[0], power[0]); pix[1] = powf(pix[1], power[1]); pix[2] = powf(pix[2], power[2]); } template<> inline void ApplyPower<false>(float * pix, const float * power) { // Note: Set NaNs to 0 to match the SSE path. pix[0] = IsNan(pix[0]) ? 0.0f : (pix[0]<0.f ? pix[0] : powf(pix[0], power[0])); pix[1] = IsNan(pix[1]) ? 0.0f : (pix[1]<0.f ? pix[1] : powf(pix[1], power[1])); pix[2] = IsNan(pix[2]) ? 0.0f : (pix[2]<0.f ? pix[2] : powf(pix[2], power[2])); } class CDLOpCPU; typedef OCIO_SHARED_PTR<CDLOpCPU> CDLOpCPURcPtr; // Base class for the CDL operation renderers class CDLOpCPU : public OpCPU { public: CDLOpCPU() = delete; CDLOpCPU(ConstCDLOpDataRcPtr & cdl); protected: RenderParams m_renderParams; }; template<bool CLAMP> class CDLRendererFwd : public CDLOpCPU { public: CDLRendererFwd(ConstCDLOpDataRcPtr & cdl) : CDLOpCPU(cdl) { } virtual void apply(const void * inImg, void * outImg, long numPixels) const; }; #ifdef USE_SSE template<bool CLAMP> class CDLRendererFwdSSE : public CDLRendererFwd<CLAMP> { public: CDLRendererFwdSSE(ConstCDLOpDataRcPtr & cdl) : CDLRendererFwd<CLAMP>(cdl) { } virtual void apply(const void * inImg, void * outImg, long numPixels) const; }; #endif template<bool CLAMP> class CDLRendererRev : public CDLOpCPU { public: CDLRendererRev(ConstCDLOpDataRcPtr & cdl) : CDLOpCPU(cdl) { } virtual void apply(const void * inImg, void * outImg, long numPixels) const; }; #ifdef USE_SSE template<bool CLAMP> class CDLRendererRevSSE : public CDLRendererRev<CLAMP> { public: CDLRendererRevSSE(ConstCDLOpDataRcPtr & cdl) : CDLRendererRev<CLAMP>(cdl) { } virtual void apply(const void * inImg, void * outImg, long numPixels) const; }; #endif CDLOpCPU::CDLOpCPU(ConstCDLOpDataRcPtr & cdl) : OpCPU() { m_renderParams.update(cdl); } #ifdef USE_SSE void LoadRenderParams(const RenderParams & renderParams, __m128 & slope, __m128 & offset, __m128 & power, __m128 & saturation) { slope = _mm_loadu_ps(renderParams.getSlope()); offset = _mm_loadu_ps(renderParams.getOffset()); power = _mm_loadu_ps(renderParams.getPower()); saturation = _mm_set1_ps(renderParams.getSaturation()); } #endif #ifdef USE_SSE template<bool CLAMP> void CDLRendererFwdSSE<CLAMP>::apply(const void * inImg, void * outImg, long numPixels) const { __m128 slope, offset, power, saturation, pix; LoadRenderParams(this->m_renderParams, slope, offset, power, saturation); float inAlpha; const float * in = (const float *)inImg; float * out = (float *)outImg; for(long idx=0; idx<numPixels; ++idx) { pix = LoadPixel(in, inAlpha); pix = _mm_mul_ps(pix, slope); pix = _mm_add_ps(pix, offset); ApplyPower<CLAMP>(pix, power); ApplySaturation(pix, saturation); ApplyClamp<CLAMP>(pix); StorePixel(out, pix, inAlpha); in += 4; out += 4; } } #endif template<bool CLAMP> void CDLRendererFwd<CLAMP>::apply(const void * inImg, void * outImg, long numPixels) const { const float * in = static_cast<const float *>(inImg); float * out = static_cast<float *>(outImg); const float * slope = m_renderParams.getSlope(); float inSlope[3] = {slope[0], slope[1], slope[2]}; for (long idx = 0; idx<numPixels; ++idx) { const float inAlpha = in[3]; // NB: 'in' and 'out' could be pointers to the same memory buffer. memcpy(out, in, 4 * sizeof(float)); ApplySlope(out, inSlope); ApplyOffset(out, m_renderParams.getOffset()); ApplyPower<CLAMP>(out, m_renderParams.getPower()); ApplySaturation(out, m_renderParams.getSaturation()); ApplyClamp<CLAMP>(out); out[3] = inAlpha; in += 4; out += 4; } } #ifdef USE_SSE template<bool CLAMP> void CDLRendererRevSSE<CLAMP>::apply(const void * inImg, void * outImg, long numPixels) const { __m128 slopeRev, offsetRev, powerRev, saturationRev, pix; LoadRenderParams(this->m_renderParams, slopeRev, offsetRev, powerRev, saturationRev); float inAlpha = 1.0f; const float * in = (const float *)inImg; float * out = (float *)outImg; for(long idx=0; idx<numPixels; ++idx) { pix = LoadPixel(in, inAlpha); ApplyClamp<CLAMP>(pix); ApplySaturation(pix, saturationRev); ApplyPower<CLAMP>(pix, powerRev); pix = _mm_add_ps(pix, offsetRev); pix = _mm_mul_ps(pix, slopeRev); ApplyClamp<CLAMP>(pix); StorePixel(out, pix, inAlpha); in += 4; out += 4; } } #endif template<bool CLAMP> void CDLRendererRev<CLAMP>::apply(const void * inImg, void * outImg, long numPixels) const { const float * in = static_cast<const float *>(inImg); float * out = static_cast<float *>(outImg); for (long idx = 0; idx<numPixels; ++idx) { const float inAlpha = in[3]; // NB: 'in' and 'out' could be pointers to the same memory buffer. memcpy(out, in, 4 * sizeof(float)); ApplyClamp<CLAMP>(out); ApplySaturation(out, m_renderParams.getSaturation()); ApplyPower<CLAMP>(out, m_renderParams.getPower()); ApplyOffset(out, m_renderParams.getOffset()); ApplySlope(out, m_renderParams.getSlope()); ApplyClamp<CLAMP>(out); out[3] = inAlpha; in += 4; out += 4; } } // Note that if power is 1, the optimizer is able to convert the CDL op into a pair of matrices and // clamp (when needed). So by default, the following will only get called when power is not 1. ConstOpCPURcPtr GetCDLCPURenderer(ConstCDLOpDataRcPtr & cdl, bool fastPower) { #ifndef USE_SSE std::ignore = fastPower; #endif switch(cdl->getStyle()) { case CDLOpData::CDL_V1_2_FWD: #ifdef USE_SSE if (fastPower) return std::make_shared<CDLRendererFwdSSE<true>>(cdl); else #endif return std::make_shared<CDLRendererFwd<true>>(cdl); case CDLOpData::CDL_NO_CLAMP_FWD: #ifdef USE_SSE if (fastPower) return std::make_shared<CDLRendererFwdSSE<false>>(cdl); else #endif return std::make_shared<CDLRendererFwd<false>>(cdl); case CDLOpData::CDL_V1_2_REV: #ifdef USE_SSE if (fastPower) return std::make_shared<CDLRendererRevSSE<true>>(cdl); else #endif return std::make_shared<CDLRendererRev<true>>(cdl); case CDLOpData::CDL_NO_CLAMP_REV: #ifdef USE_SSE if (fastPower) return std::make_shared<CDLRendererRevSSE<false>>(cdl); else #endif return std::make_shared<CDLRendererRev<false>>(cdl); } throw Exception("Unknown CDL style"); return ConstOpCPURcPtr(); } } // namespace OCIO_NAMESPACE
26.95499
99
0.644112
omi-lab
b3836fd9bba957a496ea400bae54631ac88acc6a
1,017
cpp
C++
simpleMaxCounter/main.cpp
zlum/simple
b5eaf45ad814ec6a2236828ce2ae78b16193bfc1
[ "MIT" ]
null
null
null
simpleMaxCounter/main.cpp
zlum/simple
b5eaf45ad814ec6a2236828ce2ae78b16193bfc1
[ "MIT" ]
null
null
null
simpleMaxCounter/main.cpp
zlum/simple
b5eaf45ad814ec6a2236828ce2ae78b16193bfc1
[ "MIT" ]
null
null
null
#include <cstdint> #include <iostream> #include <string> using namespace std; struct Res { explicit Res(int size): arr(new int[size]), n(size) {} ~Res() { delete[] arr; } int* arr = nullptr; int n = 0; }; Res* findMax(int a[], int n) { if(n == 0) return nullptr; int max = a[0]; int count = 1; for(int i = 1; i < n - 1; ++i) { if(a[i] > max) { max = a[i]; count = 1; } else if(a[i] == max) { ++count; } } Res* res = new Res(count); for(int i = 0; i < count; ++i) { res->arr[i] = max; } return res; } int main() { int arr[] = {1,10,12,22,34,7,3,34,2}; Res* res = findMax(arr, sizeof(arr) / sizeof(int)); if(res != nullptr) { for(int i = 0; i < res->n; ++i) { cout << res->arr[i]; if(i < res->n - 1) cout << ", "; } cout << endl; delete res; } return 0; }
14.955882
58
0.410029
zlum
b385c5e95c2af92bd65606f96a4d039f08a891e9
118
cpp
C++
examples/qml-keypad/imports/tests/keypad/tst_keypad.cpp
bstubert/tdd-training-add-ons
c6ee54069ad056f6bb468c23c99b090d034b42a3
[ "BSD-3-Clause" ]
1
2021-11-25T20:27:19.000Z
2021-11-25T20:27:19.000Z
examples/qml-keypad/imports/tests/keypad/tst_keypad.cpp
bstubert/tdd-training-add-ons
c6ee54069ad056f6bb468c23c99b090d034b42a3
[ "BSD-3-Clause" ]
null
null
null
examples/qml-keypad/imports/tests/keypad/tst_keypad.cpp
bstubert/tdd-training-add-ons
c6ee54069ad056f6bb468c23c99b090d034b42a3
[ "BSD-3-Clause" ]
null
null
null
// Copyright, Burkhard Stubert (burkhard.stubert@embeddeduse.com) #include <QtQuickTest> QUICK_TEST_MAIN(QmlKeypad)
19.666667
65
0.805085
bstubert
b3873f0356795ff40801a4737dad683a84e5637c
10,439
cpp
C++
test/test_mock_mock.cpp
lingjf/h2unit
5a55c718bc22ba52bd4500997b2df18939996efa
[ "Apache-2.0" ]
5
2015-03-02T22:29:00.000Z
2020-06-28T08:52:00.000Z
test/test_mock_mock.cpp
lingjf/h2unit
5a55c718bc22ba52bd4500997b2df18939996efa
[ "Apache-2.0" ]
5
2019-05-10T02:28:00.000Z
2021-07-17T00:53:18.000Z
test/test_mock_mock.cpp
lingjf/h2unit
5a55c718bc22ba52bd4500997b2df18939996efa
[ "Apache-2.0" ]
5
2016-05-25T07:31:16.000Z
2021-08-29T04:25:18.000Z
#include "../source/h2_unit.cpp" #include "test_types.hpp" SUITE(mock function) { Case(once) { MOCK(foobar2, int(int, const char*)).Once(1, "A").Return(11); OK(11, foobar2(1, "A")); } Case(twice) { MOCK(foobar2, int(int, const char*)).Twice(Eq(1), _).Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "BC")); } Case(3 times) { MOCK(foobar2, int(int, const char*)).Times(3).With(Ge(1), "A").Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } Case(any 0) { MOCK(foobar2, int(int, const char*)).Any(1, "A"); } Case(any 1) { MOCK(foobar2, int(int, const char*)).Any().With(1, "A").Return(11); OK(11, foobar2(1, "A")); } Case(any 2) { MOCK(foobar2, int(int, const char*)).Any().With(1, "A").Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } Case(atleast 2) { MOCK(foobar2, int(int, const char*)).Atleast(2).With(1, "A").Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } Case(atleast 3) { MOCK(foobar2, int(int, const char*)).Atleast(2).With(1, "A").Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } Case(atmost 1) { MOCK(foobar2, int(int, const char*)).Atmost(2).With(1, "A").Return(11); OK(11, foobar2(1, "A")); } Case(atmost 2) { MOCK(foobar2, int(int, const char*)).Atmost(2).With(1, "A").Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } Case(between) { MOCK(foobar2, int(int, const char*)).Between(2, 4).With(1, "A").Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } Case(void return) { MOCK(foobar21, void(int& a, char*)).Once(1, (char*)"A"); char t[32] = "A"; int a1 = 1; foobar21(a1, t); } Case(Th0) { MOCK(foobar21, void(int& a, char*)).Once().Th0(1); char t[32] = ""; int a1 = 1; foobar21(a1, t); } Case(Th1) { MOCK(foobar21, void(int& a, char*)).Once().Th1((char*)"A"); char t[32] = "A"; int a1 = 1; foobar21(a1, t); } Case(zero parameter) { MOCK(foobar22, void()).Once(); foobar22(); } Case(Is Null Matcher) { MOCK(foobar2, int(int, const char*)).Once(1, NULL).Return(11); OK(11, foobar2(1, NULL)); } Case(Substr Matcher) { MOCK(foobar2, int(int, const char*)).Once(1, Substr("BC")).Return(11); OK(11, foobar2(1, "ABCD")); } Case(Not Matcher) { MOCK(foobar2, int(int, const char*)).Once(Not(2), _).Return(11); OK(11, foobar2(1, "A")); } Case(AllOf Matcher) { MOCK(foobar2, int(int, const char*)).Once(AllOf(1, Ge(1)), _).Return(11); OK(11, foobar2(1, "A")); } Case(AnyOf Matcher) { MOCK(foobar2, int(int, const char*)).Once(AnyOf(Le(1), Gt(2)), _).Return(11); OK(11, foobar2(1, "A")); } Case(NoneOf Matcher) { MOCK(foobar2, int(int, const char*)).Once(NoneOf(1, Ge(1)), _).Return(11); OK(11, foobar2(0, "A")); } Case(arguments up to 15) { MOCK(foobar16, int(int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int)).Once().Return(11); OK(11, foobar16(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)); } } SUITE(multi line) { Case(1 checkin) { MOCK(foobar2, int(int, const char*)).Once(1, "A").Return(11).Once().With(2, "B").Return(22).Twice(3, "C").Return(33); OK(11, foobar2(1, "A")); OK(22, foobar2(2, "B")); OK(33, foobar2(3, "C")); OK(33, foobar2(3, "C")); } Case(2 checkin) { MOCK(foobar2, int(int, const char*)).Once(1, "A").Return(11).Twice().With(2, "B").Return(22); OK(11, foobar2(1, "A")); OK(22, foobar2(2, "B")); OK(22, foobar2(2, "B")); } } SUITE(mock greed) { Case(greed default true) { MOCK(foobar2, int(int, const char*)) // .greed(true) // default is true .Between(1, 3) .With(1, "A") .Return(11) .Once(1, _) .Return(22); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); OK(22, foobar2(1, "A")); } Case(greed false) { MOCK(foobar2, int(int, const char*)).greed(false).Between(1, 3).With(1, "A").Return(11).Once(1, _).Return(22); OK(11, foobar2(1, "A")); OK(22, foobar2(1, "A")); } } SUITE(mock Return) { Case(delegate to origin without Return) { MOCK(foobar2, int(int, const char*)).Once(1, "A"); OK(2, foobar2(1, "A")); } } SUITE(mock member function) { B_DerivedClass b; Case(static member function) { MOCK(B_DerivedClass::static_f2, const char*(int a, int b)).Once(1, 2).Return("+B.static_f2"); OK("+B.static_f2", B_DerivedClass::static_f2(1, 2)); } Case(normal member function) { MOCK(B_DerivedClass, normal_f2, const char*(int, int)).Once(1, 2).Return("+B.normal_f2"); OK("+B.normal_f2", b.normal_f2(1, 2)); } Case(const member function) { MOCK(B_DerivedClass, const_f, const char*(int)).Once(1, 2).Return("+B.const_f"); OK("+B.const_f", b.const_f(1)); } Case(noexcept member function) { MOCK(B_DerivedClass, noexcept_f, const char*(int)).Once(1, 2).Return("+B.noexcept_f"); OK("+B.noexcept_f", b.noexcept_f(1)); } Case(const noexcept member function) { MOCK(B_DerivedClass, const_noexcept_f, const char*(int)).Once(1, 2).Return("+B.const_noexcept_f"); OK("+B.const_noexcept_f", b.const_noexcept_f(1)); } Case(overload member function) { C_OverrideClass c; // MOCK(C_OverrideClass, overload_f, const char*()).Once().Return("+C.overload_f0"); // OK("+C.overload_f0", c.overload_f()); MOCK(C_OverrideClass, overload_f, const char*(int, int)).Once(1, 2).Return("+C.overload_f2"); OK("+C.overload_f2", c.overload_f(1, 2)); MOCK(C_OverrideClass, overload_f, const char*(int, int, int)).Once(1, 2, 3).Return("+C.overload_f3"); OK("+C.overload_f3", c.overload_f(1, 2, 3)); } Case(virtual member function) { MOCK(B_DerivedClass, virtual_f2, const char*(int, int)).Once(1, 2).Return("+B.virtual_f2"); OK("+B.virtual_f2", b.virtual_f2(1, 2)); } #if !defined WIN32 Case(no default constructor) { MOCK(D_NoConstructorClass, virtual_f3, const char*(int, int, int)).Once().Return("+D.virtual_f3"); D_NoConstructorClass d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); OK("+D.virtual_f3", d.virtual_f3(1, 2, 3)); } Case(abstract class) { MOCK(A_AbstractClass, virtual_f1, const char*(int)).Once().Return("+A.virtual_f1"); OK("+A.virtual_f1", b.virtual_f1(1)); } #endif Case(abstract virtual member function with object) { B_DerivedClass b; OK("A.virtual_f1(1)a", b.virtual_f1(1)); A_AbstractClass* a = dynamic_cast<A_AbstractClass*>(&b); MOCK(a, A_AbstractClass, virtual_f1, const char*(int)).Once().Return("+A.virtual_f1"); OK("+A.virtual_f1", b.virtual_f1(1)); } Case(no default constructor with object) { D_NoConstructorClass d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); MOCK(d, D_NoConstructorClass, virtual_f3, const char*(int, int, int)).Once().Return("+D.virtual_f3"); OK("+D.virtual_f3", d.virtual_f3(1, 2, 3)); } } SUITE(mock template function) { Case(function 1 typename) { OK(4, foobar4<int>(0)); MOCK(foobar4<int>, int(int a)).Once().Return(-4); OK(-4, foobar4<int>(0)); } Case(function 2 typename) { OK(5, (foobar5<int, int>(1, 2))); MOCK((foobar5<int, int>), int(int a, int b)).Once().Return(-5); OK(-5, (foobar5<int, int>(1, 2))); } } SUITE(mock template member function) { Case(member function 1 typename) { F_TemplateClass<int> f; OK("F.static_f1(1)", f.static_f1(1)); OK("F.normal_f1(1)f", f.normal_f1(1)); OK("F.virtual_f1(1)f", f.virtual_f1(1)); MOCK(F_TemplateClass<int>::static_f1, const char*(int a)).Return("+F.static_f1"); OK("+F.static_f1", f.static_f1(0)); MOCK(F_TemplateClass<int>, normal_f1<int>, const char*(int a)).Return("+F.normal_f1"); OK("+F.normal_f1", f.normal_f1(0)); MOCK(F_TemplateClass<int>, virtual_f1, const char*(int a)).Return("+F.virtual_f1"); OK("+F.virtual_f1", f.virtual_f1(0)); } Case(member function 2 typename) { G_TemplateClass<int, int> g; OK("G.static_f2(1,2)", (g.static_f2<int, int>(1, 2))); OK("G.normal_f2(1,2)g", (g.normal_f2<int, int>(1, 2))); OK(Pair("G.virtual_f2", 12.7), (g.virtual_f2<int, int>(1, 2))); MOCK((G_TemplateClass<int, int>::static_f2<int, int>), const char*(int a, int b)).Return("+G.static_f2"); OK("+G.static_f2", (g.static_f2<int, int>(0, 0))); MOCK((G_TemplateClass<int, int>), (normal_f2<int, int>), const char*(int a, int b)).Return("+G.normal_f2"); OK("+G.normal_f2", (g.normal_f2<int, int>(0, 0))); #if !defined WIN32 // Suck when member return Object MOCK((G_TemplateClass<int, int>), (virtual_f2<int, int>), (std::pair<const char*, double>(int a, int b))).Return(std::make_pair("+G.virtual_f2", 0.0)); OK(Pair("+G.virtual_f2", 0.0), (g.virtual_f2<int, int>(0, 0))); #endif } } SUITE(mock omit checkin) { Case(only With) { MOCK(foobar2, int(int, const char*)).With(1, "A").Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } Case(only Th0) { MOCK(foobar2, int(int, const char*)).Th0(1).Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } Case(only Return) { MOCK(foobar2, int(int, const char*)).Return(22); OK(22, foobar2(1, "A")); OK(22, foobar2(1, "A")); } Case(only None) { MOCK(foobar2, int(int, const char*)).Return(11); OK(11, foobar2(1, "A")); OK(11, foobar2(1, "A")); } } SUITE(mock by function name) { Todo(time) // nm undefined time() { MOCK("time", time_t(time_t*)).Once().Return(11); OK(42, time(NULL)); } Todo(time) { MOCK(time, time_t(time_t*)).Once().Return((time_t)0); } Case(foobar) { MOCK("foobar0", int()).Once().Return(1); OK(1, foobar0()); } }
25.775309
157
0.552831
lingjf
b38c5d40162417d29e9c1f4c40ed5f73abb180c9
4,544
cpp
C++
os/fs/iso9660/iso9660Stream.cpp
rvedam/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
2
2020-11-30T18:38:20.000Z
2021-06-07T07:44:03.000Z
os/fs/iso9660/iso9660Stream.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
1
2019-01-14T03:09:45.000Z
2019-01-14T03:09:45.000Z
os/fs/iso9660/iso9660Stream.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008, 2009 Google Inc. * Copyright 2006 Nintendo 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. */ #include <string.h> #include <es.h> #include <es/formatter.h> #include "iso9660Stream.h" Iso9660Stream:: Iso9660Stream(Iso9660FileSystem* fileSystem, Iso9660Stream* parent, u32 offset, u8* record) : fileSystem(fileSystem), ref(1), cache(0), parent(parent), offset(offset) { if (parent) { parent->addRef(); dirLocation = parent->location; } else { dirLocation = 0; } location = LittleEndian::dword(record + DR_Location) + LittleEndian::byte(record + DR_AttributeRecordLength); location *= fileSystem->bytsPerSec; size = LittleEndian::dword(record + DR_DataLength); flags = LittleEndian::byte(record + DR_FileFlags); dateTime = fileSystem->getTime(record + DR_RecordingDateAndTime); // XXX interleave cache = es::Cache::createInstance(this); fileSystem->add(this); } Iso9660Stream:: ~Iso9660Stream() { if (cache) { delete cache; } if (parent) { parent->release(); dirLocation = parent->location; } else { dirLocation = 0; } fileSystem->remove(this); } bool Iso9660Stream:: isRoot() { return parent ? false : true; } int Iso9660Stream:: hashCode() const { return Iso9660FileSystem::hashCode(dirLocation, offset); } long long Iso9660Stream:: getPosition() { return 0; } void Iso9660Stream:: setPosition(long long pos) { } long long Iso9660Stream:: getSize() { return this->size; } void Iso9660Stream:: setSize(long long newSize) { } int Iso9660Stream:: read(void* dst, int count) { return -1; } int Iso9660Stream:: read(void* dst, int count, long long offset) { if (size <= offset || count <= 0) { return 0; } if (size - offset < count) { count = size - offset; } int len; int n; for (len = 0; len < count; len += n, offset += n) { n = fileSystem->disk->read((u8*) dst + len, ((count - len) + fileSystem->bytsPerSec - 1) & ~(fileSystem->bytsPerSec - 1), location + offset + len); if (n <= 0) { break; } } return len; } int Iso9660Stream:: write(const void* src, int count) { return -1; } int Iso9660Stream:: write(const void* src, int count, long long offset) { return -1; } void Iso9660Stream:: flush() { } bool Iso9660Stream:: findNext(es::Stream* dir, u8* record) { ASSERT(isDirectory()); while (0 < dir->read(record, 1)) { if (record[DR_Length] <= DR_FileIdentifier) { break; } if (dir->read(record + 1, record[DR_Length] - 1) < record[DR_Length] - 1) { break; } if (record[DR_FileIdentifierLength] == 0) { break; } if (record[DR_FileIdentifierLength] != 1 || record[DR_FileIdentifier] != 0 && record[DR_FileIdentifier] != 1) { return true; } } return false; } Object* Iso9660Stream:: queryInterface(const char* riid) { Object* objectPtr; if (isDirectory() && strcmp(riid, es::Context::iid()) == 0) { objectPtr = static_cast<es::Context*>(this); } else if (strcmp(riid, es::File::iid()) == 0) { objectPtr = static_cast<es::File*>(this); } else if (strcmp(riid, es::Binding::iid()) == 0) { objectPtr = static_cast<es::Binding*>(this); } else if (strcmp(riid, Object::iid()) == 0) { objectPtr = static_cast<es::Stream*>(this); } else { return NULL; } objectPtr->addRef(); return objectPtr; } unsigned int Iso9660Stream:: addRef() { return ref.addRef(); } unsigned int Iso9660Stream:: release() { unsigned int count = ref.release(); if (count == 0) { delete this; return 0; } return count; }
20.106195
113
0.589349
rvedam
b399fd285905f88ac99223bdc65fbf66a5fa3c2f
869
hpp
C++
engine.hpp
ichristen/pGDS
c6959ea7db0cc01549eb170b7fdc273801735dbc
[ "MIT" ]
null
null
null
engine.hpp
ichristen/pGDS
c6959ea7db0cc01549eb170b7fdc273801735dbc
[ "MIT" ]
null
null
null
engine.hpp
ichristen/pGDS
c6959ea7db0cc01549eb170b7fdc273801735dbc
[ "MIT" ]
null
null
null
#ifndef ENGINE_HPP #define ENGINE_HPP #include <stdio.h> #include <string> #include <array> #include <vector> #include <map> #ifdef __APPLE__ // #include <OpenGL/OpenGL.h> // #include <Cocoa/Cocoa.h> #endif #ifdef __MINGW32__ #endif #ifdef __linux__ #endif #include "window.hpp" #include "vector.hpp" #include "device.hpp" //#include <extern/include/engine.h> // MATLAB engine; it is slightly confusing that this has the same name... //class WINDOW { //#ifdef __APPLE__ // NSView* view; //#endif //}; class ENGINE { WINDOW* window = nullptr; // The window that we render to. // Engine* engine = nullptr; // Our encapsulated MATLAB context. DEVICE* focus = nullptr; // The device we are looking at. std::string path; // The current MATLAB path. ENGINE(); void update(); }; #endif
18.891304
111
0.638665
ichristen
b39a35483919cfbd0466862cd87d1f943ef337a6
1,839
cpp
C++
test/test_simple_enc.cpp
cwxcode/HDR_EXR2MKV
3b5403cb5789cc7e098c5393bcebf673b1cb123b
[ "BSD-3-Clause" ]
46
2016-07-05T14:55:24.000Z
2021-12-24T05:10:00.000Z
test/test_simple_enc.cpp
cwxcode/HDR_EXR2MKV
3b5403cb5789cc7e098c5393bcebf673b1cb123b
[ "BSD-3-Clause" ]
8
2018-05-25T07:36:41.000Z
2021-04-08T14:27:54.000Z
test/test_simple_enc.cpp
cwxcode/HDR_EXR2MKV
3b5403cb5789cc7e098c5393bcebf673b1cb123b
[ "BSD-3-Clause" ]
16
2016-05-29T13:39:23.000Z
2022-02-22T13:53:05.000Z
#include <luma_encoder.h> #include "exr_interface.h" #include <string.h> int main(int argc, char* argv[]) { if (argc > 1 && !(strcmp(argv[1], "-h") && strcmp(argv[1], "--help")) ) { printf("Usage: ./test_simple_enc <hdr_frames> <start_frame> <end_frame> <output>\n"); return 1; } char *hdrFrames = NULL, *outputFile = NULL; int startFrame = 1, endFrame = 5; if (argc > 1) hdrFrames = argv[1]; if (argc > 2) startFrame = atoi(argv[2]); if (argc > 3) endFrame = atoi(argv[3]); if (argc > 4) outputFile = argv[4]; LumaEncoder encoder; LumaEncoderParams params = encoder.getParams(); params.profile = 2; params.bitrate = 1000; params.keyframeInterval = 0; params.bitDepth = 12; params.ptfBitDepth = 11; params.colorBitDepth = 8; params.lossLess = 0; // --> // 0; params.quantizerScale = 4; params.ptf = LumaQuantizer::PTF_PQ; params.colorSpace = LumaQuantizer::CS_LUV; // LDR //params.profile = 0; //params.bitDepth = 8; //params.ptfBitDepth = 8; encoder.setParams(params); char str[500]; for (int f = startFrame; f <= endFrame; f++) { printf("Encoding frame %d.\n", f ); LumaFrame frame; if (hdrFrames != NULL) { sprintf(str, hdrFrames, f); ExrInterface::readFrame(str, frame); } else ExrInterface::testFrame(frame); if (!encoder.initialized()) encoder.initialize(outputFile == NULL ? "output.mkv" : outputFile, frame.width, frame.height); encoder.encode(&frame); } encoder.finish(); printf("Encoding finished. %d frames encoded.\n", endFrame-startFrame+1); return 0; }
24.851351
106
0.553562
cwxcode
b39fe748855d4d54a9ee69a535a5b35f9b54fe66
7,702
hpp
C++
sdk/packages/dynamixel/gems/registers.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
sdk/packages/dynamixel/gems/registers.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
sdk/packages/dynamixel/gems/registers.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <cstdint> #include <map> #include "engine/core/byte.hpp" #include "engine/core/math/utils.hpp" namespace isaac { namespace dynamixel { namespace { constexpr double kRpmRatio = 60.0; } // namespace // Serial port baudrate // The integer values are mapped to the external dynamixel library enum class Baudrate { k4_5M = 7, k4M = 6, k3M = 5, k2M = 4, k1M = 3, k115200 = 2, k57600 = 1, k9600 = 0, kInvalid = -1 }; // Dynamixel model // https://www.trossenrobotics.com/robot-servos enum class Model { AX12A = 0, XM430 = 1, MX12W = 2, XC430 = 3, INVALID = -1 }; // Servo register struct ServoRegister { uint16_t address; uint8_t size; int min; int max; }; // Register keys enum RegisterKey { MODEL_NUMBER, // 0 FIRMWARE_VERSION, // 1 DYNAMIXEL_ID, // 2 BAUDRATE, // 3 RETURN_DELAY_TIME, // 4 DRIVE_MODE, // 5 OPERATING_MODE, // 6 PROTOCOL_VERSION, // 7 CW_ANGLE_LIMIT, // 8 CCW_ANGLE_LIMIT, // 9 HOME_POSITION_OFFSET, // 10 TEMPERATURE_LIMIT, // 11 MIN_VOLTAGE_LIMIT, // 12 MAX_VOLTAGE_LIMIT, // 13 MAX_TORQUE, // 14 TORQUE_LIMIT, // 15 STATUS_RETURN_LEVEL, // 16 ALARM_LED, // 17 SHUTDOWN, // 18 TORQUE_ENABLE, // 19 GOAL_POSITION, // 20 MOVING_SPEED, // 21 CURRENT_POSITION, // 22 CURRENT_SPEED, // 23 CURRENT_LOAD, // 24 CURRENT_TEMPERATURE, // 25 CURRENT_VOLTAGE, // 26 ACCELERATION_VALUE_OF_PROFILE, // 27 VELOCITY_VALUE_OF_PROFILE, // 27 TIME_MS, // 28 LED, // 29 MOVING // 30 }; // Number of Dynamixel "position ticks" for a full rotation (from Dynamixel spec sheet) constexpr int kAngleResolutionXM430 = 4096; constexpr int kAngleResolutionXC430 = 4096; constexpr int kAngleResolutionAX12A = 4096; constexpr int kAngleResolutionMX12W = 4096; // Rotations per minute per Dynamixel "speed tick" (from Dynamixel spec sheet) constexpr double kRpmResolutionXM430 = 0.229; constexpr double kRpmResolutionXC430 = 0.229; constexpr double kRpmResolutionAX12A = 0.916; constexpr double kRpmResolutionMX12W = 0.916; // Hardware status codes (from Dynamixel spec sheet) constexpr byte kStatusOk = 0x00; constexpr byte kStatusInputVoltageError = 0x01; constexpr byte kStatusAngleLimitError = 0x02; constexpr byte kStatusOverheating = 0x04; constexpr byte kStatusRangeError = 0x08; constexpr byte kStatusChecksumError = 0x10; constexpr byte kStatusOverloaded = 0x20; constexpr byte kStatusInstructionError = 0x40; // Max valid moving speed (from Dynamixel spec sheet) constexpr int kMaxMovingSpeed = 0x3FF; // Flag to control moving direction (from Dynamixel spec sheet) constexpr int kMovingSpeedDirectionFlagAX12A = 0x400; constexpr int kMovingSpeedDirectionFlagMX12W = 0x400; // Inits registers depending on the Servo Model // For instance for AX12 // http://emanual.robotis.com/docs/en/dxl/ax/ax-12a/#control-table std::map<RegisterKey, ServoRegister> InitRegisters(Model model); // Map enum values to integer values for the external dynamixel library inline int GetBaudrateValue(Baudrate baudrate) { switch (baudrate) { case Baudrate::k4_5M: return 4'500'000; case Baudrate::k4M: return 4'000'000; case Baudrate::k3M: return 3'000'000; case Baudrate::k2M: return 2'000'000; case Baudrate::k1M: return 1'000'000; case Baudrate::k115200: return 115'200; case Baudrate::k57600: return 57'600; case Baudrate::k9600: return 9'600; case Baudrate::kInvalid: break; } return 0; } // Gets protocol for instructions and status packet inline float GetProtocol(Model model) { switch (model) { case Model::AX12A: return 1.0; case Model::MX12W: return 1.0; case Model::XM430: return 2.0; case Model::XC430: return 2.0; case Model::INVALID: break; } return 0.0; } // Gets Angle value depending on motor model inline int GetAngleResolution(Model model) { switch (model) { case Model::AX12A: return kAngleResolutionAX12A; case Model::MX12W: return kAngleResolutionMX12W; case Model::XM430: return kAngleResolutionXM430; case Model::XC430: return kRpmResolutionXC430; case Model::INVALID: break; } return 0; } // Gets RPM value depending on motor model inline double GetRpmResolution(Model model) { switch (model) { case Model::AX12A: return kRpmResolutionAX12A; case Model::MX12W: return kRpmResolutionMX12W; case Model::XM430: return kRpmResolutionXM430; case Model::XC430: return kRpmResolutionXM430; case Model::INVALID: break; } return 0.0; } // Converts a dynamixel joint position to the corresponding angle in radians. inline double TicksToAngle(Model model, int position_ticks) { const int angle_resolution = GetAngleResolution(model); const double factor = TwoPi<double> / static_cast<double>(angle_resolution); return factor * static_cast<double>(position_ticks); } // Inverse of TicksToAngle inline int AngleToTicks(Model model, double angle) { const double factor = static_cast<double>(GetAngleResolution(model)) / TwoPi<double>; return static_cast<int>(factor * WrapTwoPi(angle)); } // Converts a dynamixel joint speed to the corresponding angular speed in radians per second. inline double TicksToAngularSpeed(Model model, int speed_ticks) { const double factor = (GetRpmResolution(model) * TwoPi<double>) / kRpmRatio; switch (model) { case Model::AX12A: if (speed_ticks & kMovingSpeedDirectionFlagAX12A) { speed_ticks = kMovingSpeedDirectionFlagAX12A - speed_ticks; } break; case Model::MX12W: if (speed_ticks & kMovingSpeedDirectionFlagMX12W) { speed_ticks = kMovingSpeedDirectionFlagMX12W - speed_ticks; } break; default: break; } return factor * static_cast<double>(speed_ticks); } // Depending on the dynamixel model the negative value is stored differently. This option computes // the correct negative value associated to `value` depending on the dynamixel model. inline void ReverseValue(Model model, int& value) { switch (model) { case Model::AX12A: value |= kMovingSpeedDirectionFlagAX12A; return; case Model::MX12W: value |= kMovingSpeedDirectionFlagMX12W; return; default: value = -value; } } // Inverse of TicksToSpeed inline int AngularSpeedToTicks(Model model, double angular_speed) { const double factor = kRpmRatio / (GetRpmResolution(model) * TwoPi<double>); int ticks = std::min(kMaxMovingSpeed, static_cast<int>(factor * std::abs(angular_speed))); if (angular_speed < 0) { ReverseValue(model, ticks); } return ticks; } } // namespace dynamixel } // namespace isaac
29.737452
98
0.664762
ddr95070
b3a42bde03db67b2845476db5e55ba0ba41e6ad2
230
hpp
C++
engine/include/engine/Serializable.hpp
kkitsune/GoblinEngine
f69a82b13b418391554f1aeb8957f445352184b6
[ "MIT" ]
9
2016-02-04T16:42:31.000Z
2016-12-05T04:34:03.000Z
engine/include/engine/Serializable.hpp
kkitsune/GoblinEngine
f69a82b13b418391554f1aeb8957f445352184b6
[ "MIT" ]
null
null
null
engine/include/engine/Serializable.hpp
kkitsune/GoblinEngine
f69a82b13b418391554f1aeb8957f445352184b6
[ "MIT" ]
null
null
null
#pragma once #include <json.hpp> #include <ABI.h> using Json = nlohmann::basic_json<>; class E_ABI(engine) Serializable { public: virtual ~Serializable() {} virtual Json save() = 0; virtual void load(Json const&) = 0; };
12.777778
36
0.678261
kkitsune
b3a7acbb2b12389223b884089ce1ec21b6a26c6b
978
cpp
C++
naive_simulation_works/systemc_for_dummies/four_bit_adder/main.cpp
VSPhaneendraPaluri/pvsdrudgeworks
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
[ "MIT" ]
null
null
null
naive_simulation_works/systemc_for_dummies/four_bit_adder/main.cpp
VSPhaneendraPaluri/pvsdrudgeworks
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
[ "MIT" ]
null
null
null
naive_simulation_works/systemc_for_dummies/four_bit_adder/main.cpp
VSPhaneendraPaluri/pvsdrudgeworks
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
[ "MIT" ]
null
null
null
#include <systemc.h> #include "Four_Bit_Adder.h" #include "MyTestBenchDriver.h" #include "MyTestBenchMonitor.h" int sc_main(int sc_argc, char* sc_argv[]) { sc_signal<sc_lv<1> > pb_a[4], pb_b[4], pb_z[5]; int i = 0; Four_Bit_Adder MyAdder("MyAdder"); for(i=0; i < 4; i++) { MyAdder.a[i](pb_a[i]); MyAdder.b[i](pb_b[i]); MyAdder.z[i](pb_z[i]); cout << "Instantiated MyAdder : " << i << endl; } MyAdder.z[4](pb_z[4]); MyTestBenchDriver MyTBDriver("MyTBDriver"); for(i=0; i < 4; i++) { MyTBDriver.TBD_a[i](pb_a[i]); MyTBDriver.TBD_b[i](pb_b[i]); cout << "Instantiated MyTestBenchDriver : " << i << endl; } MyTestBenchMonitor MyTBMonitor("MyTBMonitor"); for(i=0; i < 4; i++) { MyTBMonitor.TBM_a[i](pb_a[i]); MyTBMonitor.TBM_b[i](pb_b[i]); MyTBMonitor.TBM_z[i](pb_z[i]); cout << "Instantiated MyTestBenchMonitor : " << i << endl; } MyTBMonitor.TBM_z[4](pb_z[4]); sc_set_time_resolution(1, SC_NS); sc_start(60.0, SC_NS); return 0; }
21.26087
60
0.639059
VSPhaneendraPaluri
b3aecb9d7320b9ae30e0550e265e2bff6d69fe20
6,653
cpp
C++
connectors/dds4ccm/tests/LateBinding/ReadGet/Receiver/RG_LateBinding_Receiver_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
10
2016-07-20T00:55:50.000Z
2020-10-04T19:07:10.000Z
connectors/dds4ccm/tests/LateBinding/ReadGet/Receiver/RG_LateBinding_Receiver_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
13
2016-09-27T14:08:27.000Z
2020-11-11T10:45:56.000Z
connectors/dds4ccm/tests/LateBinding/ReadGet/Receiver/RG_LateBinding_Receiver_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
12
2016-04-20T09:57:02.000Z
2021-12-24T17:23:45.000Z
// -*- C++ -*- /** * Code generated by the The ACE ORB (TAO) IDL Compiler v1.8.2 * TAO and the TAO IDL Compiler have been developed by: * Center for Distributed Object Computing * Washington University * St. Louis, MO * USA * http://www.cs.wustl.edu/~schmidt/doc-center.html * and * Distributed Object Computing Laboratory * University of California at Irvine * Irvine, CA * USA * and * Institute for Software Integrated Systems * Vanderbilt University * Nashville, TN * USA * http://www.isis.vanderbilt.edu/ * * Information about TAO is available at: * http://www.dre.vanderbilt.edu/~schmidt/TAO.html **/ #include "RG_LateBinding_Receiver_exec.h" #include "RG_LateBinding_Receiver_impl.h" #include "tao/ORB_Core.h" #include "ace/Reactor.h" namespace CIAO_RG_LateBinding_Receiver_Impl { /** * Facet Executor Implementation Class: info_get_status_exec_i */ info_get_status_exec_i::info_get_status_exec_i ( ::RG_LateBinding::CCM_Receiver_Context_ptr ctx) : ciao_context_ ( ::RG_LateBinding::CCM_Receiver_Context::_duplicate (ctx)) { } info_get_status_exec_i::~info_get_status_exec_i (void) { } // Operations from ::CCM_DDS::PortStatusListener void info_get_status_exec_i::on_requested_deadline_missed (::DDS::DataReader_ptr /* the_reader */, const ::DDS::RequestedDeadlineMissedStatus & /* status */) { /* Your code here. */ } void info_get_status_exec_i::on_sample_lost (::DDS::DataReader_ptr /* the_reader */, const ::DDS::SampleLostStatus & /* status */) { /* Your code here. */ } /** * Facet Executor Implementation Class: info_read_status_exec_i */ info_read_status_exec_i::info_read_status_exec_i ( ::RG_LateBinding::CCM_Receiver_Context_ptr ctx) : ciao_context_ ( ::RG_LateBinding::CCM_Receiver_Context::_duplicate (ctx)) { } info_read_status_exec_i::~info_read_status_exec_i (void) { } // Operations from ::CCM_DDS::PortStatusListener void info_read_status_exec_i::on_requested_deadline_missed (::DDS::DataReader_ptr /* the_reader */, const ::DDS::RequestedDeadlineMissedStatus & /* status */) { /* Your code here. */ } void info_read_status_exec_i::on_sample_lost (::DDS::DataReader_ptr /* the_reader */, const ::DDS::SampleLostStatus & /* status */) { /* Your code here. */ } /** * Facet Executor Implementation Class: reader_start_exec_i */ reader_start_exec_i::reader_start_exec_i ( ::RG_LateBinding::CCM_Receiver_Context_ptr ctx, Receiver_exec_i &callback) : ciao_context_ ( ::RG_LateBinding::CCM_Receiver_Context::_duplicate (ctx)) , callback_ (callback) { } reader_start_exec_i::~reader_start_exec_i (void) { } // Operations from ::ReaderStarter void reader_start_exec_i::start_read (void) { this->callback_.start_read (); } void reader_start_exec_i::set_reader_properties (::CORBA::UShort nr_keys, ::CORBA::UShort nr_iterations) { this->callback_.keys (nr_keys); this->callback_.iterations (nr_iterations); } /** * Component Executor Implementation Class: Receiver_exec_i */ Receiver_exec_i::Receiver_exec_i (void) : impl_ (0) , keys_ (5) , iterations_ (0) { } Receiver_exec_i::~Receiver_exec_i (void) { delete this->impl_; } // Supported operations and attributes. void Receiver_exec_i::start_read (void) { ACE_NEW_THROW_EX (this->impl_, RG_LateBinding_Receiver_impl ( this->ciao_context_.in (), this->iterations_, this->keys_), ::CORBA::INTERNAL ()); this->impl_->start (); } void Receiver_exec_i::keys (::CORBA::UShort keys) { this->keys_ = keys; } void Receiver_exec_i::iterations (::CORBA::UShort iterations) { this->iterations_ = iterations; } // Component attributes and port operations. ::CCM_DDS::CCM_PortStatusListener_ptr Receiver_exec_i::get_info_get_status (void) { if ( ::CORBA::is_nil (this->ciao_info_get_status_.in ())) { info_get_status_exec_i *tmp = 0; ACE_NEW_RETURN ( tmp, info_get_status_exec_i ( this->ciao_context_.in ()), ::CCM_DDS::CCM_PortStatusListener::_nil ()); this->ciao_info_get_status_ = tmp; } return ::CCM_DDS::CCM_PortStatusListener::_duplicate ( this->ciao_info_get_status_.in ()); } ::CCM_DDS::CCM_PortStatusListener_ptr Receiver_exec_i::get_info_read_status (void) { if ( ::CORBA::is_nil (this->ciao_info_read_status_.in ())) { info_read_status_exec_i *tmp = 0; ACE_NEW_RETURN ( tmp, info_read_status_exec_i ( this->ciao_context_.in ()), ::CCM_DDS::CCM_PortStatusListener::_nil ()); this->ciao_info_read_status_ = tmp; } return ::CCM_DDS::CCM_PortStatusListener::_duplicate ( this->ciao_info_read_status_.in ()); } ::CCM_ReaderStarter_ptr Receiver_exec_i::get_start_reading (void) { if ( ::CORBA::is_nil (this->ciao_reader_start_.in ())) { reader_start_exec_i *tmp = 0; ACE_NEW_RETURN ( tmp, reader_start_exec_i ( this->ciao_context_.in (), *this), ::CCM_ReaderStarter::_nil ()); this->ciao_reader_start_ = tmp; } return ::CCM_ReaderStarter::_duplicate ( this->ciao_reader_start_.in ()); } // Operations from Components::SessionComponent. void Receiver_exec_i::set_session_context ( ::Components::SessionContext_ptr ctx) { this->ciao_context_ = ::RG_LateBinding::CCM_Receiver_Context::_narrow (ctx); if ( ::CORBA::is_nil (this->ciao_context_.in ())) { throw ::CORBA::INTERNAL (); } } void Receiver_exec_i::configuration_complete (void) { /* Your code here. */ } void Receiver_exec_i::ccm_activate (void) { /* Your code here. */ } void Receiver_exec_i::ccm_passivate (void) { /* Your code here. */ } void Receiver_exec_i::ccm_remove (void) { /* Your code here. */ } extern "C" RECEIVER_EXEC_Export ::Components::EnterpriseComponent_ptr create_RG_LateBinding_Receiver_Impl (void) { ::Components::EnterpriseComponent_ptr retval = ::Components::EnterpriseComponent::_nil (); ACE_NEW_NORETURN ( retval, Receiver_exec_i); return retval; } }
23.34386
96
0.63881
qinwang13
a2a5e51de7fd35e2aebcddd5162c3c5f867bf381
1,348
cpp
C++
src_sycl/gen.cpp
frengels/cuda-to-sycl-nbody
989f01cabb7fa0eceb70b18610e1b8b1e03eb8af
[ "MIT" ]
null
null
null
src_sycl/gen.cpp
frengels/cuda-to-sycl-nbody
989f01cabb7fa0eceb70b18610e1b8b1e03eb8af
[ "MIT" ]
3
2022-02-02T09:25:33.000Z
2022-02-17T15:43:48.000Z
src_sycl/gen.cpp
frengels/cuda-to-sycl-nbody
989f01cabb7fa0eceb70b18610e1b8b1e03eb8af
[ "MIT" ]
1
2022-02-16T17:45:43.000Z
2022-02-16T17:45:43.000Z
#include "gen.hpp" #include <random> const float PI = 3.14159265358979323846; // Copyright (C) 2016 - 2018 Sarah Le Luron // Copyright (C) 2022 Codeplay Software Limited using namespace std; mt19937 rng; uniform_real_distribution<> dis(0, 1); glm::vec4 randomParticlePos() { // Random position on a 'thick disk' glm::vec4 particle; float t = dis(rng) * 2 * PI; float s = dis(rng) * 100; particle.x = cos(t) * s; particle.y = sin(t) * s; particle.z = dis(rng) * 4; particle.w = 1.f; return particle; } glm::vec4 randomParticleVel(glm::vec4 pos) { // Initial velocity is 'orbital' velocity from position glm::vec3 vel = glm::cross(glm::vec3(pos), glm::vec3(0, 0, 1)); float orbital_vel = sqrt(2.0 * glm::length(vel)); vel = glm::normalize(vel) * orbital_vel; return glm::vec4(vel, 0.0); } std::vector<float> genFlareTex(int tex_size) { std::vector<float> pixels(tex_size * tex_size); float sigma2 = tex_size / 2.0; float A = 1.0; for (int i = 0; i < tex_size; ++i) { float i1 = i - tex_size / 2; for (int j = 0; j < tex_size; ++j) { float j1 = j - tex_size / 2; // gamma corrected gauss pixels[i * tex_size + j] = pow( A * exp(-((i1 * i1) / (2 * sigma2) + (j1 * j1) / (2 * sigma2))), 2.2); } } return pixels; }
26.431373
77
0.588279
frengels
a2a8a9372654535bc6a4d7a017816f70de1f23f0
334
cpp
C++
Bit Manipulation/Clear_all_bits_from_LSB_to_i.cpp
pranav918/DSA-Implementations-Under-Construction
4127d18b084652ae19959fc4f0da9cfad360df8d
[ "MIT" ]
1
2021-06-18T13:59:38.000Z
2021-06-18T13:59:38.000Z
Bit Manipulation/Clear_all_bits_from_LSB_to_i.cpp
pranav918/DSA-Implementations-Under-Construction
4127d18b084652ae19959fc4f0da9cfad360df8d
[ "MIT" ]
null
null
null
Bit Manipulation/Clear_all_bits_from_LSB_to_i.cpp
pranav918/DSA-Implementations-Under-Construction
4127d18b084652ae19959fc4f0da9cfad360df8d
[ "MIT" ]
null
null
null
/* Author : Pranav Deshmukh PICT,Pune Stay Focused! */ #include <bits/stdc++.h> using namespace std; int main() { int n, i; cout << "Enter number followed by ith(from 0) bit place:" << endl; cin >> n >> i; int m = ~((1 << (i + 1)) - 1); n = n & m; cout << "Answer is " << n << endl; return 0; }
19.647059
68
0.505988
pranav918
a2a9174a976f58acebc1a7dcbeda149d508fe888
2,777
hpp
C++
Week2-Data-Structure-I/ZhengQianYi/src/ft/cuckoo_filter.hpp
zhengqianyi/training-plan
456cce5d124de171fe73f8e108a7c61c08e7a326
[ "MIT" ]
1
2021-09-29T04:35:36.000Z
2021-09-29T04:35:36.000Z
Week2-Data-Structure-I/ZhengQianYi/src/ft/cuckoo_filter.hpp
zqyi/training-plan
456cce5d124de171fe73f8e108a7c61c08e7a326
[ "MIT" ]
null
null
null
Week2-Data-Structure-I/ZhengQianYi/src/ft/cuckoo_filter.hpp
zqyi/training-plan
456cce5d124de171fe73f8e108a7c61c08e7a326
[ "MIT" ]
null
null
null
#ifndef FT_CUCKOO_FILTER_HPP #define FT_CUCKOO_FILTER_HPP #include "filter.hpp" #include "cuckoo_vector.hpp" #include "hasher.hpp" #include "Rand_int.hpp" #include <cmath> namespace ft { class cuckoo_filter : public filter { private: size_t cells_; size_t fingerprint_size_; size_t seed_; cuckoo_vector v_; HashType hash_name_; public: cuckoo_filter(HashType hash_name, size_t cells, size_t fingerprint_size); using filter::add; using filter::lookup; /// Adds an element to the Bloom filter. virtual void add(std::string const &o) override; /// Retrieves the count of an element. virtual bool lookup(std::string const &o) const override; /// delete void del(std::string const &o); std::string get_v() const; size_t get_cell() { return cells_; } }; cuckoo_filter ::cuckoo_filter(HashType hash_name, size_t cells, size_t fingerprint_size) : cells_(cells), fingerprint_size_(fingerprint_size), v_(cells, fingerprint_size), hash_name_(hash_name) { Rand_int rnd{1, 10000000}; seed_ = rnd(); } void cuckoo_filter ::add(std::string const &o) { size_t fp = hashf(hash_name_, seed_, o) % (int)pow(2, (double)fingerprint_size_); size_t idx = fp % cells_; int flag = 0; auto last_fp = v_.set(flag, idx, fp); auto max_kick = cells_ * 2; while (max_kick-- > 0) { if (last_fp == 0) { break; } else { //把上次拿出来的再插入 idx = (idx ^ hashf(hash_name_, seed_, last_fp)) % cells_; flag = (flag + 1) % 2; last_fp = v_.set(flag, idx, last_fp); } } //空间已满 } bool cuckoo_filter ::lookup(std::string const &o) const { size_t fp = hashf(hash_name_, seed_, o) % (int)pow(2, (double)fingerprint_size_); size_t idx_0 = fp % cells_; size_t idx_1 = (idx_0 ^ hashf(hash_name_, seed_, fp)) % cells_; bool hit = v_.check(0, idx_0); if (hit == false) { hit = v_.check(1, idx_1); } return hit; } void cuckoo_filter ::del(std::string const &o) { size_t fp = hashf(hash_name_, seed_, o) % (int)pow(2, (double)fingerprint_size_); size_t idx_0 = fp % cells_; size_t idx_1 = (idx_0 ^ hashf(hash_name_, seed_, fp)) % cells_; if (v_.del(0, idx_0) == false) { v_.del(1, idx_1); } } std::string cuckoo_filter::get_v() const { return v_.to_string(); } } // namespace ft #endif
23.141667
197
0.548073
zhengqianyi
a2ac58994f69c2901dd523177a165ed8737edc8d
667
cc
C++
iridium/files/patch-chrome_browser_profiles_chrome__browser__main__extra__parts__profiles.cc
behemoth3663/ports_local
ad57042ae62c907f9340ee696f468fdfeb562a8b
[ "BSD-3-Clause" ]
1
2022-02-08T02:24:08.000Z
2022-02-08T02:24:08.000Z
iridium/files/patch-chrome_browser_profiles_chrome__browser__main__extra__parts__profiles.cc
behemoth3663/ports_local
ad57042ae62c907f9340ee696f468fdfeb562a8b
[ "BSD-3-Clause" ]
null
null
null
iridium/files/patch-chrome_browser_profiles_chrome__browser__main__extra__parts__profiles.cc
behemoth3663/ports_local
ad57042ae62c907f9340ee696f468fdfeb562a8b
[ "BSD-3-Clause" ]
null
null
null
--- chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc.orig 2020-03-16 18:40:29 UTC +++ chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc @@ -295,7 +295,7 @@ void ChromeBrowserMainExtraPartsProfiles:: if (base::FeatureList::IsEnabled(media::kUseMediaHistoryStore)) media_history::MediaHistoryKeyedServiceFactory::GetInstance(); #if defined(OS_WIN) || defined(OS_MACOSX) || \ - (defined(OS_LINUX) && !defined(OS_CHROMEOS)) + (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_BSD) metrics::DesktopProfileSessionDurationsServiceFactory::GetInstance(); #endif ModelTypeStoreServiceFactory::GetInstance();
55.583333
100
0.775112
behemoth3663
a2ad0de602bed30a14fbe3b1da51a6820b913644
1,788
cpp
C++
Source/FishEngine/ECS.cpp
yushroom/FishEngine-ECS
99e96f96d30a1cc624a7ffb410a34e418449dd81
[ "MIT" ]
10
2018-08-28T17:07:06.000Z
2021-06-19T09:51:27.000Z
Source/FishEngine/ECS.cpp
yushroom/FishEngine-ECS
99e96f96d30a1cc624a7ffb410a34e418449dd81
[ "MIT" ]
1
2018-10-25T19:42:10.000Z
2018-10-30T09:34:05.000Z
Source/FishEngine/ECS.cpp
yushroom/FishEngine-ECS
99e96f96d30a1cc624a7ffb410a34e418449dd81
[ "MIT" ]
5
2018-10-25T19:39:26.000Z
2020-08-09T05:47:57.000Z
#include <FishEngine/ECS/Component.hpp> #include <FishEngine/ECS/GameObject.hpp> #include <FishEngine/ECS/Scene.hpp> #include <FishEngine/ECS/System.hpp> #include <FishEngine/Components/Transform.hpp> #include <FishEngine/Serialization/Archive.hpp> using namespace FishEngine; GameObject::GameObject(EntityID entityID, Scene* scene) : ID(entityID) { } void Component::Deserialize(InputArchive& archive) { archive.AddNVP("m_EntityID", this->entityID); archive.AddNVP("m_Enabled", this->m_Enabled); } void Component::Serialize(OutputArchive& archive) const { archive.AddNVP("m_EntityID", this->entityID); archive.AddNVP("m_Enabled", this->m_Enabled); } void Scene::Start() { std::sort(m_Systems.begin(), m_Systems.end(), [](System* a, System* b) { return a->m_Priority < b->m_Priority; }); for (System* s : m_Systems) { s->Start(); } } void Scene::Update() { for (System* s : m_Systems) { if (s->m_Enabled) s->Update(); } } void Scene::PostUpdate() { for (System* s : m_Systems) { s->PostUpdate(); } } GameObject* Scene::CreateGameObject() { m_LastEntityID++; EntityID id = m_LastEntityID; GameObject* go = new GameObject(id, this); m_GameObjects[id] = go; go->m_Transform = GameObjectAddComponent<Transform>(go); go->m_Scene = this; m_RootTransforms.push_back(go->GetTransform()); return go; } void Scene::AddRootTransform(Transform* t) { if (m_Cleaning) return; m_RootTransforms.push_back(t); // t->m_RootOrder = m_RootTransforms.size() - 1; } void Scene::RemoveRootTransform(Transform* t) { auto pos = std::find(m_RootTransforms.begin(), m_RootTransforms.end(), t); //assert(pos != m_RootTransforms.end()); if (pos == m_RootTransforms.end()) { //LogWarning("transform not found"); return; } m_RootTransforms.erase(pos); }
20.089888
75
0.706935
yushroom
a2adb990212cd924d9398e7fbe452c0d0d30865c
6,878
hxx
C++
include/knapsack_object.hxx
LPMP/equality-knapsack
2a44a156aa8cd2bee1757a8b23facdc2be3246e0
[ "BSD-2-Clause" ]
null
null
null
include/knapsack_object.hxx
LPMP/equality-knapsack
2a44a156aa8cd2bee1757a8b23facdc2be3246e0
[ "BSD-2-Clause" ]
null
null
null
include/knapsack_object.hxx
LPMP/equality-knapsack
2a44a156aa8cd2bee1757a8b23facdc2be3246e0
[ "BSD-2-Clause" ]
null
null
null
#ifndef EKP_KNAPSACK_OBJECT_HXX #define EKP_KNAPSACK_OBJECT_HXX #include <config.hxx> #include <algorithm> #include <vector> #include <numeric> #include <memory> #include <stack> #include <tuple> namespace ekp { class ekp_instance { public: using node = std::tuple<REAL,REAL,REAL,REAL>; struct knapsack_item { REAL cost; INDEX weight; INDEX var; REAL val = 0.0; bool removed = false; knapsack_item* next = NULL; knapsack_item* prev = NULL; }; template<typename M> ekp_instance(M& m) : ekp_instance(m.costs,m.weights,m.b) { } ekp_instance(std::vector<REAL> c,std::vector<INDEX> w,INDEX b) : nVars_(c.size()),rhs_(b) { items_.reserve(nVars_); items_ptr_.reserve(nVars_); removed_.reserve(nVars_); for(INDEX i=0;i<nVars_;i++){ std::shared_ptr<knapsack_item> item(new knapsack_item); item->cost = c[i]; item->weight = (REAL) w[i]; item->var = i; items_.push_back(item.get()); items_ptr_.push_back(item); } this->sort(); } REAL cost(INDEX i){ assert(i<nVars_); return items_[i]->cost; } INDEX weight(INDEX i){ assert(i<nVars_); return items_[i]->weight; } INDEX index(INDEX i){ assert(i<nVars_); return items_[i]->var; } INDEX rhs() const { return rhs_; } INDEX numberOfVars() const { return nVars_; }; knapsack_item* item(INDEX i){ assert(i<nVars_); return items_ptr_[i].get(); } knapsack_item* Begin() const { return begin_; } knapsack_item* End() const { return end_; } void sort(){ auto f = [&](knapsack_item* i,knapsack_item* j){ REAL iv = i->cost/((REAL) i->weight); REAL jv = j->cost/((REAL) j->weight); return iv < jv; }; std::sort(items_.begin(),items_.end(),f); this->UpdateList(); } bool remove(knapsack_item* p){ if( rhs_ < p->val*p->weight ){ return false; } assert( p->removed == false ); p->removed = true; removed_.push_back(p); auto prev = p->prev; auto next = p->next; assert( p->val == 0 || p->val == 1 ); rhs_ = rhs_ - p->val*p->weight; if( prev != NULL ){ prev->next = next; } else { begin_ = next; } if( next != NULL ){ next->prev = prev; } return true; } bool restore(){ if( removed_.empty() ){ return false; } else { auto p = removed_.back(); p->removed = false; auto prev = p->prev; auto next = p->next; assert( p->val == 0 || p->val == 1 ); rhs_ = rhs_ + p->val*p->weight; if( prev != NULL ){ prev->next = p; } else { begin_ = p; } if( next != NULL ){ next->prev = p; } removed_.pop_back(); return true; } } /** * Create solution vector and calculate cost **/ void solution(std::vector<REAL>& x){ x.resize(nVars_ + fixed_.size() ,0.0); cost_ = 0.0; weight_ = 0.0; REAL weight_removed = 0.0; for( auto v : items_ ){ assert( 0.0 <= v->val && v->val <= 1.0 ); x[v->var] = v->val; cost_ += v->val*v->cost; weight_ += v->val*((REAL) v->weight); if( v->removed ){ weight_removed += v->val*((REAL) v->weight); } } assert( weight_ == rhs_ + weight_removed ); assert( rhs_ == 0 || weight_ > 0.0 ); for( auto v : fixed_ ){ assert( 0 <= std::get<0>(v) && std::get<0>(v) < x.size() ); assert( std::get<1>(v) == 0.0 || std::get<1>(v) == 1.0 ); x[std::get<0>(v)] = std::get<1>(v); cost_ += std::get<1>(v)*std::get<2>(v); weight_ += std::get<1>(v)*std::get<3>(v); } } bool feasible(REAL bestIntSol = EKPINF){ if( begin_ == end_ ){ assert( begin_ == NULL && end_ == NULL ); INDEX w = 0; for( auto p : removed_ ){ w += p->weight; } for( auto p : fixed_ ){ w += std::get<3>(p); } return w == rhs_; } else { INDEX w = 0; INDEX wk = begin_->weight; INDEX wwk = begin_->weight; INDEX bk = 0; REAL ck = EKPINF; REAL zk = 0; for( auto item = begin_;item!=end_;item=item->next ){ w += item->weight; if( item->weight < wk ){ wwk = wk; wk = item->weight; } if( wk < item->weight && item->weight < wwk ){ wwk = item->weight; } if( item->cost < ck ){ ck = item->cost; } } for( auto p : removed_ ){ zk += p->val*p->cost; } for( auto p : fixed_ ){ zk += std::get<1>(p)*std::get<2>(p); } bool temp = true; if( rhs_ > 0 ){ temp = temp && !(wk < rhs_ && rhs_ < wwk); temp = temp && !(rhs_ < wk); temp = temp && ck + zk < bestIntSol; } return temp; } } REAL cost(){ assert(cost_ < EKPINF); return cost_; } REAL weight(){ assert( weight_ > 0.0 ); return weight_; } private: void UpdateList(){ auto p0 = items_.begin(); auto p1 = items_.begin(); p1++; begin_ = *p0; while ( p1 != items_.end() ) { (*p0)->next = *p1; (*p1)->prev = *p0; p0++;p1++; } } INDEX nVars_; INDEX rhs_; REAL cost_ = EKPINF; REAL weight_ = 0.0; std::vector<knapsack_item*> items_; std::vector<std::shared_ptr<knapsack_item>> items_ptr_; knapsack_item* begin_; knapsack_item* end_ = NULL; std::vector<knapsack_item*> removed_; std::vector<node> fixed_; }; template<> ekp_instance::ekp_instance(ekp_instance& ekp) : rhs_(ekp.rhs()){ items_.reserve(ekp.numberOfVars()); items_ptr_.reserve(ekp.numberOfVars()); knapsack_item* it = ekp.Begin(); knapsack_item* end = ekp.End(); while( it != end ){ std::shared_ptr<knapsack_item> item(new knapsack_item); item->cost = it->cost; item->weight = it->weight; item->var = it->var; items_.push_back(item.get()); items_ptr_.push_back(item); it = it->next; } fixed_.reserve( ekp.removed_.size() + ekp.fixed_.size() ); for( auto p : ekp.fixed_ ){ fixed_.push_back(p); } for( auto p : ekp.removed_ ){ assert( p->val == 0.0 || p->val == 1.0 ); fixed_.push_back(std::make_tuple(p->var,p->val,p->cost,p->weight)); } nVars_ = items_.size(); if( nVars_ > 0){ removed_.reserve(nVars_); this->UpdateList(); } else { begin_ = NULL; end_ = NULL; } assert( fixed_.size() + nVars_ == ekp.numberOfVars() + ekp.fixed_.size() ); } } #endif // EKP_KNAPSACK_OBJECT_HXX
26.867188
82
0.508287
LPMP
a2b079c7c95647c2bc8228fbb9a17fbaec414162
33,132
hpp
C++
src/frame_graph/frame_graph.hpp
LaisoEmilio/WispRenderer
8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572
[ "Apache-2.0" ]
203
2019-04-26T10:52:22.000Z
2022-03-15T17:42:44.000Z
src/frame_graph/frame_graph.hpp
LaisoEmilio/WispRenderer
8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572
[ "Apache-2.0" ]
90
2018-11-23T09:07:05.000Z
2019-04-13T10:44:03.000Z
src/frame_graph/frame_graph.hpp
LaisoEmilio/WispRenderer
8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572
[ "Apache-2.0" ]
14
2019-06-19T00:52:00.000Z
2021-02-19T13:44:01.000Z
/*! * Copyright 2019 Breda University of Applied Sciences and Team Wisp (Viktor Zoutman, Emilio Laiso, Jens Hagen, Meine Zeinstra, Tahar Meijs, Koen Buitenhuis, Niels Brunekreef, Darius Bouma, Florian Schut) * * 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. */ #pragma once #include <vector> #include <string> #include <type_traits> #include <stack> #include <deque> #include <future> #include <any> #include "../util/thread_pool.hpp" #include "../util/delegate.hpp" #include "../renderer.hpp" #include "../platform_independend_structs.hpp" #include "../settings.hpp" #include "../d3d12/d3d12_settings.hpp" #include "../structs.hpp" #include "../wisprenderer_export.hpp" #ifndef _DEBUG #define FG_MAX_PERFORMANCE #endif template<typename ...Ts> std::vector<std::reference_wrapper<const std::type_info>> FG_DEPS() { return { (typeid(Ts))... }; } namespace wr { enum class RenderTaskType { DIRECT, COMPUTE, COPY }; enum class CPUTextureType { PIXEL_DATA, DEPTH_DATA }; struct CPUTextures { std::optional<CPUTexture> pixel_data = std::nullopt; std::optional<CPUTexture> depth_data = std::nullopt; }; //! Typedef for the render task handle. using RenderTaskHandle = std::uint32_t; // Forward declarations. class FrameGraph; /*! Structure that describes a render task */ /*! All non default initialized member variables should be fully initialized to prevent undifined behaviour. */ struct RenderTaskDesc { // Typedef the function pointer types to keep the code readable. using setup_func_t = util::Delegate<void(RenderSystem&, FrameGraph&, RenderTaskHandle, bool)>; using execute_func_t = util::Delegate<void(RenderSystem&, FrameGraph&, SceneGraph&, RenderTaskHandle)>; using destroy_func_t = util::Delegate<void(FrameGraph&, RenderTaskHandle, bool)>; /*! The type of the render task.*/ RenderTaskType m_type = RenderTaskType::DIRECT; /*! The function pointers for the task.*/ setup_func_t m_setup_func; execute_func_t m_execute_func; destroy_func_t m_destroy_func; /*! The properties for the render target this task renders to. If this is `std::nullopt` no render target will be created. */ std::optional<RenderTargetProperties> m_properties; bool m_allow_multithreading = true; }; //! Frame Graph /*! The Frame Graph is responsible for managing all tasks the renderer should perform. The idea is you can add tasks to the scene graph and when you call `RenderSystem::Render` it will run the tasks added. It will not just run tasks but will also assign command lists and render targets to the tasks. The Frame Graph is also capable of mulithreaded execution. It will split the command lists that are allowed to be multithreaded on X amount of threads specified in `settings.hpp` */ class FrameGraph { // Obtain the type definitions from `RenderTaskDesc` to keep the code readable. using setup_func_t = RenderTaskDesc::setup_func_t; using execute_func_t = RenderTaskDesc::execute_func_t; using destroy_func_t = RenderTaskDesc::destroy_func_t; public: //! Constructor. /*! This constructor is able to reserve space for render tasks. This works by calling `std::vector::reserve`. \param num_reserved_tasks Amount of tasks we should reserve space for. */ FrameGraph(std::size_t num_reserved_tasks = 1) : m_render_system(nullptr), m_num_tasks(0), m_thread_pool(new util::ThreadPool(settings::num_frame_graph_threads)), m_uid(GetFreeUID()) { // lambda to simplify reserving space. auto reserve = [num_reserved_tasks](auto v) { v.reserve(num_reserved_tasks); }; // Reserve space for all vectors. reserve(m_setup_funcs); reserve(m_execute_funcs); reserve(m_destroy_funcs); reserve(m_cmd_lists); reserve(m_render_targets); reserve(m_data); reserve(m_data_type_info); #ifndef FG_MAX_PERFORMANCE reserve(m_dependencies); reserve(m_names); #endif reserve(m_types); reserve(m_rt_properties); m_settings = decltype(m_settings)(num_reserved_tasks, std::nullopt); // Resizing so I can initialize it with null since this is an optional value. m_futures.resize(num_reserved_tasks); // std::thread doesn't allow me to reserve memory for the vector. Hence I'm resizing. } //! Destructor /*! This destructor destroys all the task data and the thread pool. If you want to reuse the frame graph I recommend calling `FrameGraph::Destroy` */ ~FrameGraph() { delete m_thread_pool; Destroy(); } FrameGraph(const FrameGraph&) = delete; FrameGraph(FrameGraph&&) = delete; FrameGraph& operator=(const FrameGraph&) = delete; FrameGraph& operator=(FrameGraph&&) = delete; //! Setup the render tasks /*! Calls all setup function pointers and obtains the required render targets and command lists. It is recommended to try to avoid calling this during runtime because it can cause stalls if the setup functions are expensive. \param render_system The render system we want to use for rendering. */ inline void Setup(RenderSystem& render_system) { bool is_valid = Validate(); if (!is_valid) { LOGE("Framegraph validation failed. Aborting setup."); return; } // Resize these vectors since we know the end size already. m_cmd_lists.resize(m_num_tasks); m_should_execute.resize(m_num_tasks, true); // All tasks should execute by default. m_render_targets.resize(m_num_tasks); m_futures.resize(m_num_tasks); m_render_system = &render_system; auto get_command_list_from_render_system = [this](auto type) { switch (type) { case RenderTaskType::DIRECT: return m_render_system->GetDirectCommandList(d3d12::settings::num_back_buffers); case RenderTaskType::COMPUTE: return m_render_system->GetComputeCommandList(d3d12::settings::num_back_buffers); case RenderTaskType::COPY: return m_render_system->GetCopyCommandList(d3d12::settings::num_back_buffers); default: LOGC("Tried creating a command list of a type that is not supported."); return static_cast<wr::CommandList*>(nullptr); } }; if constexpr (settings::use_multithreading) { for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { // Get the proper command list from the render system. m_cmd_lists[i] = get_command_list_from_render_system(m_types[i]); #ifndef FG_MAX_PERFORMANCE render_system.SetCommandListName(m_cmd_lists[i], m_names[i]); #endif // Get a render target from the render system. if (m_rt_properties[i].has_value()) { m_render_targets[i] = render_system.GetRenderTarget(m_rt_properties[i].value()); #ifndef FG_MAX_PERFORMANCE render_system.SetRenderTargetName(m_render_targets[i], m_names[i]); #endif } } Setup_MT_Impl(); } else { // Itterate over all the tasks. for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { // Get the proper command list from the render system. m_cmd_lists[i] = get_command_list_from_render_system(m_types[i]); #ifndef FG_MAX_PERFORMANCE render_system.SetCommandListName(m_cmd_lists[i], m_names[i]); #endif // Get a render target from the render system. if (m_rt_properties[i].has_value()) { m_render_targets[i] = render_system.GetRenderTarget(m_rt_properties[i].value()); #ifndef FG_MAX_PERFORMANCE render_system.SetRenderTargetName(m_render_targets[i], m_names[i]); #endif } // Call the setup function pointer. m_setup_funcs[i](render_system, *this, i, false); } } // Finish the setup before continuing for savety. for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { WaitForCompletion(i); } } /*! Execute all render tasks */ /*! For every render task call the setup function pointers and tell the render system we started a render task of a certain type. \param render_system The render system we want to use for rendering. \param scene_graph The scene graph we want to render. */ inline void Execute(SceneGraph& scene_graph) { ResetOutputTexture(); // Check if we need to disable some tasks while (!m_should_execute_change_request.empty()) { auto front = m_should_execute_change_request.front(); m_should_execute[front.first] = front.second; m_should_execute_change_request.pop(); } if constexpr (settings::use_multithreading) { Execute_MT_Impl(scene_graph); } else { Execute_ST_Impl(scene_graph); } } /*! Resize all render tasks */ /*! This function calls resize all render tasks to a specific width and height. The width and height parameters should be the output size. Please note this function calls Destroy than setup with the resize boolean set to true. */ inline void Resize(std::uint32_t width, std::uint32_t height) { // Make sure the tasks are finished executing for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { WaitForCompletion(i); } // Make sure the GPU has finished with the tasks m_render_system->WaitForAllPreviousWork(); for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { m_destroy_funcs[i](*this, i, true); if (m_rt_properties[i].has_value() && !m_rt_properties[i].value().m_is_render_window) { m_render_system->ResizeRenderTarget(&m_render_targets[i], static_cast<std::uint32_t>(std::ceil(width * m_rt_properties[i].value().m_resolution_scale.Get())), static_cast<std::uint32_t>(std::ceil(height * m_rt_properties[i].value().m_resolution_scale.Get()))); } m_setup_funcs[i](*m_render_system, *this, i, true); } } /*! Get Resolution scale of specified Render Task */ /*! Checks if specified RenderTask has valid properties and returns it's resolution scalar. */ [[nodiscard]] inline const float GetRenderTargetResolutionScale(RenderTaskHandle handle) const { if (m_rt_properties[handle].has_value()) { return m_rt_properties[handle].value().m_resolution_scale.Get(); } else { LOGW("Error: GetResolutionScale tried accessing invalid data!") } return 1.0f; } /*! Destroy all tasks */ /*! Calls all destroy functions and release any allocated data. */ void Destroy() { // Make sure all tasks finished executing for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { WaitForCompletion(i); } m_render_system->WaitForAllPreviousWork(); // Send the destroy events to the render tasks. for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { m_destroy_funcs[i](*this, i, false); } // Make sure we free the data objects we allocated. for (auto& data : m_data) { data.reset(); } for (auto& cmd_list : m_cmd_lists) { m_render_system->DestroyCommandList(cmd_list); } for(decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { if(m_rt_properties[i].has_value() && !m_rt_properties[i]->m_is_render_window) { m_render_system->DestroyRenderTarget(&m_render_targets[i]); } } // Reset all members in the case of the user wanting to reuse this frame graph after `FrameGraph::Destroy`. m_setup_funcs.clear(); m_execute_funcs.clear(); m_destroy_funcs.clear(); m_cmd_lists.clear(); m_render_targets.clear(); m_data.clear(); m_data_type_info.clear(); m_settings.clear(); #ifndef FG_MAX_PERFORMANCE m_dependencies.clear(); m_names.clear(); #endif m_types.clear(); m_rt_properties.clear(); m_futures.clear(); m_num_tasks = 0; } /* Stall the current thread until the render task has finished. */ inline void WaitForCompletion(RenderTaskHandle handle) { // If we are not allowed to use multithreading let the compiler optimize this away completely. if constexpr (settings::use_multithreading) { if (auto& future = m_futures[handle]; future.valid()) { future.wait(); } } } /*! Wait for a previous task. */ /*! This function loops over all tasks and checks whether it has the same type information as the template variable. If a task was found it waits for it. If no task is found with the type specified a nullptr will be returned and a error message send to the logging system. The template parameter should be a Data struct of a the task you want to wait for. */ template<typename T> inline void WaitForPredecessorTask() { static_assert(std::is_class<T>::value || std::is_floating_point<T>::value || std::is_integral<T>::value, "The template variable should be a class, struct, floating point value or a integral value."); static_assert(!std::is_pointer<T>::value, "The template variable type should not be a pointer. Its implicitly converted to a pointer."); for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++) { if (typeid(T) == m_data_type_info[i]) { WaitForCompletion(i); return; } } LOGC("Failed to find predecessor data! Please check your task order."); return; } /*! Get the data of a task. (Modifyable) */ /*! The template variable is used to specify the type of the data structure. \param handle The handle to the render task. (Given by the `Setup`, `Execute` and `Destroy` functions) */ template<typename T = void*> [[nodiscard]] inline auto & GetData(RenderTaskHandle handle) const { static_assert(std::is_class<T>::value || std::is_floating_point<T>::value || std::is_integral<T>::value, "The template variable should be a class, struct, floating point value or a integral value."); static_assert(!std::is_pointer<T>::value, "The template variable type should not be a pointer. Its implicitly converted to a pointer."); return *static_cast<T*>(m_data[handle].get()); } /*! Get the data of a previously ran task. (Constant) */ /*! This function loops over all tasks and checks whether it has the same type information as the template variable. If no task is found with the type specified a nullptr will be returned and a error message send to the logging system. \param handle The handle to the render task. (Given by the `Setup`, `Execute` and `Destroy` functions) */ template<typename T> [[nodiscard]] inline auto const & GetPredecessorData() { static_assert(std::is_class<T>::value || std::is_floating_point<T>::value || std::is_integral<T>::value, "The template variable should be a class, struct, floating point value or a integral value."); static_assert(!std::is_pointer<T>::value, "The template variable type should not be a pointer. Its implicitly converted to a pointer."); for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++) { if (typeid(T) == m_data_type_info[i]) { WaitForCompletion(i); return *static_cast<T*>(m_data[i].get()); } } LOGC("Failed to find predecessor data! Please check your task order.") return *static_cast<T*>(nullptr); } /*! Get the render target of a previously ran task. (Constant) */ /*! This function loops over all tasks and checks whether it has the same type information as the template variable. If no task is found with the type specified a nullptr will be returned and a error message send to the logging system. */ template<typename T> [[nodiscard]] inline RenderTarget* GetPredecessorRenderTarget() { static_assert(std::is_class<T>::value, "The template variable should be a class or struct."); static_assert(!std::is_pointer<T>::value, "The template variable type should not be a pointer. Its implicitly converted to a pointer."); for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++) { if (typeid(T) == m_data_type_info[i]) { WaitForCompletion(i); return m_render_targets[i]; } } LOGC("Failed to find predecessor render target! Please check your task order."); return nullptr; } /*! Get the command list of a task. */ /*! The template variable allows you to cast the command list to a "non platform independent" different type. For example a `D3D12CommandList`. \param handle The handle to the render task. (Given by the `Setup`, `Execute` and `Destroy` functions) */ template<typename T = CommandList> [[nodiscard]] inline auto GetCommandList(RenderTaskHandle handle) const { static_assert(std::is_class<T>::value || std::is_void<T>::value, "The template variable should be a void, class or struct."); static_assert(!std::is_pointer<T>::value, "The template variable type should not be a pointer. Its implicitly converted to a pointer."); return static_cast<T*>(m_cmd_lists[handle]); } /*! Get the command list of a previously ran task. */ /*! The function allows the user to get a command list from another render task. These command lists are not meant to be used as they could be closed or in flight. This function was created only so that ray tracing tasks could get the heap from the acceleration structure command list. */ template<typename T> [[nodiscard]] inline wr::CommandList* GetPredecessorCommandList() { static_assert(std::is_class<T>::value, "The template variable should be a void, class or struct."); static_assert(!std::is_pointer<T>::value, "The template variable type should not be a pointer. Its implicitly converted to a pointer."); for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++) { if (typeid(T) == m_data_type_info[i]) { WaitForCompletion(i); return m_cmd_lists[i]; } } LOGC("Failed to find predecessor command list! Please check your task order."); return nullptr; } template<typename T> [[nodiscard]] std::vector<T*> GetAllCommandLists() { std::vector<T*> retval; retval.reserve(m_num_tasks); // TODO: Just return the fucking vector as const ref. for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++) { // Don't return command lists from tasks that don't require to be executed. if (!m_should_execute[i]) { continue; } WaitForCompletion(i); retval.push_back(static_cast<T*>(m_cmd_lists[i])); } return retval; } /*! Get the render target of a task. */ /*! The template variable allows you to cast the render target to a "non platform independent" different type. For example a `D3D12RenderTarget`. \param handle The handle to the render task. (Given by the `Setup`, `Execute` and `Destroy` functions) */ template<typename T = RenderTarget> [[nodiscard]] inline auto GetRenderTarget(RenderTaskHandle handle) const { static_assert(std::is_class<T>::value || std::is_void<T>::value, "The template variable should be a void, class or struct."); static_assert(!std::is_pointer<T>::value, "The template variable type should not be a pointer. Its implicitly converted to a pointer."); return static_cast<T*>(m_render_targets[handle]); } /*! Check if this frame graph has a task. */ /*! This checks if the frame graph has the task that has been given as the template variable. */ template<typename T> inline bool HasTask() const { return GetHandleFromType<T>().has_value(); } /*! Validates the frame graph for correctness */ /*! This function uses the dependencies to check whether the frame graph is constructed properly by the user. Note: This function only works when `FG_MAX_PERFORMANCE` is defined. */ bool Validate() { bool result = true; #ifndef FG_MAX_PERFORMANCE // Loop over all the tasks. for (decltype(m_num_tasks) handle = 0; handle < m_num_tasks; ++handle) { // Loop over the task's dependencies. for (auto dependency : m_dependencies[handle]) { bool found_dependency = false; // Loop over the predecessor tasks. for (decltype(m_num_tasks) prev_handle = 0; prev_handle < handle; ++prev_handle) { const auto& task_type_info = m_data_type_info[prev_handle].get(); if (task_type_info == dependency.get()) { found_dependency = true; } } if (!found_dependency) { LOGW("Framegraph validation: Failed to find dependency {}", dependency.get().name()); result = false; } } } #endif return result; } /*! Add a task to the Frame Graph. */ /*! This creates a new render task based on a description. The dependencies parameters can contain a list of typeid's of render tasks this task depends on. You can use the FG_DEPS macro as followed: `AddTask<desc, FG_DEPS(OtherTaskData)>` \param desc A description of the render task. */ template<typename T> inline void AddTask(RenderTaskDesc& desc, std::wstring const & name, std::vector<std::reference_wrapper<const std::type_info>> dependencies = {}) { static_assert(std::is_class<T>::value || std::is_floating_point<T>::value || std::is_integral<T>::value, "The template variable should be a class, struct, floating point value or a integral value."); static_assert(std::is_default_constructible<T>::value, "The template variable is not default constructible or nothrow consructible!"); static_assert(!std::is_pointer<T>::value, "The template variable type should not be a pointer. Its implicitly converted to a pointer."); m_setup_funcs.emplace_back(desc.m_setup_func); m_execute_funcs.emplace_back(desc.m_execute_func); m_destroy_funcs.emplace_back(desc.m_destroy_func); #ifndef FG_MAX_PERFORMANCE m_dependencies.emplace_back(dependencies); m_names.emplace_back(name); #endif m_settings.resize(m_num_tasks + 1ull); m_types.emplace_back(desc.m_type); m_rt_properties.emplace_back(desc.m_properties); m_data.emplace_back(std::make_shared<T>()); m_data_type_info.emplace_back(typeid(T)); // If we are allowed to do multithreading place the task in the appropriate vector if constexpr (settings::use_multithreading) { if (desc.m_allow_multithreading) { m_multi_threaded_tasks.emplace_back(m_num_tasks); } else { m_single_threaded_tasks.emplace_back(m_num_tasks); } } m_num_tasks++; } /*! Return the frame graph's unique id.*/ [[nodiscard]] const std::uint64_t GetUID() const noexcept { return m_uid; }; /*! Return the cpu texture. */ [[nodiscard]] CPUTextures const & GetOutputTexture() const noexcept { return m_output_cpu_textures; } /*! Save a render target to disc */ /* Tells the render system to save a render target to disc as a image. \param index The index of the render target from the task you want to save. */ template<typename T> void SaveTaskToDisc(std::string const & path, int index = 0) { auto handle = GetHandleFromType<T>(); if (handle.has_value()) { m_render_system->RequestRenderTargetSaveToDisc(path, m_render_targets[handle.value()], index); } else { LOGW("Failed to save render task to disc, Task was not found."); } } /*! Set the cpu texture's data. */ void SetOutputTexture(const CPUTexture& output_texture, CPUTextureType type) { switch (type) { case wr::CPUTextureType::PIXEL_DATA: if (m_output_cpu_textures.pixel_data != std::nullopt) { LOGW("Warning: CPU texture pixel data is written to more than once a frame!"); } // Save the pixel data m_output_cpu_textures.pixel_data = output_texture; break; case wr::CPUTextureType::DEPTH_DATA: if (m_output_cpu_textures.depth_data != std::nullopt) { LOGW("Warning: CPU texture depth data is written to more than once a frame!"); } // Save the depth data m_output_cpu_textures.depth_data = output_texture; break; default: // Should never happen LOGC("Invalid CPU texture type supplied!") break; } } /*! Enable or disable execution of a task. */ inline void SetShouldExecute(RenderTaskHandle handle, bool value) { m_should_execute_change_request.emplace(std::make_pair(handle, value)); } /*! Enable or disable execution of a task. Templated version */ template<typename T> inline void SetShouldExecute(bool value) { auto handle = GetHandleFromType<T>(); if (handle.has_value()) { SetShouldExecute(handle.value(), value); } else { LOGW("Failed to mark the task for execution, Task was not found."); } } /*! Update the settings of a task. */ /*! This is used to update settings of a render task. This must ge called BEFORE `FrameGraph::Setup` or `RenderSystem::Render`. */ template<typename T> inline void UpdateSettings(std::any settings) { auto handle = GetHandleFromType<T>(); if (handle.has_value()) { m_settings[handle.value()] = settings; } else { LOGW("Failed to update settings, Could not find render task"); } } /*! Gives you the settings of a task by handle. */ /*! This gives you the settings for a render task casted to `R`. Meant to be used for INSIDE the tasks. The return value can be a nullptr. \tparam T The render task data type used for identification. \tparam R The type of the settings object. */ template<typename T, typename R> [[nodiscard]] inline R GetSettings() const try { static_assert(std::is_class<T>::value || std::is_floating_point<T>::value || std::is_integral<T>::value, "The first template variable should be a class, struct, floating point value or a integral value."); for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++) { if (typeid(T) == m_data_type_info[i]) { return std::any_cast<R>(m_settings[i].value()); } } LOGC("Failed to find task settings! Does your frame graph contain this task?"); return R(); } catch (const std::bad_any_cast & e) { LOGC("A task settings requested failed to cast to T. ({})", e.what()); return R(); } /*! Gives you the settings of a task by handle. */ /*! This gives you the settings for a render task casted to `T`. Meant to be used for INSIDE the tasks. The return value can be a nullptr. */ template<typename T> [[nodiscard]] inline T GetSettings(RenderTaskHandle handle) const try { static_assert(std::is_class<T>::value || std::is_floating_point<T>::value || std::is_integral<T>::value, "The template variable should be a class, struct, floating point value or a integral value."); return std::any_cast<T>(m_settings[handle].value()); } catch (const std::bad_any_cast& e) { LOGW("A task settings requested failed to cast to T. ({})", e.what()); return T(); } /*! Resets the CPU texture data for this frame. */ inline void ResetOutputTexture() { // Frame has been rendered, allow a task to write to the CPU texture in the next frame m_output_cpu_textures.pixel_data = std::nullopt; m_output_cpu_textures.depth_data = std::nullopt; } private: /*! Get the handle from a task by data type */ /* This function is zero overhead with GCC-8.2, -03 */ template<typename T> inline std::optional<RenderTaskHandle> GetHandleFromType() const { for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { if (m_data_type_info[i].get() == typeid(T)) { return i; } } return std::nullopt; } /*! Setup tasks multi threaded */ inline void Setup_MT_Impl() { // Multithreading behaviour for (const auto handle : m_multi_threaded_tasks) { m_futures[handle] = m_thread_pool->Enqueue([this, handle] { m_setup_funcs[handle](*m_render_system, *this, handle, false); }); } // Singlethreading behaviour for (const auto handle : m_single_threaded_tasks) { m_setup_funcs[handle](*m_render_system, *this, handle, false); } } /*! Execute tasks multi threaded */ inline void Execute_MT_Impl(SceneGraph& scene_graph) { // Multithreading behaviour for (const auto handle : m_multi_threaded_tasks) { // Skip this task if it doesn't need to be executed if (!m_should_execute[handle]) { continue; } m_futures[handle] = m_thread_pool->Enqueue([this, handle, &scene_graph] { ExecuteSingleTask(scene_graph, handle); }); } // Singlethreading behaviour for (const auto handle : m_single_threaded_tasks) { // Skip this task if it doesn't need to be executed if (!m_should_execute[handle]) { continue; } ExecuteSingleTask(scene_graph, handle); } } /*! Execute tasks single threaded */ inline void Execute_ST_Impl(SceneGraph& scene_graph) { for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i) { // Skip this task if it doesn't need to be executed if (!m_should_execute[i]) { continue; } ExecuteSingleTask(scene_graph, i); } } /*! Execute a single task */ inline void ExecuteSingleTask(SceneGraph& sg, RenderTaskHandle handle) { auto cmd_list = m_cmd_lists[handle]; auto render_target = m_render_targets[handle]; auto rt_properties = m_rt_properties[handle]; m_render_system->ResetCommandList(cmd_list); switch (m_types[handle]) { case RenderTaskType::DIRECT: if (rt_properties.has_value()) { m_render_system->StartRenderTask(cmd_list, { render_target, rt_properties.value() }); } m_execute_funcs[handle](*m_render_system, *this, sg, handle); if (rt_properties.has_value()) { m_render_system->StopRenderTask(cmd_list, { render_target, rt_properties.value() }); } break; case RenderTaskType::COMPUTE: if (rt_properties.has_value()) { m_render_system->StartComputeTask(cmd_list, { render_target, rt_properties.value() }); } m_execute_funcs[handle](*m_render_system, *this, sg, handle); if (rt_properties.has_value()) { m_render_system->StopComputeTask(cmd_list, { render_target, rt_properties.value() }); } break; case RenderTaskType::COPY: if (rt_properties.has_value()) { m_render_system->StartCopyTask(cmd_list, { render_target, rt_properties.value() }); } m_execute_funcs[handle](*m_render_system, *this, sg, handle); if (rt_properties.has_value()) { m_render_system->StopCopyTask(cmd_list, { render_target, rt_properties.value() }); } break; } m_render_system->CloseCommandList(cmd_list); } /*! Get a free unique ID. */ static std::uint64_t GetFreeUID() { if (!m_free_uids.empty()) { std::uint64_t uid = m_free_uids.top(); m_free_uids.pop(); return uid; } std::uint64_t uid = m_largest_uid; m_largest_uid++; return uid; } /*! Get a release a unique ID for reuse. */ WISPRENDERER_EXPORT static void ReleaseUID(std::uint64_t uid) { m_free_uids.push(uid); } RenderSystem* m_render_system; /*! The number of tasks we have added. */ std::uint32_t m_num_tasks; /*! The thread pool used for multithreading */ util::ThreadPool* m_thread_pool; /*! Vectors which allow us to itterate over only single threader or only multithreaded tasks. */ std::vector<RenderTaskHandle> m_multi_threaded_tasks; std::vector<RenderTaskHandle> m_single_threaded_tasks; /*! Holds the textures that can be written to memory. */ CPUTextures m_output_cpu_textures; /*! Task function pointers. */ std::vector<setup_func_t> m_setup_funcs; std::vector<execute_func_t> m_execute_funcs; std::vector<destroy_func_t> m_destroy_funcs; /*! Task target and command list. */ std::vector<CommandList*> m_cmd_lists; std::vector<RenderTarget*> m_render_targets; /*! Task data and the type information of the original data structure. */ std::vector<std::shared_ptr<void>> m_data; std::vector<std::reference_wrapper<const std::type_info>> m_data_type_info; /*! Task settings that can be passed to the frame graph from outside the task. */ std::vector<std::optional<std::any>> m_settings; /*! Defines whether a task should execute or not. */ std::vector<bool> m_should_execute; /*! Used to queue a request to change the should execute value */ std::queue<std::pair<RenderTaskHandle, bool>> m_should_execute_change_request; /*! Descriptions of the tasks. */ #ifndef FG_MAX_PERFORMANCE /*! Stored the dependencies of a task. */ std::vector<std::vector<std::reference_wrapper<const std::type_info>>> m_dependencies; /*! The names of the render targets meant for debugging */ std::vector<std::wstring> m_names; #endif std::vector<RenderTaskType> m_types; std::vector<std::optional<RenderTargetProperties>> m_rt_properties; std::vector<std::future<void>> m_futures; const std::uint64_t m_uid; static inline std::uint64_t m_largest_uid = 0; static inline std::stack<std::uint64_t> m_free_uids = {}; }; } /* wr */
31.464387
204
0.696125
LaisoEmilio