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
152a2f6f5098907a377a999bbe11ec8076d0c120
7,381
cpp
C++
bindings/python/algorithm/expose-frames.cpp
andreadelprete/pinocchio
6fa1c7d5502629ee126f84f1a05471815fba30f4
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
bindings/python/algorithm/expose-frames.cpp
andreadelprete/pinocchio
6fa1c7d5502629ee126f84f1a05471815fba30f4
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
bindings/python/algorithm/expose-frames.cpp
andreadelprete/pinocchio
6fa1c7d5502629ee126f84f1a05471815fba30f4
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// // Copyright (c) 2015-2019 CNRS INRIA // #include "pinocchio/bindings/python/algorithm/algorithms.hpp" #include "pinocchio/algorithm/frames.hpp" namespace pinocchio { namespace python { static Data::Matrix6x get_frame_jacobian_proxy(const Model & model, Data & data, const Model::FrameIndex frame_id, ReferenceFrame rf) { Data::Matrix6x J(6,model.nv); J.setZero(); getFrameJacobian(model, data, frame_id, rf, J); return J; } static Data::Matrix6x compute_frame_jacobian_proxy(const Model & model, Data & data, const Eigen::VectorXd & q, const Model::FrameIndex frame_id) { Data::Matrix6x J(6,model.nv); J.setZero(); computeFrameJacobian(model, data, q, frame_id, J); return J; } static Data::Matrix6x get_frame_jacobian_time_variation_proxy(const Model & model, Data & data, Model::FrameIndex jointId, ReferenceFrame rf) { Data::Matrix6x dJ(6,model.nv); dJ.setZero(); getFrameJacobianTimeVariation(model,data,jointId,rf,dJ); return dJ; } static Data::Matrix6x frame_jacobian_time_variation_proxy(const Model & model, Data & data, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const Model::FrameIndex frame_id, const ReferenceFrame rf) { computeJointJacobiansTimeVariation(model,data,q,v); updateFramePlacements(model,data); return get_frame_jacobian_time_variation_proxy(model, data, frame_id, rf); } void exposeFramesAlgo() { using namespace Eigen; bp::def("updateFramePlacements", &updateFramePlacements<double,0,JointCollectionDefaultTpl>, bp::args("Model","Data"), "Computes the placements of all the operational frames according to the current joint placement stored in data" "and puts the results in data."); bp::def("updateFramePlacement", &updateFramePlacement<double,0,JointCollectionDefaultTpl>, bp::args("Model","Data","Operational frame ID (int)"), "Computes the placement of the given operational frames according to the current joint placement stored in data," "puts the results in data and returns it.", bp::return_value_policy<bp::return_by_value>()); bp::def("getFrameVelocity", &getFrameVelocity<double,0,JointCollectionDefaultTpl>, bp::args("Model","Data","Operational frame ID (int)"), "Returns the spatial velocity of the frame expressed in the LOCAL frame coordinate system." "Fist or second order forwardKinematics should be called first."); bp::def("getFrameAcceleration", &getFrameAcceleration<double,0,JointCollectionDefaultTpl>, bp::args("Model","Data","Operational frame ID (int)"), "Returns the spatial velocity of the frame expressed in the LOCAL frame coordinate system." "Second order forwardKinematics should be called first."); bp::def("framesForwardKinematics", &framesForwardKinematics<double,0,JointCollectionDefaultTpl,VectorXd>, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Update first the placement of the joints according to the given configuration value." "And computes the placements of all the operational frames" "and put the results in data."); bp::def("computeFrameJacobian", &compute_frame_jacobian_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Operational frame ID (int)"), "Computes the Jacobian of the frame given by its ID." "The columns of the Jacobian are expressed in the frame coordinates.\n" "In other words, the velocity of the frame vF expressed in the local coordinate is given by J*v," "where v is the time derivative of the configuration q."); bp::def("getFrameJacobian", &get_frame_jacobian_proxy, bp::args("Model","Data", "Operational frame ID (int)", "Reference frame rf (either ReferenceFrame.LOCAL or ReferenceFrame.WORLD)"), "Computes the Jacobian of the frame given by its ID either in the local or the world frames." "The columns of the Jacobian are expressed in the frame coordinates.\n" "In other words, the velocity of the frame vF expressed in the local coordinate is given by J*v," "where v is the time derivative of the configuration q.\n" "Be aware that computeJointJacobians and framesKinematics must have been called first."); bp::def("frameJacobianTimeVariation",&frame_jacobian_time_variation_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Joint velocity v (size Model::nv)", "Operational frame ID (int)", "Reference frame rf (either ReferenceFrame.LOCAL or ReferenceFrame.WORLD)"), "Computes the Jacobian Time Variation of the frame given by its ID either in the local or the world frames." "The columns of the Jacobian time variation are expressed in the frame coordinates.\n" "In other words, the velocity of the frame vF expressed in the local coordinate is given by J*v," "where v is the time derivative of the configuration q."); bp::def("getFrameJacobianTimeVariation",get_frame_jacobian_time_variation_proxy, bp::args("Model, the model of the kinematic tree", "Data, the data associated to the model where the results are stored", "Frame ID, the index of the frame.", "Reference frame rf (either ReferenceFrame.LOCAL or ReferenceFrame.WORLD)"), "Returns the Jacobian time variation of a specific frame (specified by Frame ID) expressed either in the world or the local frame." "You have to call computeJointJacobiansTimeVariation and framesKinematics first." "If rf is set to LOCAL, it returns the jacobian time variation associated to the frame index. Otherwise, it returns the jacobian time variation of the frame coinciding with the world frame."); } } // namespace python } // namespace pinocchio
51.978873
206
0.568216
andreadelprete
152e47ae503ee7a4db2b74ea2ca8f9b9841c1e68
1,385
cpp
C++
quiz8/quiz8/quiz8.cpp
keithwj1/FoothillCS2C
88da66fb5f3ab65a62a1fcd29c10816c7134766a
[ "MIT" ]
null
null
null
quiz8/quiz8/quiz8.cpp
keithwj1/FoothillCS2C
88da66fb5f3ab65a62a1fcd29c10816c7134766a
[ "MIT" ]
null
null
null
quiz8/quiz8/quiz8.cpp
keithwj1/FoothillCS2C
88da66fb5f3ab65a62a1fcd29c10816c7134766a
[ "MIT" ]
null
null
null
// quiz8.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <vector> #include <string> #include <algorithm> template<typename T> void insert_sort(std::vector<T> &input) { T key; for (size_t i = 1; i < input.size(); ++i) { key = input[i]; int j = i - 1; for (j; j >= 0 && input[j] > key;--j) { input[j + 1] = input[j]; } input[j + 1] = key; } } template<typename T> void swap(T* x, T* y){ T temp = *x; *x = *y; *y = temp; } template<typename T> void bubble_sort(std::vector<T> &input) { int size = input.size(); for (int i = 0; i < size - 1; ++i) { for (int j = 0; j < size - i - 1; ++j) { if (input[j] > input[j + 1]) { swap(&input[j], &input[j + 1]); } } } } template<typename T> void question3(std::vector<T> & input) { //std::sort(input.begin(), input.end()); bubble_sort(input); } template<typename T> void question4(std::vector<T>& input) { //std::sort(input.begin(), input.end()); insert_sort(input); } int main() { std::vector<std::string> input = { "b","a","f","l","k","n","z","x","y" }; question3(input); //question4(input); for (auto& elem : input) { std::cout << elem << ", "; } std::cout << std::endl; }
20.671642
95
0.509025
keithwj1
153000080fece1679922225f16fd384deec78e6a
517
cpp
C++
cpp/create-vector-cpp.cpp
dereckdemezquita/cs-Rcpp
1f991adb52a56cc4ca672bffe150b00391b27a13
[ "MIT" ]
null
null
null
cpp/create-vector-cpp.cpp
dereckdemezquita/cs-Rcpp
1f991adb52a56cc4ca672bffe150b00391b27a13
[ "MIT" ]
null
null
null
cpp/create-vector-cpp.cpp
dereckdemezquita/cs-Rcpp
1f991adb52a56cc4ca672bffe150b00391b27a13
[ "MIT" ]
null
null
null
#include <Rcpp.h> using namespace Rcpp; // Set the return type to IntegerVector // [[Rcpp::export]] IntegerVector seq_cpp(int lo, int hi) { int n = hi - lo + 1; // Create a new integer vector, sequence, of size n IntegerVector sequence(n); for(int i = 0; i < n; i++) { // Set the ith element of sequence to lo plus i sequence[i] = lo + i; } return sequence; } /*** R lo <- -2 hi <- 5 seq_cpp(lo, hi) # Does it give the same answer as R's seq() function? identical(seq_cpp(lo, hi), seq(lo, hi)) */
19.148148
53
0.628627
dereckdemezquita
1537c063394968c81630ec46431e7e291cc24945
1,812
cpp
C++
ValleyThief/ValleyThiefGameModeBase.cpp
ShanuPatel/Project_ValleyThief
b101148cb926cbbcc1ca74f84f1dd4e35b9e7352
[ "MIT" ]
null
null
null
ValleyThief/ValleyThiefGameModeBase.cpp
ShanuPatel/Project_ValleyThief
b101148cb926cbbcc1ca74f84f1dd4e35b9e7352
[ "MIT" ]
null
null
null
ValleyThief/ValleyThiefGameModeBase.cpp
ShanuPatel/Project_ValleyThief
b101148cb926cbbcc1ca74f84f1dd4e35b9e7352
[ "MIT" ]
1
2021-03-13T07:42:16.000Z
2021-03-13T07:42:16.000Z
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "ValleyThiefGameModeBase.h" #include "ValleyThief/ValleyThief.h" #include "ValleyThief/Public/BaseHUD.h" #include "ValleyThief/Private/MyCharacter.h" #include "UObject/ConstructorHelpers.h" #include "Kismet/GameplayStatics.h" #include "Engine.h" void AValleyThiefGameModeBase::StartPlay() { { Super::StartPlay(); if (GEngine) { UGameplayStatics::PlaySound2D(this, PlayWind,3.0); //GEngine->AddOnScreenDebugMessage(-1, 5.0, FColor::Purple, TEXT("Test message Sample")); } } } AValleyThiefGameModeBase::AValleyThiefGameModeBase() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnClassFinder(TEXT("/Game/Character/Blueprints/BP_MyCharacter")); DefaultPawnClass = PlayerPawnClassFinder.Class; // use our custom HUD class HUDClass = ABaseHUD::StaticClass(); } void AValleyThiefGameModeBase::CompleteMission(APawn* InstigatorPawn, bool bIsMissionComplete) { if (InstigatorPawn) { InstigatorPawn->DisableInput(nullptr); if (SpectatingCameraClass) { TArray<AActor*> ListAllActor; UGameplayStatics::GetAllActorsOfClass(this, SpectatingCameraClass, ListAllActor); if (ListAllActor.Num() > 0) { AActor* NewCameraView = ListAllActor[0]; APlayerController* PC = Cast<APlayerController>(InstigatorPawn->GetController()); if (PC) { PC->SetViewTargetWithBlend(NewCameraView, 1.5f, EViewTargetBlendFunction::VTBlend_Cubic); PC->bShowMouseCursor =true; PC->bEnableClickEvents = true; PC->bEnableMouseOverEvents = true; } } } else { UE_LOG(LogTemp, Log, TEXT("Not Spectating because is nullptr, and the pawn player is not valid")) } } OnMissionComplete(InstigatorPawn, bIsMissionComplete); }
28.761905
121
0.747792
ShanuPatel
15397c6f2497c134d69d67c14f95e99afcb2224a
630
cpp
C++
Codeforces/1230A - Dawid and Bags of Candies.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1230A - Dawid and Bags of Candies.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1230A - Dawid and Bags of Candies.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; vector<int> coins(4); int func( int pos, int left ) { if ( left == 0 ) return 1; if ( pos > 3 ) return 0; int p = 0, q = 0; if ( left - coins[pos] >= 0 ) p = func( pos + 1, left - coins[pos] ) ; q = func( pos + 1, left ) ; return p | q; } int main() { int s = 0; for (int i = 0; i < 4; ++i) { cin >> coins[i]; s += coins[i]; } if ( s % 2 != 0 ) cout << "NO" << endl; else { if ( func(0, s / 2) ) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
19.090909
52
0.434921
naimulcsx
153a0b8bf8f6d926b2b29f10b8c26db63dd07fa4
1,544
hxx
C++
include/opengm/inference/cgc/visitors.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
include/opengm/inference/cgc/visitors.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
include/opengm/inference/cgc/visitors.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#ifndef OPENGM_CGC_VISITORS #define OPENGM_CGC_VISITORS #include <opengm/opengm.hxx> template<class CGC> class CgcStateVisitor{ public: typedef CGC InfType; typedef typename InfType::AccumulationType AccumulationType; typedef typename InfType::GraphicalModelType GraphicalModelType; OPENGM_GM_TYPE_TYPEDEFS; CgcStateVisitor( const GraphicalModelType & gm, std::list< std::vector<typename GraphicalModelType::LabelType> >& l, const size_t visitNth=10,const size_t skipN=10 ) : gm_(gm), visitNth_(visitNth), visitNr_(0), skipN_(skipN), l_(l) { OPENGM_CHECK_OP(visitNth,>=,1," "); } void begin(InfType & inf ,const ValueType val,const ValueType bound){ } void end(InfType & inf ,const ValueType val,const ValueType bound){ } void operator()(InfType & inf ,const ValueType val,const ValueType bound){ const bool inRecursive2Coloring = inf.inRecursive2Coloring(); const bool inGreedy2Coloring = inf.inRecursive2Coloring(); if(visitNr_>=skipN_ && ( (visitNr_-skipN_)==0 || (visitNr_-skipN_) % visitNth_==0) ){ // get arg inf.arg(argBuffer_); l_.push_back(argBuffer_); } else { throw std::runtime_error("no!"); } ++visitNr_; } private: GraphicalModelType gm_; size_t visitNth_; size_t visitNr_; size_t skipN_; std::vector<LabelType> argBuffer_; std::list< std::vector<LabelType> >& l_; }; #endif // OPENGM_CGC_VISITORS
24.903226
92
0.656736
jasjuang
153b57bd965a1b0b01e30e6674588b71d64d7eaf
687
hpp
C++
Kuplung/kuplung/ui/components/materialeditor/MENode_Color.hpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
14
2017-02-17T17:12:40.000Z
2021-12-22T01:55:06.000Z
Kuplung/kuplung/ui/components/materialeditor/MENode_Color.hpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
null
null
null
Kuplung/kuplung/ui/components/materialeditor/MENode_Color.hpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
1
2019-10-15T08:10:10.000Z
2019-10-15T08:10:10.000Z
// // MENode_Color.hpp // Kuplung // // Created by Sergey Petrov on 11/17/15. // Copyright © 2015 supudo.net. All rights reserved. // #ifndef MENode_Color_hpp #define MENode_Color_hpp #include "kuplung/utilities/imgui/imgui.h" #include "kuplung/ui/components/materialeditor/MENode.hpp" class MENode_Color: public MENode { public: MENode_Color(int id, std::string const& name, const ImVec2& pos, float value, const ImVec4& color, int inputs_count, int outputs_count, std::string const& textureFilename="", std::string const& textureImage=""); virtual void draw(ImVec2 node_rect_min, ImVec2 NODE_WINDOW_PADDING, bool showPreview, float scale); }; #endif /* MENode_Color_hpp */
31.227273
213
0.754003
supudo
153cf2cf8794c16def9446b257a390ddc32d6e3e
666
cpp
C++
src/euler_dot_cpp/problems/50_59/problem_51.cpp
GediminasMasaitis/euler-dot-cpp
d127f5443e339eb57e1ac568df050c983b83d6df
[ "MIT" ]
1
2018-05-04T22:03:16.000Z
2018-05-04T22:03:16.000Z
src/euler_dot_cpp/problems/50_59/problem_51.cpp
GediminasMasaitis/euler-dot-cpp
d127f5443e339eb57e1ac568df050c983b83d6df
[ "MIT" ]
null
null
null
src/euler_dot_cpp/problems/50_59/problem_51.cpp
GediminasMasaitis/euler-dot-cpp
d127f5443e339eb57e1ac568df050c983b83d6df
[ "MIT" ]
null
null
null
#include "stdafx.hpp" #include "problem_51.hpp" using namespace std; int64_t impl_51_1::solve() { for(auto total_dig_cnt = 2; total_dig_cnt <= 5; ++total_dig_cnt) { const auto repl_dig_cnt = total_dig_cnt - 1; const auto mask_lim = 1 << repl_dig_cnt; for(auto mask = 1; mask < mask_lim; ++mask) { auto base_mul = 0; auto round_mul = 10; for(auto mask2 = mask; mask2 != 0; mask2 >>= 1) { if(mask2 & 1) { base_mul += round_mul; } round_mul *= 10; } } } return 0LL; }
24.666667
68
0.474474
GediminasMasaitis
15411a7145de56f30fe63858374792ed6c8063b2
1,439
cpp
C++
src/QormDatabaseSettings.cpp
marcobusemann/QMetaOrm
3d133f0e7f9a42cf9abb5dcb9ff79d85f83729b4
[ "MIT" ]
null
null
null
src/QormDatabaseSettings.cpp
marcobusemann/QMetaOrm
3d133f0e7f9a42cf9abb5dcb9ff79d85f83729b4
[ "MIT" ]
1
2017-07-29T21:22:10.000Z
2017-07-29T21:22:10.000Z
src/QormDatabaseSettings.cpp
marcobusemann/QMetaOrm
3d133f0e7f9a42cf9abb5dcb9ff79d85f83729b4
[ "MIT" ]
null
null
null
#include <QMetaOrm/QormDatabaseSettings.h> #include <QSqlDatabase> const QString& QormDatabaseSettings::getDatabaseName() const { return databaseName; } void QormDatabaseSettings::setDatabaseName(const QString& databaseName) { this->databaseName = databaseName; } const QString& QormDatabaseSettings::getHostName() const { return hostName; } void QormDatabaseSettings::setHostName(const QString& hostName) { this->hostName = hostName; } int QormDatabaseSettings::getPort() const { return port; } void QormDatabaseSettings::setPort(int port) { this->port = port; } const QString& QormDatabaseSettings::getUserName() const { return userName; } void QormDatabaseSettings::setUserName(const QString& userName) { this->userName = userName; } const QString& QormDatabaseSettings::getPassword() const { return password; } void QormDatabaseSettings::setPassword(const QString& password) { this->password = password; } void QormDatabaseSettings::applyTo(QSqlDatabase* database) const { if (!hostName.isEmpty()) database->setHostName(hostName); if (port>0) database->setPort(port); if (!databaseName.isEmpty()) database->setDatabaseName(databaseName); if (!userName.isEmpty()) database->setUserName(userName); if (!password.isEmpty()) database->setPassword(password); } QormDatabaseSettings::QormDatabaseSettings() :port(0) { }
18.934211
71
0.720639
marcobusemann
15430a36080b9ffff19a3dafb1f44d6a8de7d65b
1,002
cpp
C++
src/PopUpMenu.cpp
geovens/TransWinove
a6bd77e9b7f8aae55f19b5dfda5e88e9119751c3
[ "MIT" ]
null
null
null
src/PopUpMenu.cpp
geovens/TransWinove
a6bd77e9b7f8aae55f19b5dfda5e88e9119751c3
[ "MIT" ]
1
2017-06-26T04:11:43.000Z
2018-03-09T11:39:56.000Z
src/PopUpMenu.cpp
geovens/TransWinove
a6bd77e9b7f8aae55f19b5dfda5e88e9119751c3
[ "MIT" ]
null
null
null
#include "TransApp.h" #include "PopUpMenu.h" BEGIN_EVENT_TABLE(PopUpMenu, wxMenu) EVT_MENU(1, PopUpMenu::OnMenu) EVT_MENU(2, PopUpMenu::OnMenu) EVT_MENU(3, PopUpMenu::OnMenu) END_EVENT_TABLE() PopUpMenu::PopUpMenu(TransApp *owner) : wxMenu() { Owner = owner; ItemGhost = AppendCheckItem(2, L"Ghost Mode", L"Set the selected window invisible to mouse."); ItemPin = AppendCheckItem(3, L"Pin Mode", L"set the selected window always on top."); Append(1, L"Exit", L"Quit TransWinove."); if (Owner->IfNoHit) { ItemGhost->Check(true); ItemPin->Check(false); } else { ItemGhost->Check(false); ItemPin->Check(true); } } void PopUpMenu::OnMenu(wxCommandEvent &event) { if (event.GetId() == 3) { Owner->IfNoHit = false; ItemGhost->Check(false); ItemPin->Check(true); } else if (event.GetId() == 2) { Owner->IfNoHit = true; ItemGhost->Check(true); ItemPin->Check(false); } else if (event.GetId() == 1) Owner->Quit(); }
20.875
96
0.645709
geovens
154649841934c6afb3b2153244a2ed524324b9ec
2,699
cpp
C++
ut/source/framework.cpp
dicroce/pri_q
b76db4a67a7fbebcc73a5a76663e1d44ff9d911e
[ "BSD-2-Clause" ]
12
2015-03-27T21:29:02.000Z
2016-11-26T23:43:52.000Z
ut/source/framework.cpp
dicroce/pri_q
b76db4a67a7fbebcc73a5a76663e1d44ff9d911e
[ "BSD-2-Clause" ]
1
2017-01-18T00:32:12.000Z
2017-01-18T00:32:12.000Z
ut/source/framework.cpp
dicroce/pri_q
b76db4a67a7fbebcc73a5a76663e1d44ff9d911e
[ "BSD-2-Clause" ]
6
2015-02-08T13:10:27.000Z
2017-01-18T00:24:47.000Z
#include "framework.h" #include <algorithm> #include <time.h> #include <stdarg.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> using namespace std; vector<shared_ptr<test_fixture>> _test_fixtures; void rtf_usleep(unsigned int usec) { usleep(usec); } string rtf_format(const char* fmt, ...) { va_list args; va_start(args, fmt); const string result = rtf_format(fmt, args); va_end(args); return result; } string rtf_format(const char* fmt, va_list& args) { va_list newargs; va_copy(newargs, args); const int chars_written = vsnprintf(nullptr, 0, fmt, newargs); const int len = chars_written + 1; vector<char> str(len); va_copy(newargs, args); vsnprintf(&str[0], len, fmt, newargs); string formatted(&str[0]); return formatted; } // This is a globally (across test) incrementing counter so that tests can avoid having hardcoded port // numbers but can avoid stepping on eachothers ports. int _next_port = 5000; int rtf_next_port() { int ret = _next_port; _next_port++; return ret; } std::string rtf_os_scratch_dir() { #if defined(IS_IOS) return string("tmp/"); #else return string("./"); #endif } void handle_terminate() { printf( "\nuncaught exception terminate handler called!\n" ); fflush(stdout); std::exception_ptr p = std::current_exception(); if( p ) { try { std::rethrow_exception( p ); } catch(std::exception& ex) { printf("%s\n",ex.what()); fflush(stdout); } catch(...) { printf("caught an unknown exception in custom terminate handler.\n"); } } } int main( int argc, char* argv[] ) { set_terminate( handle_terminate ); std::vector<std::string> args; for(int i = 1; i < argc; ++i) args.push_back(argv[i]); bool dontWaitOnFail = (std::find(args.begin(), args.end(), "--dont-wait-on-fail") != args.end()); bool forceWait = (std::find(args.begin(), args.end(), "--force-wait") != args.end()); std::string fixture_name; for(auto arg : args) if(arg.find("--") == string::npos) fixture_name = arg; srand( time(0) ); bool something_failed = false; for(auto& tf : _test_fixtures) { if( !fixture_name.empty() ) if(tf->get_name() != fixture_name ) continue; tf->run_tests(); if( tf->something_failed() ) { something_failed = true; tf->print_failures(); } } if( !something_failed ) printf("\nSuccess.\n"); else printf("\nFailure.\n"); return 0; }
20.603053
102
0.589107
dicroce
154bc2a36f75662e690811dad9eadcf050f9f657
568
cpp
C++
API/GameEngineContents/FadeIn.cpp
jooseeun/APIportforlio
da9253f2b8dd6392c1c59511985102e8f42dc041
[ "MIT" ]
null
null
null
API/GameEngineContents/FadeIn.cpp
jooseeun/APIportforlio
da9253f2b8dd6392c1c59511985102e8f42dc041
[ "MIT" ]
null
null
null
API/GameEngineContents/FadeIn.cpp
jooseeun/APIportforlio
da9253f2b8dd6392c1c59511985102e8f42dc041
[ "MIT" ]
null
null
null
#include "FadeIn.h" #include "ContentsEnums.h" #include <GameEngine/GameEngineRenderer.h> #include <GameEngineBase/GameEngineTime.h> FadeIn::FadeIn() :IsFadeIn(false), Alpha_(255) { } FadeIn::~FadeIn() { } void FadeIn::Start() { SetPosition({ 640,360 }); Renderer_ = CreateRenderer("FadeIn.bmp"); Renderer_->SetAlpha(Alpha_); Renderer_->CameraEffectOff(); StartfadeIn(); } void FadeIn::Update() { if (IsFadeIn == true) { if (Alpha_ <= 0) { Death(); } Alpha_ -= (80.0f * GameEngineTime::GetDeltaTime()); Renderer_->SetAlpha(Alpha_); } }
14.564103
53
0.665493
jooseeun
154d5fa6080b15e9f093a58b9bba13c400e9a95e
7,039
cpp
C++
examples/Graphics/image/main.cpp
Zethes/CGUL
863d15303227cb31e970374ada219ed7b561e243
[ "BSD-2-Clause" ]
8
2015-05-06T17:48:12.000Z
2021-05-26T15:52:05.000Z
examples/Graphics/image/main.cpp
Zethes/CGUL
863d15303227cb31e970374ada219ed7b561e243
[ "BSD-2-Clause" ]
null
null
null
examples/Graphics/image/main.cpp
Zethes/CGUL
863d15303227cb31e970374ada219ed7b561e243
[ "BSD-2-Clause" ]
3
2016-04-03T09:17:25.000Z
2019-04-02T01:41:13.000Z
#include <CGUL.hpp> using namespace CGUL; #include <GL/glew.h> #include <iostream> UIntN LoadShader(const String& vertexFile, const String& fragmentFile) { // Create the shaders UIntN vertexShader, fragmentShader; vertexShader = GL::CreateShader(GL_VERTEX_SHADER); fragmentShader = GL::CreateShader(GL_FRAGMENT_SHADER); // Load the contents of the files String vertexSource, fragmentSource; File::ReadText(vertexFile, &vertexSource); File::ReadText(fragmentFile, &fragmentSource); // Set the shader sources GL::ShaderSource(vertexShader, vertexSource); GL::ShaderSource(fragmentShader, fragmentSource); // Compile the shaders GL::CompileShader(vertexShader); GL::CompileShader(fragmentShader); // Check if shaders compiled SIntN status; GL::GetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { String log; GL::GetShaderInfoLog(vertexShader, &log); throw FatalException(U8("Failed to compile shader:\n") + log); } GL::GetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { String log; GL::GetShaderInfoLog(fragmentShader, &log); throw FatalException(U8("Failed to compile shader:\n") + log); } // Create the program UIntN program = GL::CreateProgram(); // Setup the attributes GL::BindAttribLocation(program, GL::POSITION1, "vertPosition"); GL::BindAttribLocation(program, GL::TEXCOORD1, "vertTexCoord"); // Link the program GL::AttachShader(program, vertexShader); GL::AttachShader(program, fragmentShader); GL::LinkProgram(program); GL::GetProgramiv(program, GL_LINK_STATUS, &status); if (status != GL_TRUE) { String log; GL::GetProgramInfoLog(program, &log); throw FatalException(U8("Failed to link program:\n") + log); } GL::ValidateProgram(program); GL::GetProgramiv(program, GL_VALIDATE_STATUS, &status); if (status != GL_TRUE) { String log; GL::GetProgramInfoLog(program, &log); throw FatalException(U8("Failed to validate program:\n") + log); } return program; } UIntN MakeBox() { // Setup the buffer data Vector2F boxPositions[] = { Vector2F(0, 0), Vector2F(0, 1), Vector2F(1, 1), Vector2F(1, 0) }; Vector2F boxTexCoords[] = { Vector2F(0, 0), Vector2F(0, 1), Vector2F(1, 1), Vector2F(1, 0) }; // Create the vertex array object UIntN vertexArray; GL::GenVertexArrays(1, &vertexArray); GL::BindVertexArray(vertexArray); // Setup the position buffer and attach it to the vertex array UIntN buffer1; GL::GenBuffers(1, &buffer1); GL::BindBuffer(GL_ARRAY_BUFFER, buffer1); GL::BufferData(GL_ARRAY_BUFFER, 4 * sizeof(Vector2F), boxPositions, GL_STATIC_DRAW); GL::VertexAttribPointer(GL::POSITION1, 2, GL_FLOAT, false, 0, 0); GL::EnableVertexAttribArray(GL::POSITION1); // Setup the texcoord buffer and attach it to the vertex array UIntN buffer2; GL::GenBuffers(1, &buffer2); GL::BindBuffer(GL_ARRAY_BUFFER, buffer2); GL::BufferData(GL_ARRAY_BUFFER, 4 * sizeof(Vector2F), boxTexCoords, GL_STATIC_DRAW); GL::VertexAttribPointer(GL::TEXCOORD1, 2, GL_FLOAT, false, 0, 0); GL::EnableVertexAttribArray(GL::TEXCOORD1); // All done GL::BindVertexArray(0); return vertexArray; } int main() { try { std::cout << "Suported image file formats: " << std::endl; CGUL::Vector<ImageLoader*> loaders; CGUL::ImageHandler::GetInstance()->GetAllLoaders(&loaders); for (UInt32 i = 0; i < loaders.size(); i++) { std::cout << (i+1) << ". " << loaders[i]->GetName() << " (" << loaders[i]->GetExtension() << ")" << std::endl; } String fileName = "resources/logo.png"; Image* image = new Image(); if (!image->CanLoad(fileName)) { throw FatalException("Cannot load image."); } image->Load(fileName); std::cout << "Successfully loaded." << std::endl; //image->Save("out.png", "png"); //std::cout << "Successfully saved." << std::endl; image = Image::GetGrayscale(image); WindowStyle style; style.title = fileName + U8(" (") + image->GetWidth() + U8(", ") + image->GetHeight() + U8(")"); style.size = UCoord32(image->GetWidth(), image->GetHeight()); style.backgroundColor = Colors::black; style.resizable = false; Window window; window.Create(style); OpenGL::Context context; context.Create(&window); GL::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GL::Enable(GL_BLEND); GL::Enable(GL_ALPHA_TEST); GL::Enable(GL_TEXTURE_2D); UIntN program = LoadShader(U8("resources/shader.vert"), U8("resources/shader.frag")); UIntN box = MakeBox(); UIntN texture; GL::GenTextures(1, &texture); GL::BindTexture(GL_TEXTURE_2D, texture); GL::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); GL::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); GL::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); GL::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GL::TexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); GL::PixelStorei(GL_UNPACK_ALIGNMENT, 1); ImageFormat format = image->GetFormat(); GL::TexImage2D(GL_TEXTURE_2D, 0, format.glFormat, image->GetWidth(), image->GetHeight(), 0, format.glFormat, GL_UNSIGNED_BYTE, image->GetData<void>()); GL::BindTexture(GL_TEXTURE_2D, 0); Timer timer; Float32 hue = 0.0f; while (window.IsOpen()) { Timer::Sleep(1); hue = Math::Mod<Float64>(hue + timer.GetDeltaTime() * 45.0f, 360.0f); context.ClearColor(Color::MakeHSL(hue, 0.4f, 0.5f)); context.Viewport(0, 0, window.GetWidth(), window.GetHeight()); context.Clear(GL::COLOR_BUFFER_BIT | GL::DEPTH_BUFFER_BIT); GL::UseProgram(program); GL::UniformMatrix4fv(GL::GetUniformLocation(program, "orthoMatrix"), 1, false, MatrixF::MakeOrtho2D(0, 1, 1, 0).GetData()); GL::UniformMatrix4fv(GL::GetUniformLocation(program, "modelMatrix"), 1, false, MatrixF::MakeIdentity().GetData()); GL::Uniform1i(GL::GetUniformLocation(program, "texture"), 0); GL::ActiveTexture(GL_TEXTURE0); GL::BindTexture(GL_TEXTURE_2D, texture); GL::BindVertexArray(box); GL::DrawArrays(GL_QUADS, 0, 4); GL::BindVertexArray(0); GL::UseProgram(0); context.SwapBuffers(); Window::Update(); } } catch (Exception& e) { std::cout << e.what() << std::endl; std::cout << std::hex << "Error code: 0x" << e.unique << std::dec << " (decimal " << e.unique << ")" << std::endl; } }
35.550505
159
0.627504
Zethes
15572f1adab7415badb5b3a2e6b67bba39809521
466
cc
C++
examples/example_adaptor.cc
alibenD/design_pattern
1e40d3890145e7fa9385b72da9c1d50203db3346
[ "MIT" ]
null
null
null
examples/example_adaptor.cc
alibenD/design_pattern
1e40d3890145e7fa9385b72da9c1d50203db3346
[ "MIT" ]
null
null
null
examples/example_adaptor.cc
alibenD/design_pattern
1e40d3890145e7fa9385b72da9c1d50203db3346
[ "MIT" ]
null
null
null
/** * @Copyright (C) 2019 All rights reserved. * @date: 2019 * @file: example_adaptor.cc * @version: v0.0.1 * @author: aliben.develop@gmail.com * @create_date: 2019-08-06 18:50:49 * @last_modified_date: 2019-08-06 18:52:43 * @brief: TODO * @details: TODO */ //INCLUDE #include <design_pattern/adaptor.hh> //CODE int main() { IAdaptee* ptr_adaptee = new OldClass(); ITarget* ptr_target = new Adapter(ptr_adaptee); ptr_target->process(); }
20.26087
49
0.660944
alibenD
15592141d401bdde725d0b09e6b8a3a39e424ef1
9,129
cpp
C++
src/Tasks/OverwatchTaskService.cpp
cmcghan/OpenUxAS_old
7982e32432b36e7877fe27bd4024e61fe316a5ea
[ "NASA-1.3" ]
1
2018-03-18T13:41:59.000Z
2018-03-18T13:41:59.000Z
src/Tasks/OverwatchTaskService.cpp
cmcghan/OpenUxAS_old
7982e32432b36e7877fe27bd4024e61fe316a5ea
[ "NASA-1.3" ]
null
null
null
src/Tasks/OverwatchTaskService.cpp
cmcghan/OpenUxAS_old
7982e32432b36e7877fe27bd4024e61fe316a5ea
[ "NASA-1.3" ]
null
null
null
// =============================================================================== // Authors: AFRL/RQQA // Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division // // Copyright (c) 2017 Government of the United State of America, as represented by // the Secretary of the Air Force. No copyright is claimed in the United States under // Title 17, U.S. Code. All Other Rights Reserved. // =============================================================================== /* * File: Task_WatchTask.cpp * Author: steve * * Created on February 24, 2016, 6:17 PM */ #include "OverwatchTaskService.h" #include "Position.h" #include "UnitConversions.h" #include "avtas/lmcp/LmcpXMLReader.h" #include "afrl/cmasi/VehicleActionCommand.h" #include "afrl/cmasi/GimbalStareAction.h" #include "afrl/cmasi/LoiterAction.h" #include "uxas/messages/task/TaskImplementationResponse.h" #include "uxas/messages/task/TaskOption.h" #include "uxas/messages/route/RouteRequest.h" #include "uxas/messages/route/RouteResponse.h" #include "uxas/messages/route/RouteConstraints.h" #include "pugixml.hpp" #include "Constants/Convert.h" #include <sstream> //std::stringstream #include <iostream> // std::cout, cerr, etc #define STRING_XML_ENTITY_STATES "EntityStates" //TODO:: define this in some global place #define COUT_FILE_LINE_MSG(MESSAGE) std::cout << "CMPS-CMPS-CMPS-CMPS:: WatchTask:" << __FILE__ << ":" << __LINE__ << ":" << MESSAGE << std::endl;std::cout.flush(); #define CERR_FILE_LINE_MSG(MESSAGE) std::cerr << "CMPS-CMPS-CMPS-CMPS:: WatchTask:" << __FILE__ << ":" << __LINE__ << ":" << MESSAGE << std::endl;std::cerr.flush(); namespace uxas { namespace service { namespace task { OverwatchTaskService::ServiceBase::CreationRegistrar<OverwatchTaskService> OverwatchTaskService::s_registrar(OverwatchTaskService::s_registryServiceTypeNames()); OverwatchTaskService::OverwatchTaskService() : TaskServiceBase(OverwatchTaskService::s_typeName(), OverwatchTaskService::s_directoryName()) { }; OverwatchTaskService::~OverwatchTaskService() { }; bool OverwatchTaskService::configureTask(const pugi::xml_node& ndComponent) { std::string strBasePath = m_workDirectoryPath; std::stringstream sstrErrors; bool isSuccessful(true); if (isSuccessful) { if (afrl::impact::isWatchTask(m_task.get())) { m_watchTask = std::static_pointer_cast<afrl::impact::WatchTask>(m_task); if (!m_watchTask) { sstrErrors << "ERROR:: **OverwatchTaskService::bConfigure failed to cast a WatchTask from the task pointer." << std::endl; CERR_FILE_LINE_MSG(sstrErrors.str()) isSuccessful = false; } } else { sstrErrors << "ERROR:: **OverwatchTaskService::bConfigure failed: taskObject[" << m_task->getFullLmcpTypeName() << "] is not a WatchTask." << std::endl; CERR_FILE_LINE_MSG(sstrErrors.str()) isSuccessful = false; } } //isSuccessful if (isSuccessful) { pugi::xml_node entityStates = ndComponent.child(STRING_XML_ENTITY_STATES); if (entityStates) { for (auto ndEntityState = entityStates.first_child(); ndEntityState; ndEntityState = ndEntityState.next_sibling()) { std::shared_ptr<afrl::cmasi::EntityState> entityState; std::stringstream stringStream; ndEntityState.print(stringStream); avtas::lmcp::Object* object = avtas::lmcp::xml::readXML(stringStream.str()); if (object != nullptr) { entityState.reset(static_cast<afrl::cmasi::EntityState*> (object)); object = nullptr; if (entityState->getID() == m_watchTask->getWatchedEntityID()) { m_watchedEntityStateLast = entityState; break; } } } } } //if(isSuccessful) return (isSuccessful); } bool OverwatchTaskService::processReceivedLmcpMessageTask(std::shared_ptr<avtas::lmcp::Object>& receivedLmcpObject) //example: if (afrl::cmasi::isServiceStatus(receivedLmcpObject)) { auto entityState = std::dynamic_pointer_cast<afrl::cmasi::EntityState>(receivedLmcpObject); if (entityState) { if (entityState->getID() == m_watchTask->getWatchedEntityID()) { m_watchedEntityStateLast = entityState; } } return (false); // always false implies never terminating service from here }; void OverwatchTaskService::buildTaskPlanOptions() { bool isSuccessful{true}; int64_t optionId(1); int64_t taskId(m_watchTask->getTaskID()); if (isCalculateOption(taskId, optionId, m_watchTask->getEligibleEntities())) { optionId++; } std::string compositionString("+("); for (auto itOption = m_taskPlanOptions->getOptions().begin(); itOption != m_taskPlanOptions->getOptions().end(); itOption++) { compositionString += "p"; compositionString += std::to_string((*itOption)->getOptionID()); compositionString += " "; } compositionString += ")"; m_taskPlanOptions->setComposition(compositionString); // send out the options if (isSuccessful) { auto newResponse = std::static_pointer_cast<avtas::lmcp::Object>(m_taskPlanOptions); sendSharedLmcpObjectBroadcastMessage(newResponse); } }; bool OverwatchTaskService::isCalculateOption(const int64_t& taskId, int64_t& optionId, const std::vector<int64_t>& eligibleEntities) { bool isSuccessful{true}; if (m_watchedEntityStateLast) { auto taskOption = new uxas::messages::task::TaskOption; taskOption->setTaskID(taskId); taskOption->setOptionID(optionId); taskOption->getEligibleEntities() = eligibleEntities; taskOption->setStartLocation(m_watchedEntityStateLast->getLocation()->clone()); taskOption->setStartHeading(m_watchedEntityStateLast->getHeading()); taskOption->setEndLocation(m_watchedEntityStateLast->getLocation()->clone()); taskOption->setEndHeading(m_watchedEntityStateLast->getHeading()); auto pTaskOption = std::shared_ptr<uxas::messages::task::TaskOption>(taskOption->clone()); m_optionIdVsTaskOptionClass.insert(std::make_pair(optionId, std::make_shared<TaskOptionClass>(pTaskOption))); m_taskPlanOptions->getOptions().push_back(taskOption); taskOption = nullptr; //just gave up ownership } else { CERR_FILE_LINE_MSG("ERROR::Task_WatchTask:: no watchedEntityState found for Entity[" << m_watchTask->getWatchedEntityID() << "]") isSuccessful = false; } return (isSuccessful); } void OverwatchTaskService::activeEntityState(const std::shared_ptr<afrl::cmasi::EntityState>& entityState) { if (m_watchedEntityStateLast) { // point the camera at the search point auto vehicleActionCommand = std::make_shared<afrl::cmasi::VehicleActionCommand>(); //vehicleActionCommand->setCommandID(); vehicleActionCommand->setVehicleID(entityState->getID()); //vehicleActionCommand->setStatus(); auto gimbalStareAction = new afrl::cmasi::GimbalStareAction; gimbalStareAction->setStarepoint(m_watchedEntityStateLast->getLocation()->clone()); vehicleActionCommand->getVehicleActionList().push_back(gimbalStareAction); gimbalStareAction = nullptr; //gave up ownership // add the loiter auto loiterAction = new afrl::cmasi::LoiterAction(); loiterAction->setLocation(m_watchedEntityStateLast->getLocation()->clone()); if (m_idVsEntityConfiguration.find(entityState->getID()) != m_idVsEntityConfiguration.end()) { loiterAction->setAirspeed(m_idVsEntityConfiguration[entityState->getID()]->getNominalSpeed()); } else { CERR_FILE_LINE_MSG("ERROR::Task_WatchTask:: no EntityConfiguration found for Entity[" << entityState->getID() << "]") } loiterAction->setRadius(m_loiterRadius_m); loiterAction->setAxis(0.0); loiterAction->setDirection(afrl::cmasi::LoiterDirection::Clockwise); loiterAction->setDuration(-1.0); loiterAction->setLength(0.0); loiterAction->setLoiterType(afrl::cmasi::LoiterType::Circular); vehicleActionCommand->getVehicleActionList().push_back(loiterAction); loiterAction = nullptr; //gave up ownership // send out the response auto newMessage = std::static_pointer_cast<avtas::lmcp::Object>(vehicleActionCommand); sendSharedLmcpObjectBroadcastMessage(newMessage); } else { CERR_FILE_LINE_MSG("ERROR::Task_WatchTask:: no watchedEntityState found for Entity[" << m_watchTask->getWatchedEntityID() << "]") } } }; //namespace task }; //namespace service }; //namespace uxas
37.879668
164
0.655274
cmcghan
155b5001e12bf05a8245838b05853c663441929b
5,307
cpp
C++
src/OpenSpaceToolkit/Physics/Units/Mass.cpp
robinpdm/open-space-toolkit-physics
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
[ "Apache-2.0" ]
7
2020-03-30T11:51:11.000Z
2022-02-02T15:20:44.000Z
src/OpenSpaceToolkit/Physics/Units/Mass.cpp
robinpdm/open-space-toolkit-physics
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
[ "Apache-2.0" ]
24
2018-06-25T08:06:39.000Z
2020-01-05T20:34:02.000Z
src/OpenSpaceToolkit/Physics/Units/Mass.cpp
robinpdm/open-space-toolkit-physics
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
[ "Apache-2.0" ]
3
2020-03-05T18:18:38.000Z
2020-07-02T05:06:53.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Open Space Toolkit ▸ Physics /// @file OpenSpaceToolkit/Physics/Units/Mass.cpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <OpenSpaceToolkit/Physics/Units/Mass.hpp> #include <OpenSpaceToolkit/Core/Error.hpp> #include <OpenSpaceToolkit/Core/Utilities.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace ostk { namespace physics { namespace units { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Mass::Mass ( const Real& aValue, const Mass::Unit& aUnit ) : units::Unit(units::Unit::Type::Mass, aValue), unit_(aUnit) { } Mass* Mass::clone ( ) const { return new Mass(*this) ; } bool Mass::isDefined ( ) const { return units::Unit::isDefined() && (unit_ != Mass::Unit::Undefined) ; } Mass::Unit Mass::getUnit ( ) const { return unit_ ; } Real Mass::in ( const Mass::Unit& aUnit ) const { if (!this->isDefined()) { return Real::Undefined() ; } if (unit_ == aUnit) { return this->accessValue() ; } return this->accessValue() * Mass::SIRatio(unit_) / Mass::SIRatio(aUnit) ; } Real Mass::inKilograms ( ) const { return this->in(Mass::Unit::Kilogram) ; } String Mass::toString ( const Integer& aPrecision ) const { if (!this->isDefined()) { throw ostk::core::error::runtime::Undefined("Mass") ; } return this->accessValue().toString(aPrecision) + " [" + Mass::SymbolFromUnit(unit_) + "]" ; } Mass Mass::Undefined ( ) { return { Real::Undefined(), Mass::Unit::Undefined } ; } Mass Mass::Kilograms ( const Real& aValue ) { return { aValue, Mass::Unit::Kilogram } ; } // Mass Mass::Parse ( const String& aString ) // { // } String Mass::StringFromUnit ( const Mass::Unit& aUnit ) { switch (aUnit) { case Mass::Unit::Undefined: return "Undefined" ; case Mass::Unit::Kilogram: return "Kilogram" ; case Mass::Unit::Tonne: return "Tonne" ; case Mass::Unit::Pound: return "Pound" ; default: throw ostk::core::error::runtime::Wrong("Unit") ; break ; } return String::Empty() ; } String Mass::SymbolFromUnit ( const Mass::Unit& aUnit ) { switch (aUnit) { case Mass::Unit::Kilogram: return "kg" ; case Mass::Unit::Tonne: return "t" ; case Mass::Unit::Pound: return "lb" ; default: throw ostk::core::error::runtime::Wrong("Unit") ; break ; } return String::Empty() ; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Real Mass::SIRatio ( const Mass::Unit& aUnit ) { switch (aUnit) { case Mass::Unit::Kilogram: return 1.0 ; default: throw ostk::core::error::runtime::Wrong("Unit") ; break ; } return Real::Undefined() ; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
29.814607
167
0.299416
robinpdm
155c3b80d614d7baaf179efded369bfcef5e8cef
543
cpp
C++
source/aufgabe10.cpp
Vani4ka/programmiersprachen_aufgabenblatt3
b592dcf3da84c2a6e3ae060fa7beb1b11f94345e
[ "MIT" ]
null
null
null
source/aufgabe10.cpp
Vani4ka/programmiersprachen_aufgabenblatt3
b592dcf3da84c2a6e3ae060fa7beb1b11f94345e
[ "MIT" ]
null
null
null
source/aufgabe10.cpp
Vani4ka/programmiersprachen_aufgabenblatt3
b592dcf3da84c2a6e3ae060fa7beb1b11f94345e
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_RUNNER #include "catch.hpp" #include <cmath> #include <algorithm> #include <vector> TEST_CASE ("describe_vector_add", "[aufgabe10]") { std::vector<int> v1{1,2,3,4,5,6,7,8,9}; std::vector<int> v2{9,8,7,6,5,4,3,2,1}; // v(5) verändert: v3(9) std::vector<int> v3(9); std::transform(v1.begin(), v1.end(), v2.begin(),v3.begin(), [](int v1, int v2){return v1+v2;} ); REQUIRE(std::all_of(v3.begin(), v3.end(), [](int x){return x==10;})); } int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); }
23.608696
97
0.631676
Vani4ka
15637828c4bb50eb818dfe020df2f2ae702fedd6
1,733
cpp
C++
codeforcespractice.cpp
harsh6768-svg/competitive-practice
14e0d2e4563676756c0ee31acf339f6933428412
[ "MIT" ]
null
null
null
codeforcespractice.cpp
harsh6768-svg/competitive-practice
14e0d2e4563676756c0ee31acf339f6933428412
[ "MIT" ]
null
null
null
codeforcespractice.cpp
harsh6768-svg/competitive-practice
14e0d2e4563676756c0ee31acf339f6933428412
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ff first #define ss second #define int long long #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define mii map<int,int> #define pqb priority_queue<int> #define pqs priority_queue<int,vi,greater<int> > #define setbits(x) __builtin_popcountll(x) #define zrobits(x) __builtin_ctzll(x) #define mod 1000000007 #define inf LONG_LONG_MAX #define ps(x,y) fixed<<setprecision(y)<<x #define endl '\n' #define mk(arr,n,type) type *arr=new type[n] #define w(x) int x; cin >> x; while(x--) #define f(i,x,y) for(int i = x; i < y; i++) #define g(i,x,y) for(int i=x; i<=y ; i++) using namespace std; void c_p_p() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } /* ********************* Your Functions Below ********************** */ bool isperfectsquare(long double x) { if(x>=0) { long long sr=sqrt(x); return(sr*sr==x); } return false; } /* ********************* Your Functions Above ********************** */ int32_t main() { c_p_p(); #ifndef ONLINE_JUDGE // For getting input from input.txt file // For getting input from input.txt file freopen("input.exe", "r", stdin); // Printing the Output to output.txt file freopen("output.exe", "w", stdout); #endif int n,m; cin>>n>>m; int loc=1; int arr[m]; int ans=0; f(i,0,m) { cin>>arr[i]; if(arr[i]>=loc) ans+=arr[i]-loc; else ans+=n-(loc-arr[i]); loc=arr[i]; } cout<<ans<<endl; // your code goes here return 0; }
18.052083
71
0.530294
harsh6768-svg
d07f0e03c713905e231268b4084e2a32b7f47a37
162
cpp
C++
src/cpp/kcon/console.cpp
tibru/tibru
d262f0842213728715d282c65b718482e0a95a7e
[ "Apache-2.0" ]
97
2015-09-25T20:08:56.000Z
2022-01-03T20:01:10.000Z
src/cpp/kcon/console.cpp
tibru/tibru
d262f0842213728715d282c65b718482e0a95a7e
[ "Apache-2.0" ]
null
null
null
src/cpp/kcon/console.cpp
tibru/tibru
d262f0842213728715d282c65b718482e0a95a7e
[ "Apache-2.0" ]
6
2015-09-28T16:34:15.000Z
2021-02-02T04:24:07.000Z
#include "../elpa/console.tpp" #include "interpreter.h" #include "shell.h" using namespace kcon; using namespace elpa; template class Console<KConInterpreter>;
18
40
0.765432
tibru
d080f348b557b1380e70360fc6b3d934dc62da1a
2,666
hpp
C++
deadcell/pe/types.hpp
sdkabuser/DEADCELL-CSGO
dfcd31394c5348529b3c098640466db136b89e0c
[ "MIT" ]
506
2019-03-16T08:34:47.000Z
2022-03-29T14:08:59.000Z
deadcell/pe/types.hpp
sdkabuser/DEADCELL-CSGO
dfcd31394c5348529b3c098640466db136b89e0c
[ "MIT" ]
124
2019-03-17T02:54:57.000Z
2021-03-29T01:51:05.000Z
deadcell/pe/types.hpp
sdkabuser/DEADCELL-CSGO
dfcd31394c5348529b3c098640466db136b89e0c
[ "MIT" ]
219
2019-03-16T21:39:01.000Z
2022-03-30T08:59:24.000Z
#pragma once // note - dex; these are not complete structs, they only contain needed things for this project. // all of these structs are taken from x86-64 Windows 7 Home Premium ( Service Pack 1 ). namespace pe { namespace types { enum EXCEPTION_DISPOSITION : size_t { ExceptionContinueExecution = 0, ExceptionContinueSearch, ExceptionNestedException, ExceptionCollidedUnwind }; struct EXCEPTION_REGISTRATION_RECORD { EXCEPTION_REGISTRATION_RECORD *Next; EXCEPTION_DISPOSITION Handler; }; struct NT_TIB { EXCEPTION_REGISTRATION_RECORD *ExceptionList; uintptr_t StackBase; uintptr_t StackLimit; uintptr_t SubSystemTib; union { uintptr_t FiberData; uint32_t Version; }; uintptr_t ArbitraryUserPointer; NT_TIB *Self; }; struct CLIENT_ID { uintptr_t UniqueProcess; uintptr_t UniqueThread; }; struct LIST_ENTRY { LIST_ENTRY *Flink; LIST_ENTRY *Blink; }; struct PEB_LDR_DATA { uint32_t Length; uint8_t Initialized; uintptr_t SsHandle; LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; }; struct UNICODE_STRING { uint16_t Length; uint16_t MaximumLength; wchar_t *Buffer; }; struct ACTIVATION_CONTEXT { // todo - dex; no symbols for this? }; struct LDR_DATA_TABLE_ENTRY { LIST_ENTRY InLoadOrderLinks; LIST_ENTRY InMemoryOrderLinks; LIST_ENTRY InInitializationOrderLinks; uintptr_t DllBase; uintptr_t EntryPoint; uint32_t SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; }; // Process Environment Block. struct PEB { uint8_t InheritedAddressSpace; uint8_t ReadImageFileExecOptions; uint8_t BeingDebugged; union { uint8_t BitField; struct { uint8_t ImageUsesLargePages : 1; uint8_t IsProtectedProcess : 1; uint8_t IsLegacyProcess : 1; uint8_t IsImageDynamicallyRelocated : 1; uint8_t SkipPatchingUser32Forwarders : 1; uint8_t SpareBits : 1 /* 3 */; }; }; uintptr_t Mutant; uintptr_t ImageBaseAddress; PEB_LDR_DATA *Ldr; }; // Thread Environment Block ( aka Thread Information Block ). struct TEB { NT_TIB NtTib; uintptr_t EnvironmentPointer; CLIENT_ID ClientId; uintptr_t ActiveRpcHandle; uintptr_t ThreadLocalStoragePointer; PEB *ProcessEnvironmentBlock; uint32_t LastErrorValue; uint32_t CountOfOwnedCriticalSections; uintptr_t CsrClientThread; uintptr_t Win32ThreadInfo; uint32_t User32Reserved[ 26 ]; uint32_t UserReserved[ 5 ]; uintptr_t WOW32Reserved; // note - dex; some syscalls use this, but it depends on architecture. }; } }
22.982759
101
0.725431
sdkabuser
d0835288e263da468d9e15d951ec79d9c7f26c6c
1,443
hh
C++
src/api/assets/audio.hh
izzyaxel/Loft
809b4e3df2c2b08092c6b3a94073f4509240b4f2
[ "BSD-3-Clause" ]
null
null
null
src/api/assets/audio.hh
izzyaxel/Loft
809b4e3df2c2b08092c6b3a94073f4509240b4f2
[ "BSD-3-Clause" ]
null
null
null
src/api/assets/audio.hh
izzyaxel/Loft
809b4e3df2c2b08092c6b3a94073f4509240b4f2
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <string> #include <vector> /// Decibels to volume % [[nodiscard]] float dBToVolume(float dB); /// Volume % to decibels [[nodiscard]] float volumeTodB(float vol); enum struct AudioFormat { NONE = 0, OGG = 1, WAVE = 2, }; struct AudioInfo { AudioInfo() = default; AudioInfo(std::vector<int16_t> const &samples, int16_t numChannels, int16_t bitsPerSample, int32_t sampleRate, AudioFormat format) : samples(samples), numChannels(numChannels), bitsPerSample(bitsPerSample), sampleRate(sampleRate), format(format) {} std::vector<int16_t> samples{}; int16_t numChannels = 0, bitsPerSample = 0; int32_t sampleRate = 0; AudioFormat format = AudioFormat::NONE; }; [[nodiscard]] AudioInfo decodeAudio(FILE *input, std::string const &filePath); [[nodiscard]] AudioInfo decodeAudio(std::vector<uint8_t> const &input, std::string const &fileName); [[nodiscard]] AudioInfo fromWAV(FILE *input, std::string const &filePath); [[nodiscard]] AudioInfo fromOGG(FILE *input, std::string const &filePath); //[[nodiscard]] AudioInfo fromOpus(FILE *input, std::string const &filePath); //TODO need to use libopus directly for this [[nodiscard]] AudioInfo fromWAV(std::vector<uint8_t> const &input, std::string const &fileName); [[nodiscard]] AudioInfo fromOGG(std::vector<uint8_t> const &input, std::string const &fileName); [[nodiscard]] AudioInfo fromOpus(std::vector<uint8_t> const &input, std::string const &fileName);
35.195122
133
0.739432
izzyaxel
d08653745f67118fdda232eac2d60b2314b86a86
2,038
cpp
C++
TRayTracer/gShader.cpp
gabriellanzer/TRayTracer
1baabaf1a9b7accc8992a18bdfc83fe6e06aa30f
[ "MIT" ]
1
2018-03-11T23:46:21.000Z
2018-03-11T23:46:21.000Z
TRayTracer/gShader.cpp
TwinRavens/TRayTracer
1baabaf1a9b7accc8992a18bdfc83fe6e06aa30f
[ "MIT" ]
11
2018-05-17T12:16:45.000Z
2018-07-05T13:37:11.000Z
TRayTracer/gShader.cpp
TwinRavens/TRayTracer
1baabaf1a9b7accc8992a18bdfc83fe6e06aa30f
[ "MIT" ]
1
2018-08-08T12:28:15.000Z
2018-08-08T12:28:15.000Z
#include "gShader.h" rav::Shader::Shader(const string & shader_data, GLuint shader_type, const string & shader_name) : data(shader_data), type(shader_type), name(shader_name), compiled(false) { //Ask for OpenGL to create a shader ID of that Shader Type ID = glCreateShader(shader_type); //Assert if no name or data empty _ASSERT(!shader_name.empty() && !shader_data.empty()); } rav::Shader::~Shader() { //Ask for OpenGL to delete that shader glDeleteShader(ID); }; bool rav::Shader::Compile() { //Get const char from string data cstr cdata = data.c_str(); //Set source text for shader data glShaderSource(ID, 1, &cdata, NULL); //Point out that we are compiling rvDebug.Log("Compiling Shader " + name); //Tell OpenGL to compile it glCompileShader(ID); //Get Compilation Result Code GLint isCompiled = 0; glGetShaderiv(ID, GL_COMPILE_STATUS, &isCompiled); //If got an error if (isCompiled == GL_FALSE) { //Get size of info log GLint maxLength = 0; glGetShaderiv(ID, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character GLchar *errorLog = new GLchar[maxLength]; glGetShaderInfoLog(ID, maxLength, &maxLength, &errorLog[0]); //Error header rvDebug.Log("Error compiling Shader " + name, Debug::Error); //Create message string msg((const char*)errorLog); //Pop last \0 char msg.pop_back(); //Log Error through Debugger rvDebug.Log(msg, Debug::Error); //Don't leak the shader glDeleteShader(ID); //Exit with failure. return (compiled = false); } //Log sucesfull compilation message rvDebug.Log("Sucessfully compiled!\n"); //No compilation error! Compilation succeded! return (compiled = true); } bool rav::Shader::isCompiled() const { //Return compiled flag return compiled; } GLuint rav::Shader::getID() const { return ID; } unsigned int rav::Shader::getType() const { return (unsigned int)type; } string rav::Shader::getName() const { return name; } void rav::Shader::setName(const string& shader_name) { name = shader_name; }
20.585859
170
0.707556
gabriellanzer
d08931422115a0987c8fc2af707ffd6f3583c881
467
cpp
C++
geeksforgeeks/Hashing/Kth smallest element - medium/Answer.cpp
theCodeTeen/CP_Collection
78a0a564e8da47038232b0cca6f26153725af029
[ "MIT" ]
null
null
null
geeksforgeeks/Hashing/Kth smallest element - medium/Answer.cpp
theCodeTeen/CP_Collection
78a0a564e8da47038232b0cca6f26153725af029
[ "MIT" ]
null
null
null
geeksforgeeks/Hashing/Kth smallest element - medium/Answer.cpp
theCodeTeen/CP_Collection
78a0a564e8da47038232b0cca6f26153725af029
[ "MIT" ]
null
null
null
int kthSmallest(int arr[], int l, int r, int k) { int max=-1; for(int i=0;i<=r;i++) if(arr[i]>max) max=arr[i]; vector<bool> hash(max+1,false); for(int i=0;i<=r;i++) hash[arr[i]]=true; for(int i=0;i<=max;i++) { if(hash[i]==true) { k--; if(k==0) return i; } } }
22.238095
48
0.316916
theCodeTeen
d089e62aec48519e6816a03d06e7b79154c4c628
2,197
cpp
C++
src/Syntax/parse asgn.cpp
Kerndog73/STELA
11449b4bb440494f3ec4b1172b2688b5ec1bcd0a
[ "MIT" ]
10
2018-06-20T05:12:59.000Z
2021-11-23T02:56:04.000Z
src/Syntax/parse asgn.cpp
Kerndog73/STELA
11449b4bb440494f3ec4b1172b2688b5ec1bcd0a
[ "MIT" ]
null
null
null
src/Syntax/parse asgn.cpp
Kerndog73/STELA
11449b4bb440494f3ec4b1172b2688b5ec1bcd0a
[ "MIT" ]
null
null
null
// // parse asgn.cpp // STELA // // Created by Indi Kernick on 5/9/18. // Copyright © 2018 Indi Kernick. All rights reserved. // #include "parse asgn.hpp" #include "parse expr.hpp" using namespace stela; namespace { ast::AsgnPtr makeAssign(ParseTokens &tok, const ast::AssignOp op, ast::ExprPtr dst) { auto assign = make_retain<ast::CompAssign>(); assign->loc = tok.lastLoc(); assign->dst = std::move(dst); assign->oper = op; assign->src = tok.expectNode(parseExpr, "expression"); return assign; } } ast::AsgnPtr stela::parseAsgn(ParseTokens &tok) { ast::ExprPtr dst = parseNested(tok); if (!dst) { return nullptr; } if (auto *ident = dynamic_cast<ast::Identifier *>(dst.get())) { if (tok.checkOp(":=")) { auto decl = make_retain<ast::DeclAssign>(); decl->loc = tok.lastLoc(); decl->name = ident->name; decl->expr = tok.expectNode(parseExpr, "expression"); return decl; } } if (const bool incr = tok.checkOp("++"); incr || tok.checkOp("--")) { auto incrDecr = make_retain<ast::IncrDecr>(); incrDecr->loc = tok.lastLoc(); incrDecr->incr = incr; incrDecr->expr = std::move(dst); return incrDecr; } if (tok.checkOp("=")) { auto assign = make_retain<ast::Assign>(); assign->loc = tok.lastLoc(); assign->dst = std::move(dst); assign->src = tok.expectNode(parseExpr, "expression"); return assign; } #define CHECK(TOKEN, ENUM) \ if (tok.checkOp(#TOKEN)) { \ return makeAssign(tok, ast::AssignOp::ENUM, std::move(dst)); \ } CHECK(+=, add) CHECK(-=, sub) CHECK(*=, mul) CHECK(/=, div) CHECK(%=, mod) CHECK(<<=, bit_shl) CHECK(>>=, bit_shr) CHECK(&=, bit_and) CHECK(^=, bit_xor) CHECK(|=, bit_or) #undef CHECK if (auto *call = dynamic_cast<ast::FuncCall *>(dst.get())) { auto assign = make_retain<ast::CallAssign>(); assign->loc = call->loc; assign->call = std::move(*call); return assign; } tok.log().error(dst->loc) << "Expression used outside of assignment or function call" << fatal; }
25.546512
97
0.575785
Kerndog73
d08b1482a446aa62a81140cc8134f69a95a265b8
5,181
cpp
C++
source/ray/interaction.cpp
triplu-zero/monte-carlo-ray-tracer
8b36d5154204fc67e13376ad15b8bac33065c2d1
[ "MIT" ]
149
2020-03-06T00:39:43.000Z
2022-03-31T07:28:36.000Z
source/ray/interaction.cpp
triplu-zero/monte-carlo-ray-tracer
8b36d5154204fc67e13376ad15b8bac33065c2d1
[ "MIT" ]
4
2020-07-27T15:33:09.000Z
2022-02-24T11:34:40.000Z
source/ray/interaction.cpp
triplu-zero/monte-carlo-ray-tracer
8b36d5154204fc67e13376ad15b8bac33065c2d1
[ "MIT" ]
17
2020-03-23T16:05:36.000Z
2022-02-21T02:38:31.000Z
#include "interaction.hpp" #include "../material/fresnel.hpp" #include "../material/material.hpp" #include "../random/random.hpp" #include "../common/constants.hpp" #include "../common/coordinate-system.hpp" #include "../surface/surface.hpp" #include "../common/constexpr-math.hpp" Interaction::Interaction(const Intersection &isect, const Ray &ray, double external_ior) : t(isect.t), ray(ray), out(-ray.direction), n1(ray.medium_ior), material(isect.surface->material), surface(isect.surface), position(ray(t)), normal(isect.surface->normal(position)) { double cos_theta = glm::dot(ray.direction, normal); inside = cos_theta > 0.0; n2 = (inside && !material->opaque) ? external_ior : material->ior; glm::dvec3 shading_normal = normal; if (isect.interpolate) { shading_normal = isect.surface->interpolatedNormal(isect.uv); if (cos_theta < 0.0 != glm::dot(ray.direction, shading_normal) < 0.0) { shading_normal = normal; } } if (cos_theta > 0.0) { normal = -normal; shading_normal = -shading_normal; } shading_cs = CoordinateSystem(shading_normal); if (material->rough_specular) specular_normal = shading_cs.from(material->visibleMicrofacet(shading_cs.to(out))); else specular_normal = shading_normal; // Specular reflect probability R = Fresnel::dielectric(n1, n2, glm::dot(specular_normal, out)); // Transmission probability once ray has passed through specular layer T = material->transparency; // Ensure that both reflection and transmission has a chance to contribute for arbitrary wi, // even if importance sampled ray spawned by interaction is e.g. total internal reflection. if (material->rough_specular) { R = glm::clamp(R, 0.1, 0.9); } selectType(); dirac_delta = type != DIFFUSE && !material->rough_specular; } bool Interaction::sampleBSDF(glm::dvec3& bsdf_absIdotN, double& pdf, Ray& new_ray, bool flux) const { new_ray = Ray(*this); glm::dvec3 wi = shading_cs.to(new_ray.direction); if ((new_ray.refraction && wi.z >= 0.0) || (!new_ray.refraction && wi.z <= 0.0)) { return false; } glm::dvec3 wo = shading_cs.to(out); bsdf_absIdotN = BSDF(wo, wi, pdf, flux, new_ray.dirac_delta) * std::abs(wi.z); return pdf > 0.0; } bool Interaction::BSDF(glm::dvec3& bsdf_absIdotN, const glm::dvec3& world_wi, double& pdf) const { glm::dvec3 wi = shading_cs.to(world_wi); glm::dvec3 wo = shading_cs.to(out); bsdf_absIdotN = BSDF(wo, wi, pdf, false, false) * std::abs(wi.z); return pdf > 0.0; } glm::dvec3 Interaction::BSDF(const glm::dvec3& wo, const glm::dvec3& wi, double &pdf, bool flux, bool wi_dirac_delta) const { double cos_theta = wo.z; if(material->rough_specular) { if (wi.z > 0.0) { cos_theta = glm::dot(wo, glm::normalize(wo + wi)); } else { glm::dvec3 m = glm::normalize(wo * n1 + wi * n2); cos_theta = glm::dot(wo, m); if (n1 < n2) cos_theta = -cos_theta; } } // Full specular reflect probability if (material->perfect_mirror || material->complex_ior) { glm::dvec3 brdf = material->specularReflection(wi, wo, pdf); if (material->complex_ior) { brdf *= Fresnel::conductor(n1, material->complex_ior.get(), cos_theta); } return brdf; } // Full diffuse reflect probability if (n2 < 1.0) { return material->diffuseReflection(wi, wo, pdf); } double F = Fresnel::dielectric(n1, n2, cos_theta); double pdf_s, pdf_d; glm::dvec3 brdf_s = material->specularReflection(wi, wo, pdf_s); glm::dvec3 brdf_d = material->diffuseReflection(wi, wo, pdf_d); double pdf_t = pdf_s; glm::dvec3 btdf = brdf_s; if (F < 1.0) { btdf = material->specularTransmission(wi, wo, n1, n2, pdf_t, inside, flux); } if (wi_dirac_delta) { // wi guaranteed to be direction of ray spawned by interaction if (type == REFLECT) { pdf = R; return brdf_s * F; } else { pdf = T * (1.0 - R); return btdf * T * (1.0 - F); } } else if (!material->rough_specular) { pdf = pdf_d * (1.0 - R) * (1.0 - T); return brdf_d * (1.0 - F) * (1.0 - T); } pdf = glm::mix(glm::mix(pdf_d, pdf_t, T), pdf_s, R); return glm::mix(glm::mix(brdf_d, btdf, T), brdf_s, F); } // Selects the interaction type of the next ray spawned by interaction. void Interaction::selectType() { if (material->perfect_mirror || material->complex_ior) { type = REFLECT; } else if (n2 < 1.0) { type = DIFFUSE; } else { double p = Random::unit(); if (R > p) { type = REFLECT; } else if (R + (1.0 - R) * T > p) { type = REFRACT; } else // R + (1 - R) * T + (1 - R) * (1 - T) = 1 > p { type = DIFFUSE; } } }
27.412698
123
0.580583
triplu-zero
d08f19ff9d7043241e073cc6f15267bcf2b2d190
3,509
cpp
C++
src/Band/add_nl_h_o_pw.cpp
cocteautwins/SIRIUS-develop
8ab09ca7cc69e9a7dc76475b7b562b20d56deea3
[ "BSD-2-Clause" ]
null
null
null
src/Band/add_nl_h_o_pw.cpp
cocteautwins/SIRIUS-develop
8ab09ca7cc69e9a7dc76475b7b562b20d56deea3
[ "BSD-2-Clause" ]
null
null
null
src/Band/add_nl_h_o_pw.cpp
cocteautwins/SIRIUS-develop
8ab09ca7cc69e9a7dc76475b7b562b20d56deea3
[ "BSD-2-Clause" ]
null
null
null
#include "band.h" namespace sirius { void Band::add_nl_h_o_pw(K_point* kp__, int n__, matrix<double_complex>& phi__, matrix<double_complex>& hphi__, matrix<double_complex>& ophi__, matrix<double_complex>& beta_gk__, mdarray<int, 1>& packed_mtrx_offset__, mdarray<double_complex, 1>& d_mtrx_packed__, mdarray<double_complex, 1>& q_mtrx_packed__) { STOP(); //bool economize_gpu_memory = true; ///* <\beta_{\xi}^{\alpha}|\phi_j> */ //matrix<double_complex> beta_phi(unit_cell_.mt_basis_size(), n__); ///* Q or D multiplied by <\beta_{\xi}^{\alpha}|\phi_j> */ //matrix<double_complex> work(unit_cell_.mt_basis_size(), n__); //#ifdef __GPU //if (parameters_.processing_unit() == GPU) //{ // beta_phi.allocate_on_device(); // work.allocate_on_device(); //} //#endif //if (parameters_.processing_unit() == CPU || (parameters_.processing_unit() == GPU && !economize_gpu_memory)) //{ // /* compute <beta|phi> */ // kp__->generate_beta_phi(unit_cell_.mt_basis_size(), phi__, n__, 0, beta_gk__, beta_phi); // // #ifdef __PRINT_OBJECT_CHECKSUM // auto c1 = beta_phi.checksum(); // DUMP("checksum(beta_phi) : %18.10f %18.10f", std::real(c1), std::imag(c1)); // #endif // // /* add |beta>D<beta|phi> to |hphi> */ // kp__->add_non_local_contribution(unit_cell_.num_atoms(), unit_cell_.mt_basis_size(), unit_cell_.beta_chunk(0).desc_, // beta_gk__, d_mtrx_packed__, packed_mtrx_offset__, beta_phi, // hphi__, n__, 0, complex_one, work); // // /* add |beta>Q<beta|phi> to |ophi> */ // kp__->add_non_local_contribution(unit_cell_.num_atoms(), unit_cell_.mt_basis_size(), unit_cell_.beta_chunk(0).desc_, // beta_gk__, q_mtrx_packed__, packed_mtrx_offset__, beta_phi, // ophi__, n__, 0, complex_one, work); //} //else //{ // #ifdef __GPU // kp__->generate_beta_gk(unit_cell_.num_atoms(), unit_cell_.beta_chunk(0).atom_pos_, unit_cell_.beta_chunk(0).desc_, beta_gk__); // // phi__.copy_to_device(); // kp__->generate_beta_phi(unit_cell_.mt_basis_size(), phi__, n__, 0, beta_gk__, beta_phi); // // hphi__.copy_to_device(); // kp__->add_non_local_contribution(unit_cell_.num_atoms(), unit_cell_.mt_basis_size(), unit_cell_.beta_chunk(0).desc_, // beta_gk__, d_mtrx_packed__, packed_mtrx_offset__, beta_phi, // hphi__, n__, 0, complex_one, work); // hphi__.copy_to_host(); // // ophi__.copy_to_device(); // kp__->add_non_local_contribution(unit_cell_.num_atoms(), unit_cell_.mt_basis_size(), unit_cell_.beta_chunk(0).desc_, // beta_gk__, q_mtrx_packed__, packed_mtrx_offset__, beta_phi, // ophi__, n__, 0, complex_one, work); // ophi__.copy_to_host(); // #else // TERMINATE_NO_GPU // #endif //} //#ifdef __GPU //if (parameters_.processing_unit() == GPU) cuda_device_synchronize(); //#endif } };
42.792683
136
0.553434
cocteautwins
d090e6c53bce152e9dff63a682636db4f99b229a
1,204
cpp
C++
YorozuyaGSLib/source/_UNIT_DB_BASE.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/_UNIT_DB_BASE.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/_UNIT_DB_BASE.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <_UNIT_DB_BASE.hpp> START_ATF_NAMESPACE void _UNIT_DB_BASE::Init() { using org_ptr = void (WINAPIV*)(struct _UNIT_DB_BASE*); (org_ptr(0x1400765c0L))(this); }; _UNIT_DB_BASE::_UNIT_DB_BASE() { using org_ptr = void (WINAPIV*)(struct _UNIT_DB_BASE*); (org_ptr(0x1400763f0L))(this); }; void _UNIT_DB_BASE::ctor__UNIT_DB_BASE() { using org_ptr = void (WINAPIV*)(struct _UNIT_DB_BASE*); (org_ptr(0x1400763f0L))(this); }; void _UNIT_DB_BASE::_LIST::DelUnit() { using org_ptr = void (WINAPIV*)(struct _UNIT_DB_BASE::_LIST*); (org_ptr(0x1401082c0L))(this); }; void _UNIT_DB_BASE::_LIST::Init(char byIndex) { using org_ptr = void (WINAPIV*)(struct _UNIT_DB_BASE::_LIST*, char); (org_ptr(0x1400764b0L))(this, byIndex); }; _UNIT_DB_BASE::_LIST::_LIST() { using org_ptr = void (WINAPIV*)(struct _UNIT_DB_BASE::_LIST*); (org_ptr(0x140076460L))(this); }; void _UNIT_DB_BASE::_LIST::ctor__LIST() { using org_ptr = void (WINAPIV*)(struct _UNIT_DB_BASE::_LIST*); (org_ptr(0x140076460L))(this); }; END_ATF_NAMESPACE
29.365854
76
0.621262
lemkova
d0a1e9e5b265343cae602a6fd50f48c43076e2ae
339
cpp
C++
Drzewa binarne/zad1.cpp
Gieted/AiSD
23d7ecdfb8e4b25bd02a6f1d60ee35347eb74b38
[ "MIT" ]
null
null
null
Drzewa binarne/zad1.cpp
Gieted/AiSD
23d7ecdfb8e4b25bd02a6f1d60ee35347eb74b38
[ "MIT" ]
null
null
null
Drzewa binarne/zad1.cpp
Gieted/AiSD
23d7ecdfb8e4b25bd02a6f1d60ee35347eb74b38
[ "MIT" ]
null
null
null
#include <iostream> struct node { int data; node *left; node *right; }; node *search(node *tree, int x) { while (tree != NULL && tree->data != x) { if (x < tree->data) { tree = tree->left; } else { tree = tree->right; } } return tree; }
13.56
43
0.421829
Gieted
d0a4e00be53e5b6b2ad62dfd54fb6f06c5c0962d
6,636
cpp
C++
dense_tiles/dense_tiles.cpp
alex85k/osmium-contrib
2a2ba087968e837589faf91909e6c086b5406f16
[ "Naumen", "Condor-1.1", "MS-PL" ]
16
2015-01-16T12:25:07.000Z
2019-06-27T07:53:45.000Z
dense_tiles/dense_tiles.cpp
alex85k/osmium-contrib
2a2ba087968e837589faf91909e6c086b5406f16
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2015-03-16T20:05:07.000Z
2020-08-21T00:57:25.000Z
dense_tiles/dense_tiles.cpp
alex85k/osmium-contrib
2a2ba087968e837589faf91909e6c086b5406f16
[ "Naumen", "Condor-1.1", "MS-PL" ]
9
2015-03-16T23:41:27.000Z
2020-05-03T04:52:42.000Z
/** * dense_tiles * * Computes densest data tiles from OSM file. * * Frederik Ramm <frederik@remote.org> */ #include <algorithm> #include <cstdlib> #include <getopt.h> #include <iostream> #include <limits> #include <utility> #include <vector> #include <osmium/geom/tile.hpp> #include <osmium/io/any_input.hpp> #include <osmium/io/input_iterator.hpp> #include <osmium/util/file.hpp> #include <osmium/util/progress_bar.hpp> void print_help(const char* progname) { std::cerr << "Usage: " << progname << " [OPTIONS] OSMFILE\n"; std::cerr << "List the (meta) tiles in the input file ordered by node density,\n"; std::cerr << "highest first. In meta tile mode, which is the default, only\n"; std::cerr << "coordinates for the upper left tile in an 8x8 tile block will be\n"; std::cerr << "output.\n"; std::cerr << " --help | -h this help\n"; std::cerr << " --zoom <n> | -z <n> compute for zoom n [14]\n"; std::cerr << " --max <n> | -m <n> list a maximum of n tiles [100000]\n"; std::cerr << " Use --max 0 to set to 'no limit'.\n"; std::cerr << " --min-nodes <n> | -M <n> list only tiles with more than n nodes\n"; std::cerr << " [1];\n"; std::cerr << " --single | -s compute for single tiles, not meta tiles\n"; std::cerr << " --count | -c print number of nodes in each tile\n"; std::cerr << " --progress | -p display progress bar\n"; } int main(int argc, char* argv[]) { bool enable_progress_bar = false; bool print_count = false; bool single_tile = false; unsigned int zoom = 14; unsigned int effective_zoom; unsigned int max = 100000; unsigned int min_nodes = 1; static struct option long_options[] = { { "help", no_argument, 0, 'h' }, { "zoom", required_argument, 0, 'z' }, { "max", required_argument, 0, 'm' }, { "min-nodes", required_argument, 0, 'M' }, { "single", no_argument, 0, 's' }, { "count", no_argument, 0, 'c' }, { "progress", no_argument, 0, 'p' }, { 0, 0, 0, 0 } }; while (true) { const int c = getopt_long(argc, argv, "hm:M:pcsz:", long_options, 0); if (c == -1) { break; } switch (c) { case 'h': print_help(argv[0]); std::exit(0); case 'm': max = std::atoi(optarg); break; case 'M': min_nodes = std::atoi(optarg); break; case 'p': enable_progress_bar = true; break; case 'c': print_count = true; break; case 's': single_tile = true; break; case 'z': zoom = std::atoi(optarg); if ((zoom < 5) || (zoom > 18)) { std::cerr << "--zoom must be in range 5..18\n"; print_help(argv[0]); std::exit(1); } break; default: print_help(argv[0]); std::exit(1); } } std::string input; const int remaining_args = argc - optind; if (remaining_args > 1) { std::cerr << "extra arguments on command line\n"; print_help(argv[0]); std::exit(1); } else if (remaining_args == 1) { input = argv[optind]; } else { print_help(argv[0]); std::exit(1); } // in standard (metatile) mode, we effectively work with tiles that // are three zoom levels below what has been asked for, since one // single tile on z(n) equals one meta tile on z(n+3) effective_zoom = zoom; if (!single_tile) { effective_zoom -= 3; } // shortcut for users – `-m 0` prints all tiles if (max == 0) { max = 1 << (2 * effective_zoom); } // vector holds one counter for each tile std::vector<unsigned int> grid(1 << (2 * effective_zoom)); osmium::io::File infile{input}; osmium::io::Reader reader{infile, osmium::osm_entity_bits::node, osmium::io::read_meta::no}; // Initialize progress bar, enable it only if STDERR is a TTY. osmium::ProgressBar progress{reader.file_size(), osmium::util::isatty(2) && enable_progress_bar}; // Create range of input iterators that will iterator over all objects // delivered from input file through the "reader". auto input_range = osmium::io::make_input_iterator_range<osmium::OSMObject>(reader); auto callback = [&](const osmium::OSMObject& object) { progress.update(reader.offset()); if (object.type() != osmium::item_type::node) return; const osmium::Node& n = static_cast<const osmium::Node&>(object); // use osmium::geom::Tile to do the coordinate->tile conversion osmium::geom::Tile t{effective_zoom, n.location()}; const unsigned int offset = (t.y << effective_zoom) + t.x; if (grid[offset] < std::numeric_limits<unsigned int>::max()) { grid[offset]++; } }; // this runs the counting std::for_each(input_range.begin(), input_range.end(), callback); // Progress bar is done. progress.done(); reader.close(); // copy counters to a vector with pairs, remembering the position in // grid[] which is the tile coordinate std::vector<std::pair<unsigned int, unsigned int>> sorter; for (unsigned int i = 0; i < grid.size(); ++i) { if (grid[i] >= min_nodes) { sorter.emplace_back(grid[i], i); } } // sort the sorter vector // NB C++14 lets you use "auto" for the lambda args but C++11 // requires spelling out std::sort(sorter.begin(), sorter.end(), [](const std::pair<unsigned int, unsigned int>& left, const std::pair<unsigned int, unsigned int>& right) { return left.first > right.first; }); // dump first "max" elements of sorter vector if (max > sorter.size()) max=sorter.size(); for (unsigned int i=0; i<max; i++) { unsigned int y = sorter[i].second >> effective_zoom; unsigned int x = sorter[i].second & ((1 << effective_zoom) - 1); if (single_tile) { std::cout << zoom << "/" << x << "/" << y; } else { std::cout << zoom << "/" << (x<<3) << "/" << (y<<3); } if (print_count) { std::cout << " " << sorter[i].first; } std::cout << "\n"; } }
34.926316
151
0.534961
alex85k
d0a79109a62172f6b7d3a9c546c26d736421cd48
2,017
hpp
C++
g.hpp
userElaina/computer-graphics
0f27b8366f96182d8c9d66d38d8b0b35e4acff35
[ "MIT" ]
2
2021-09-17T05:28:37.000Z
2021-09-19T13:36:15.000Z
g.hpp
userElaina/computer-graphics
0f27b8366f96182d8c9d66d38d8b0b35e4acff35
[ "MIT" ]
null
null
null
g.hpp
userElaina/computer-graphics
0f27b8366f96182d8c9d66d38d8b0b35e4acff35
[ "MIT" ]
null
null
null
// code by userElaina // pop version that you can start quickly #pragma once #include "bmp24bits.hpp" BMP24bits*nft; int ox,oy; int col=0x000000; double xa=1,xb=0,ya=1,yb=0; inline int NewImage(int x,int y){ ox=((x>>2)+1)<<2; oy=((y>>2)+1)<<2; nft=new BMP24bits(ox<<1,oy<<1); printf("NewImage: O(%d,%d)\n",ox,oy); return 0; } inline int LoadImage(std::string pth){ nft=new BMP24bits(pth); ox=nft->width>>1; oy=nft->height>>1; printf("LoadImage: O(%d,%d)\n",ox,oy); return 0; } inline int SetAxis(){ for(int i=0;i<nft->width;i++) nft->setpixel(nft->getp(i,oy)); for(int i=0;i<nft->height;i++) nft->setpixel(nft->getp(ox,i)); return 0; } inline int SetColor(int color=0x000000){ col=color; return 0; } inline int SetPixel(int x,int y,int rgb=(-1)){ if(rgb==(-1))rgb=col; return nft->setpixel(nft->getp(x+ox,y+oy),rgb); } inline int SetPixel(double x,double y,int rgb=(-1)){ return SetPixel((int)(x>0?x+0.5:x-0.5),(int)(y>0?y+0.5:y-0.5),rgb); } inline int SetPixel(std::pair<int,int>p,int rgb=(-1)){ return SetPixel(p.first,p.second,rgb); } inline int SetPixel(std::pair<double,double>p,int rgb=(-1)){ return SetPixel(p.first,p.second,rgb); } inline int SetPixel2(int x,int y,int rgb=(-1)){ return SetPixel(x,y,rgb)+SetPixel(-x,-y,rgb); } inline int SetPixel4(int x,int y,int rgb=(-1)){ return SetPixel2(x,y,rgb)+SetPixel2(-x,y,rgb); } inline int SetPixel8(int x,int y,int rgb=(-1)){ return SetPixel4(x,y,rgb)+SetPixel4(y,x,rgb); } inline int SetPixel_map(double x,double y,int rgb=(-1)){ return SetPixel(x*xa+xb,y*ya+yb,rgb); } inline int GetPixel(int x,int y){ return nft->getpixel(nft->getp(x+ox,y+oy)); } inline int RGB(int r,int g,int b,int a=0){ return argb(r,g,b,a); } inline int Save(std::string pth){ return nft->save(pth); } inline int Clear(){ nft->white(); return 0; }
22.411111
72
0.593951
userElaina
d0a8306780ff3cfc1c3d34c3e91803e42e68c4b6
1,292
cpp
C++
normal/SimpleSort.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
1
2018-01-13T06:01:49.000Z
2018-01-13T06:01:49.000Z
normal/SimpleSort.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
null
null
null
normal/SimpleSort.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void Swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // 冒泡排序 void bubble_sort(int data[], int length) { for (int i = 0; i < length - 1; i++) { for (int j = 0; j < length - 1 - i; j++) { if (data[j] > data[j + 1]) Swap(&data[j], &data[j + 1]); } } } // 插入排序 void insert_sort(int data[], int length) { for (int i = 1; i < length; i++) { int j = i - 1; int temp = data[i]; while (j >= 0 && temp < data[j]) { data[j + 1] = data[j]; j--; } data[j + 1] = temp; } } // 选择排序 void select_sort(int data[], int length) { for (int i = 0; i < length - 1; i++) { int min = i; for (int j = i + 1; j < length; j++) { if (data[j] < data[min]) min = j; } int temp = data[i]; data[i] = data[min]; data[min] = temp; } } int main(int argc, char const *argv[]) { int test1[] = {5, 8, 1, 10, 3}; for (int i : test1) { cout << i << ' '; } cout << endl; select_sort(test1, 5); for (int i : test1) { cout << i << ' '; } cout << endl; return 0; }
18.197183
48
0.396285
thewangcj
d0aa38dd7353f1649bd4cc7ec972c5d2251e9eb7
2,992
hpp
C++
include/TypeMap.hpp
gusc/BinarySerializer
39a9c9f17205eafcd5b932dfc7107cd0da6b2c8c
[ "MIT" ]
1
2021-01-15T16:18:50.000Z
2021-01-15T16:18:50.000Z
include/TypeMap.hpp
gusc/BinarySerializer
39a9c9f17205eafcd5b932dfc7107cd0da6b2c8c
[ "MIT" ]
null
null
null
include/TypeMap.hpp
gusc/BinarySerializer
39a9c9f17205eafcd5b932dfc7107cd0da6b2c8c
[ "MIT" ]
null
null
null
// // TypeMap.hpp // Serializer // // Created by Gusts Kaksis on 01/09/2020. // Copyright © 2020 Gusts Kaksis. All rights reserved. // #ifndef TypeMap_h #define TypeMap_h #include <vector> #include <map> namespace gusc::Serializer { template<typename TType> struct TypeTlvMap; enum class SerializableType : uint32_t { Bool = 1, Int8 = 10, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, Float = 100, Double, Vector = 200, Map, Custom = 1000 // Define your mapped types with values of Custom+N }; template<typename TType> struct SerializableTypeMap; // Map definitions template<> struct SerializableTypeMap<bool> { static constexpr SerializableType typeId = SerializableType::Bool; }; template<> struct SerializableTypeMap<int8_t> { static constexpr SerializableType typeId = SerializableType::Int8; }; template<> struct SerializableTypeMap<char> { static constexpr SerializableType typeId = SerializableType::UInt8; }; template<> struct SerializableTypeMap<uint8_t> { static constexpr SerializableType typeId = SerializableType::UInt8; }; template<> struct SerializableTypeMap<int16_t> { static constexpr SerializableType typeId = SerializableType::Int16; }; template<> struct SerializableTypeMap<uint16_t> { static constexpr SerializableType typeId = SerializableType::UInt16; }; template<> struct SerializableTypeMap<long> { static constexpr SerializableType typeId = SerializableType::Int32; }; template<> struct SerializableTypeMap<int32_t> { static constexpr SerializableType typeId = SerializableType::Int32; }; template<> struct SerializableTypeMap<unsigned long> { static constexpr SerializableType typeId = SerializableType::UInt32; }; template<> struct SerializableTypeMap<uint32_t> { static constexpr SerializableType typeId = SerializableType::UInt32; }; template<> struct SerializableTypeMap<int64_t> { static constexpr SerializableType typeId = SerializableType::Int64; }; template<> struct SerializableTypeMap<uint64_t> { static constexpr SerializableType typeId = SerializableType::UInt64; }; template<> struct SerializableTypeMap<float> { static constexpr SerializableType typeId = SerializableType::Float; }; template<> struct SerializableTypeMap<double> { static constexpr SerializableType typeId = SerializableType::Double; }; template<typename TValue> struct SerializableTypeMap<std::vector<TValue>> { static constexpr SerializableType typeId = SerializableType::Vector; }; template<typename TKey, typename TValue> struct SerializableTypeMap<std::map<TKey, TValue>> { static constexpr SerializableType typeId = SerializableType::Map; }; // End map definitions template<typename TType> uint32_t FindTypeId() { return static_cast<uint32_t>(SerializableTypeMap<TType>::typeId); } } #endif /* TypeMap_h */
18.936709
72
0.729278
gusc
d0b054c0622dee70df8137f780322d4348a128e2
4,736
hpp
C++
hpx/traits/acquire_shared_state.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
hpx/traits/acquire_shared_state.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
hpx/traits/acquire_shared_state.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2016 Hartmut Kaiser // Copyright (c) 2016 Agustin Berge // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef HPX_TRAITS_ACQUIRE_SHARED_STATE_HPP #define HPX_TRAITS_ACQUIRE_SHARED_STATE_HPP #include <hpx/config.hpp> #include <hpx/iterator_support/traits/is_range.hpp> #include <hpx/iterator_support/range.hpp> #include <hpx/memory/intrusive_ptr.hpp> #include <hpx/traits/future_access.hpp> #include <hpx/traits/future_traits.hpp> #include <hpx/traits/is_future.hpp> #include <hpx/traits/is_future_range.hpp> #include <hpx/util/detail/reserve.hpp> #include <algorithm> #include <cstddef> #include <iterator> #include <type_traits> #include <utility> #include <vector> namespace hpx { namespace traits { namespace detail { template <typename T, typename Enable = void> struct acquire_shared_state_impl; } template <typename T, typename Enable = void> struct acquire_shared_state : detail::acquire_shared_state_impl<typename std::decay<T>::type> {}; struct acquire_shared_state_disp { template <typename T> HPX_FORCEINLINE typename acquire_shared_state<T>::type operator()(T && t) const { return acquire_shared_state<T>()(std::forward<T>(t)); } }; namespace detail { /////////////////////////////////////////////////////////////////////// template <typename T, typename Enable> struct acquire_shared_state_impl { static_assert(!is_future_or_future_range<T>::value, ""); typedef T type; template <typename T_> HPX_FORCEINLINE T operator()(T_ && value) const { return std::forward<T_>(value); } }; /////////////////////////////////////////////////////////////////////// template <typename Future> struct acquire_shared_state_impl< Future, typename std::enable_if< is_future<Future>::value >::type > { typedef typename traits::detail::shared_state_ptr< typename traits::future_traits<Future>::type >::type const& type; HPX_FORCEINLINE type operator()(Future const& f) const { return traits::future_access<Future>::get_shared_state(f); } }; /////////////////////////////////////////////////////////////////////// template <typename Range> struct acquire_shared_state_impl< Range, typename std::enable_if< traits::is_future_range<Range>::value >::type > { typedef typename traits::future_range_traits<Range>::future_type future_type; typedef typename traits::detail::shared_state_ptr_for<future_type>::type shared_state_ptr; typedef std::vector<shared_state_ptr> type; template <typename Range_> HPX_FORCEINLINE std::vector<shared_state_ptr> operator()(Range_&& futures) const { std::vector<shared_state_ptr> values; detail::reserve_if_random_access_by_range(values, futures); std::transform(util::begin(futures), util::end(futures), std::back_inserter(values), acquire_shared_state_disp()); return values; } }; } /////////////////////////////////////////////////////////////////////////// namespace detail { template <typename T> HPX_FORCEINLINE typename acquire_shared_state<T>::type get_shared_state(T && t) { return acquire_shared_state<T>()(std::forward<T>(t)); } template <typename R> HPX_FORCEINLINE hpx::intrusive_ptr<lcos::detail::future_data_base<R> > const& get_shared_state( hpx::intrusive_ptr<lcos::detail::future_data_base<R> > const& t) { return t; } /////////////////////////////////////////////////////////////////////// template <typename Future> struct wait_get_shared_state { HPX_FORCEINLINE typename traits::detail::shared_state_ptr_for<Future>::type const& operator()(Future const& f) const { return traits::detail::get_shared_state(f); } }; } }} #endif /*HPX_TRAITS_ACQUIRE_SHARED_STATE_HPP*/
30.554839
84
0.548775
McKillroy
d0bf7696da0db8465ba553471401dd281a25a760
791
cpp
C++
AtCoder/abc143/d/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/abc143/d/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/abc143/d/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> a(n, 0); for (int i = 0; i < n; i++) cin >> a[i]; long long int ans = 0; vector<int> cnt(2000, 0); for (int i = 0; i < n; i++) cnt[a[i]]++; for (int i = 1; i < 2000; i++) cnt[i] += cnt[i - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; int x = max(a[i] - a[j], a[j] - a[i]), y = a[i] + a[j]; int c = 0; if (0 <= y - 1) c = cnt[y - 1]; c -= cnt[x]; if (x < a[i] && a[i] < y) c--; if (x < a[j] && a[j] < y) c--; ans += c; } } ans /= 6; cout << ans << endl; }
27.275862
67
0.378003
H-Tatsuhiro
d0c261788f5bb35ff97e66a51d03bd5380f0569e
887
cc
C++
src/openvslam/optimize/g2o/landmark_vertex_container.cc
htwang1996/openvslam_marker
e798e6e242f3a2c001a32dfd393fe9815026ad84
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
17
2021-04-17T07:16:13.000Z
2022-03-29T01:56:40.000Z
src/openvslam/optimize/g2o/landmark_vertex_container.cc
htwang1996/openvslam_marker
e798e6e242f3a2c001a32dfd393fe9815026ad84
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
4
2020-03-18T12:52:38.000Z
2020-03-31T16:59:59.000Z
src/openvslam/optimize/g2o/landmark_vertex_container.cc
htwang1996/openvslam_marker
e798e6e242f3a2c001a32dfd393fe9815026ad84
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
20
2021-02-28T09:41:34.000Z
2022-03-15T19:45:26.000Z
#include "openvslam/optimize/g2o/landmark_vertex_container.h" namespace openvslam { namespace optimize { namespace g2o { landmark_vertex_container::landmark_vertex_container(const unsigned int offset, const unsigned int num_reserve) : offset_(offset) { vtx_container_.reserve(num_reserve); } landmark_vertex* landmark_vertex_container::create_vertex(const unsigned int id, const Vec3_t& pos_w, const bool is_constant) { // vertexを作成 const auto vtx_id = offset_ + id; auto vtx = new landmark_vertex(); vtx->setId(vtx_id); vtx->setEstimate(pos_w); vtx->setFixed(is_constant); vtx->setMarginalized(true); // databaseに登録 vtx_container_[id] = vtx; // max IDを更新 if (max_vtx_id_ < vtx_id) { max_vtx_id_ = vtx_id; } // 作成したvertexをreturn return vtx; } } // namespace g2o } // namespace optimize } // namespace openvslam
26.878788
127
0.713641
htwang1996
d0c66736a3389cfc165d0fe83b0e0eb527dd8346
2,829
cpp
C++
src/sw/so/preparation/posts_parser.cpp
sewenew/so
a7220b70fe0a0697393d263c838a9a3bc19f3c2e
[ "Apache-2.0" ]
1
2019-07-08T06:26:46.000Z
2019-07-08T06:26:46.000Z
src/sw/so/preparation/posts_parser.cpp
sewenew/so
a7220b70fe0a0697393d263c838a9a3bc19f3c2e
[ "Apache-2.0" ]
null
null
null
src/sw/so/preparation/posts_parser.cpp
sewenew/so
a7220b70fe0a0697393d263c838a9a3bc19f3c2e
[ "Apache-2.0" ]
null
null
null
/************************************************************************** Copyright (c) 2018 sewenew Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************/ #include <string> #include <iostream> #include "record_reader.h" int main(int argc, char **argv) { if (argc != 2) { std::cerr << "Usage: posts_parser path_to_xml_file" << std::endl; return -1; } auto fields = {"Id", "PostTypeId", "ParentId", "AcceptedAnswerId", "CreationDate", "Score", "ViewCount", "Body", "OwnerUserId", "LastEditorUserId", "LastEditDate", "CommunityOwnedDate", "Title", "Tags", "AnswerCount", "FavoriteCount" }; sw::so::RecordReader reader(argv[1], 1024 * 1024, fields.begin(), fields.end()); size_t total = 0; size_t cnt = 0; size_t empty = 0; size_t err = 0; while (true) { try { ++total; auto record = reader.next(); if (record.is_null()) { ++empty; continue; } auto iter = record.find("Score"); if (iter == record.end()) { continue; } auto score = std::stoi(iter.value().get<std::string>()); if (score <= 0) { continue; } iter = record.find("PostTypeId"); if (iter == record.end()) { continue; } if (iter.value().get<std::string>() == "1") { iter = record.find("AnswerCount"); if (iter == record.end()) { continue; } auto answer_cnt = std::stoi(iter.value().get<std::string>()); if (answer_cnt == 0) { continue; } } std::cout << record << "\n"; ++cnt; } catch (const sw::so::EofError &e) { break; } catch (const sw::so::Error &e) { ++err; std::cerr << "Error: " << e.what() << std::endl; } } std::cerr << "total: " << total << ", cnt: " << cnt << ", empty: " << empty << ", err: " << err << std::endl; return 0; }
31.087912
84
0.468363
sewenew
d0c6d430d8e088174c216e6a56e42a04e2274435
979
cpp
C++
count-sub-islands.cpp
cleamoon/Leetcode_solutions
e7f4a700d7130abd7257435779a4ae193c08080a
[ "MIT" ]
null
null
null
count-sub-islands.cpp
cleamoon/Leetcode_solutions
e7f4a700d7130abd7257435779a4ae193c08080a
[ "MIT" ]
null
null
null
count-sub-islands.cpp
cleamoon/Leetcode_solutions
e7f4a700d7130abd7257435779a4ae193c08080a
[ "MIT" ]
null
null
null
class Solution { public: bool isSub = true; void dfs(vector<vector<int>>& grid, int x, int y, vector<vector<int>>& base) { if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] == 0) { return; } if (base[x][y] == 0) isSub = false; grid[x][y] = 0; dfs(grid, x - 1, y, base); dfs(grid, x + 1, y, base); dfs(grid, x, y - 1, base); dfs(grid, x, y + 1, base); } int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) { int ret = 0; for (int i = 0; i < grid2.size(); i++) { for (int j = 0; j < grid2[0].size(); j++) { if (grid2[i][j] == 1) { dfs(grid2, i, j, grid1); if (isSub) { ret++; } isSub = true; } } } return ret; } };
27.194444
91
0.369765
cleamoon
d0c6fe3072ce55c0f037b472fd84687e559b090e
810
cpp
C++
src/syntax/AST/ReadFloat.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
src/syntax/AST/ReadFloat.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
src/syntax/AST/ReadFloat.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
#include "ReadFloat.h" AbstractExpr * ReadFloat::Clone() { return new ReadFloat(); } void ReadFloat::Display(string tab) { cout << tab << ">[READFLOAT]" << endl; } AbstractType * ReadFloat::VerifyExpr( EnvironmentType * env_types, EnvironmentExp * env_exp, string * class_name) { m_expr_type = new FloatType(); return m_expr_type; } void ReadFloat::CodeGenExpr( EnvironmentType * env_types, GeneratorEnvironment * gen_env) { gen_env->output_file << "invokestatic java/lang/System.console()Ljava/io/Console;" << endl; gen_env->output_file << "invokevirtual java/io/Console.readLine()Ljava/lang/String;" << endl; gen_env->output_file << "invokestatic java/lang/Float.parseFloat(Ljava/lang/String;)F" << endl; }
22.5
74
0.654321
pougetat
d0cbca173a141fa00869f1f4ebd41de798d88e1e
41,540
cpp
C++
Engine/Engine.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
null
null
null
Engine/Engine.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
null
null
null
Engine/Engine.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
null
null
null
// ------------------------------------ // #include "Engine.h" #include "Application/AppDefine.h" #include "Application/Application.h" #include "Application/ConsoleInput.h" #include "Common/DataStoring/DataStore.h" #include "Common/StringOperations.h" #include "Common/Types.h" #include "Entities/GameWorld.h" #include "Entities/GameWorldFactory.h" #include "Entities/Serializers/EntitySerializer.h" #include "Events/EventHandler.h" #include "FileSystem.h" #include "GUI/GuiManager.h" #include "GlobalCEFHandler.h" #include "Handlers/IDFactory.h" #include "Handlers/OutOfMemoryHandler.h" #include "Handlers/ResourceRefreshHandler.h" #include "Iterators/StringIterator.h" #include "Networking/NetworkHandler.h" #include "Networking/RemoteConsole.h" #include "Newton/NewtonManager.h" #include "Newton/PhysicsMaterialManager.h" #include "ObjectFiles/ObjectFileProcessor.h" #include "Rendering/Graphics.h" #include "Script/Console.h" #include "Sound/SoundDevice.h" #include "Statistics/RenderingStatistics.h" #include "Statistics/TimingMonitor.h" #include "Threading/QueuedTask.h" #include "Threading/ThreadingManager.h" #include "TimeIncludes.h" #include "Utility/Random.h" #include "Window.h" #include "utf8.h" #include "OgreWindowEventUtilities.h" #ifdef LEVIATHAN_USES_LEAP #include "Leap/LeapManager.h" #endif #ifdef LEVIATHAN_USING_SDL2 #include <SDL.h> #endif #include <chrono> #include <future> using namespace Leviathan; using namespace std; // ------------------------------------ // //! Used to detect when accessed from main thread static thread_local int MainThreadMagic = 0; constexpr auto THREAD_MAGIC = 42; DLLEXPORT Engine::Engine(LeviathanApplication* owner) : Owner(owner) { // This makes sure that uninitialized engine will have at least some last frame time // LastTickTime = Time::GetTimeMs64(); instance = this; } DLLEXPORT Engine::~Engine() { // Reset the instance ptr // instance = nullptr; _ConsoleInput.reset(); } DLLEXPORT Engine* Engine::instance = nullptr; Engine* Engine::GetEngine() { return instance; } DLLEXPORT Engine* Engine::Get() { return instance; } DLLEXPORT bool Engine::IsOnMainThread() const { return MainThreadMagic == THREAD_MAGIC; } // ------------------------------------ // DLLEXPORT bool Engine::Init( AppDef* definition, NETWORKED_TYPE ntype, NetworkInterface* packethandler) { GUARD_LOCK(); MainThreadMagic = THREAD_MAGIC; // Get the time, for monitoring how long loading takes // auto InitStartTime = Time::GetTimeMs64(); // Store parameters // Define = definition; IsClient = ntype == NETWORKED_TYPE::Client; // Create all the things // OutOMemory = new OutOfMemoryHandler(); IDDefaultInstance = new IDFactory(); // Create threading facilities // _ThreadingManager = new ThreadingManager(); if(!_ThreadingManager->Init()) { Logger::Get()->Error("Engine: Init: cannot start threading"); return false; } // Create the randomizer // MainRandom = new Random((int)InitStartTime); MainRandom->SetAsMain(); // Console might be the first thing we want // if(!NoSTDInput) { _ConsoleInput = std::make_unique<ConsoleInput>(); if(!_ConsoleInput->Init( std::bind(&Engine::_ReceiveConsoleInput, this, std::placeholders::_1), NoGui ? true : false)) { Logger::Get()->Error("Engine: Init: failed to read stdin, perhaps pass --nocin"); return false; } } if(NoGui) { // Tell window title // Logger::Get()->Write( "// ----------- " + Define->GetWindowDetails().Title + " ----------- //"); } // We could immediately receive a remote console request so this should be // ready when networking is started _RemoteConsole = new RemoteConsole(); // We want to send a request to the master server as soon as possible // { Lock lock(NetworkHandlerLock); _NetworkHandler = new NetworkHandler(ntype, packethandler); _NetworkHandler->Init(Define->GetMasterServerInfo()); } // These should be fine to be threaded // // File change listener // _ResourceRefreshHandler = new ResourceRefreshHandler(); if(!_ResourceRefreshHandler->Init()) { Logger::Get()->Error("Engine: Init: cannot start resource monitor"); return false; } // Data storage // Mainstore = new DataStore(true); if(!Mainstore) { Logger::Get()->Error("Engine: Init: failed to create main data store"); return false; } // Search data folder for files // MainFileHandler = new FileSystem(); if(!MainFileHandler) { Logger::Get()->Error("Engine: Init: failed to create FileSystem"); return false; } if(!MainFileHandler->Init(Logger::Get())) { Logger::Get()->Error("Engine: Init: failed to init FileSystem"); return false; } // File parsing // ObjectFileProcessor::Initialize(); // Main program wide event dispatcher // MainEvents = new EventHandler(); if(!MainEvents) { Logger::Get()->Error("Engine: Init: failed to create MainEvents"); return false; } if(!MainEvents->Init()) { Logger::Get()->Error("Engine: Init: failed to init MainEvents"); return false; } // Check is threading properly started // if(!_ThreadingManager->CheckInit()) { Logger::Get()->Error("Engine: Init: threading start failed"); return false; } // create script interface before renderer // std::promise<bool> ScriptInterfaceResult; // Ref is OK to use since this task finishes before this function // _ThreadingManager->QueueTask(std::make_shared<QueuedTask>(std::bind<void>( [](std::promise<bool>& returnvalue, Engine* engine) -> void { try { engine->MainScript = new ScriptExecutor(); } catch(const Exception&) { Logger::Get()->Error("Engine: Init: failed to create ScriptInterface"); returnvalue.set_value(false); return; } // create console after script engine // engine->MainConsole = new ScriptConsole(); if(!engine->MainConsole) { Logger::Get()->Error("Engine: Init: failed to create ScriptConsole"); returnvalue.set_value(false); return; } if(!engine->MainConsole->Init(engine->MainScript)) { Logger::Get()->Error("Engine: Init: failed to initialize Console, " "continuing anyway"); } returnvalue.set_value(true); }, std::ref(ScriptInterfaceResult), this))); // create newton manager before any newton resources are needed // std::promise<bool> NewtonManagerResult; // Ref is OK to use since this task finishes before this function // _ThreadingManager->QueueTask(std::make_shared<QueuedTask>(std::bind<void>( [](std::promise<bool>& returnvalue, Engine* engine) -> void { engine->_NewtonManager = new NewtonManager(); if(!engine->_NewtonManager) { Logger::Get()->Error("Engine: Init: failed to create NewtonManager"); returnvalue.set_value(false); return; } // next force application to load physical surface materials // engine->PhysMaterials = new PhysicsMaterialManager(engine->_NewtonManager); if(!engine->PhysMaterials) { Logger::Get()->Error("Engine: Init: failed to create PhysicsMaterialManager"); returnvalue.set_value(false); return; } engine->Owner->RegisterApplicationPhysicalMaterials(engine->PhysMaterials); returnvalue.set_value(true); }, std::ref(NewtonManagerResult), this))); // Create the default serializer // _EntitySerializer = std::make_unique<EntitySerializer>(); if(!_EntitySerializer) { Logger::Get()->Error("Engine: Init: failed to instantiate entity serializer"); return false; } // Check if we don't want a window // if(NoGui) { Logger::Get()->Info("Engine: Init: starting in console mode " "(won't allocate graphical objects) "); if(!_ConsoleInput->IsAttachedToConsole()) { Logger::Get()->Error( "Engine: Init: in nogui mode and no input terminal connected, " "quitting"); return false; } } else { ObjectFileProcessor::LoadValueFromNamedVars<int>( Define->GetValues(), "MaxFPS", FrameLimit, 120, Logger::Get(), "Graphics: Init:"); Graph = new Graphics(); } // We need to wait for all current tasks to finish // _ThreadingManager->WaitForAllTasksToFinish(); // Check return values // if(!ScriptInterfaceResult.get_future().get() || !NewtonManagerResult.get_future().get()) { Logger::Get()->Error("Engine: Init: one or more queued tasks failed"); return false; } // We can queue some more tasks // // create leap controller // #ifdef LEVIATHAN_USES_LEAP // Disable leap if in non-gui mode // if(NoGui) NoLeap = true; std::thread leapinitthread; if(!NoLeap) { Logger::Get()->Info("Engine: will try to create Leap motion connection"); // Seems that std::threads are joinable when constructed with default constructor leapinitthread = std::thread(std::bind<void>( [](Engine* engine) -> void { engine->LeapData = new LeapManager(engine); if(!engine->LeapData) { Logger::Get()->Error("Engine: Init: failed to create LeapManager"); return; } // try here just in case // try { if(!engine->LeapData->Init()) { Logger::Get()->Info( "Engine: Init: No Leap controller found, not using one"); } } catch(...) { // threw something // Logger::Get()->Error( "Engine: Init: Leap threw something, even without leap " "this shouldn't happen; continuing anyway"); } }, this)); } #endif // sound device // std::promise<bool> SoundDeviceResult; // Ref is OK to use since this task finishes before this function // _ThreadingManager->QueueTask(std::make_shared<QueuedTask>(std::bind<void>( [](std::promise<bool>& returnvalue, Engine* engine) -> void { if(!engine->NoGui) { engine->Sound = new SoundDevice(); if(!engine->Sound) { Logger::Get()->Error("Engine: Init: failed to create Sound"); returnvalue.set_value(false); return; } if(!engine->Sound->Init()) { Logger::Get()->Error( "Engine: Init: failed to init SoundDevice. Continuing anyway"); } } if(!engine->NoGui) { // measuring // engine->RenderTimer = new RenderingStatistics(); if(!engine->RenderTimer) { Logger::Get()->Error("Engine: Init: failed to create RenderingStatistics"); returnvalue.set_value(false); return; } } returnvalue.set_value(true); }, std::ref(SoundDeviceResult), this))); if(!NoGui) { if(!Graph) { Logger::Get()->Error("Engine: Init: failed to create instance of Graphics"); return false; } // call init // if(!Graph->Init(definition)) { Logger::Get()->Error("Failed to init Engine, Init graphics failed! Aborting"); return false; } // create window // GraphicalEntity1 = new Window(Graph, definition); } if(!SoundDeviceResult.get_future().get()) { Logger::Get()->Error("Engine: Init: sound device queued tasks failed"); return false; } #ifdef LEVIATHAN_USES_LEAP // We can probably assume here that leap creation has stalled if the thread is running // if(!NoLeap) { auto start = WantedClockType::now(); while(leapinitthread.joinable()) { auto elapsed = WantedClockType::now() - start; if(elapsed > std::chrono::milliseconds(150)) { Logger::Get()->Warning("LeapController creation would have stalled the game!"); Logger::Get()->Write("TODO: allow increasing wait period"); leapinitthread.detach(); break; } std::this_thread::sleep_for(std::chrono::milliseconds(5)); } } #endif PostLoad(); Logger::Get()->Info( "Engine init took " + Convert::ToString(Time::GetTimeMs64() - InitStartTime) + " ms"); return true; } void Engine::PostLoad() { // increase start count // int startcounts = 0; if(Mainstore->GetValueAndConvertTo<int>("StartCount", startcounts)) { // increase // Mainstore->SetValue("StartCount", new VariableBlock(new IntBlock(startcounts + 1))); } else { Mainstore->AddVar( std::make_shared<NamedVariableList>("StartCount", new VariableBlock(1))); // set as persistent // Mainstore->SetPersistance("StartCount", true); } // Check if we are attached to a terminal // ClearTimers(); // get time // LastTickTime = Time::GetTimeMs64(); ExecuteCommandLine(); // Run startup command line // _RunQueuedConsoleCommands(); } // ------------------------------------ // DLLEXPORT void Engine::PreRelease() { GUARD_LOCK(); if(PreReleaseWaiting || PreReleaseCompleted) return; PreReleaseWaiting = true; // This will stay true until the end of times // PreReleaseCompleted = true; // Stop command handling first // if(_ConsoleInput) { _ConsoleInput->Release(false); Logger::Get()->Info("Successfully stopped command handling"); } // Automatically destroy input sources // _NetworkHandler->ReleaseInputHandler(); // Then kill the network // { Lock lock(NetworkHandlerLock); _NetworkHandler->GetInterface()->CloseDown(); } // Let the game release it's resources // Owner->EnginePreShutdown(); // Close remote console // SAFE_DELETE(_RemoteConsole); // Close all connections // { Lock lock(NetworkHandlerLock); SAFE_RELEASEDEL(_NetworkHandler); } SAFE_RELEASEDEL(_ResourceRefreshHandler); // Set worlds to empty // { Lock lock(GameWorldsLock); for(auto iter = GameWorlds.begin(); iter != GameWorlds.end(); ++iter) { // Set all objects to release // (*iter)->MarkForClear(); } } // Set tasks to a proper state // _ThreadingManager->SetDiscardConditionalTasks(true); _ThreadingManager->SetDisallowRepeatingTasks(true); Logger::Get()->Info("Engine: prerelease done, waiting for a tick"); } void Engine::Release(bool forced) { GUARD_LOCK(); if(!forced) LEVIATHAN_ASSERT(PreReleaseDone, "PreReleaseDone must be done before actual release!"); // Force garbase collection // if(MainScript) MainScript->CollectGarbage(); // Make windows clear their stored objects // for(size_t i = 0; i < AdditionalGraphicalEntities.size(); i++) { AdditionalGraphicalEntities[i]->UnlinkAll(); } // Finally the main window // if(GraphicalEntity1) { GraphicalEntity1->UnlinkAll(); } // Destroy worlds // { Lock lock(GameWorldsLock); while(GameWorlds.size()) { GameWorlds[0]->Release(); GameWorlds.erase(GameWorlds.begin()); } } if(_NetworkHandler) _NetworkHandler->ShutdownCache(); // Wait for tasks to finish // if(!forced) _ThreadingManager->WaitForAllTasksToFinish(); // Destroy windows // for(size_t i = 0; i < AdditionalGraphicalEntities.size(); i++) { SAFE_DELETE(AdditionalGraphicalEntities[i]); } AdditionalGraphicalEntities.clear(); SAFE_DELETE(GraphicalEntity1); // Release newton // SAFE_DELETE(PhysMaterials); SAFE_DELETE(_NewtonManager); #ifdef LEVIATHAN_USES_LEAP SAFE_RELEASEDEL(LeapData); #endif // Console needs to be released before script release // SAFE_RELEASEDEL(MainConsole); SAFE_DELETE(MainScript); // Save at this point (just in case it crashes before exiting) // Logger::Get()->Save(); SAFE_DELETE(RenderTimer); _EntitySerializer.reset(); SAFE_RELEASEDEL(Sound); SAFE_DELETE(Mainstore); // If graphics aren't unregistered crashing will occur // _ThreadingManager->UnregisterGraphics(); // Stop threads // SAFE_RELEASEDEL(_ThreadingManager); SAFE_RELEASEDEL(Graph); SAFE_RELEASEDEL(MainEvents); // delete randomizer last, for obvious reasons // SAFE_DELETE(MainRandom); ObjectFileProcessor::Release(); SAFE_DELETE(MainFileHandler); // clears all running timers that might have accidentally been left running // TimingMonitor::ClearTimers(); // safe to delete this here // SAFE_DELETE(OutOMemory); SAFE_DELETE(IDDefaultInstance); Logger::Get()->Write("Goodbye cruel world!"); } // ------------------------------------ // DLLEXPORT void Engine::MessagePump() { Ogre::WindowEventUtilities::messagePump(); // CEF events (Also on windows as multi_threaded_message_loop makes rendering harder) GlobalCEFHandler::DoCEFMessageLoopWork(); SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: LOG_INFO("SDL_QUIT received, marked as closing"); MarkQuit(); break; case SDL_KEYDOWN: { Window* win = GetWindowFromSDLID(event.key.windowID); if(win) { // LOG_WRITE("SDL_KEYDOWN: " + Convert::ToString(event.key.keysym.sym)); win->InjectKeyDown(event); } break; } case SDL_KEYUP: { Window* win = GetWindowFromSDLID(event.key.windowID); if(win) { // LOG_WRITE("SDL_KEYUP: " + Convert::ToString(event.key.keysym.sym)); win->InjectKeyUp(event); } break; } case SDL_TEXTINPUT: { Window* win = GetWindowFromSDLID(event.text.windowID); if(win) { const auto text = std::string(event.text.text); // LOG_WRITE("TextInput: " + text); std::vector<uint32_t> codepoints; utf8::utf8to32( std::begin(text), std::end(text), std::back_inserter(codepoints)); // LOG_WRITE("Codepoints(" + Convert::ToString(codepoints.size()) + "): "); // for(auto codepoint : codepoints) // LOG_WRITE(" " + Convert::ToString(codepoint)); for(auto codepoint : codepoints) { win->InjectCodePoint(event); } } break; } // TODO: implement this // case SDL_TEXTEDITING: (https://wiki.libsdl.org/Tutorials/TextInput) case SDL_MOUSEBUTTONDOWN: { Window* win = GetWindowFromSDLID(event.button.windowID); if(win) win->InjectMouseButtonDown(event); break; } case SDL_MOUSEBUTTONUP: { Window* win = GetWindowFromSDLID(event.button.windowID); if(win) win->InjectMouseButtonUp(event); break; } case SDL_MOUSEMOTION: { Window* win = GetWindowFromSDLID(event.motion.windowID); if(win) win->InjectMouseMove(event); break; } case SDL_MOUSEWHEEL: { Window* win = GetWindowFromSDLID(event.motion.windowID); if(win) win->InjectMouseWheel(event); break; } case SDL_WINDOWEVENT: { switch(event.window.event) { case SDL_WINDOWEVENT_RESIZED: { Window* win = GetWindowFromSDLID(event.window.windowID); if(win) { int32_t width, height; win->GetSize(width, height); LOG_INFO("SDL window resize: " + Convert::ToString(width) + "x" + Convert::ToString(height)); win->OnResize(width, height); } break; } case SDL_WINDOWEVENT_CLOSE: { LOG_INFO("SDL window close"); Window* win = GetWindowFromSDLID(event.window.windowID); GUARD_LOCK(); // Detect closed windows // if(win == GraphicalEntity1) { // Window closed // ReportClosedWindow(guard, GraphicalEntity1); } for(size_t i = 0; i < AdditionalGraphicalEntities.size(); i++) { if(AdditionalGraphicalEntities[i] == win) { ReportClosedWindow(guard, AdditionalGraphicalEntities[i]); break; } } break; } case SDL_WINDOWEVENT_FOCUS_GAINED: { Window* win = GetWindowFromSDLID(event.window.windowID); if(win) win->OnFocusChange(true); break; } case SDL_WINDOWEVENT_FOCUS_LOST: { Window* win = GetWindowFromSDLID(event.window.windowID); if(win) win->OnFocusChange(false); break; } } } } } // CEF needs to be let handle the keyboard events now to make sure that they can be // dispatched to further on listeners GlobalCEFHandler::DoCEFMessageLoopWork(); // Reset input states // if(GraphicalEntity1) { // TODO: fix initial mouse position being incorrect GraphicalEntity1->InputEnd(); } for(auto iter = AdditionalGraphicalEntities.begin(); iter != AdditionalGraphicalEntities.end(); ++iter) { (*iter)->InputEnd(); } } DLLEXPORT Window* Engine::GetWindowFromSDLID(uint32_t sdlid) { if(GraphicalEntity1 && GraphicalEntity1->GetSDLID() == sdlid) { return GraphicalEntity1; } for(auto iter = AdditionalGraphicalEntities.begin(); iter != AdditionalGraphicalEntities.end(); ++iter) { if((*iter)->GetSDLID() == sdlid) { return *iter; } } return nullptr; } // ------------------------------------ // void Engine::Tick() { // Always try to update networking // { Lock lock(NetworkHandlerLock); if(_NetworkHandler) _NetworkHandler->UpdateAllConnections(); } // And handle invokes // ProcessInvokes(); GUARD_LOCK(); if(PreReleaseWaiting) { PreReleaseWaiting = false; PreReleaseDone = true; Logger::Get()->Info("Engine: performing final release tick"); // Call last tick event // return; } // Get the passed time since the last update // auto CurTime = Time::GetTimeMs64(); TimePassed = (int)(CurTime - LastTickTime); if((TimePassed < TICKSPEED)) { // It's not tick time yet // return; } LastTickTime += TICKSPEED; TickCount++; // Update input // #ifdef LEVIATHAN_USES_LEAP if(LeapData) LeapData->OnTick(TimePassed); #endif if(!NoGui) { // sound tick // if(Sound) Sound->Tick(TimePassed); // update windows // if(GraphicalEntity1) GraphicalEntity1->Tick(TimePassed); for(size_t i = 0; i < AdditionalGraphicalEntities.size(); i++) { AdditionalGraphicalEntities[i]->Tick(TimePassed); } } // Update worlds // { Lock lock(GameWorldsLock); // This will also update physics // auto end = GameWorlds.end(); for(auto iter = GameWorlds.begin(); iter != end; ++iter) { (*iter)->Tick(TickCount); } } // Some dark magic here // if(TickCount % 25 == 0) { // update values Mainstore->SetTickCount(TickCount); Mainstore->SetTickTime(TickTime); if(!NoGui) { // send updated rendering statistics // RenderTimer->ReportStats(Mainstore); } } // Update file listeners // if(_ResourceRefreshHandler) _ResourceRefreshHandler->CheckFileStatus(); // Send the tick event // if(MainEvents) MainEvents->CallEvent(new Event(EVENT_TYPE_TICK, new IntegerEventData(TickCount))); // Call the default app tick // Owner->Tick(TimePassed); TickTime = (int)(Time::GetTimeMs64() - CurTime); } DLLEXPORT void Engine::PreFirstTick() { GUARD_LOCK(); if(_ThreadingManager) _ThreadingManager->NotifyQueuerThread(); ClearTimers(); Logger::Get()->Info("Engine: PreFirstTick: everything fine to start running"); } // ------------------------------------ // void Engine::RenderFrame() { // We want to totally ignore this if we are in text mode // if(NoGui) return; int SinceLastFrame = -1; GUARD_LOCK(); // limit check // if(!RenderTimer->CanRenderNow(FrameLimit, SinceLastFrame)) { // fps would go too high // return; } // since last frame is in microseconds 10^-6 convert to milliseconds // // SinceLastTickTime is always more than 1000 (always 1 ms or more) // SinceLastFrame /= 1000; FrameCount++; // advanced statistic start monitoring // RenderTimer->RenderingStart(); MainEvents->CallEvent( new Event(EVENT_TYPE_FRAME_BEGIN, new IntegerEventData(SinceLastFrame))); // Calculate parameters for GameWorld frame rendering systems // int64_t timeintick = Time::GetTimeMs64() - LastTickTime; int moreticks = 0; while(timeintick > TICKSPEED) { timeintick -= TICKSPEED; moreticks++; } bool shouldrender = false; // Render // if(GraphicalEntity1 && GraphicalEntity1->Render(SinceLastFrame, TickCount + moreticks, static_cast<int>(timeintick))) shouldrender = true; for(size_t i = 0; i < AdditionalGraphicalEntities.size(); i++) { if(AdditionalGraphicalEntities[i]->Render( SinceLastFrame, TickCount + moreticks, static_cast<int>(timeintick))) shouldrender = true; } guard.unlock(); if(shouldrender) Graph->Frame(); guard.lock(); MainEvents->CallEvent(new Event(EVENT_TYPE_FRAME_END, new IntegerEventData(FrameCount))); // advanced statistics frame has ended // RenderTimer->RenderingEnd(); } // ------------------------------------ // DLLEXPORT void Engine::SaveScreenShot() { LEVIATHAN_ASSERT(!NoGui, "really shouldn't try to screenshot in text-only mode"); GUARD_LOCK(); const string fileprefix = MainFileHandler->GetDataFolder() + "Screenshots/Captured_frame_"; GraphicalEntity1->SaveScreenShot(fileprefix); } DLLEXPORT int Engine::GetWindowOpenCount() { int openwindows = 0; // If we are in text only mode always return 1 // if(NoGui) return 1; GUARD_LOCK(); // TODO: should there be an IsOpen method? if(GraphicalEntity1) openwindows++; for(size_t i = 0; i < AdditionalGraphicalEntities.size(); i++) { if(AdditionalGraphicalEntities[i]) openwindows++; } return openwindows; } // ------------------------------------ // DLLEXPORT Window* Engine::OpenNewWindow() { AppDef winparams; winparams.SetWindowDetails(WindowDataDetails("My Second window", 1280, 720, "no", Define->GetWindowDetails().VSync, // Opens on same display as the other window // TODO: open on next display Define->GetWindowDetails().DisplayNumber, Define->GetWindowDetails().FSAA, true, // no gamma false, #ifdef _WIN32 NULL, #endif NULL)); auto newwindow = std::make_unique<Window>(Graph, &winparams); GUARD_LOCK(); AdditionalGraphicalEntities.push_back(newwindow.get()); return newwindow.release(); } DLLEXPORT void Engine::ReportClosedWindow(Lock& guard, Window* windowentity) { windowentity->UnlinkAll(); if(GraphicalEntity1 == windowentity) { SAFE_DELETE(GraphicalEntity1); return; } for(size_t i = 0; i < AdditionalGraphicalEntities.size(); i++) { if(AdditionalGraphicalEntities[i] == windowentity) { SAFE_DELETE(AdditionalGraphicalEntities[i]); AdditionalGraphicalEntities.erase(AdditionalGraphicalEntities.begin() + i); return; } } // Didn't find the target // Logger::Get()->Error("Engine: couldn't find closing Window"); } DLLEXPORT void Engine::MarkQuit() { if(Owner) Owner->MarkAsClosing(); } // ------------------------------------ // DLLEXPORT void Engine::Invoke(const std::function<void()>& function) { RecursiveLock lock(InvokeLock); InvokeQueue.push_back(function); } DLLEXPORT void Engine::ProcessInvokes() { RecursiveLock lock(InvokeLock); while(!InvokeQueue.empty()) { const auto& func = InvokeQueue.front(); // Recursive mutex allows the invoke to call extra invokes func(); InvokeQueue.pop_front(); } } DLLEXPORT void Engine::RunOnMainThread(const std::function<void()>& function) { if(!IsOnMainThread()) { Invoke(function); } else { function(); } } // ------------------------------------ // DLLEXPORT std::shared_ptr<GameWorld> Engine::CreateWorld(Window* owningwindow, int worldtype) { auto tmp = GameWorldFactory::Get()->CreateNewWorld(worldtype); tmp->Init(_NetworkHandler->GetNetworkType(), NoGui ? nullptr : Graph->GetOgreRoot()); if(owningwindow) owningwindow->LinkObjects(tmp); Lock lock(GameWorldsLock); GameWorlds.push_back(tmp); return GameWorlds.back(); } DLLEXPORT void Engine::DestroyWorld(const shared_ptr<GameWorld>& world) { if(!world) return; // Release the world first // world->Release(); // Then delete it // Lock lock(GameWorldsLock); auto end = GameWorlds.end(); for(auto iter = GameWorlds.begin(); iter != end; ++iter) { if((*iter).get() == world.get()) { GameWorlds.erase(iter); return; } } } // ------------------------------------ // DLLEXPORT void Engine::ClearTimers() { Lock lock(GameWorldsLock); for(auto iter = GameWorlds.begin(); iter != GameWorlds.end(); ++iter) { } } // ------------------------------------ // void Engine::_NotifyThreadsRegisterOgre() { if(NoGui) return; // Register threads to use graphical objects // _ThreadingManager->MakeThreadsWorkWithOgre(); } // ------------------------------------ // DLLEXPORT int64_t Leviathan::Engine::GetTimeSinceLastTick() const { return Time::GetTimeMs64() - LastTickTime; } DLLEXPORT int Engine::GetCurrentTick() const { return TickCount; } // ------------------------------------ // void Engine::_AdjustTickClock(int amount, bool absolute /*= true*/) { GUARD_LOCK(); if(!absolute) { Logger::Get()->Info("Engine: adjusted tick timer by " + Convert::ToString(amount)); LastTickTime += amount; return; } // Calculate the time in the current last tick // int64_t templasttick = LastTickTime; int64_t curtime = Time::GetTimeMs64(); while(curtime - templasttick >= TICKSPEED) { templasttick += TICKSPEED; } // Check how far off we are from the target // int64_t intolasttick = curtime - templasttick; int changeamount = amount - static_cast<int>(intolasttick); Logger::Get()->Info("Engine: changing tick counter by " + Convert::ToString(changeamount)); LastTickTime += changeamount; } void Engine::_AdjustTickNumber(int tickamount, bool absolute) { GUARD_LOCK(); if(!absolute) { TickCount += tickamount; Logger::Get()->Info("Engine: adjusted tick by " + Convert::ToString(tickamount) + ", tick is now " + Convert::ToString(TickCount)); return; } TickCount = tickamount; Logger::Get()->Info("Engine: tick set to " + Convert::ToString(TickCount)); } // ------------------------------------ // int TestCrash(int writenum) { int* target = nullptr; (*target) = writenum; Logger::Get()->Write("It didn't crash..."); return 42; } bool Engine::ParseSingleCommand( StringIterator& itr, int& argindex, const int argcount, char* args[]) { // Split all flags and check for some flags that might be set // unique_ptr<string> splitval; while((splitval = itr.GetNextCharacterSequence<string>( UNNORMALCHARACTER_TYPE_WHITESPACE | UNNORMALCHARACTER_TYPE_CONTROLCHARACTERS)) != NULL) { if(*splitval == "--nogui") { NoGui = true; Logger::Get()->Info("Engine starting in non-GUI mode"); continue; } if(*splitval == "--noleap") { NoLeap = true; #ifdef LEVIATHAN_USES_LEAP Logger::Get()->Info("Engine starting with LeapMotion disabled"); #endif continue; } if(*splitval == "--nocin") { NoSTDInput = true; Logger::Get()->Info("Engine not listening for terminal commands"); continue; } if(*splitval == "--nonothing") { // Shouldn't try to open the console on windows // DEBUG_BREAK; } if(*splitval == "--crash") { Logger::Get()->Info("Engine testing crash handling"); // TODO: write a file that disables crash handling // Make the log say something useful // Logger::Get()->Save(); // Test crashing // TestCrash(12); continue; } if(*splitval == "--cmd" || *splitval == "cmd") { if(itr.GetCharacter() == '=') itr.MoveToNext(); auto cmd = itr.GetNextCharacterSequence<string>(UNNORMALCHARACTER_TYPE_WHITESPACE); if(!cmd || cmd->empty()) { if(argindex + 1 < argcount) { // Next argument is the command // ++argindex; cmd = std::make_unique<std::string>(args[argindex]); } else { LOG_ERROR("Engine: command line parsing failed, no command " "after '--cmd'"); continue; } } if(StringOperations::IsCharacterQuote(cmd->at(0))) { StringIterator itr2(cmd.get()); auto withoutquotes = itr2.GetStringInQuotes<std::string>(QUOTETYPE_BOTH); if(withoutquotes) { QueuedConsoleCommands.push_back(std::move(withoutquotes)); } else { LOG_WARNING("Engine: command line '--cmd' command in quotes is empty"); } } else { // cmd is the final command QueuedConsoleCommands.push_back(std::move(cmd)); } continue; } // Add (if not processed already) // PassedCommands.push_back(std::move(splitval)); } return true; } DLLEXPORT bool Engine::PassCommandLine(int argcount, char* args[]) { if(argcount < 1) return true; LOG_INFO("Engine: Command line: " + (args[0] ? std::string(args[0]) : std::string())); for(int i = 1; i < argcount; ++i) { LOG_WRITE("\t> " + (args[i] ? std::string(args[i]) : std::string())); } int argindex = 0; while(argindex < argcount) { if(!args[argindex]) { ++argindex; continue; } StringIterator itr(args[argindex]); while(!itr.IsOutOfBounds()) { if(!ParseSingleCommand(itr, argindex, argcount, args)) { return false; } } ++argindex; } return true; } DLLEXPORT void Engine::ExecuteCommandLine() { StringIterator itr; // Iterate over the commands and process them // for(size_t i = 0; i < PassedCommands.size(); i++) { itr.ReInit(PassedCommands[i].get()); // Skip the preceding '-'s // itr.SkipCharacters('-'); // Get the command // auto firstpart = itr.GetUntilNextCharacterOrAll<string>(':'); // Execute the wanted command // if(StringOperations::CompareInsensitive<string>(*firstpart, "RemoteConsole")) { // Get the next command // auto commandpart = itr.GetUntilNextCharacterOrAll<string>(L':'); if(*commandpart == "CloseIfNone") { // Set the command // _RemoteConsole->SetCloseIfNoRemoteConsole(true); Logger::Get()->Info("Engine will close when no active/waiting remote console " "sessions"); } else if(*commandpart == "OpenTo") { // Get the to part // auto topart = itr.GetStringInQuotes<string>(QUOTETYPE_BOTH); int token = 0; auto numberpart = itr.GetNextNumber<string>(DECIMALSEPARATORTYPE_NONE); if(numberpart->size() == 0) { Logger::Get()->Warning("Engine: ExecuteCommandLine: RemoteConsole: " "no token number provided"); continue; } // Convert to a real number. Maybe we could see if the token is // complex enough here, but that isn't necessary token = Convert::StringTo<int>(*numberpart); if(token == 0) { // Invalid number? // Logger::Get()->Warning("Engine: ExecuteCommandLine: RemoteConsole: " "couldn't parse token number, " + *numberpart); continue; } // Create a connection (or potentially use an existing one) // shared_ptr<Connection> tmpconnection = _NetworkHandler->OpenConnectionTo(*topart); // Tell remote console to open a command to it // if(tmpconnection) { _RemoteConsole->OfferConnectionTo(tmpconnection, "AutoOpen", token); } else { // Something funky happened... // Logger::Get()->Warning("Engine: ExecuteCommandLine: RemoteConsole: " "couldn't open connection to " + *topart + ", couldn't resolve address"); } } else { // Unknown command // Logger::Get()->Warning("Engine: ExecuteCommandLine: unknown RemoteConsole " "command: " + *commandpart + ", whole argument: " + *PassedCommands[i]); } } } PassedCommands.clear(); // Now we can set some things that require command line arguments // // _RemoteConsole might be NULL // if(_RemoteConsole) _RemoteConsole->SetAllowClose(); } // ------------------------------------ // void Engine::_RunQueuedConsoleCommands() { if(QueuedConsoleCommands.empty()) return; if(!MainConsole) { LOG_FATAL("Engine: MainConsole has not been created before running command line " "passed commands"); return; } LOG_INFO("Engine: Running PostStartup command line. Commands: " + Convert::ToString(QueuedConsoleCommands.size())); for(auto& command : QueuedConsoleCommands) { LOG_INFO("Engine: Running \"" + *command + "\""); MainConsole->RunConsoleCommand(*command); } QueuedConsoleCommands.clear(); } // ------------------------------------ // bool Engine::_ReceiveConsoleInput(const std::string& command) { Invoke([=]() { if(MainConsole) { MainConsole->RunConsoleCommand(command); } else { LOG_WARNING("No console handler attached, cannot run command"); } }); // Listening thread quits if PreReleaseWaiting is true return PreReleaseWaiting; } // ------------------------------------ //
26.851972
95
0.569403
Higami69
d0cd6570644307ee6ca3b39bee2ad5b4b1188256
737
cpp
C++
backends/mysql/row-id.cpp
staticlibs/lookaside_soci
b3326cff7d4cf2dc122179eb8b988f2521944550
[ "BSL-1.0" ]
null
null
null
backends/mysql/row-id.cpp
staticlibs/lookaside_soci
b3326cff7d4cf2dc122179eb8b988f2521944550
[ "BSL-1.0" ]
null
null
null
backends/mysql/row-id.cpp
staticlibs/lookaside_soci
b3326cff7d4cf2dc122179eb8b988f2521944550
[ "BSL-1.0" ]
null
null
null
// // Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton // MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski // 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) // #define SOCI_MYSQL_SOURCE #include "soci-mysql.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4355 4702) #endif using namespace soci; using namespace soci::details; mysql_rowid_backend::mysql_rowid_backend( mysql_session_backend & /* session */) { throw soci_error("RowIDs are not supported."); } mysql_rowid_backend::~mysql_rowid_backend() { } #ifdef _MSC_VER #pragma warning(pop) #endif
22.333333
64
0.723202
staticlibs
d0d06ffe811817925db4472422f345a36206e6dd
992
cpp
C++
CppStudio/Easy/01.cpp
vvhappyguy/Access-to-IT
1452c64f8c03addf6836a846af63123f65a9f620
[ "Apache-2.0" ]
null
null
null
CppStudio/Easy/01.cpp
vvhappyguy/Access-to-IT
1452c64f8c03addf6836a846af63123f65a9f620
[ "Apache-2.0" ]
null
null
null
CppStudio/Easy/01.cpp
vvhappyguy/Access-to-IT
1452c64f8c03addf6836a846af63123f65a9f620
[ "Apache-2.0" ]
null
null
null
// Compile with g++ (gcc ver. 8.2.0) // 1. Алгебраическая сумма // Найти Y, если Y = X1 + X2 + … + Xn, X = Z^3 - B + A^2 / tg^2?. // Количество X вводятся пользователем программы. // Для каждого X значения Z, B, А, ? разные (вводятся пользователем программы). // Input: count, count * (z, b, a, ?) // Output: (float) y #include <iostream> #include <cmath> using namespace std; int main() { size_t count = 0; cin >> count; float* z = new float; float* b = new float; float* a = new float; float* angle = new float; float* x_array = new float[count]; float* y = new float; for(size_t i = 0; i < count; i++) { cout << "Enter z, b, a, angle values: "; cin >> *z >> *b >> *a >> *angle; x_array[i] = pow(*z, 3) + pow(*a / tan(*angle),2) - *b; *y += x_array[i]; } cout << "Y = sum(x_array) = " << *y << endl; delete b; delete a; delete angle; delete y; delete []x_array; return 0; }
22.545455
79
0.530242
vvhappyguy
d0d80c2dd9e2f9dc31a403e16cb4b240da60ae72
8,862
cpp
C++
src/bkGL/renderable/background/GradientBackground.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
4
2018-12-08T15:35:38.000Z
2021-08-06T03:23:06.000Z
src/bkGL/renderable/background/GradientBackground.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
src/bkGL/renderable/background/GradientBackground.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018-2019 Benjamin Köhler * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <bkGL/renderable/background/GradientBackground.h> #include <bkGL/buffer/VBO.h> #include <bkGL/vao/VAO.h> #include <bkTools/color/ColorRGBA.h> namespace bk { //==================================================================================================== //===== MEMBERS //==================================================================================================== struct GradientBackground::Impl { color_type col_bottom_left; color_type col_top_right; bool vertical; Impl() : col_bottom_left(166.0 / 255.0, 197.0 / 255.0, 1), col_top_right(ColorRGBA::White()), vertical(true) { /* do nothing */ } Impl(const Impl&) = default; Impl(Impl&&) noexcept = default; ~Impl() = default; [[maybe_unused]] Impl& operator=(const Impl&) = default; [[maybe_unused]] Impl& operator=(Impl&&) noexcept = default; }; //==================================================================================================== //===== CONSTRUCTORS & DESTRUCTOR //==================================================================================================== /// @{ -------------------------------------------------- CTOR #ifndef BK_LIB_QT_AVAILABLE GradientBackground::GradientBackground() : base_type() #else GradientBackground::GradientBackground(bk::qt_gl_functions* gl) : base_type(gl) #endif { /* do nothing */ } GradientBackground::GradientBackground(self_type&&) noexcept = default; /// @} /// @{ -------------------------------------------------- DTOR GradientBackground::~GradientBackground() = default; /// @} //==================================================================================================== //===== GETTER //==================================================================================================== /// @{ -------------------------------------------------- GET COLOR auto GradientBackground::color_bottom_or_left() const -> const color_type& { return _pdata->col_bottom_left; } auto GradientBackground::color_top_or_right() const -> const color_type& { return _pdata->col_top_right; } /// @} //==================================================================================================== //===== SETTER //==================================================================================================== /// @{ -------------------------------------------------- OPERATOR = auto GradientBackground::operator=(self_type&& other) noexcept -> self_type& = default; /// @} /// @{ -------------------------------------------------- SET COLOR void GradientBackground::set_color_bottom_or_left(const color_type& col) { _pdata->col_bottom_left.set(col); } void GradientBackground::set_color_bottom_or_left(color_type&& col) { _pdata->col_bottom_left.set(std::move(col)); } void GradientBackground::set_color_bottom_or_left(double r, double g, double b, double a) { _pdata->col_bottom_left.set(r, g, b, a); } void GradientBackground::set_color_top_or_right(const color_type& col) { _pdata->col_top_right.set(col); } void GradientBackground::set_color_top_or_right(color_type&& col) { _pdata->col_top_right.set(std::move(col)); } void GradientBackground::set_color_top_or_right(double r, double g, double b, double a) { _pdata->col_top_right.set(r, g, b, a); } /// @} /// @{ -------------------------------------------------- SET VERTICAL / HORIZONTAL void GradientBackground::set_vertical() { _pdata->vertical = true; update_colors(); } void GradientBackground::set_horizontal() { _pdata->vertical = false; update_colors(); } /// @} /// @{ -------------------------------------------------- SET DEFAULT void GradientBackground::set_default_bk() { set_vertical(); set_color_bottom_or_left(166.0 / 255.0, 197.0 / 255.0, 1); set_color_top_or_right(ColorRGBA::White()); update_colors(); } void GradientBackground::set_default_gray_vertical() { set_vertical(); set_color_bottom_or_left(ColorRGBA::Dark_Gray()); set_color_top_or_right(ColorRGBA::Light_Gray()); update_colors(); } void GradientBackground::set_default_transparent() { set_vertical(); set_color_bottom_or_left(0, 0, 0, 0); set_color_top_or_right(0, 0, 0, 0); update_colors(); } /// @} //==================================================================================================== //===== FUNCTIONS //==================================================================================================== /// @{ -------------------------------------------------- INIT void GradientBackground::init_vbo_vao() { constexpr const unsigned int N = 24; /* vertex ordering: 2 ------ 3 |\ | | \ | | \ | | \ | 0 ------ 1 */ const GLfloat blr = static_cast<GLfloat>(_pdata->col_bottom_left[0]); const GLfloat blg = static_cast<GLfloat>(_pdata->col_bottom_left[1]); const GLfloat blb = static_cast<GLfloat>(_pdata->col_bottom_left[2]); const GLfloat bla = static_cast<GLfloat>(_pdata->col_bottom_left[3]); const GLfloat trr = static_cast<GLfloat>(_pdata->col_top_right[0]); const GLfloat trg = static_cast<GLfloat>(_pdata->col_top_right[1]); const GLfloat trb = static_cast<GLfloat>(_pdata->col_top_right[2]); const GLfloat tra = static_cast<GLfloat>(_pdata->col_top_right[3]); if (_pdata->vertical) { const GLfloat vertices_colors_interleaved[N] = { /*vert 0*/ -1, -1, /* col 0*/ blr, blg, blb, bla, /*vert 1*/ 1, -1, /* col 1*/ blr, blg, blb, bla, /*vert 2*/ -1, 1, /* col 2*/ trr, trg, trb, tra, /*vert 3*/ 1, 1, /* col 3*/ trr, trg, trb, tra}; vbo().init(vertices_colors_interleaved, N * sizeof(GLfloat)); } else { const GLfloat vertices_colors_interleaved[N] = { /*vert 0*/ -1, -1, /* col 0*/ blr, blg, blb, bla, /*vert 1*/ 1, -1, /* col 1*/ trr, trg, trb, tra, /*vert 2*/ -1, 1, /* col 2*/ blr, blg, blb, bla, /*vert 3*/ 1, 1, /* col 3*/ trr, trg, trb, tra}; vbo().init(vertices_colors_interleaved, N * sizeof(GLfloat)); } vao().init(vbo()); } /// @} /// @{ -------------------------------------------------- UPDATE void GradientBackground::update_colors() { bool do_update = false; if (this->is_initialized()) { GLfloat* x = vbo().map_write_only<GLfloat>(); if (x != nullptr) { constexpr unsigned int floatsPerVertex = 6; for (unsigned int k = 0; k < 4; ++k) { x[0 * floatsPerVertex + 2 + k] = static_cast<GLfloat>(_pdata->col_bottom_left[k]); x[1 * floatsPerVertex + 2 + k] = static_cast<GLfloat>(_pdata->vertical ? _pdata->col_top_right[k] : _pdata->col_bottom_left[k]); x[2 * floatsPerVertex + 2 + k] = static_cast<GLfloat>(_pdata->vertical ? _pdata->col_bottom_left[k] : _pdata->col_top_right[k]); x[3 * floatsPerVertex + 2 + k] = static_cast<GLfloat>(_pdata->col_top_right[k]); } vbo().unmap_and_release(); do_update = true; } } if (do_update) { this->emit_signal_update_required(); } } /// @} } // namespace bk
35.733871
146
0.50756
BenKoehler
d0daef4196825b138b51f73826452e2c82535665
339
cpp
C++
Tests/UnitTests/V2LibraryTests/Main.cpp
alexboukhvalova/CNTK
8835d4f61b393f068a4f019424bbc80c0b4e761a
[ "RSA-MD" ]
null
null
null
Tests/UnitTests/V2LibraryTests/Main.cpp
alexboukhvalova/CNTK
8835d4f61b393f068a4f019424bbc80c0b4e761a
[ "RSA-MD" ]
null
null
null
Tests/UnitTests/V2LibraryTests/Main.cpp
alexboukhvalova/CNTK
8835d4f61b393f068a4f019424bbc80c0b4e761a
[ "RSA-MD" ]
null
null
null
#include "CNTKLibrary.h" #include <functional> void NDArrayViewTests(); void TensorTests(); void FeedForwardTests(); void RecurrentFunctionTests(); int main() { NDArrayViewTests(); TensorTests(); FeedForwardTests(); RecurrentFunctionTests(); fprintf(stderr, "\nCNTKv2Library tests: Passed\n"); fflush(stderr); }
17.842105
55
0.707965
alexboukhvalova
d0db0219b4d358ebc924ef1e693d5c2ba21093fe
1,059
cpp
C++
N2195-Append-K-Integers-With-Minimal-Sum/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
null
null
null
N2195-Append-K-Integers-With-Minimal-Sum/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
null
null
null
N2195-Append-K-Integers-With-Minimal-Sum/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
2
2022-01-25T05:31:31.000Z
2022-02-26T07:22:23.000Z
// // main.cpp // LeetCode-Solution // // Created by Loyio Hex on 3/6/22. // #include <iostream> #include <chrono> #include <vector> #include <algorithm> using namespace std; using namespace std::chrono; class Solution { public: long long minimalKSum(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); int n = unique(nums.begin(), nums.end()) - nums.begin(); long long res = 0; for (int i = 0; i < n; ++i) { if (nums[i] <= k){ res += nums[i]; ++k; } } return (1LL + k)*k/2-res; } }; int main(int argc, const char * argv[]) { auto start = high_resolution_clock::now(); // Main Start vector<int> nums = {1,4,25,10,25}; int k = 2; Solution solution; cout << solution.minimalKSum(nums, k); // Main End auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << endl << "Runnig time : " << duration.count() << "ms;" << endl; return 0; }
21.18
74
0.543909
loyio
d0dba1faf3369258b378450c55f337b2ca2cd4f4
1,182
cpp
C++
source/Ch18/ch18.cpp
AttilaAV/UDProg-Introduction
791fe2120cfa3c47346e28cc588d06420842cf5f
[ "CC0-1.0" ]
null
null
null
source/Ch18/ch18.cpp
AttilaAV/UDProg-Introduction
791fe2120cfa3c47346e28cc588d06420842cf5f
[ "CC0-1.0" ]
null
null
null
source/Ch18/ch18.cpp
AttilaAV/UDProg-Introduction
791fe2120cfa3c47346e28cc588d06420842cf5f
[ "CC0-1.0" ]
null
null
null
#include "std_lib_facilities.h" class My_vector { private: long unsigned int sz; //meret double* elem; // memoria ter a free storeban public: My_vector(int s): sz(s), elem{new double[s]}//konstruktor, s = elem { for (int i = 0; i < s; ++i) elem[i] = 0; } My_vector(initializer_list<double> lst): sz{lst.size()}, elem{new double[sz]} { copy(lst.begin(), lst.end(), elem); } My_vector(const My_vector& arg) : sz{arg.sz}, elem{new double[arg.sz]} { copy(arg.elem, arg.elem+arg.sz, elem); } My_vector& operator=(const My_vector& arg) { double *p = new double[arg.sz]; copy(arg.elem, arg.elem+arg.sz, p); delete[] elem; elem = p; sz = arg.sz; return *this; } ~My_vector() { delete[] elem; } //destruktor double get(int n) const { return elem[n]; } void set(int n, double val) { elem[n] = val; } int size() const { return sz; } }; int main() { My_vector v2 { 12.2, 13.3, 14.4 }; for(int i = 0; i < v2.size(); ++i) cout << v2.get(i) << endl; My_vector v3 {v2}; for(int i = 0; i < v3.size(); ++i) cout << v3.get(i) << endl; My_vector v4(10); v4 = v3; for(int i = 0; i < v4.size(); ++i) cout << v4.get(i) << endl; return 0; }
20.033898
78
0.592217
AttilaAV
d0df595d79ff863b8d2ea1c27da613a0c3f178af
470
hpp
C++
src/console/ConsoleView.hpp
zer0main/bin_game_mvc
ddaddd598f417188e5b3d95c600b5775afbe2911
[ "MIT" ]
1
2015-03-13T15:46:42.000Z
2015-03-13T15:46:42.000Z
src/console/ConsoleView.hpp
zer0main/bin_game_mvc
ddaddd598f417188e5b3d95c600b5775afbe2911
[ "MIT" ]
4
2015-08-30T15:53:03.000Z
2016-02-27T20:03:22.000Z
src/console/ConsoleView.hpp
zer0main/bin_game_mvc
ddaddd598f417188e5b3d95c600b5775afbe2911
[ "MIT" ]
null
null
null
/* * Copyright (C) 2014-2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #ifndef IOBASE_HPP_ #define IOBASE_HPP_ #include "ConsoleBotView.hpp" class ConsoleView: public ConsoleBotView { protected: int getWinNumber_impl() const; int getDeskSize_impl() const; int getTimeNumber_impl() const; Points getIndex_impl() const; void output_impl() const; private: int getInitialParameter(TypeOfChecking type) const; }; #endif
15.666667
55
0.719149
zer0main
d0e22edc4f0be0882b37f5f96300b40e7b2344a2
9,310
hpp
C++
sampling/include/var_opt_union.hpp
FluorineDog/datasketches-cpp
8635abe98710f99cbcf0b64b85f5d0e416999f9b
[ "Apache-2.0" ]
64
2021-01-10T19:13:34.000Z
2022-03-29T00:31:02.000Z
sampling/include/var_opt_union.hpp
FluorineDog/datasketches-cpp
8635abe98710f99cbcf0b64b85f5d0e416999f9b
[ "Apache-2.0" ]
74
2021-01-04T18:43:50.000Z
2022-03-17T22:11:02.000Z
sampling/include/var_opt_union.hpp
FluorineDog/datasketches-cpp
8635abe98710f99cbcf0b64b85f5d0e416999f9b
[ "Apache-2.0" ]
26
2021-01-03T08:39:48.000Z
2022-03-29T00:31:07.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef _VAR_OPT_UNION_HPP_ #define _VAR_OPT_UNION_HPP_ #include "var_opt_sketch.hpp" #include "common_defs.hpp" #include "serde.hpp" #include <vector> namespace datasketches { template<typename A> using AllocU8 = typename std::allocator_traits<A>::template rebind_alloc<uint8_t>; /** * Provides a unioning operation over var_opt_sketch objects. This union allows * the sample size k to float, possibly increasing or decreasing as warranted by * the available data. * * The union currently allows serialization and deserialization, even though transporting * union objects seems to be an anti-pattern with most sketches. We currently provide it here * because the get_result() call may need to discard samples and decrease k in order to * return a valid sketch, even if future calls to update() would allow k to remain larger. * * The (de)serialization methods may be deprecated and subsequently removed in future versions. * * author Kevin Lang * author Jon Malkin */ template <typename T, typename S = serde<T>, typename A = std::allocator<T>> class var_opt_union { public: static const uint32_t MAX_K = ((uint32_t) 1 << 31) - 2; explicit var_opt_union(uint32_t max_k, const A& allocator = A()); var_opt_union(const var_opt_union& other); var_opt_union(var_opt_union&& other) noexcept; ~var_opt_union(); var_opt_union& operator=(const var_opt_union& other); var_opt_union& operator=(var_opt_union&& other); /** * Updates this union with the given sketch * This method takes an lvalue. * @param sk a sketch to add to the union */ void update(const var_opt_sketch<T,S,A>& sk); /** * Updates this union with the given sketch * This method takes an rvalue. * @param sk a sketch to add to the union */ void update(var_opt_sketch<T,S,A>&& sk); /** * Gets the varopt sketch resulting from the union of any input sketches. * @return a varopt sketch */ var_opt_sketch<T,S,A> get_result() const; /** * Resets the union to its default, empty state. */ void reset(); /** * Computes size needed to serialize the current state of the union. * This version is for all other types and can be expensive since every item needs to be looked at. * @return size in bytes needed to serialize this sketch */ size_t get_serialized_size_bytes() const; // This is a convenience alias for users // The type returned by the following serialize method typedef vector_u8<A> vector_bytes; /** * NOTE: This method may be deprecated in a future version. * This method serializes the sketch as a vector of bytes. * An optional header can be reserved in front of the sketch. * It is a blank space of a given size. * This header is used in Datasketches PostgreSQL extension. * @param header_size_bytes space to reserve in front of the sketch */ vector_bytes serialize(unsigned header_size_bytes = 0) const; /** * NOTE: This method may be deprecated in a future version. * This method serializes the sketch into a given stream in a binary form * @param os output stream */ void serialize(std::ostream& os) const; /** * NOTE: This method may be deprecated in a future version. * This method deserializes a union from a given stream. * @param is input stream * @return an instance of a union */ static var_opt_union deserialize(std::istream& is, const A& allocator = A()); /** * NOTE: This method may be deprecated in a future version. * This method deserializes a union from a given array of bytes. * @param bytes pointer to the array of bytes * @param size the size of the array * @return an instance of a union */ static var_opt_union deserialize(const void* bytes, size_t size, const A& allocator = A()); /** * Prints a summary of the union as a string. * @return the summary as a string */ string<A> to_string() const; private: typedef typename std::allocator_traits<A>::template rebind_alloc<var_opt_sketch<T,S,A>> AllocSketch; static const uint8_t PREAMBLE_LONGS_EMPTY = 1; static const uint8_t PREAMBLE_LONGS_NON_EMPTY = 4; static const uint8_t SER_VER = 2; static const uint8_t FAMILY_ID = 14; static const uint8_t EMPTY_FLAG_MASK = 4; uint64_t n_; // cumulative over all input sketches // outer tau is the largest tau of any input sketch double outer_tau_numer_; // total weight of all input R-zones where tau = outer_tau // total cardinality of the same R-zones, or zero if no input sketch was in estimation mode uint64_t outer_tau_denom_; uint32_t max_k_; var_opt_sketch<T,S,A> gadget_; var_opt_union(uint64_t n, double outer_tau_numer, uint64_t outer_tau_denom, uint32_t max_k, var_opt_sketch<T,S,A>&& gadget); /* IMPORTANT NOTE: the "gadget" in the union object appears to be a varopt sketch, but in fact is NOT because it doesn't satisfy the mathematical definition of a varopt sketch of the concatenated input streams. Therefore it could be different from a true varopt sketch with that value of K, in which case it could easily provide worse estimation accuracy for subset-sum queries. This should not surprise you; the approximation guarantees of varopt sketches do not apply to things that merely resemble varopt sketches. However, even though the gadget is not a varopt sketch, the result of the unioning process IS a varopt sketch. It is constructed by a somewhat complicated "resolution" process which determines the largest K that a valid varopt sketch could have given the available information, then constructs a varopt sketch of that size and returns it. However, the gadget itself is not touched during the resolution process, and additional sketches could subsequently be merged into the union, at which point a varopt result could again be requested. */ /* Explanation of "marked items" in the union's gadget: The boolean value "true" in an pair indicates that the item came from an input sketch's R zone, so it is already the result of sampling. Therefore it must not wind up in the H zone of the final result, because that would imply that the item is "exact". However, it is okay for a marked item to hang out in the gadget's H zone for a while. And once the item has moved to the gadget's R zone, the mark is never checked again, so no effort is made to ensure that its value is preserved or even makes sense. */ /* Note: if the computer could perform exact real-valued arithmetic, the union could finalize its result by reducing k until inner_tau > outer_tau. [Due to the vagaries of floating point arithmetic, we won't attempt to detect and specially handle the inner_tau = outer_tau special case.] In fact, we won't even look at tau while while reducing k. Instead the logic will be based on the more robust integer quantity num_marks_in_h_ in the gadget. It is conceivable that due to round-off error we could end up with inner_tau slightly less than outer_tau, but that should be fairly harmless since we will have achieved our goal of getting the marked items out of H. Also, you might be wondering why we are bothering to maintain the numerator and denominator separately instead of just having a single variable outer_tau. This allows us (in certain cases) to add an input's entire R-zone weight into the result sketch, as opposed to subdividing it then adding it back up. That would be a source of numerical inaccuracy. And even more importantly, this design choice allows us to exactly re-construct the input sketch when there is only one of them. */ inline void merge_items(const var_opt_sketch<T,S,A>& sk); inline void merge_items(var_opt_sketch<T,S,A>&& sk); inline void resolve_tau(const var_opt_sketch<T,S,A>& sketch); double get_outer_tau() const; var_opt_sketch<T,S,A> simple_gadget_coercer() const; bool there_exist_unmarked_h_items_lighter_than_target(double threshold) const; bool detect_and_handle_subcase_of_pseudo_exact(var_opt_sketch<T,S,A>& sk) const; void mark_moving_gadget_coercer(var_opt_sketch<T,S,A>& sk) const; void migrate_marked_items_by_decreasing_k(var_opt_sketch<T,S,A>& sk) const; static void check_preamble_longs(uint8_t preamble_longs, uint8_t flags); static void check_family_and_serialization_version(uint8_t family_id, uint8_t ser_ver); }; } #include "var_opt_union_impl.hpp" #endif // _VAR_OPT_UNION_HPP_
38.791667
103
0.741568
FluorineDog
d0e67e7e7610f19a824ea0280334139757ae2098
3,083
cpp
C++
UltraDV/Source/Editors/Source/TAudioPlayButton.cpp
ModeenF/UltraDV
30474c60880de541b33687c96293766fe0dc4aef
[ "Unlicense" ]
null
null
null
UltraDV/Source/Editors/Source/TAudioPlayButton.cpp
ModeenF/UltraDV
30474c60880de541b33687c96293766fe0dc4aef
[ "Unlicense" ]
null
null
null
UltraDV/Source/Editors/Source/TAudioPlayButton.cpp
ModeenF/UltraDV
30474c60880de541b33687c96293766fe0dc4aef
[ "Unlicense" ]
null
null
null
//--------------------------------------------------------------------- // // File: TAudioPlayButton.cpp // // Author: Gene Z. Ragan // // Date: 02.19.98 // /// Desc: Audio Editor Play button. Clicking cause adio file to be played // // Copyright ©1998 mediapede Software // //--------------------------------------------------------------------- // Includes #include "BuildApp.h" #include <app/Application.h> #include <support/Debug.h> #include "AppConstants.h" #include "AppMessages.h" #include "MuseumApp.h" #include "TAudioPlayButton.h" #include "TAudioEditorToolbar.h" // Constants //--------------------------------------------------------------------- // Constructor //--------------------------------------------------------------------- // // TAudioPlayButton::TAudioPlayButton(TAudioEditorToolbar *parent, BRect bounds, const char *name, BBitmap *offBitmap, BBitmap *onBitmap, BHandler *handler) : BView(bounds, name, B_FOLLOW_TOP | B_FOLLOW_LEFT, B_WILL_DRAW) { // Save parent view m_Parent = parent; // Save handler m_Handler = handler; // button state flag m_ButtonState = false; // Store bitmaps m_OffBitmap = offBitmap; m_OnBitmap = onBitmap; // Perform default initialization Init(); } //--------------------------------------------------------------------- // Destructor //--------------------------------------------------------------------- // // TAudioPlayButton::~TAudioPlayButton() { // Free data delete m_OffBitmap; delete m_OnBitmap; } //--------------------------------------------------------------------- // Init //--------------------------------------------------------------------- // // Perform default initialization tasks void TAudioPlayButton::Init() { } #pragma mark - #pragma mark === Drawing Routines === //--------------------------------------------------------------------- // Draw //--------------------------------------------------------------------- // // void TAudioPlayButton::Draw(BRect updateRect) { // Draw proper bitmap state, if m_State is true, draw on bitmap if (m_ButtonState) DrawBitmap(m_OffBitmap, B_ORIGIN); else DrawBitmap(m_OnBitmap, B_ORIGIN); } //--------------------------------------------------------------------- // MouseDown //--------------------------------------------------------------------- // // Handle mouse down events // void TAudioPlayButton::MouseDown(BPoint where) { // Set flag that we have been clicked. When the MouseUp method // is implimented we can remove this if (m_ButtonState) { // Tell sound to stop BMessage *message = new BMessage(AUDIO_STOP_BUTTON_MSG); //m_Parent->Window()->PostMessage(message, m_Handler); m_Parent->Window()->PostMessage(message, NULL); delete message; m_ButtonState = false; } else { // Tell sound to play BMessage *message = new BMessage(AUDIO_PLAY_BUTTON_MSG); //m_Parent->Window()->PostMessage(message, m_Handler); m_Parent->Window()->PostMessage(message, NULL); delete message; m_ButtonState = true; } // Force redraw to reflect new state Invalidate(); }
22.837037
218
0.507298
ModeenF
d0ea741e493e7c3f9ffb767068d03a266257d9b6
4,233
cpp
C++
src/components/Body.cpp
TheoVerhelst/Aphelion
357df0ba5542ce22dcff10c434aa4a20da0c1b17
[ "Beerware" ]
8
2022-01-18T09:58:21.000Z
2022-02-21T00:08:58.000Z
src/components/Body.cpp
TheoVerhelst/Aphelion
357df0ba5542ce22dcff10c434aa4a20da0c1b17
[ "Beerware" ]
null
null
null
src/components/Body.cpp
TheoVerhelst/Aphelion
357df0ba5542ce22dcff10c434aa4a20da0c1b17
[ "Beerware" ]
null
null
null
#include <algorithm> #include <components/Body.hpp> #include <Scene.hpp> Vector2f Body::localToWorld(const Vector2f& point) const { return rotate(point, rotation) + position; } Vector2f Body::worldToLocal(const Vector2f& point) const { return rotate(point - position, -rotation); } std::vector<Vector2f> Body::shadowTerminator(const Vector2f& lightSource, const Scene& scene, EntityId id) const { if (scene.hasComponent<CircleBody>(id)) { return scene.getComponent<CircleBody>(id).shadowTerminator(lightSource, *this); } else { return scene.getComponent<PolygonBody>(id).shadowTerminator(lightSource, *this); } } CircleBody::CircleBody(Body& body, float radius_): radius{radius_} { body.mass = pi * radius * radius * body.density; body.centerOfMass = {radius, radius}; body.momentOfInertia = body.mass * radius * radius / 2.f; } std::vector<Vector2f> CircleBody::shadowTerminator(const Vector2f& lightSource, const Body& body) const { // Get the left-sided normal vector Vector2f orthogonal{perpendicular(body.position - lightSource, true)}; orthogonal /= norm(orthogonal); return {body.position + orthogonal * radius, body.position - orthogonal * radius}; } PolygonBody::PolygonBody(Body& body, const std::vector<Vector2f>& vertices_): vertices{vertices_} { auto triangulation = earClipping(vertices); auto componentIndices = HertelMehlhorn(vertices, triangulation); for (std::vector<std::size_t>& indices : componentIndices) { std::vector<Vector2f> componentVertices; for (std::size_t index : indices) { componentVertices.push_back(vertices[index]); } components.emplace_back(componentVertices); } float area{0}; body.centerOfMass = {0, 0}; for (ConvexPolygon& component : components) { auto [compArea, compCenterOfMass] = component.areaAndCenterOfMass(); area += compArea; body.centerOfMass += compArea * compCenterOfMass; } body.centerOfMass /= area; body.mass = area * body.density; body.momentOfInertia = 0; for (ConvexPolygon& component : components) { body.momentOfInertia += component.momentOfInertia(body.density, body.centerOfMass); } } std::vector<Vector2f> PolygonBody::shadowTerminator(const Vector2f& lightSource, const Body& body) const { std::vector<float> angles(vertices.size()); std::vector<Vector2f> worldV; std::transform(vertices.begin(), vertices.end(), std::back_inserter(worldV), [&body] (const Vector2f& v) { return body.localToWorld(v - body.centerOfMass); } ); angles[0] = 0.f; const float angle0{angle(worldV[0] - lightSource)}; for (std::size_t i{1}; i < worldV.size(); ++i) { angles[i] = angle(worldV[i] - lightSource) - angle0; } // Find which vertices have the greatest and smallest angles. Greater angle // means the rightmost respective to the light source (since the y-axis goes // down). auto pair = std::minmax_element(angles.begin(), angles.end()); const Vector2f A{*(worldV.begin() + std::distance(angles.begin(), pair.first))}; const Vector2f B{*(worldV.begin() + std::distance(angles.begin(), pair.second))}; // We make an approximation of the correct list of shadow vertices. Instead // of going along the shape, we just return two points outside of the shape // that result in the correct projected shadow, and such that the terminator // is still perpendicular to the light ray. First, we compute the vector // normal to the light ray. const Vector2f n{perpendicular(body.position - lightSource, true)}; // Find the intersection between the normal vector and the light ray going // to A, and then to B auto [u, a] = intersection(body.position, body.position + n, lightSource, A); auto [v, b] = intersection(body.position, body.position + n, lightSource, B); return {body.position + n * u, body.position + n * v}; } Vector2f PolygonBody::supportFunction(const Vector2f& direction, const ConvexPolygon& component, const Body& body) { return body.localToWorld(component.supportFunction(rotate(direction, -body.rotation)) - body.centerOfMass); }
44.09375
116
0.692653
TheoVerhelst
d0f0a74641c2239c848319e4bef8d5b5795e416b
454
cpp
C++
src/single-number-ii.cpp
Liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
9
2015-09-09T20:28:31.000Z
2019-05-15T09:13:07.000Z
src/single-number-ii.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2015-02-25T13:10:09.000Z
2015-02-25T13:10:09.000Z
src/single-number-ii.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2016-08-31T19:14:52.000Z
2016-08-31T19:14:52.000Z
class Solution { public: int singleNumber(int A[], int n) { int Cnt[32]; memset(Cnt, 0, sizeof Cnt); for (int i=0; i<n; ++i) { for (int j=0; j<32; ++j) { if ((A[i] >> j)&1)Cnt[j]++; } } int ans = 0, base = 1; for (int i=0; i<32; ++i) { ans += Cnt[i]%3 * base; base *= 2; } return ans; } };
20.636364
43
0.334802
Liuchang0812
d0f2bc6b7e4ddddb2e12a2b2ec8955b9b07e238c
472
hpp
C++
components/net/cpp/include/ftl/net/common_fwd.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
4
2020-12-28T15:29:15.000Z
2021-06-27T12:37:15.000Z
components/net/cpp/include/ftl/net/common_fwd.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
null
null
null
components/net/cpp/include/ftl/net/common_fwd.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
2
2021-01-13T05:28:39.000Z
2021-05-04T03:37:11.000Z
/** * @file common_fwd.hpp * @copyright Copyright (c) 2020 University of Turku, MIT License * @author Nicolas Pope */ #ifndef _FTL_NET_COMMON_FORWARD_HPP_ #define _FTL_NET_COMMON_FORWARD_HPP_ #ifndef WIN32 #define INVALID_SOCKET -1 #define SOCKET int #else // WIN32 #if defined(_WIN64) typedef unsigned __int64 UINT_PTR; #else typedef unsigned int UINT_PTR, *PUINT_PTR; #endif typedef UINT_PTR SOCKET; #define INVALID_SOCKET (SOCKET)(~0) #endif #endif
16.857143
65
0.752119
knicos
d0f5417068a640c5d517c3f3d3d6422c3c4a3a91
384
cpp
C++
day.4-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day.4-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day.4-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
/* 显示逆向的值 */ #include <stdio.h> int main(void) { int num; do { printf("请输入一个正整数:"); scanf_s("%d", &num); if (num <= 0) puts("请不要输入非正整数:\a"); } while (num <= 0); printf("该正整数的逆向显示值是"); while (num > 10) { /*只要num大于10则重新再来一遍*/ printf("%d", num % 10); /* 是不是存在一个定理叫做余数优先输出,每次的余数都会先输出*/ num /= 10; } puts("。"); return 0; }
14.222222
61
0.494792
duasong111
d0fa089289f358a5f42f38645950e6dc092cef13
1,462
cpp
C++
phxrpc/network/uthread_context_base.cpp
bombshen/phxrpc
465db10bd4c4bf6d95f6e8b431cc7abcda731ffb
[ "BSD-3-Clause" ]
1,117
2017-08-02T06:03:59.000Z
2022-03-31T18:36:53.000Z
phxrpc/network/uthread_context_base.cpp
bombshen/phxrpc
465db10bd4c4bf6d95f6e8b431cc7abcda731ffb
[ "BSD-3-Clause" ]
31
2017-08-16T08:43:35.000Z
2021-02-13T22:49:25.000Z
phxrpc/network/uthread_context_base.cpp
bombshen/phxrpc
465db10bd4c4bf6d95f6e8b431cc7abcda731ffb
[ "BSD-3-Clause" ]
359
2017-08-04T07:32:41.000Z
2022-03-31T10:19:45.000Z
/* Tencent is pleased to support the open source community by making PhxRPC available. Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/BSD-3-Clause 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. See the AUTHORS file for names of contributors. */ #include "uthread_context_base.h" namespace phxrpc { ContextCreateFunc_t UThreadContext::context_create_func_ = nullptr; UThreadContext * UThreadContext :: Create(size_t stack_size, UThreadFunc_t func, void * args, UThreadDoneCallback_t callback, const bool need_stack_protect) { if (context_create_func_ != nullptr) { return context_create_func_(stack_size, func, args, callback, need_stack_protect); } return nullptr; } void UThreadContext :: SetContextCreateFunc(ContextCreateFunc_t context_create_func) { context_create_func_ = context_create_func; } ContextCreateFunc_t UThreadContext :: GetContextCreateFunc() { return context_create_func_; } } //namespace phxrpc
31.782609
90
0.777702
bombshen
cb9c16aaa260edc09765e6eade4bc609033f805a
2,010
cpp
C++
Source/EngineStd/GameAssetManager/Factory/Components/EngineObject/GameAssetEngineObject.cpp
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
2
2015-12-30T00:32:09.000Z
2016-02-27T14:50:06.000Z
Source/EngineStd/GameAssetManager/Factory/Components/EngineObject/GameAssetEngineObject.cpp
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
null
null
null
Source/EngineStd/GameAssetManager/Factory/Components/EngineObject/GameAssetEngineObject.cpp
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
null
null
null
// include engine headers #include "EngineStd.h" #include "GameAssetEngineObject.h" // constant const GameAssetType GameAssetEngineObject::g_Type = GAType_EngineObject; GameAssetEngineObject::GameAssetEngineObject(Context* context) : BaseComponent(context) { m_pNodeStaticModel = NULL; // Null static model } GameAssetEngineObject::GameAssetEngineObject() : BaseComponent() { m_pNodeStaticModel = NULL; // Null static model } GameAssetEngineObject::~GameAssetEngineObject() { } bool GameAssetEngineObject::VInit(const GameAsset* pGameAsset) { // Get Resource ResourceCache* resCache = g_pApp->GetConstantResCache(); FileSystem* filesystem = g_pApp->GetFileSystem(); // Set type and state to nothing for now m_GameAssetType = GAType_EngineObject; m_GameAssetState = GAState_None; // Set flag if(pGameAsset->IsPhysical()) { bPhysicalObject=true; PhysicalModel=pGameAsset->GetPhysicalModel(); } return true; } // Initialize void GameAssetEngineObject::Initialize(void) { // Get Attached node - preventing segfault problems Node * pThisNode = this->GetNode(); if(!pThisNode) { return; } // Get resource cache ResourceCache* resCache = g_pApp->GetConstantResCache(); // Is Physical if(bPhysicalObject) { // Create a model and string String ModelFile = String("Models/") + PhysicalModel+String(".mdl"); // create a static model m_pNodeStaticModel = pThisNode->CreateComponent<StaticModel>(Urho3D::CreateMode::LOCAL, pThisNode->GetID()); // Set model and force default material loading m_pNodeStaticModel->SetModel(resCache->GetResource<Model>(ModelFile)); m_pNodeStaticModel->ApplyMaterialList(); // Set Default paramet m_pNodeStaticModel->SetCastShadows(true); // Set Light Mask m_pNodeStaticModel->SetLightMask(1); // Default mask } return; }
24.814815
117
0.679104
vivienneanthony
cb9ed6eb6c491e024101733dc7485af57dd96468
260
cpp
C++
src/depricated_code/kmer_freq.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
22
2016-08-11T06:16:25.000Z
2022-02-22T00:06:59.000Z
src/depricated_code/kmer_freq.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
9
2016-12-08T12:42:38.000Z
2021-12-28T20:12:15.000Z
src/depricated_code/kmer_freq.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
8
2017-06-26T13:15:06.000Z
2021-11-12T18:39:54.000Z
#include "kmer_freq.h" #include "typdefine.h" namespace barcodeSpace{ kmers_freq::kmers_freq(kmer k, freq f):_key(k),_freq(f){} kmers_freq::kmers_freq(const kmers_freq& e){ this->_key = e._key; this->_freq = e._freq; } } // namespace barcodeSpace
21.666667
57
0.696154
LaoZZZZZ
cba3df8a91f2c24fac4a13346de48b1233f2063e
22,520
cc
C++
wrappers/8.1.1/vtkPointGaussianMapperWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkPointGaussianMapperWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkPointGaussianMapperWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkPolyDataMapperWrap.h" #include "vtkPointGaussianMapperWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkPiecewiseFunctionWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkPointGaussianMapperWrap::ptpl; VtkPointGaussianMapperWrap::VtkPointGaussianMapperWrap() { } VtkPointGaussianMapperWrap::VtkPointGaussianMapperWrap(vtkSmartPointer<vtkPointGaussianMapper> _native) { native = _native; } VtkPointGaussianMapperWrap::~VtkPointGaussianMapperWrap() { } void VtkPointGaussianMapperWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkPointGaussianMapper").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("PointGaussianMapper").ToLocalChecked(), ConstructorGetter); } void VtkPointGaussianMapperWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkPointGaussianMapperWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkPolyDataMapperWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkPolyDataMapperWrap::ptpl)); tpl->SetClassName(Nan::New("VtkPointGaussianMapperWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "EmissiveOff", EmissiveOff); Nan::SetPrototypeMethod(tpl, "emissiveOff", EmissiveOff); Nan::SetPrototypeMethod(tpl, "EmissiveOn", EmissiveOn); Nan::SetPrototypeMethod(tpl, "emissiveOn", EmissiveOn); Nan::SetPrototypeMethod(tpl, "GetEmissive", GetEmissive); Nan::SetPrototypeMethod(tpl, "getEmissive", GetEmissive); Nan::SetPrototypeMethod(tpl, "GetOpacityArray", GetOpacityArray); Nan::SetPrototypeMethod(tpl, "getOpacityArray", GetOpacityArray); Nan::SetPrototypeMethod(tpl, "GetOpacityArrayComponent", GetOpacityArrayComponent); Nan::SetPrototypeMethod(tpl, "getOpacityArrayComponent", GetOpacityArrayComponent); Nan::SetPrototypeMethod(tpl, "GetOpacityTableSize", GetOpacityTableSize); Nan::SetPrototypeMethod(tpl, "getOpacityTableSize", GetOpacityTableSize); Nan::SetPrototypeMethod(tpl, "GetScalarOpacityFunction", GetScalarOpacityFunction); Nan::SetPrototypeMethod(tpl, "getScalarOpacityFunction", GetScalarOpacityFunction); Nan::SetPrototypeMethod(tpl, "GetScaleArray", GetScaleArray); Nan::SetPrototypeMethod(tpl, "getScaleArray", GetScaleArray); Nan::SetPrototypeMethod(tpl, "GetScaleArrayComponent", GetScaleArrayComponent); Nan::SetPrototypeMethod(tpl, "getScaleArrayComponent", GetScaleArrayComponent); Nan::SetPrototypeMethod(tpl, "GetScaleFactor", GetScaleFactor); Nan::SetPrototypeMethod(tpl, "getScaleFactor", GetScaleFactor); Nan::SetPrototypeMethod(tpl, "GetScaleFunction", GetScaleFunction); Nan::SetPrototypeMethod(tpl, "getScaleFunction", GetScaleFunction); Nan::SetPrototypeMethod(tpl, "GetScaleTableSize", GetScaleTableSize); Nan::SetPrototypeMethod(tpl, "getScaleTableSize", GetScaleTableSize); Nan::SetPrototypeMethod(tpl, "GetSplatShaderCode", GetSplatShaderCode); Nan::SetPrototypeMethod(tpl, "getSplatShaderCode", GetSplatShaderCode); Nan::SetPrototypeMethod(tpl, "GetTriangleScale", GetTriangleScale); Nan::SetPrototypeMethod(tpl, "getTriangleScale", GetTriangleScale); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetEmissive", SetEmissive); Nan::SetPrototypeMethod(tpl, "setEmissive", SetEmissive); Nan::SetPrototypeMethod(tpl, "SetOpacityArray", SetOpacityArray); Nan::SetPrototypeMethod(tpl, "setOpacityArray", SetOpacityArray); Nan::SetPrototypeMethod(tpl, "SetOpacityArrayComponent", SetOpacityArrayComponent); Nan::SetPrototypeMethod(tpl, "setOpacityArrayComponent", SetOpacityArrayComponent); Nan::SetPrototypeMethod(tpl, "SetOpacityTableSize", SetOpacityTableSize); Nan::SetPrototypeMethod(tpl, "setOpacityTableSize", SetOpacityTableSize); Nan::SetPrototypeMethod(tpl, "SetScalarOpacityFunction", SetScalarOpacityFunction); Nan::SetPrototypeMethod(tpl, "setScalarOpacityFunction", SetScalarOpacityFunction); Nan::SetPrototypeMethod(tpl, "SetScaleArray", SetScaleArray); Nan::SetPrototypeMethod(tpl, "setScaleArray", SetScaleArray); Nan::SetPrototypeMethod(tpl, "SetScaleArrayComponent", SetScaleArrayComponent); Nan::SetPrototypeMethod(tpl, "setScaleArrayComponent", SetScaleArrayComponent); Nan::SetPrototypeMethod(tpl, "SetScaleFactor", SetScaleFactor); Nan::SetPrototypeMethod(tpl, "setScaleFactor", SetScaleFactor); Nan::SetPrototypeMethod(tpl, "SetScaleFunction", SetScaleFunction); Nan::SetPrototypeMethod(tpl, "setScaleFunction", SetScaleFunction); Nan::SetPrototypeMethod(tpl, "SetScaleTableSize", SetScaleTableSize); Nan::SetPrototypeMethod(tpl, "setScaleTableSize", SetScaleTableSize); Nan::SetPrototypeMethod(tpl, "SetSplatShaderCode", SetSplatShaderCode); Nan::SetPrototypeMethod(tpl, "setSplatShaderCode", SetSplatShaderCode); Nan::SetPrototypeMethod(tpl, "SetTriangleScale", SetTriangleScale); Nan::SetPrototypeMethod(tpl, "setTriangleScale", SetTriangleScale); #ifdef VTK_NODE_PLUS_VTKPOINTGAUSSIANMAPPERWRAP_INITPTPL VTK_NODE_PLUS_VTKPOINTGAUSSIANMAPPERWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkPointGaussianMapperWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkPointGaussianMapper> native = vtkSmartPointer<vtkPointGaussianMapper>::New(); VtkPointGaussianMapperWrap* obj = new VtkPointGaussianMapperWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkPointGaussianMapperWrap::EmissiveOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->EmissiveOff(); } void VtkPointGaussianMapperWrap::EmissiveOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->EmissiveOn(); } void VtkPointGaussianMapperWrap::GetEmissive(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetEmissive(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointGaussianMapperWrap::GetOpacityArray(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOpacityArray(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointGaussianMapperWrap::GetOpacityArrayComponent(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOpacityArrayComponent(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointGaussianMapperWrap::GetOpacityTableSize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOpacityTableSize(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointGaussianMapperWrap::GetScalarOpacityFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); vtkPiecewiseFunction * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetScalarOpacityFunction(); VtkPiecewiseFunctionWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkPiecewiseFunctionWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkPiecewiseFunctionWrap *w = new VtkPiecewiseFunctionWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkPointGaussianMapperWrap::GetScaleArray(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetScaleArray(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointGaussianMapperWrap::GetScaleArrayComponent(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetScaleArrayComponent(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointGaussianMapperWrap::GetScaleFactor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetScaleFactor(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointGaussianMapperWrap::GetScaleFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); vtkPiecewiseFunction * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetScaleFunction(); VtkPiecewiseFunctionWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkPiecewiseFunctionWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkPiecewiseFunctionWrap *w = new VtkPiecewiseFunctionWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkPointGaussianMapperWrap::GetScaleTableSize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetScaleTableSize(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointGaussianMapperWrap::GetSplatShaderCode(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetSplatShaderCode(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointGaussianMapperWrap::GetTriangleScale(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); float r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTriangleScale(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointGaussianMapperWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); vtkPointGaussianMapper * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkPointGaussianMapperWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkPointGaussianMapperWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkPointGaussianMapperWrap *w = new VtkPointGaussianMapperWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkPointGaussianMapperWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkPointGaussianMapper * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkPointGaussianMapperWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkPointGaussianMapperWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkPointGaussianMapperWrap *w = new VtkPointGaussianMapperWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetEmissive(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetEmissive( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetOpacityArray(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOpacityArray( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetOpacityArrayComponent(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOpacityArrayComponent( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetOpacityTableSize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOpacityTableSize( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetScalarOpacityFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPiecewiseFunctionWrap::ptpl))->HasInstance(info[0])) { VtkPiecewiseFunctionWrap *a0 = ObjectWrap::Unwrap<VtkPiecewiseFunctionWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetScalarOpacityFunction( (vtkPiecewiseFunction *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetScaleArray(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetScaleArray( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetScaleArrayComponent(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetScaleArrayComponent( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetScaleFactor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetScaleFactor( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetScaleFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPiecewiseFunctionWrap::ptpl))->HasInstance(info[0])) { VtkPiecewiseFunctionWrap *a0 = ObjectWrap::Unwrap<VtkPiecewiseFunctionWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetScaleFunction( (vtkPiecewiseFunction *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetScaleTableSize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetScaleTableSize( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetSplatShaderCode(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetSplatShaderCode( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointGaussianMapperWrap::SetTriangleScale(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointGaussianMapperWrap *wrapper = ObjectWrap::Unwrap<VtkPointGaussianMapperWrap>(info.Holder()); vtkPointGaussianMapper *native = (vtkPointGaussianMapper *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTriangleScale( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); }
33.915663
113
0.750533
axkibe
cba6c59ae0600f12106c1c68e82caa993e793c4d
718
hpp
C++
mod/money/old.hpp
WangYneos/bdlauncher
e5644cf732f0602fd4147d77c3be24f3daf8cf69
[ "MIT" ]
1
2020-01-29T15:59:25.000Z
2020-01-29T15:59:25.000Z
mod/money/old.hpp
WangYneos/bdlauncher
e5644cf732f0602fd4147d77c3be24f3daf8cf69
[ "MIT" ]
null
null
null
mod/money/old.hpp
WangYneos/bdlauncher
e5644cf732f0602fd4147d77c3be24f3daf8cf69
[ "MIT" ]
null
null
null
#include "seral.hpp" static void DO_DATA_CONVERT(const char *buf, int sz) { do_log("size %d", sz); DataStream ds; ds.dat = string(buf, sz); int length; ds >> length; for (int i = 0; i < length; ++i) { string key, val; ds >> key >> val; do_log("key %s val %d", key.c_str(), access(val.data(), int, 0)); db.Put(key, val); } } static void load() { // char *buf; // int sz; struct stat tmp; if (stat("data/money/money.db", &tmp) != -1) { FileBuffer fb("data/money/money.db"); DO_DATA_CONVERT(fb.data, fb.size); do_log("DATA CONVERT DONE;old:data/money/money.db.old"); link("data/money/money.db", "data/money/money.db.old"); unlink("data/money/money.db"); } }
27.615385
69
0.591922
WangYneos
cba965ff27aa6b873ff02190914b85e337a31444
9,876
cxx
C++
sources/raytracer/app.cxx
sergeyreznik/etx-tracer
e9941102daa5693af2a975e561022920a85826ef
[ "MIT" ]
180
2022-01-18T18:55:06.000Z
2022-03-21T14:24:39.000Z
sources/raytracer/app.cxx
sergeyreznik/etx-tracer
e9941102daa5693af2a975e561022920a85826ef
[ "MIT" ]
1
2022-02-25T14:05:49.000Z
2022-02-25T14:05:49.000Z
sources/raytracer/app.cxx
sergeyreznik/etx-tracer
e9941102daa5693af2a975e561022920a85826ef
[ "MIT" ]
7
2022-02-02T00:57:57.000Z
2022-02-22T15:53:15.000Z
#include <etx/core/environment.hxx> #include <etx/log/log.hxx> #include <etx/render/host/image_pool.hxx> #include <etx/render/shared/scene.hxx> #include "app.hxx" #include <tinyexr.hxx> #include <stb_image.hxx> #include <stb_image_write.hxx> namespace etx { RTApplication::RTApplication() : render(raytracing.scheduler()) , scene(raytracing.scheduler()) , camera_controller(scene.camera()) { } void RTApplication::init() { render.init(); ui.initialize(); ui.set_integrator_list(_integrator_array, std::size(_integrator_array)); ui.callbacks.reference_image_selected = std::bind(&RTApplication::on_referenece_image_selected, this, std::placeholders::_1); ui.callbacks.save_image_selected = std::bind(&RTApplication::on_save_image_selected, this, std::placeholders::_1, std::placeholders::_2); ui.callbacks.scene_file_selected = std::bind(&RTApplication::on_scene_file_selected, this, std::placeholders::_1); ui.callbacks.integrator_selected = std::bind(&RTApplication::on_integrator_selected, this, std::placeholders::_1); ui.callbacks.preview_selected = std::bind(&RTApplication::on_preview_selected, this); ui.callbacks.run_selected = std::bind(&RTApplication::on_run_selected, this); ui.callbacks.stop_selected = std::bind(&RTApplication::on_stop_selected, this, std::placeholders::_1); ui.callbacks.reload_scene_selected = std::bind(&RTApplication::on_reload_scene_selected, this); ui.callbacks.reload_geometry_selected = std::bind(&RTApplication::on_reload_geometry_selected, this); ui.callbacks.options_changed = std::bind(&RTApplication::on_options_changed, this); ui.callbacks.reload_integrator = std::bind(&RTApplication::on_reload_integrator_selected, this); _options.load_from_file(env().file_in_data("options.json")); if (_options.has("integrator") == false) { _options.add("integrator", "none"); } if (_options.has("scene") == false) { _options.add("scene", "none"); } if (_options.has("ref") == false) { _options.add("ref", "none"); } auto integrator = _options.get("integrator", std::string{}).name; for (uint64_t i = 0; (integrator.empty() == false) && (i < std::size(_integrator_array)); ++i) { ETX_ASSERT(_integrator_array[i] != nullptr); if (integrator == _integrator_array[i]->name()) { _current_integrator = _integrator_array[i]; } } ui.set_current_integrator(_current_integrator); _current_scene_file = _options.get("scene", std::string{}).name; if (_current_scene_file.empty() == false) { on_scene_file_selected(_current_scene_file); } auto ref = _options.get("ref", std::string{}).name; if (ref.empty() == false) { on_referenece_image_selected(ref); } } void RTApplication::save_options() { _options.save_to_file(env().file_in_data("options.json")); } void RTApplication::frame() { const float4* c_image = nullptr; const float4* l_image = nullptr; const char* status = "Not running"; bool can_change_camera = true; bool c_image_updated = false; bool l_image_updated = false; if (_current_integrator != nullptr) { _current_integrator->update(); status = _current_integrator->status(); if (_reset_images == false) { c_image_updated = _current_integrator->have_updated_camera_image(); c_image = _current_integrator->get_camera_image(false); l_image_updated = _current_integrator->have_updated_light_image(); l_image = _current_integrator->get_light_image(false); } can_change_camera = _current_integrator->state() == Integrator::State::Preview; } auto dt = time_measure.lap(); if (can_change_camera && camera_controller.update(dt) && (_current_integrator != nullptr)) { _current_integrator->preview(ui.integrator_options()); } render.set_view_options(ui.view_options()); render.start_frame(); if (_reset_images || c_image_updated) { render.update_camera_image(c_image); } if (_reset_images || l_image_updated) { render.update_light_image(l_image); } _reset_images = false; ui.build(dt, status); render.end_frame(); } void RTApplication::cleanup() { render.cleanup(); } void RTApplication::process_event(const sapp_event* e) { if (ui.handle_event(e) || (raytracing.has_scene() == false)) { return; } camera_controller.handle_event(e); } void RTApplication::load_scene_file(const std::string& file_name, uint32_t options, bool start_rendering) { _current_scene_file = file_name; log::warning("Loading scene %s...", _current_scene_file.c_str()); if (_current_integrator) { _current_integrator->stop(Integrator::Stop::Immediate); } _options.set("scene", _current_scene_file); save_options(); if (scene.load_from_file(_current_scene_file.c_str(), options) == false) { log::error("Failed to load scene from file: %s", _current_scene_file.c_str()); return; } raytracing.set_scene(scene.scene()); if (scene) { render.set_output_dimensions(scene.scene().camera.image_size); if (_current_integrator != nullptr) { if (start_rendering) { _current_integrator->run(ui.integrator_options()); } else { _current_integrator->set_output_size(scene.scene().camera.image_size); _current_integrator->preview(ui.integrator_options()); } } } } void RTApplication::on_referenece_image_selected(std::string file_name) { log::warning("Loading reference image %s...", file_name.c_str()); _options.set("ref", file_name); save_options(); render.set_reference_image(file_name.c_str()); } void RTApplication::on_save_image_selected(std::string file_name, SaveImageMode mode) { if (_current_integrator == nullptr) { return; } auto c_image = _current_integrator->get_camera_image(true); auto l_image = _current_integrator->get_light_image(true); uint2 image_size = {raytracing.scene().camera.image_size.x, raytracing.scene().camera.image_size.y}; std::vector<float4> output(image_size.x * image_size.y, float4{}); for (uint32_t i = 0, e = image_size.x * image_size.y; (c_image != nullptr) && (i < e); ++i) { output[i] = c_image[i]; } for (uint32_t i = 0, e = image_size.x * image_size.y; (l_image != nullptr) && (i < e); ++i) { output[i] += l_image[i]; } for (uint32_t i = 0, e = image_size.x * image_size.y; (mode != SaveImageMode::XYZ) && (i < e); ++i) { auto rgb = spectrum::xyz_to_rgb(to_float3(output[i])); output[i] = {rgb.x, rgb.y, rgb.z, 1.0f}; } if (mode == SaveImageMode::TonemappedLDR) { if (strlen(get_file_ext(file_name.c_str())) == 0) { file_name += ".png"; } float exposure = ui.view_options().exposure; std::vector<ubyte4> tonemapped(image_size.x * image_size.y); for (uint32_t i = 0, e = image_size.x * image_size.y; (mode != SaveImageMode::XYZ) && (i < e); ++i) { tonemapped[i].x = static_cast<uint8_t>(255.0f * saturate(powf(1.0f - expf(-exposure * output[i].x), 1.0f / 2.2f))); tonemapped[i].y = static_cast<uint8_t>(255.0f * saturate(powf(1.0f - expf(-exposure * output[i].y), 1.0f / 2.2f))); tonemapped[i].z = static_cast<uint8_t>(255.0f * saturate(powf(1.0f - expf(-exposure * output[i].z), 1.0f / 2.2f))); tonemapped[i].w = 255u; } if (stbi_write_png(file_name.c_str(), image_size.x, image_size.y, 4, tonemapped.data(), 0) != 1) { log::error("Failed to save PNG image to %s", file_name.c_str()); } } else { if (strlen(get_file_ext(file_name.c_str())) == 0) { file_name += ".exr"; } const char* error = nullptr; if (SaveEXR(reinterpret_cast<const float*>(output.data()), image_size.x, image_size.y, 4, false, file_name.c_str(), &error) != TINYEXR_SUCCESS) { log::error("Failed to save EXR image to %s: %s", file_name.c_str(), error); } } } void RTApplication::on_scene_file_selected(std::string file_name) { load_scene_file(file_name, SceneRepresentation::LoadEverything, false); } void RTApplication::on_integrator_selected(Integrator* i) { if (_current_integrator == i) { return; } _options.set("integrator", i->name()); save_options(); if (_current_integrator != nullptr) { _current_integrator->stop(Integrator::Stop::Immediate); } _current_integrator = i; ui.set_current_integrator(_current_integrator); if (scene) { _current_integrator->set_output_size(scene.scene().camera.image_size); _current_integrator->preview(ui.integrator_options()); } _reset_images = true; } void RTApplication::on_preview_selected() { ETX_ASSERT(_current_integrator != nullptr); _current_integrator->preview(ui.integrator_options()); } void RTApplication::on_run_selected() { ETX_ASSERT(_current_integrator != nullptr); _current_integrator->run(ui.integrator_options()); } void RTApplication::on_stop_selected(bool wait_for_completion) { ETX_ASSERT(_current_integrator != nullptr); _current_integrator->stop(wait_for_completion ? Integrator::Stop::WaitForCompletion : Integrator::Stop::Immediate); } void RTApplication::on_reload_scene_selected() { if (_current_scene_file.empty() == false) { bool start_render = (_current_integrator != nullptr) && (_current_integrator->state() == Integrator::State::Running); load_scene_file(_current_scene_file, SceneRepresentation::LoadEverything, start_render); } } void RTApplication::on_reload_geometry_selected() { if (_current_scene_file.empty() == false) { bool start_render = (_current_integrator != nullptr) && (_current_integrator->state() == Integrator::State::Running); load_scene_file(_current_scene_file, SceneRepresentation::LoadGeometry, start_render); } } void RTApplication::on_options_changed() { ETX_ASSERT(_current_integrator); _current_integrator->update_options(ui.integrator_options()); } void RTApplication::on_reload_integrator_selected() { ETX_ASSERT(_current_integrator); _current_integrator->reload(); } } // namespace etx
35.397849
149
0.7097
sergeyreznik
cbaab2c8157f0d39c3cd14474868a3b51b26ab03
24,849
cpp
C++
Views/albaViewSlice.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
Views/albaViewSlice.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Views/albaViewSlice.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: albaViewSlice Authors: Gianluigi Crimi, Paolo Quadrani , Stefano Perticoni , Josef Kohout Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ const bool DEBUG_MODE = false; #include "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "albaGUI.h" #include "albaIndent.h" #include "albaViewSlice.h" #include "albaPipeSurfaceSlice.h" #include "albaPipePolylineSlice.h" #include "albaPipeMeshSlice.h" #include "albaPipeSurfaceSlice.h" #include "albaPipePolylineSlice.h" #include "albaVME.h" #include "albaVMEVolume.h" #include "albaVMESlicer.h" #include "albaVMELandmarkCloud.h" #include "albaVMELandmark.h" #include "albaPipeFactory.h" #include "albaPipe.h" #include "albaRWI.h" #include "albaSceneGraph.h" #include "albaAttachCamera.h" #include "albaPipePolylineGraphEditor.h" #include "albaTransform.h" #include "albaAbsMatrixPipe.h" #include "vtkDataSet.h" #include "vtkALBARayCast3DPicker.h" #include "vtkCellPicker.h" #include "vtkPlaneSource.h" #include "vtkOutlineFilter.h" #include "vtkCoordinate.h" #include "vtkPolyDataMapper2D.h" #include "vtkProperty2D.h" #include "vtkActor2D.h" #include "vtkRenderer.h" #include "vtkTextMapper.h" #include "vtkTextProperty.h" #include "vtkCamera.h" #include "vtkTransform.h" //---------------------------------------------------------------------------- albaCxxTypeMacro(albaViewSlice); //---------------------------------------------------------------------------- #include "albaMemDbg.h" #include "albaPipeVolumeOrthoSlice.h" #include "albaPipeVolumeArbSlice.h" const int LAST_SLICE_ORIGIN_VALUE_NOT_INITIALIZED = 0; //---------------------------------------------------------------------------- albaViewSlice::albaViewSlice(wxString label /* = */, int camera_position /* = CAMERA_CT */, bool show_axes /* = false */, bool show_grid /* = false */, int stereo /* = 0 */,bool showTICKs/* =false */,bool textureInterpolate/* =true */) :albaViewVTK(label,camera_position,show_axes,show_grid, stereo) { m_CurrentVolume = NULL; m_Border = NULL; m_Slice[0] = m_Slice[1] = m_Slice[2] = 0.0; m_TextActor=NULL; m_TextMapper=NULL; m_TextColor[0]=1; m_TextColor[1]=0; m_TextColor[2]=0; m_ShowVolumeTICKs = showTICKs; m_TrilinearInterpolationOn = TRUE; m_TextureInterpolate = textureInterpolate; InitializeSlice(m_Slice); //to correctly set the normal m_SliceInitialized = false; //reset initialized to false } //---------------------------------------------------------------------------- albaViewSlice::~albaViewSlice() { BorderDelete(); vtkDEL(m_TextMapper); vtkDEL(m_TextActor); m_SlicingVector.clear(); } //---------------------------------------------------------------------------- albaView *albaViewSlice::Copy(albaObserver *Listener, bool lightCopyEnabled) { m_LightCopyEnabled = lightCopyEnabled; albaViewSlice *v = new albaViewSlice(m_Label, m_CameraPositionId, m_ShowAxes,m_ShowGrid, m_StereoType,m_ShowVolumeTICKs,m_TextureInterpolate); v->m_Listener = Listener; v->m_Id = m_Id; v->m_PipeMap = m_PipeMap; v->m_LightCopyEnabled = lightCopyEnabled; v->Create(); return v; } //---------------------------------------------------------------------------- void albaViewSlice::Create() { if(m_LightCopyEnabled) return; //COPY_LIGHT RWI_LAYERS num_layers = m_CameraPositionId != CAMERA_OS_P ? TWO_LAYER : ONE_LAYER; m_Rwi = new albaRWI(albaGetFrame(), num_layers, m_ShowGrid, m_ShowAxes, m_StereoType); m_Rwi->SetListener(this); m_Rwi->CameraSet(m_CameraPositionId); m_Win = m_Rwi->m_RwiBase; m_Sg = new albaSceneGraph(this,m_Rwi->m_RenFront,m_Rwi->m_RenBack,m_Rwi->m_AlwaysVisibleRenderer); m_Sg->SetListener(this); m_Rwi->m_Sg = m_Sg; vtkNEW(m_Picker3D); vtkNEW(m_Picker2D); m_Picker2D->SetTolerance(0.005); m_Picker2D->InitializePickList(); // text stuff m_Text = ""; m_TextMapper = vtkTextMapper::New(); m_TextMapper->SetInput(m_Text.c_str()); m_TextMapper->GetTextProperty()->AntiAliasingOff(); m_TextActor = vtkActor2D::New(); m_TextActor->SetMapper(m_TextMapper); m_TextActor->SetPosition(3,3); m_TextActor->GetProperty()->SetColor(m_TextColor); m_Rwi->m_RenFront->AddActor(m_TextActor); } //---------------------------------------------------------------------------- void albaViewSlice::SetTextColor(double color[3]) { m_TextColor[0]=color[0]; m_TextColor[1]=color[1]; m_TextColor[2]=color[2]; m_TextActor->GetProperty()->SetColor(m_TextColor); m_TextMapper->Modified(); } //---------------------------------------------------------------------------- void albaViewSlice::UpdateText(int ID) { if (m_TextMapper) { m_Text = ""; if (ID == 1) { switch (m_CameraPositionId) { case CAMERA_OS_X: m_Text = "X = "; m_Text += wxString::Format("%.1f", m_Slice[0]); break; case CAMERA_OS_Y: m_Text = "Y = "; m_Text += wxString::Format("%.1f", m_Slice[1]); break; case CAMERA_OS_Z: m_Text = "Z = "; m_Text += wxString::Format("%.1f", m_Slice[2]); break; default: break; } m_TextMapper->SetInput(m_Text.c_str()); m_TextMapper->Modified(); } else { m_Text = ""; m_TextMapper->SetInput(m_Text.c_str()); m_TextMapper->Modified(); } } } //---------------------------------------------------------------------------- void albaViewSlice::InitializeSlice(double* Origin) { memcpy(m_Slice, Origin, sizeof(m_Slice)); if (m_CameraPositionId == CAMERA_ARB) this->GetRWI()->GetCamera()->GetViewPlaneNormal(m_SliceNormal); else { m_SliceNormal[0] = m_SliceNormal[1] = m_SliceNormal[2] = 0.0; switch (m_CameraPositionId) { case CAMERA_OS_X: m_SliceNormal[0] = 1; break; case CAMERA_OS_Y: m_SliceNormal[1] = 1; break; //case CAMERA_OS_Z, CAMERA_OS_P default: m_SliceNormal[2] = 1; break; } } m_SliceInitialized = true; } //---------------------------------------------------------------------------- void albaViewSlice::VmeCreatePipe(albaVME *vme) { albaString pipe_name = ""; GetVisualPipeName(vme, pipe_name); albaSceneNode *n = m_Sg->Vme2Node(vme); assert(n && !n->GetPipe()); if (pipe_name != "") { m_NumberOfVisibleVme++; albaPipeFactory *pipe_factory = albaPipeFactory::GetInstance(); assert(pipe_factory!=NULL); albaObject *obj= NULL; obj = pipe_factory->CreateInstance(pipe_name); albaPipe *pipe = (albaPipe*)obj; if (pipe != NULL) { pipe->SetListener(this); if (pipe->IsA("albaPipeVolumeOrthoSlice")) { m_CurrentVolume = n; if (m_AttachCamera) m_AttachCamera->SetVme(m_CurrentVolume->GetVme()); int slice_mode; vtkDataSet *data = vme->GetOutput()->GetVTKData(); assert(data); data->Update(); switch(m_CameraPositionId) { case CAMERA_OS_X: slice_mode = albaPipeVolumeOrthoSlice::SLICE_X; break; case CAMERA_OS_Y: slice_mode = albaPipeVolumeOrthoSlice::SLICE_Y; break; case CAMERA_OS_P: slice_mode = albaPipeVolumeOrthoSlice::SLICE_ORTHO; break; default: slice_mode = albaPipeVolumeOrthoSlice::SLICE_Z; } if (m_SliceInitialized) { ((albaPipeVolumeOrthoSlice *)pipe)->InitializeSliceParameters(slice_mode, m_Slice, false,false,m_TextureInterpolate); ((albaPipeVolumeOrthoSlice *)pipe)->SetNormal(m_SliceNormal); } else { ((albaPipeVolumeOrthoSlice *)pipe)->InitializeSliceParameters(slice_mode,false,false,m_TextureInterpolate); } if(m_ShowVolumeTICKs) ((albaPipeVolumeOrthoSlice *)pipe)->ShowTICKsOn(); else ((albaPipeVolumeOrthoSlice *)pipe)->ShowTICKsOff(); ((albaPipeVolumeOrthoSlice *)pipe)->SetInterpolation(m_TrilinearInterpolationOn); UpdateText(); } else if (pipe->IsA("albaPipeVolumeArbSlice")) { m_CurrentVolume = n; if (m_AttachCamera) m_AttachCamera->SetVme(m_CurrentVolume->GetVme()); int slice_mode; vtkDataSet *data = vme->GetOutput()->GetVTKData(); assert(data); data->Update(); if (m_SliceInitialized) { ((albaPipeVolumeArbSlice *)pipe)->InitializeSliceParameters(m_Slice, false, false, m_TextureInterpolate); ((albaPipeVolumeArbSlice *)pipe)->SetNormal(m_SliceNormal); } else { ((albaPipeVolumeArbSlice *)pipe)->InitializeSliceParameters(false, false, m_TextureInterpolate); } if (m_ShowVolumeTICKs) ((albaPipeVolumeArbSlice *)pipe)->ShowTICKsOn(); else ((albaPipeVolumeArbSlice *)pipe)->ShowTICKsOff(); ((albaPipeVolumeArbSlice *)pipe)->SetTrilinearInterpolation(m_TrilinearInterpolationOn); UpdateText(); } else { //not a VolumeSlice pipe, check, if it is some slicer albaPipeSlice* spipe = albaPipeSlice::SafeDownCast(pipe); if (spipe != NULL) { albaPipeMeshSlice *meshPipe; if(pipe->IsA("albaPipePolylineGraphEditor")) { if(m_CameraPositionId==CAMERA_OS_P) ((albaPipePolylineGraphEditor *)pipe)->SetModalityPerspective(); else ((albaPipePolylineGraphEditor *)pipe)->SetModalitySlice(); } else if (meshPipe = albaPipeMeshSlice::SafeDownCast(pipe)) { if (m_CameraPositionId == CAMERA_OS_X) meshPipe->SetFlipNormalOff(); } //common stuff m_SlicingVector.push_back(n); double positionSlice[3]; positionSlice[0] = m_Slice[0]; positionSlice[1] = m_Slice[1]; positionSlice[2] = m_Slice[2]; MultiplyPointByInputVolumeABSMatrix(positionSlice); spipe->SetSlice(positionSlice, m_SliceNormal); } } //end else [it is not volume slicing] pipe->Create(n); } else albaErrorMessage("Cannot create visual pipe object of type \"%s\"!",pipe_name.GetCStr()); } } //---------------------------------------------------------------------------- void albaViewSlice::VmeDeletePipe(albaVME *vme) { albaSceneNode *n = m_Sg->Vme2Node(vme); m_NumberOfVisibleVme--; if (vme->GetOutput()->IsA("albaVMEOutputVolume")) { m_CurrentVolume = NULL; if (m_AttachCamera) { m_AttachCamera->SetVme(NULL); } } assert(n && n->GetPipe()); n->DeletePipe(); if(vme->IsALBAType(albaVMELandmark)) UpdateSurfacesList(vme); } //------------------------------------------------------------------------- int albaViewSlice::GetNodeStatus(albaVME *vme) { albaSceneNode *n = NULL; albaVMELandmark *lm = albaVMELandmark::SafeDownCast(vme); if (lm) { albaVMELandmarkCloud *lmc = albaVMELandmarkCloud::SafeDownCast(lm->GetParent()); if (lmc) { if ((m_Sg->GetNodeStatus(lmc) == NODE_VISIBLE_ON) && lmc->IsLandmarkShow(lm)) return NODE_VISIBLE_ON; } } if (m_Sg != NULL) { n = m_Sg->Vme2Node(vme); if (vme->GetOutput()->IsA("albaVMEOutputVolume") || vme->IsALBAType(albaVMESlicer)) { if (n != NULL) n->SetMutex(true); } else if (vme->IsALBAType(albaVMEImage)) { if (n != NULL) n->SetPipeCreatable(false); } } return m_Sg ? m_Sg->GetNodeStatus(vme) : NODE_NON_VISIBLE; } //------------------------------------------------------------------------- albaGUI *albaViewSlice::CreateGui() { assert(m_Gui == NULL); m_Gui = albaView::CreateGui(); m_AttachCamera = new albaAttachCamera(m_Gui, m_Rwi, this); m_Gui->AddGui(m_AttachCamera->GetGui()); // Added by Losi 11.25.2009 if (m_CurrentVolume) { albaPipeVolumeOrthoSlice *po = NULL; po = albaPipeVolumeOrthoSlice::SafeDownCast(this->GetNodePipe(m_CurrentVolume->GetVme())); if (po) // Is this required? po->SetInterpolation(m_TrilinearInterpolationOn); albaPipeVolumeArbSlice *pa = NULL; pa = albaPipeVolumeArbSlice::SafeDownCast(this->GetNodePipe(m_CurrentVolume->GetVme())); if (pa) // Is this required? pa->SetTrilinearInterpolation(m_TrilinearInterpolationOn); }; m_Gui->Divider(1); m_Gui->Bool(ID_TRILINEAR_INTERPOLATION, "Interpolation", &m_TrilinearInterpolationOn, 1); m_Gui->Divider(); return m_Gui; } //---------------------------------------------------------------------------- void albaViewSlice::OnEvent(albaEventBase *alba_event) { // Added by Losi 11.25.2009 if (albaEvent *e = albaEvent::SafeDownCast(alba_event)) { switch(alba_event->GetId()) { case ID_TRILINEAR_INTERPOLATION: { if (m_CurrentVolume) { albaPipeVolumeOrthoSlice *po = NULL; po = albaPipeVolumeOrthoSlice::SafeDownCast(this->GetNodePipe(m_CurrentVolume->GetVme())); if(po) { po->SetInterpolation(m_TrilinearInterpolationOn); this->CameraUpdate(); } albaPipeVolumeArbSlice *pa = NULL; pa = albaPipeVolumeArbSlice::SafeDownCast(this->GetNodePipe(m_CurrentVolume->GetVme())); if (pa) { pa->SetTrilinearInterpolation(m_TrilinearInterpolationOn); this->CameraUpdate(); } } } break; } } Superclass::OnEvent(alba_event); } //---------------------------------------------------------------------------- void albaViewSlice::SetLutRange(double low_val, double high_val) { if(!m_CurrentVolume) return; albaPipeVolumeOrthoSlice *pipeOrtho = albaPipeVolumeOrthoSlice::SafeDownCast(m_CurrentVolume->GetPipe()); if (pipeOrtho != NULL) { pipeOrtho->SetLutRange(low_val, high_val); } albaPipeVolumeArbSlice *pipeArb = albaPipeVolumeArbSlice::SafeDownCast(m_CurrentVolume->GetPipe()); if (pipeArb != NULL) { pipeArb->SetLutRange(low_val, high_val); } } //---------------------------------------------------------------------------- void albaViewSlice::SetSlice(double* Origin, double* Normal) { //set slice origin and normal if (Origin != NULL) memcpy(m_Slice, Origin, sizeof(double) * 3); if (Normal != NULL) memcpy(m_SliceNormal,Normal, sizeof(double) * 3); //and now set it for every VME if (m_CurrentVolume) { albaPipeSlice* pipe = albaPipeSlice::SafeDownCast(m_CurrentVolume->GetPipe()); if (pipe != NULL) pipe->SetSlice(Origin, NULL); } double coord[3]; coord[0]= m_Slice[0]; coord[1]= m_Slice[1]; coord[2]= m_Slice[2]; MultiplyPointByInputVolumeABSMatrix(coord); for(int i = 0; i < m_SlicingVector.size(); i++) { albaPipeSlice *pipe = albaPipeSlice::SafeDownCast(m_SlicingVector.at(i)->GetPipe()); if(pipe) pipe->SetSlice(coord, m_SliceNormal); } // update text this->UpdateText(); } //---------------------------------------------------------------------------- void albaViewSlice::SetSliceAxis(int sliceAxis) { switch (sliceAxis) { case 0: m_CameraPositionId = CAMERA_OS_X; break; case 1: m_CameraPositionId = CAMERA_OS_Y; break; case 2: m_CameraPositionId = CAMERA_OS_Z; break; default: m_CameraPositionId = CAMERA_OS_P; } if (m_CurrentVolume) { albaPipeVolumeOrthoSlice* pipe = albaPipeVolumeOrthoSlice::SafeDownCast(m_CurrentVolume->GetPipe()); if (pipe != NULL) pipe->SetSliceDirection(sliceAxis); } InitializeSlice(m_Slice); if(m_CurrentVolume) SetCameraParallelToDataSetLocalAxis(sliceAxis); } //---------------------------------------------------------------------------- void albaViewSlice::GetSlice(double* Origin, double* Normal) { if (Origin != NULL) memcpy(Origin, m_Slice, sizeof(m_Slice)); if (Normal != NULL) memcpy(Normal, m_SliceNormal, sizeof(m_SliceNormal)); } //---------------------------------------------------------------------------- void albaViewSlice::BorderUpdate() { if (NULL != m_Border) BorderCreate(m_BorderColor); } //---------------------------------------------------------------------------- void albaViewSlice::BorderCreate(double col[3]) { m_BorderColor[0] = col[0]; m_BorderColor[1] = col[1]; m_BorderColor[2] = col[2]; if(m_Border) BorderDelete(); int size[2]; this->GetWindow()->GetSize(&size[0],&size[1]); vtkPlaneSource *ps = vtkPlaneSource::New(); ps->SetOrigin(0, 0, 0); ps->SetPoint1(size[0]-1, 0, 0); ps->SetPoint2(0, size[1]-1, 0); vtkOutlineFilter *of = vtkOutlineFilter::New(); of->SetInput((vtkDataSet *)ps->GetOutput()); vtkCoordinate *coord = vtkCoordinate::New(); coord->SetCoordinateSystemToDisplay(); coord->SetValue(size[0]-1, size[1]-1, 0); vtkPolyDataMapper2D *pdmd = vtkPolyDataMapper2D::New(); pdmd->SetInput(of->GetOutput()); pdmd->SetTransformCoordinate(coord); vtkProperty2D *pd = vtkProperty2D::New(); pd->SetDisplayLocationToForeground(); pd->SetLineWidth(4); pd->SetColor(col[0],col[1],col[2]); m_Border = vtkActor2D::New(); m_Border->SetMapper(pdmd); m_Border->SetProperty(pd); m_Border->SetPosition(1,1); m_Rwi->m_RenFront->AddActor(m_Border); vtkDEL(ps); vtkDEL(of); vtkDEL(coord); vtkDEL(pdmd); vtkDEL(pd); } //---------------------------------------------------------------------------- void albaViewSlice::SetBorderOpacity(double value) { if(m_Border) { m_Border->GetProperty()->SetOpacity(value); m_Border->Modified(); } } //---------------------------------------------------------------------------- void albaViewSlice::BorderDelete() { if(m_Border) { m_Rwi->m_RenFront->RemoveActor(m_Border); vtkDEL(m_Border); } } //---------------------------------------------------------------------------- void albaViewSlice::UpdateSurfacesList(albaVME *vme) { albaSceneNode *sceneNode = m_Sg->Vme2Node(vme); for(int i=0;i<m_SlicingVector.size();i++) if (sceneNode== m_SlicingVector[i]) m_SlicingVector.erase(m_SlicingVector.begin()+i); } //---------------------------------------------------------------------------- void albaViewSlice::VmeShow(albaVME *vme, bool show) { if (vme->GetOutput()->IsA("albaVMEOutputVolume")) { if (show) { if(m_AttachCamera) m_AttachCamera->SetVme(vme); } else { if(m_AttachCamera) m_AttachCamera->SetVme(NULL); this->UpdateText(0); } } else this->UpdateSurfacesList(vme); Superclass::VmeShow(vme, show); } //---------------------------------------------------------------------------- void albaViewSlice::VmeRemove(albaVME *vme) { this->UpdateSurfacesList(vme); Superclass::VmeRemove(vme); } //------------------------------------------------------------------------- void albaViewSlice::Print(std::ostream& os, const int tabs)// const { albaIndent indent(tabs); os << indent << "albaViewSlice" << '\t' << this << std::endl; os << indent << "Name" << '\t' << m_Label << std::endl; os << std::endl; m_Sg->Print(os,1); } //------------------------------------------------------------------------- void albaViewSlice::MultiplyPointByInputVolumeABSMatrix(double *point) { if(m_CurrentVolume && m_CurrentVolume->GetVme()) { albaMatrix *mat = m_CurrentVolume->GetVme()->GetAbsMatrixPipe()->GetMatrixPointer(); double coord[4]; coord[0] = point[0]; coord[1] = point[1]; coord[2] = point[2]; double result[4]; vtkTransform *newT = vtkTransform::New(); newT->SetMatrix(mat->GetVTKMatrix()); newT->TransformPoint(coord, result); vtkDEL(newT); point[0] = result[0]; point[1] = result[1]; point[2] = result[2]; } } //------------------------------------------------------------------------- void albaViewSlice::CameraUpdate() { if (m_CurrentVolume) { albaVME *volume = m_CurrentVolume->GetVme(); std::ostringstream stringStream; stringStream << "VME " << volume->GetName() << " ABS matrix:" << std::endl; volume->GetAbsMatrixPipe()->GetMatrixPointer()->Print(stringStream); m_NewABSPose = volume->GetAbsMatrixPipe()->GetMatrix(); if (DEBUG_MODE == true) albaLogMessage(stringStream.str().c_str()); // Fix bug #2085: Added by Losi 05.11.2010 // Avoid pan & zoom reset while changing timestamp albaMatrix oldABSPoseForEquals; oldABSPoseForEquals.DeepCopy(&m_OldABSPose); oldABSPoseForEquals.SetTimeStamp(m_NewABSPose.GetTimeStamp()); if (m_NewABSPose.Equals(&oldABSPoseForEquals)) { if (DEBUG_MODE == true) albaLogMessage("Calling Superclass Camera Update "); Superclass::CameraUpdate(); } else { if (DEBUG_MODE == true) albaLogMessage("Calling Rotated Volumes Camera Update "); m_OldABSPose = m_NewABSPose; CameraUpdateForRotatedVolumes(); } } else { if (DEBUG_MODE == true) albaLogMessage("Calling Superclass Camera Update "); Superclass::CameraUpdate(); } } //------------------------------------------------------------------------- void albaViewSlice::SetCameraParallelToDataSetLocalAxis( int axis ) { double oldCameraPosition[3] = {0,0,0}; double oldCameraFocalPoint[3] = {0,0,0}; double *oldCameraOrientation; this->GetRWI()->GetCamera()->GetFocalPoint(oldCameraFocalPoint); this->GetRWI()->GetCamera()->GetPosition(oldCameraPosition); oldCameraOrientation = this->GetRWI()->GetCamera()->GetOrientation(); albaVME *currentVMEVolume = m_CurrentVolume->GetVme(); assert(currentVMEVolume); vtkDataSet *vmeVTKData = currentVMEVolume->GetOutput()->GetVTKData(); vtkMatrix4x4 *vmeABSMatrix = currentVMEVolume->GetAbsMatrixPipe()->GetMatrix().GetVTKMatrix(); double absDataBounds[6] = {0,0,0,0,0,0}; currentVMEVolume->GetOutput()->GetBounds(absDataBounds); double newCameraFocalPoint[3] = {0,0,0}; newCameraFocalPoint[0] = (absDataBounds[0] + absDataBounds[1]) / 2; newCameraFocalPoint[1] = (absDataBounds[2] + absDataBounds[3]) / 2; newCameraFocalPoint[2] = (absDataBounds[4] + absDataBounds[5]) / 2; double newCameraViewUp[3] = {0,0,0}; double newCameraPosition[3] = {0,0,0}; if (axis == albaTransform::X) { albaTransform::GetVersor(albaTransform::Z,albaMatrix(vmeABSMatrix),newCameraViewUp ); double xVersor[3] = {0,0,0}; albaTransform::GetVersor(albaTransform::X,albaMatrix(vmeABSMatrix),xVersor ); albaTransform::MultiplyVectorByScalar(100, xVersor, xVersor); albaTransform::AddVectors(newCameraFocalPoint, xVersor, newCameraPosition); } else if (axis == albaTransform::Y) { albaTransform::GetVersor(albaTransform::Z,albaMatrix(vmeABSMatrix),newCameraViewUp ); double yVersor[3] = {0,0,0}; albaTransform::GetVersor(albaTransform::Y,albaMatrix(vmeABSMatrix),yVersor ); albaTransform::MultiplyVectorByScalar(-100, yVersor, yVersor); albaTransform::AddVectors(newCameraFocalPoint, yVersor, newCameraPosition); } else if (axis == albaTransform::Z) { albaTransform::GetVersor(albaTransform::Y,albaMatrix(vmeABSMatrix),newCameraViewUp ); albaTransform::MultiplyVectorByScalar(-1, newCameraViewUp, newCameraViewUp); double zVersor[3] = {0,0,0}; albaTransform::GetVersor(albaTransform::Z,albaMatrix(vmeABSMatrix),zVersor ); albaTransform::MultiplyVectorByScalar(-100, zVersor, zVersor); albaTransform::AddVectors(newCameraFocalPoint, zVersor, newCameraPosition); } vtkCamera *camera = this->GetRWI()->GetCamera(); camera->SetFocalPoint(newCameraFocalPoint); camera->SetPosition(newCameraPosition); camera->SetViewUp(newCameraViewUp); camera->SetClippingRange(0.1,1000); } //------------------------------------------------------------------------- void albaViewSlice::CameraUpdateForRotatedVolumes() { int axis; if (m_CameraPositionId == CAMERA_OS_X) axis = albaTransform::X; else if (m_CameraPositionId == CAMERA_OS_Y) axis = albaTransform::Y; else //CAMERA_OS_Z, CAMERA_OS_P axis = albaTransform::Z; if (m_CurrentVolume != NULL) { SetCameraParallelToDataSetLocalAxis(axis); // needed to update surface slices during camera rotation if (m_SlicingVector.size() != 0) SetSlice(); this->CameraReset(m_CurrentVolume->GetVme()); } Superclass::CameraUpdate(); }
29.866587
237
0.612137
IOR-BIC
cbad50fee5543f1384dc04f2af0d42dff82d4a3d
2,329
hh
C++
tests/Titon/Debug/GlobalFunctionTest.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
206
2015-01-02T20:01:12.000Z
2021-04-15T09:49:56.000Z
tests/Titon/Debug/GlobalFunctionTest.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
44
2015-01-02T06:03:43.000Z
2017-11-20T18:29:06.000Z
tests/Titon/Debug/GlobalFunctionTest.hh
titon/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
27
2015-01-03T05:51:29.000Z
2022-02-21T13:50:40.000Z
<?hh namespace Titon\Debug; use Titon\Debug\Exception\FatalErrorException; use Titon\Test\TestCase; class GlobalFunctionTest extends TestCase { public function testBacktrace(): void { ob_start(); \backtrace(); $actual = ob_get_clean(); $this->assertRegExp('/^#01/', $actual); } public function testBacktraceNoReporting(): void { Debugger::disable(); ob_start(); \backtrace(); $actual = ob_get_clean(); $this->assertEquals('', $actual); Debugger::enable(); } public function testDebug(): void { ob_start(); \debug(1); $actual = ob_get_clean(); $this->assertRegExp('/^\[src\]/', $actual); } public function testDebugNoReporting(): void { Debugger::disable(); ob_start(); \debug(1); $actual = ob_get_clean(); $this->assertEquals('', $actual); Debugger::enable(); } public function testDump(): void { ob_start(); \dump(1); $actual = ob_get_clean(); $this->assertRegExp('/^\[src\]/', $actual); } public function testDumpNoReporting(): void { Debugger::disable(); ob_start(); \dump(1); $actual = ob_get_clean(); $this->assertEquals('', $actual); Debugger::enable(); } public function testInspect(): void { ob_start(); \inspect(new FatalErrorException('Systems critical!')); $actual = ob_get_clean(); $this->assertRegExp('/^Titon\\\\Debug\\\\Exception\\\\FatalErrorException/', $actual); } public function testInspectNoReporting(): void { Debugger::disable(); ob_start(); \inspect(new FatalErrorException('Systems critical!')); $actual = ob_get_clean(); $this->assertEquals('', $actual); Debugger::enable(); } public function testExport(): void { ob_start(); \export('foo'); $actual = ob_get_clean(); $this->assertEquals("'foo'", $actual); } public function testExportNoReporting(): void { Debugger::disable(); ob_start(); \export('foo'); $actual = ob_get_clean(); $this->assertEquals('', $actual); Debugger::enable(); } }
21.172727
94
0.548304
ciklon-z
cbae2186214d45ea9fecfd02224649243793213b
686
cpp
C++
int_utils.cpp
vaidyakhil/cpp-utils
4d89f5abd88a06e4169a18fccd4a738eb6518c3f
[ "MIT" ]
1
2022-03-06T11:12:32.000Z
2022-03-06T11:12:32.000Z
int_utils.cpp
vaidyakhil/cpp-utils
4d89f5abd88a06e4169a18fccd4a738eb6518c3f
[ "MIT" ]
null
null
null
int_utils.cpp
vaidyakhil/cpp-utils
4d89f5abd88a06e4169a18fccd4a738eb6518c3f
[ "MIT" ]
null
null
null
class IntUtils { public: int minm(int a, int b) { return a < b ? a : b; } int maxm(int a, int b) { return a < b ? b : a; } /* ** GCD(a, b, c) -> GCD (GCD(a, b), c); ** ** LCM (a, b) -> (a * b) / gcd(a, b); ** ** LCM (a, b, c) -> (LCM(a,b) * c)/ (GCD(a,b) * c) */ int gcd(int a, int b) { if (a < b) { return gcd(b, a); } if (b == 0) { return a; } return gcd(b, a%b); } /* ** Input string contains only digits */ int getInt(string s) { int res; for (char ch: s) { res = 10 * res + (ch - '0'); } return res; } };
16.731707
52
0.360058
vaidyakhil
cbb18905645cd009effc20de57401bb14e7a73ac
435
cpp
C++
6. Polymorphism/1. Function Overloading/1.NormalFunction.cpp
Imran4424/C-Plus-Plus-Object-Oriented
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
[ "MIT" ]
3
2019-11-06T15:43:06.000Z
2020-06-05T10:47:28.000Z
6. Polymorphism/1. Function Overloading/1.NormalFunction.cpp
Imran4424/C-Plus-Plus-Object-Oriented
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
[ "MIT" ]
null
null
null
6. Polymorphism/1. Function Overloading/1.NormalFunction.cpp
Imran4424/C-Plus-Plus-Object-Oriented
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
[ "MIT" ]
1
2019-09-06T03:37:08.000Z
2019-09-06T03:37:08.000Z
/* This code demonstrate the normal function calling */ #include <iostream> using namespace std; int Add(int a, int b) { return a + b; } int main(int argc, char const *argv[]) { cout << Add(3, 7) << endl; cout << Add(10, 7) << endl; cout << Add(10, 15) << endl; return 0; } /* This is a normal function calling it three times with different values this function takes two int values and return the sum(int type) */
14.032258
64
0.650575
Imran4424
cbb267f0fd7e1073d5aa59e8d0fd788dab4dcd76
1,565
cxx
C++
fluid/MainGui.cxx
Accessory/RocksDbViewer
9d3f45a826914a3cb4566087dd6c0f55c02213d5
[ "Apache-2.0" ]
null
null
null
fluid/MainGui.cxx
Accessory/RocksDbViewer
9d3f45a826914a3cb4566087dd6c0f55c02213d5
[ "Apache-2.0" ]
null
null
null
fluid/MainGui.cxx
Accessory/RocksDbViewer
9d3f45a826914a3cb4566087dd6c0f55c02213d5
[ "Apache-2.0" ]
null
null
null
// generated by Fast Light User Interface Designer (fluid) version 1.0308 #include "MainGui.h" Fl_Double_Window* MainGui::make_window() { { mainWindow = new Fl_Double_Window(995, 690, "RocksDbViewer"); mainWindow->user_data((void*)(this)); { Fl_Menu_Bar* o = new Fl_Menu_Bar(10, 0, 666, 26); o->box(FL_NO_BOX); o->color((Fl_Color)40); } // Fl_Menu_Bar* o { input_path = new Fl_Input(50, 25, 830, 30, "Path:"); } // Fl_Input* input_path { browser_column_families = new Fl_Browser(15, 100, 215, 545, "Column Familes"); browser_column_families->type(2); browser_column_families->align(Fl_Align(FL_ALIGN_TOP)); } // Fl_Browser* browser_column_families { browser_keys = new Fl_Browser(235, 100, 340, 545, "Keys"); browser_keys->type(2); browser_keys->align(Fl_Align(FL_ALIGN_TOP)); } // Fl_Browser* browser_keys { text_value = new Fl_Text_Display(580, 100, 410, 580); Fl_Group::current()->resizable(text_value); } // Fl_Text_Display* text_value { button_connect = new Fl_Light_Button(900, 25, 90, 30, "Connect"); } // Fl_Light_Button* button_connect { input_filter_column_families = new Fl_Input(50, 650, 180, 30, "Filter"); input_filter_column_families->when(FL_WHEN_CHANGED); } // Fl_Input* input_filter_column_families { input_filter_keys = new Fl_Input(275, 650, 300, 30, "Filter"); input_filter_keys->when(FL_WHEN_CHANGED); } // Fl_Input* input_filter_keys mainWindow->end(); } // Fl_Double_Window* mainWindow return mainWindow; }
42.297297
84
0.683706
Accessory
cbb38a4fb738734bc644bff79e44a6edebab0839
2,560
hpp
C++
libEPLViz/src/pluginEditor/PluginEditorBase.hpp
epl-viz/EPL-Viz
80d790110113f83da6845ce124997d13bfd45270
[ "BSD-3-Clause" ]
3
2017-01-23T13:29:21.000Z
2021-03-08T17:40:42.000Z
libEPLViz/src/pluginEditor/PluginEditorBase.hpp
epl-viz/EPL-Viz
80d790110113f83da6845ce124997d13bfd45270
[ "BSD-3-Clause" ]
4
2017-03-26T12:56:08.000Z
2017-08-18T20:32:37.000Z
libEPLViz/src/pluginEditor/PluginEditorBase.hpp
epl-viz/EPL-Viz
80d790110113f83da6845ce124997d13bfd45270
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017, EPL-Vizards * * 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 EPL-Vizards 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 EPL-Vizards BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*! * \file PluginEditorBase.hpp */ #pragma once #include "PluginEditorWidget.hpp" #include <QWidget> class PluginEditorBase : public QWidget { Q_OBJECT public: PluginEditorBase(PluginEditorWidget *parent) : QWidget(parent) {} ~PluginEditorBase() = default; public: virtual void updateStatusBar(bool enabled) = 0; virtual void openConfig() = 0; virtual void selectDocument(QString doc) = 0; virtual void closeDocument(QString name) = 0; virtual void openDocument(QUrl file) = 0; virtual void newDocument() = 0; virtual void cleanUp() = 0; virtual void save() = 0; virtual void saveAs() = 0; signals: void nameChanged(QString name); void urlChanged(QString url); void modifiedChanged(bool modified); void pluginsSaved(QMap<QString, QString> savedPlugins); private slots: virtual void modified() = 0; virtual void nameChange() = 0; virtual void urlChange() = 0; };
39.384615
83
0.710156
epl-viz
cbb5b6c382fb3c55e6bab6893e40d2dc4124df0a
5,883
cpp
C++
opt/qneptunea/harmattan/notification.cpp
qt-users-jp/qneptunea
5c45475590375df32c9c8dde5e677b66753a2eea
[ "BSD-3-Clause" ]
null
null
null
opt/qneptunea/harmattan/notification.cpp
qt-users-jp/qneptunea
5c45475590375df32c9c8dde5e677b66753a2eea
[ "BSD-3-Clause" ]
null
null
null
opt/qneptunea/harmattan/notification.cpp
qt-users-jp/qneptunea
5c45475590375df32c9c8dde5e677b66753a2eea
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2012-2013 QNeptunea Project. * 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 QNeptunea 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 QNEPTUNEA 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 "notification.h" #include <MNotification> #include <MGConfItem> #include <twitter4qml_global.h> class Notification::Private { public: Private(Notification *parent); bool publish(); bool remove(); private: Notification *q; public: QString eventType; QString summary; QString body; QString image; uint count; QString identifier; MNotification *notification; }; Notification::Private::Private(Notification *parent) : q(parent) , count(0) , notification(0) { } bool Notification::Private::publish() { if (notification) { notification->deleteLater(); notification = 0; } if (eventType == QLatin1String("qneptunea.mentions")) { MGConfItem conf("/apps/ControlPanel/QNeptunea/Notification/Mentions"); if (!conf.value().toBool()) return false; } if (eventType == QLatin1String("qneptunea.messages")) { MGConfItem conf("/apps/ControlPanel/QNeptunea/Notification/DirectMessages"); if (!conf.value().toBool()) return false; } if (eventType == QLatin1String("qneptunea.searches")) { MGConfItem conf("/apps/ControlPanel/QNeptunea/Notification/SavedSearches"); if (!conf.value().toBool()) return false; } notification = new MNotification(eventType); notification->setSummary(summary); notification->setBody(body); notification->setImage(image); notification->setCount(count); notification->setIdentifier(identifier); notification->setParent(q); MRemoteAction action("com.twitter", "/com/twitter", "com.twitter", identifier, QList<QVariant>()); notification->setAction(action); return notification->publish(); } bool Notification::Private::remove() { if (notification) { notification->remove(); return true; } return false; } Notification::Notification(QObject *parent) : QObject(parent) , d(new Private(this)) { } Notification::~Notification() { delete d; } const QString &Notification::eventType() const { return d->eventType; } void Notification::setEventType(const QString &eventType) { if (d->eventType == eventType) return; d->eventType = eventType; emit eventTypeChanged(eventType); } const QString &Notification::summary() const { return d->summary; } void Notification::setSummary(const QString &summary) { if (d->summary == summary) return; d->summary = summary; emit summaryChanged(summary); } const QString &Notification::body() const { return d->body; } void Notification::setBody(const QString &body) { if (d->body == body) return; d->body = body; emit bodyChanged(body); } const QString &Notification::image() const { return d->image; } void Notification::setImage(const QString &image) { if (d->image == image) return; d->image = image; emit imageChanged(image); } uint Notification::count() const { return d->count; } void Notification::setCount(uint count) { if (d->count == count) return; d->count = count; emit countChanged(count); } const QString &Notification::identifier() const { return d->identifier; } void Notification::setIdentifier(const QString &identifier) { if (d->identifier == identifier) return; d->identifier = identifier; emit identifierChanged(identifier); } bool Notification::publish() { return d->publish(); } bool Notification::remove() { return d->remove(); } bool Notification::isPublished() const { if (!d->notification) return false; return d->notification->isPublished(); } QList<QObject*> Notification::notifications() { QList<QObject*> ret; foreach (MNotification *mnotification, MNotification::notifications()) { Notification *notification = new Notification(this); notification->d->eventType = mnotification->eventType(); notification->d->summary = mnotification->summary(); notification->d->body = mnotification->body(); notification->d->image = mnotification->image(); notification->d->count = mnotification->count(); notification->d->identifier = mnotification->identifier(); notification->d->notification = mnotification; ret.append(notification); } return ret; }
26.381166
102
0.688594
qt-users-jp
cbbf6690e6432f0c3cc7568eb61cad1363761b23
27,456
hpp
C++
src/ArrayView.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
16
2020-07-10T00:04:08.000Z
2022-03-28T03:59:51.000Z
src/ArrayView.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
55
2020-06-30T06:26:49.000Z
2022-03-29T18:21:47.000Z
src/ArrayView.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
5
2021-02-03T02:00:20.000Z
2022-03-21T20:37:51.000Z
/* * Copyright (c) 2021, Lawrence Livermore National Security, LLC and LvArray contributors. * All rights reserved. * See the LICENSE file for details. * SPDX-License-Identifier: (BSD-3-Clause) */ /** * @file ArrayView.hpp * @brief Contains the implementation of LvArray::ArrayView. */ #pragma once // Source includes #include "ArraySlice.hpp" #include "Macros.hpp" #include "indexing.hpp" #include "limits.hpp" #include "sliceHelpers.hpp" #include "bufferManipulation.hpp" #include "umpireInterface.hpp" // System includes #if defined(LVARRAY_USE_TOTALVIEW_OUTPUT) && !defined(__CUDA_ARCH__) #include "totalview/tv_helpers.hpp" #include "totalview/tv_data_display.h" #endif namespace LvArray { /** * @class ArrayView * @brief This class serves to provide a "view" of a multidimensional array. * @tparam T type of data that is contained by the array * @tparam NDIM_TPARAM number of dimensions in array (e.g. NDIM=1->vector, NDIM=2->Matrix, etc. ). * @tparam USD the dimension with a unit stride, in an Array with a standard layout * this is the last dimension. * @tparam INDEX_TYPE the integer to use for indexing. * @tparam BUFFER_TYPE A class that defines how to actually allocate memory for the Array. Must take * one template argument that describes the type of the data being stored (T). * * @details When using the ChaiBuffer the copy copy constructor of this class calls the copy constructor for the * ChaiBuffer which will move the data to the location of the touch (host or device). In general, the * ArrayView should be what is passed by value into a lambda that is used to launch kernels as it * copy will trigger the desired data motion onto the appropriate memory space. * * Key features: * 1) When using a ChaiBuffer as the BUFFER_TYPE the ArrayView copy constructor will move the data * to the current execution space. * 2) Defines a slicing operator[]. * 3) Defines operator() array accessor. * 3) operator[] and operator() are all const and may be called in non-mutable lambdas. * 4) Conversion operators to go from ArrayView<T> to ArrayView<T const>. * 5) Since the Array is derived from ArrayView, it may be upcasted: * Array<T,NDIM> array; * ArrayView<T,NDIM> const & arrView = array; * * A good guideline is to upcast to an ArrayView when you don't need allocation capabilities that * are only present in Array. */ template< typename T, int NDIM_TPARAM, int USD_TPARAM, typename INDEX_TYPE, template< typename > class BUFFER_TYPE > class ArrayView { public: static_assert( NDIM_TPARAM > 0, "Number of dimensions must be greater than zero." ); static_assert( USD_TPARAM >= 0, "USD must be positive." ); static_assert( USD_TPARAM < NDIM_TPARAM, "USD must be less than NDIM." ); /// The type of the values in the ArrayView. using ValueType = T; /// The number of dimensions. static constexpr int NDIM = NDIM_TPARAM; /// The unit stride dimension. static constexpr int USD = USD_TPARAM; /// The integer type used for indexing. using IndexType = INDEX_TYPE; /// The type when all inner array classes are converted to const views. using NestedViewType = ArrayView< std::remove_reference_t< typeManipulation::NestedViewType< T > >, NDIM, USD, INDEX_TYPE, BUFFER_TYPE >; /// The type when all inner array classes are converted to const views and the inner most view's values are also const. using NestedViewTypeConst = ArrayView< std::remove_reference_t< typeManipulation::NestedViewTypeConst< T > >, NDIM, USD, INDEX_TYPE, BUFFER_TYPE >; /// The type of the ArrayView when converted to an ArraySlice. using SliceType = ArraySlice< T, NDIM, USD, INDEX_TYPE > const; /// The type of the ArrayView when converted to an immutable ArraySlice. using SliceTypeConst = ArraySlice< T const, NDIM, USD, INDEX_TYPE > const; /// The type of the values in the ArrayView, here for stl compatability. using value_type = T; /// The integer type used for indexing, here for stl compatability. using size_type = INDEX_TYPE; /** * @name Constructors, destructor and assignment operators. */ ///@{ /** * @brief A constructor to create an uninitialized ArrayView. * @note An uninitialized ArrayView should not be used until it is assigned to. */ ArrayView() = default; /** * @brief Copy Constructor. * @param source The object to copy. * @note Triggers the copy constructor for @tparam BUFFER_TYPE. When using the * ChaiBuffer this can move the underlying buffer to a new memory space if the execution context is set. */ DISABLE_HD_WARNING inline LVARRAY_HOST_DEVICE constexpr ArrayView( ArrayView const & source ) noexcept: m_dims{ source.m_dims }, m_strides{ source.m_strides }, m_dataBuffer{ source.m_dataBuffer, source.size() }, m_singleParameterResizeIndex( source.m_singleParameterResizeIndex ) {} /** * @brief Construct a new ArrayView from an ArrayView with a different type. * @tparam U The type to convert from. * @param source The ArrayView to convert. * @details If the size of @c T and @c U are different then either the size of @c T must be a * multiple of the size of @c U or vice versa. If the types have different size then size of the unit stride * dimension is changed accordingly. * @note This is useful for converting between single values and SIMD types such as CUDA's @c __half and @c __half2. * @code * Array< int, 2, RAJA::PERM_IJ, std::ptrdiff_t, MallocBuffer > x( 5, 10 ); * ArrayView< int[ 2 ], 2, 1, std::ptrdiff_t, MallocBuffer > y( x.toView() ); * assert( y.size( 1 ) == x.size( 1 ) / 2 ); * assert( y( 3, 4 )[ 0 ] == x( 3, 8 ) ); * @endcode */ template< typename U, typename=std::enable_if_t< !std::is_same< T, U >::value > > inline LVARRAY_HOST_DEVICE constexpr explicit ArrayView( ArrayView< U, NDIM, USD, INDEX_TYPE, BUFFER_TYPE > const & source ): m_dims{ source.dimsArray() }, m_strides{ source.stridesArray() }, m_dataBuffer{ source.dataBuffer() }, m_singleParameterResizeIndex( source.getSingleParameterResizeIndex() ) { m_dims[ USD ] = typeManipulation::convertSize< T, U >( m_dims[ USD ] ); for( int i = 0; i < NDIM; ++i ) { if( i != USD ) { m_strides[ i ] = typeManipulation::convertSize< T, U >( m_strides[ i ] ); } } } /** * @brief Move constructor, creates a shallow copy and invalidates the source. * @param source object to move. * @note Since this invalidates the source this should not be used when @p source is * the parent of an Array. Do not do this: * @code * Array< int, RAJA::PERM_I, std::ptrdiff_t, MallocBuffer > array( 10 ); * ArrayView< int, 1, 0, std::ptrdiff_t, MallocBuffer > view = std::move( array.toView() ); * @endcode * However this is ok: * @code * Array< int, RAJA::PERM_I, std::ptrdiff_t, MallocBuffer > array( 10 ); * ArrayView< int, 1, 0, std::ptrdiff_t, MallocBuffer > view = array.toView(); * ArrayView< int, 1, 0, std::ptrdiff_t, MallocBuffer > anotherView = std::move( view ); * @endcode */ ArrayView( ArrayView && source ) = default; /** * @brief Construct a new ArrayView from existing components. * @param dims The array of dimensions. * @param strides The array of strides. * @param singleParameterResizeIndex The single parameter resize index. * @param buffer The buffer to copy construct. */ inline LVARRAY_HOST_DEVICE constexpr explicit ArrayView( typeManipulation::CArray< INDEX_TYPE, NDIM > const & dims, typeManipulation::CArray< INDEX_TYPE, NDIM > const & strides, int const singleParameterResizeIndex, BUFFER_TYPE< T > const & buffer ): m_dims( dims ), m_strides( strides ), m_dataBuffer( buffer ), m_singleParameterResizeIndex( singleParameterResizeIndex ) {} /// The default destructor. ~ArrayView() = default; /** * @brief Move assignment operator, creates a shallow copy and invalidates the source. * @param rhs The object to copy. * @return *this. * @note Since this invalidates the source this should not be used when @p rhs is * the parent of an Array. Do not do this: * @code * Array< int, RAJA::PERM_I, std::ptrdiff_t, MallocBuffer > array( 10 ); * ArrayView< int, 1, 0, std::ptrdiff_t, MallocBuffer > view; * view = std::move( array.toView() ); * @endcode * However this is ok: * @code * Array< int, RAJA::PERM_I, std::ptrdiff_t, MallocBuffer > array( 10 ); * ArrayView< int, 1, 0, std::ptrdiff_t, MallocBuffer > view = array.toView(); * ArrayView< int, 1, 0, std::ptrdiff_t, MallocBuffer > anotherView; * anotherView = std::move( view ); * @endcode */ inline LVARRAY_HOST_DEVICE LVARRAY_INTEL_CONSTEXPR ArrayView & operator=( ArrayView && rhs ) { m_dataBuffer = std::move( rhs.m_dataBuffer ); m_singleParameterResizeIndex = rhs.m_singleParameterResizeIndex; for( int i = 0; i < NDIM; ++i ) { m_dims[ i ] = rhs.m_dims[ i ]; m_strides[ i ] = rhs.m_strides[ i ]; } return *this; } /** * @brief Copy assignment operator, creates a shallow copy. * @param rhs object to copy. * @return *this */ inline LVARRAY_INTEL_CONSTEXPR ArrayView & operator=( ArrayView const & rhs ) noexcept { m_dataBuffer = rhs.m_dataBuffer; m_singleParameterResizeIndex = rhs.m_singleParameterResizeIndex; for( int i = 0; i < NDIM; ++i ) { m_dims[ i ] = rhs.m_dims[ i ]; m_strides[ i ] = rhs.m_strides[ i ]; } return *this; } ///@} /** * @name ArrayView and ArraySlice creation methods and user defined conversions. */ ///@{ /** * @return Return a new ArrayView. */ inline LVARRAY_HOST_DEVICE constexpr ArrayView toView() const & { return ArrayView( m_dims, m_strides, m_singleParameterResizeIndex, m_dataBuffer ); } /** * @return Return a new ArrayView where @c T is @c const. */ inline LVARRAY_HOST_DEVICE constexpr ArrayView< T const, NDIM, USD, INDEX_TYPE, BUFFER_TYPE > toViewConst() const & { return ArrayView< T const, NDIM, USD, INDEX_TYPE, BUFFER_TYPE >( m_dims, m_strides, m_singleParameterResizeIndex, m_dataBuffer ); } /** * @brief @return Return *this after converting any nested arrays to const views. */ inline LVARRAY_HOST_DEVICE constexpr NestedViewType toNestedView() const & { return reinterpret_cast< NestedViewType const & >( *this ); } /** * @brief @return Return *this after converting any nested arrays to const views to const values. */ inline LVARRAY_HOST_DEVICE constexpr NestedViewTypeConst toNestedViewConst() const & { return reinterpret_cast< NestedViewTypeConst const & >( *this ); } /** * @return Return an ArraySlice representing this ArrayView. */ inline LVARRAY_HOST_DEVICE constexpr ArraySlice< T, NDIM, USD, INDEX_TYPE > toSlice() const & noexcept { return ArraySlice< T, NDIM, USD, INDEX_TYPE >( data(), m_dims.data, m_strides.data ); } /** * @brief Overload for rvalues that is deleted. * @return A null ArraySlice. * @note This cannot be called on a rvalue since the @c ArraySlice would * contain pointers to the dims and strides of the current @c ArrayView that is * about to be destroyed. This overload prevents that from happening. */ inline LVARRAY_HOST_DEVICE constexpr ArraySlice< T, NDIM, USD, INDEX_TYPE > toSlice() const && noexcept = delete; /** * @return Return an immutable ArraySlice representing this ArrayView. */ inline LVARRAY_HOST_DEVICE constexpr ArraySlice< T const, NDIM, USD, INDEX_TYPE > toSliceConst() const & noexcept { return ArraySlice< T const, NDIM, USD, INDEX_TYPE >( data(), m_dims.data, m_strides.data ); } /** * @brief Overload for rvalues that is deleted. * @return A null ArraySlice. * @brief This cannot be called on a rvalue since the @c ArraySlice would * contain pointers to the dims and strides of the current @c ArrayView that is * about to be destroyed. This overload prevents that from happening. */ inline LVARRAY_HOST_DEVICE constexpr ArraySlice< T const, NDIM, USD, INDEX_TYPE > toSliceConst() const && noexcept = delete; /** * @brief A user defined conversion operator (UDC) to an ArrayView< T const, ... >. * @return A new ArrayView where @c T is @c const. */ template< typename _T=T > inline LVARRAY_HOST_DEVICE constexpr operator std::enable_if_t< !std::is_const< _T >::value, ArrayView< T const, NDIM, USD, INDEX_TYPE, BUFFER_TYPE > >() const noexcept { return toViewConst(); } /** * @return Return an ArraySlice representing this ArrayView. */ inline LVARRAY_HOST_DEVICE constexpr operator ArraySlice< T, NDIM, USD, INDEX_TYPE >() const & noexcept { return toSlice(); } /** * @brief Overload for rvalues that is deleted. * @return A null ArraySlice. * @brief This conversion cannot be called on a rvalue since the @c ArraySlice would * contain pointers to the dims and strides of the current @c ArrayView that is * about to be destroyed. This overload prevents that from happening. */ inline LVARRAY_HOST_DEVICE constexpr operator ArraySlice< T, NDIM, USD, INDEX_TYPE >() const && noexcept = delete; /** * @return Return an immutable ArraySlice representing this ArrayView. */ template< typename _T=T > inline LVARRAY_HOST_DEVICE constexpr operator std::enable_if_t< !std::is_const< _T >::value, ArraySlice< T const, NDIM, USD, INDEX_TYPE > const >() const & noexcept { return toSliceConst(); } /** * @brief Overload for rvalues that is deleted. * @return A null ArraySlice. * @brief This conversion cannot be called on a rvalue since the @c ArraySlice would * contain pointers to the dims and strides of the current @c ArrayView that is * about to be destroyed. This overload prevents that from happening. */ template< typename _T=T > inline LVARRAY_HOST_DEVICE constexpr operator std::enable_if_t< !std::is_const< _T >::value, ArraySlice< T const, NDIM, USD, INDEX_TYPE > const >() const && noexcept = delete; ///@} /** * @name Attribute querying methods */ ///@{ /** * @return Return the allocated size. */ LVARRAY_HOST_DEVICE inline constexpr INDEX_TYPE size() const noexcept { #if defined( __ibmxl__ ) // Note: This used to be done with a recursive template but XL-release would produce incorrect results. // Specifically in exampleArray it would return an "old" size even after being updated, strange. INDEX_TYPE val = m_dims[ 0 ]; for( int i = 1; i < NDIM; ++i ) { val *= m_dims[ i ]; } return val; #else return indexing::multiplyAll< NDIM >( m_dims.data ); #endif } /** * @return Return the length of the given dimension. * @param dim The dimension to get the length of. */ LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK INDEX_TYPE size( int const dim ) const noexcept { #ifdef LVARRAY_BOUNDS_CHECK LVARRAY_ASSERT_GE( dim, 0 ); LVARRAY_ASSERT_GT( NDIM, dim ); #endif return m_dims[ dim ]; } /** * @return Return true if the array is empty. */ LVARRAY_HOST_DEVICE inline constexpr bool empty() const { return size() == 0; } /** * @return Return the maximum number of values the Array can hold without reallocation. */ LVARRAY_HOST_DEVICE constexpr INDEX_TYPE capacity() const { return LvArray::integerConversion< INDEX_TYPE >( m_dataBuffer.capacity() ); } /** * @return Return the default resize dimension. */ LVARRAY_HOST_DEVICE inline constexpr int getSingleParameterResizeIndex() const { return m_singleParameterResizeIndex; } /** * @tparam INDICES A variadic pack of integral types. * @return Return the linear index from a multidimensional index. * @param indices The indices of the value to get the linear index of. */ template< typename ... INDICES > LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK INDEX_TYPE linearIndex( INDICES const ... indices ) const { static_assert( sizeof ... (INDICES) == NDIM, "number of indices does not match NDIM" ); #ifdef LVARRAY_BOUNDS_CHECK indexing::checkIndices( m_dims.data, indices ... ); #endif return indexing::getLinearIndex< USD >( m_strides.data, indices ... ); } /** * @return A pointer to the array containing the size of each dimension. */ LVARRAY_HOST_DEVICE inline constexpr INDEX_TYPE const * dims() const noexcept { return m_dims.data; } /** * @return The CArray containing the size of each dimension. */ LVARRAY_HOST_DEVICE inline constexpr typeManipulation::CArray< INDEX_TYPE, NDIM > const & dimsArray() const { return m_dims; } /** * @return A pointer to the array containing the stride of each dimension. */ LVARRAY_HOST_DEVICE inline constexpr INDEX_TYPE const * strides() const noexcept { return m_strides.data; } /** * @return The CArray containing the stride of each dimension. */ LVARRAY_HOST_DEVICE inline constexpr typeManipulation::CArray< INDEX_TYPE, NDIM > const & stridesArray() const { return m_strides; } /** * @return A reference to the underlying buffer. * @note Use with caution. */ LVARRAY_HOST_DEVICE inline constexpr BUFFER_TYPE< T > const & dataBuffer() const { return m_dataBuffer; } ///@} /** * @name Methods that provide access to the data. */ ///@{ /** * @return Return a lower dimensional slice of this ArrayView. * @param index The index of the slice to create. * @note This method is only active when NDIM > 1. */ template< int _NDIM=NDIM > LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK std::enable_if_t< (_NDIM > 1), ArraySlice< T, NDIM - 1, USD - 1, INDEX_TYPE > > operator[]( INDEX_TYPE const index ) const & noexcept { ARRAY_SLICE_CHECK_BOUNDS( index ); return ArraySlice< T, NDIM-1, USD-1, INDEX_TYPE >( data() + indexing::ConditionalMultiply< USD == 0 >::multiply( index, m_strides[ 0 ] ), m_dims.data + 1, m_strides.data + 1 ); } /** * @brief Overload for rvalues that is deleted. * @param index Not used. * @return A null ArraySlice. * @brief The multidimensional operator[] cannot be called on a rvalue since the @c ArraySlice * would contain pointers to the object that is about to be destroyed. This overload * prevents that from happening. */ template< int _NDIM=NDIM > LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK std::enable_if_t< (_NDIM > 1), ArraySlice< T, NDIM - 1, USD - 1, INDEX_TYPE > > operator[]( INDEX_TYPE const index ) const && noexcept = delete; /** * @return Return a reference to the value at the given index. * @param index The index of the value to access. * @note This method is only active when NDIM == 1. */ template< int _NDIM=NDIM > LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK std::enable_if_t< _NDIM == 1, T & > operator[]( INDEX_TYPE const index ) const & noexcept { ARRAY_SLICE_CHECK_BOUNDS( index ); return data()[ indexing::ConditionalMultiply< USD == 0 >::multiply( index, m_strides[ 0 ] ) ]; } /** * @tparam INDICES A variadic pack of integral types. * @return Return a reference to the value at the given multidimensional index. * @param indices The indices of the value to access. */ template< typename ... INDICES > LVARRAY_HOST_DEVICE inline constexpr T & operator()( INDICES... indices ) const { static_assert( sizeof ... (INDICES) == NDIM, "number of indices does not match NDIM" ); return data()[ linearIndex( indices ... ) ]; } /** * @return Return a pointer to the values. */ LVARRAY_HOST_DEVICE inline constexpr T * data() const { return m_dataBuffer.data(); } /** * @return Return an iterator to the begining of the data. */ LVARRAY_HOST_DEVICE inline constexpr T * begin() const { return data(); } /** * @return Return an iterator to the end of the data. */ LVARRAY_HOST_DEVICE inline constexpr T * end() const { return data() + size(); } /** * @return Return a reference to the first value. */ T & front() const { return data()[ 0 ]; } /** * @return Return a reference to the last value. */ T & back() const { return data()[size() - 1]; } ///@} /** * @name Methods that set all the values */ ///@{ /** * @brief Set all entries in the array to @p value. * @tparam POLICY The RAJA policy to use. * @param value The value to set entries to. * @note The view is moved to and touched in the appropriate space. */ DISABLE_HD_WARNING template< typename POLICY > void setValues( T const & value ) const { auto const view = toView(); RAJA::forall< POLICY >( RAJA::TypedRangeSegment< INDEX_TYPE >( 0, size() ), [value, view] LVARRAY_HOST_DEVICE ( INDEX_TYPE const i ) { view.data()[ i ] = value; } ); } /** * @brief Use memset to set all the values in the array to 0. * @details This is preferred over setValues< POLICY >( 0 ) for numeric types since it is much faster in most cases. * If the buffer is allocated using Umpire then the Umpire ResouceManager is used, otherwise std::memset is used. * @note The memset occurs in the last space the array was used in and the view is moved and touched in that space. */ inline void zero() const { #if !defined( LVARRAY_USE_UMPIRE ) LVARRAY_ERROR_IF_NE_MSG( getPreviousSpace(), MemorySpace::host, "Without Umpire only host memory is supported." ); #endif if( size() > 0 ) { move( getPreviousSpace(), true ); umpireInterface::memset( data(), 0, size() * sizeof( T ) ); } } /** * @brief Set entries to values from another compatible ArrayView. * @tparam POLICY The RAJA policy to use. * @param rhs The source array view, must have the same dimensions and strides as *this. */ template< typename POLICY > void setValues( ArrayView< T const, NDIM, USD, INDEX_TYPE, BUFFER_TYPE > const & rhs ) const { for( int dim = 0; dim < NDIM; ++dim ) { LVARRAY_ERROR_IF_NE( size( dim ), rhs.size( dim ) ); LVARRAY_ERROR_IF_NE_MSG( strides()[ dim ], rhs.strides()[ dim ], "This method only works with Arrays with the same data layout." ); } auto const view = toView(); RAJA::forall< POLICY >( RAJA::TypedRangeSegment< INDEX_TYPE >( 0, size() ), [view, rhs] LVARRAY_HOST_DEVICE ( INDEX_TYPE const i ) { view.data()[ i ] = rhs.data()[ i ]; } ); } ///@} /** * @name Methods dealing with memory spaces */ ///@{ /** * @return The last space the Array was moved to. */ MemorySpace getPreviousSpace() const { return m_dataBuffer.getPreviousSpace(); } /** * @brief Touch the memory in @p space. * @param space The memory space in which a touch will be recorded. */ void registerTouch( MemorySpace const space ) const { m_dataBuffer.registerTouch( space ); } /** * @brief Move the Array to the given execution space, optionally touching it. * @param space the space to move the Array to. * @param touch whether the Array should be touched in the new space or not. * @note Not all Buffers support memory movement. */ void move( MemorySpace const space, bool const touch=true ) const { m_dataBuffer.moveNested( space, size(), touch ); } ///@} #if defined(LVARRAY_USE_TOTALVIEW_OUTPUT) && !defined(__CUDA_ARCH__) /** * @brief Static function that will be used by Totalview to display the array contents. * @param av A pointer to the array that is being displayed. * @return 0 if everything went OK */ static int TV_ttf_display_type( ArrayView const * av ) { if( av!=nullptr ) { int constexpr ndim = NDIM; //std::cout<<"Totalview using ("<<totalview::format<T,INDEX_TYPE>(NDIM, av->m_dims )<<") for display of // m_data;"<<std::endl; // TV_ttf_add_row( "tv(m_data)", totalview::format< T, INDEX_TYPE >( NDIM, av->m_dims ).c_str(), (av->m_data) ); // TV_ttf_add_row( "m_data", totalview::format< T, INDEX_TYPE >( 0, av->m_dims ).c_str(), (av->m_data) ); TV_ttf_add_row( "m_dims", totalview::format< INDEX_TYPE, int >( 1, &ndim ).c_str(), (av->m_dims) ); TV_ttf_add_row( "m_strides", totalview::format< INDEX_TYPE, int >( 1, &ndim ).c_str(), (av->m_strides) ); TV_ttf_add_row( "m_dataBuffer", LvArray::system::demangle< BUFFER_TYPE< T > >().c_str(), &(av->m_dataBuffer) ); TV_ttf_add_row( "m_singleParameterResizeIndex", "int", &(av->m_singleParameterResizeIndex) ); } return 0; } #endif protected: /** * @brief Protected constructor to be used by the Array class. * @note The unused boolean parameter is to distinguish this from the default constructor. */ DISABLE_HD_WARNING LVARRAY_HOST_DEVICE inline explicit CONSTEXPR_WITHOUT_BOUNDS_CHECK ArrayView( bool ) noexcept: m_dims{ 0 }, m_strides{ 0 }, m_dataBuffer( true ) { #if defined(LVARRAY_USE_TOTALVIEW_OUTPUT) && !defined(__CUDA_ARCH__) && defined(LVARRAY_BOUNDS_CHECK) ArrayView::TV_ttf_display_type( nullptr ); #endif } /** * @brief Protected constructor to be used by the Array class. * @details Construct an empty ArrayView from @p buffer. * @param buffer The buffer use. */ DISABLE_HD_WARNING inline LVARRAY_HOST_DEVICE constexpr ArrayView( BUFFER_TYPE< T > && buffer ) noexcept: m_dims{ 0 }, m_strides{ 0 }, m_dataBuffer{ std::move( buffer ) }, m_singleParameterResizeIndex{ 0 } {} /// the dimensions of the array. typeManipulation::CArray< INDEX_TYPE, NDIM > m_dims = { 0 }; /// the strides of the array. typeManipulation::CArray< INDEX_TYPE, NDIM > m_strides = { 0 }; /// this data member contains the actual data for the array. BUFFER_TYPE< T > m_dataBuffer; /// this data member specifies the dimension that will be resized as a result of a call to the /// single dimension resize method. int m_singleParameterResizeIndex = 0; }; /** * @brief True if the template type is a ArrayView. */ template< class > constexpr bool isArrayView = false; /** * @tparam T The type contained in the ArrayView. * @tparam NDIM The number of dimensions in the ArrayView. * @tparam USD The unit stride dimension. * @tparam INDEX_TYPE The integral type used as an index. * @tparam BUFFER_TYPE The type used to manager the underlying allocation. * @brief Specialization of isArrayView for the ArrayView class. */ template< typename T, int NDIM, int USD, typename INDEX_TYPE, template< typename > class BUFFER_TYPE > constexpr bool isArrayView< ArrayView< T, NDIM, USD, INDEX_TYPE, BUFFER_TYPE > > = true; } // namespace LvArray
35.065134
141
0.667832
GEOSX
cbc1daabd6b6e673f451c2294183fe88accfe460
1,155
hpp
C++
Include/Rover/Generator.hpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
null
null
null
Include/Rover/Generator.hpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
30
2019-02-05T23:18:13.000Z
2019-07-05T14:19:04.000Z
Include/Rover/Generator.hpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
1
2020-06-01T06:32:05.000Z
2020-06-01T06:32:05.000Z
#ifndef ROVER_GENERATOR_HPP #define ROVER_GENERATOR_HPP #include <type_traits> #include "Rover/Evaluator.hpp" namespace Rover { /** Interface for generating arguments. */ template<typename T> class Generator { public: /** The type of generated values. */ using Type = T; //! Generates a value. /*! \param evaluator Stores the state of the currently generated value. */ Type generate(Evaluator& evaluator); }; //! Produces an argument from a generator. /* \param generator The generator to evaluate. \return The argument produced by the <i>generator</i>. */ template<typename Generator> auto generate(Generator& generator) { auto evaluator = Evaluator(); return evaluator.evaluate(generator); } template<typename T, typename = void> struct is_generator : std::false_type {}; template<typename T> struct is_generator<T, std::enable_if_t<!std::is_same_v< decltype(std::declval<T>().generate(std::declval<Evaluator&>())), void>>> : std::true_type {}; template<typename T> inline constexpr bool is_generator_v = is_generator<T>::value; } #endif
24.574468
79
0.678788
kranar
cbc2e41cf96d3417718c4e1da3964331ff148b34
1,371
cc
C++
plugins/test_config_json/main.cc
mariuslundblad/disir-c
ae831250cfbf033a755c91e62e8af7d82135d0d8
[ "Apache-2.0" ]
4
2017-06-19T09:59:50.000Z
2019-03-20T18:49:11.000Z
plugins/test_config_json/main.cc
mariuslundblad/disir-c
ae831250cfbf033a755c91e62e8af7d82135d0d8
[ "Apache-2.0" ]
18
2017-06-25T22:19:00.000Z
2019-11-28T13:16:26.000Z
plugins/test_config_json/main.cc
mariuslundblad/disir-c
ae831250cfbf033a755c91e62e8af7d82135d0d8
[ "Apache-2.0" ]
2
2017-10-31T11:19:55.000Z
2019-11-28T12:13:13.000Z
#include <disir/plugin.h> #include <disir/fslib/json.h> #include <disir/test.h> #define RM_CONST(t, exp) (t*)((char*)NULL + ((const char*)(exp) - (char*)NULL)) extern "C" enum disir_status dio_register_plugin (struct disir_instance *instance, struct disir_register_plugin *plugin); enum disir_status dio_register_plugin (struct disir_instance *instance, struct disir_register_plugin *plugin) { (void) &instance; plugin->dp_name = RM_CONST (char, "JSON Config Test"); plugin->dp_description = RM_CONST (char, "JSON config, TEST mold"); // Storage space unused. plugin->dp_storage = NULL; plugin->dp_plugin_finished = NULL; plugin->dp_config_entry_type = RM_CONST (char, "json"); plugin->dp_config_read = dio_json_config_read; plugin->dp_config_write = dio_json_config_write; plugin->dp_config_remove = dio_json_config_remove; plugin->dp_config_fd_write = dio_json_config_fd_write; plugin->dp_config_fd_read = dio_json_config_fd_read; plugin->dp_config_entries = dio_json_config_entries; plugin->dp_config_query = dio_json_config_query; plugin->dp_mold_entry_type = RM_CONST (char, "json"); plugin->dp_mold_read = dio_test_mold_read; plugin->dp_mold_write = NULL; plugin->dp_mold_entries = dio_test_mold_entries;; plugin->dp_mold_query = dio_test_mold_query; return DISIR_STATUS_OK; }
35.153846
92
0.744712
mariuslundblad
cbc37a989af84a640e9af34c267f7d2475348d2a
7,156
hpp
C++
include/universal/number/integer/primes.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
include/universal/number/integer/primes.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
include/universal/number/integer/primes.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
#pragma once // primes.hpp: algorithms to create, categorize, classify, and identify prime factors // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <vector> #include <universal/number/integer/exceptions.hpp> namespace sw { namespace universal { /* from numerics // FUNCTION TEMPLATE gcd template<class _Mt, class _Nt> _NODISCARD constexpr common_type_t<_Mt, _Nt> gcd(const _Mt _Mx, const _Nt _Nx) noexcept // strengthened { // calculate greatest common divisor static_assert(_Is_nonbool_integral<_Mt>::value && _Is_nonbool_integral<_Nt>::value, "GCD requires nonbool integral types"); using _Common = common_type_t<_Mt, _Nt>; using _Common_unsigned = make_unsigned_t<_Common>; _Common_unsigned _Mx_magnitude = _Abs_u(_Mx); _Common_unsigned _Nx_magnitude = _Abs_u(_Nx); if (_Mx_magnitude == 0U) { return (static_cast<_Common>(_Nx_magnitude)); } if (_Nx_magnitude == 0U) { return (static_cast<_Common>(_Mx_magnitude)); } const auto _Mx_trailing_zeroes = _Stl_bitscan_forward(_Mx_magnitude); const auto _Common_factors_of_2 = _Min_value(_Mx_trailing_zeroes, _Stl_bitscan_forward(_Nx_magnitude)); _Nx_magnitude >>= _Common_factors_of_2; _Mx_magnitude >>= _Mx_trailing_zeroes; do { _Nx_magnitude >>= _Stl_bitscan_forward(_Nx_magnitude); if (_Mx_magnitude > _Nx_magnitude) { _Common_unsigned _Temp = _Mx_magnitude; _Mx_magnitude = _Nx_magnitude; _Nx_magnitude = _Temp; } _Nx_magnitude -= _Mx_magnitude; } while (_Nx_magnitude != 0U); return (static_cast<_Common>(_Mx_magnitude << _Common_factors_of_2)); } // FUNCTION TEMPLATE lcm template<class _Mt, class _Nt> _NODISCARD constexpr common_type_t<_Mt, _Nt> lcm(const _Mt _Mx, const _Nt _Nx) noexcept // strengthened { // calculate least common multiple static_assert(_Is_nonbool_integral<_Mt>::value && _Is_nonbool_integral<_Nt>::value, "LCM requires nonbool integral types"); using _Common = common_type_t<_Mt, _Nt>; using _Common_unsigned = make_unsigned_t<_Common>; const _Common_unsigned _Mx_magnitude = _Abs_u(_Mx); const _Common_unsigned _Nx_magnitude = _Abs_u(_Nx); if (_Mx_magnitude == 0 || _Nx_magnitude == 0) { return (static_cast<_Common>(0)); } return (static_cast<_Common>((_Mx_magnitude / _STD gcd(_Mx_magnitude, _Nx_magnitude)) * _Nx_magnitude)); } */ /* given two positive integers a = Product of primes p^a_p, and b = PROD p^b_p, where a_p or b_p is the exponent of the prime p that are contained by a or b greated common divisor gcd(a, b) = PROD p^min(a_p, b_p) least common multiple lcm(a, b) = PROD p^max(a_p, b_p) */ // calculate the greatest common divisor of two numbers template<typename IntegerType> IntegerType gcd(const IntegerType& a, const IntegerType& b) { return b == 0 ? a : gcd(b, a % b); } // calculate the greatest common divisor of N numbers template<typename IntegerType> IntegerType gcd(const std::vector< IntegerType >& v) { if (v.size() == 0) return 0; if (v.size() == 1) return v[0]; IntegerType gcd_n = v[0]; for (size_t i = 1; i < v.size(); ++i) { gcd_n = gcd(gcd_n, v[i]); } return gcd_n; } // calculate the least common multiple of two numbers template<typename IntegerType> IntegerType lcm(const IntegerType& a, const IntegerType& b) { return (a * b) / gcd(a, b); } // calculate the least common multiple of N numbers template<typename IntegerType> IntegerType lcm(const std::vector< IntegerType >& v) { if (v.size() == 0) return 0; if (v.size() == 1) return v[0]; IntegerType lcm = v[0]; for (size_t i = 0; i < v.size(); ++i) { lcm = (v[i] * lcm) / gcd(lcm, v[i]); } return lcm; } // check if a number is prime template<typename IntegerType> bool isPrime_(const IntegerType& a) { if (a <= 1) return false; // smallest prime number is 2 for (IntegerType i = 2; i <= a / 2; ++i) if ((a % i) == 0) return false; return true; } template<typename IntegerType> bool isPrime(const IntegerType& a) { if (a <= 1) return false; // smallest prime number is 2 if (a <= 3) return true; // 2 and 3 are primes if (a % 2 == 0 || a % 3 == 0) return false; // this allows us to skip middle for (IntegerType i = 5; i*i <= a; i += 6) if ((a % i) == 0 || a % (i + 2) == 0) return false; return true; } template<typename IntegerType> bool isPrimeTracer(const IntegerType& a) { if (a <= 1) return false; // smallest prime number is 2 if (a <= 3) return true; // 2 and 3 are primes if (a % 2 == 0 || a % 3 == 0) return false; // this allows us to skip middle for (IntegerType i = 5; i * i <= a; i += 6) { if ((a % i) == 0 || a % (i + 2) == 0) return false; std::cout << i << '\n'; } return true; } // generate prime numbers in a range template<typename IntegerType> bool primeNumbersInRange(const IntegerType low, const IntegerType high, std::vector< IntegerType >& primes) { bool bFound = false; for (IntegerType i = low; i < high; ++i) { if (isPrime(i)) { primes.push_back(i); bFound = true; } } return bFound; } // print the prime numbers in a range template<typename IntegerType> void printPrimes(const std::vector< IntegerType >& v) { constexpr size_t PAGE_WIDTH = 65; size_t nrPrimes = v.size(); if (nrPrimes == 0) return; // determine the size of the largest prime size_t COL_WIDTH = 1; auto number = v[nrPrimes - 1]; while (number >= 1) { ++COL_WIDTH; number /= 10; } std::cout << "largest prime: " << v[nrPrimes - 1] << " is " << COL_WIDTH - 1 << " decades\n"; int column = 1; for (auto p : v) { std::cout << std::setw(COL_WIDTH) << p; if (column * COL_WIDTH < PAGE_WIDTH) { ++column; } else { column = 1; std::cout << '\n'; } } std::cout << '\n'; } // prime factors of an arbitrary integer template<typename IntegerType> class primefactors : public std::vector< std::pair< IntegerType, IntegerType > > { }; // generate prime factors of an arbitrary integer template<typename IntegerType> void primeFactorization(const IntegerType& a, primefactors<IntegerType>& factors) { IntegerType i(a); IntegerType factor = 2; IntegerType power = 0; // powers of 2 while (i.iseven()) { ++power; i >>= 1; } if (power > 0) factors.push_back(std::pair<IntegerType, IntegerType>(factor, power)); // powers of odd numbers > 2 for (factor = 3; factor <= sqrt(i); factor += 2) { if (isPrime(factor)) { power = 0; while ((i % factor) == 0) { ++power; i /= factor; } if (power > 0) factors.push_back(std::pair<IntegerType, IntegerType>(factor, power)); } } if (i > 2) factors.push_back(std::pair < IntegerType, IntegerType>(i, 1)); } // Factorization using Fermat's method: precondition number must be odd // trying various values of a with the goal to find a^2 - number = b^2, a square template<typename IntegerType> IntegerType fermatFactorization(const IntegerType& number) { if (number.iseven()) return 0; // number must be odd IntegerType a = ceil_sqrt(number); IntegerType bsquare = a * a - number; while (!perfect_square(bsquare)) { ++a; bsquare = a * a - number; } return a - sqrt(bsquare); } }} // namespace sw::universal
30.978355
109
0.686138
FloEdelmann
cbc3801759b7649b7b608cf454171da109ca86af
9,084
cxx
C++
Testing/Code/Numerics/Statistics/itkGaussianDistributionTest.cxx
dtglidden/ITK
ef0c16fee4fac904d6ab706b8f7d438d4062cd96
[ "BSD-3-Clause" ]
1
2017-07-31T18:41:02.000Z
2017-07-31T18:41:02.000Z
Testing/Code/Numerics/Statistics/itkGaussianDistributionTest.cxx
dtglidden/ITK
ef0c16fee4fac904d6ab706b8f7d438d4062cd96
[ "BSD-3-Clause" ]
null
null
null
Testing/Code/Numerics/Statistics/itkGaussianDistributionTest.cxx
dtglidden/ITK
ef0c16fee4fac904d6ab706b8f7d438d4062cd96
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkGaussianDistributionTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkGaussianDistribution.h" #include <math.h> int itkGaussianDistributionTest(int, char* [] ) { std::cout << "itkGaussianDistribution Test \n \n"; typedef itk::Statistics::GaussianDistribution DistributionType; DistributionType::Pointer distributionFunction = DistributionType::New(); int i; double x; double value; double diff; int status = EXIT_SUCCESS; // Tolerance for the values. double tol = 1e-8; std::cout << "Tolerance used for test: "; std::cout.width(22); std::cout.precision(15); std::cout << tol << std::endl; std::cout << std::endl; // expected values for Gaussian cdf with mean 0 and variance 1 at // values of -5:1:5 double expected1[] = {2.866515718791942e-007, 3.167124183311998e-005, 1.349898031630095e-003, 2.275013194817922e-002, 1.586552539314571e-001, 5.000000000000000e-001, 8.413447460685429e-001, 9.772498680518208e-001, 9.986501019683699e-001, 9.999683287581669e-001, 9.999997133484281e-001}; std::cout << "Gaussian CDF" << std::endl; for (i = -5; i <= 5; ++i) { x = static_cast<double>(i); value = distributionFunction->EvaluateCDF( x ); diff = vcl_fabs(value - expected1[i+5]); std::cout << "Gaussian cdf at "; std::cout.width(2); std::cout << x << " = "; std::cout.width(22); std::cout << value << ", expected value = "; std::cout.width(22); std::cout << expected1[i+5] << ", error = "; std::cout.width(22); std::cout << diff; if (diff < tol) { std::cout << ", Passed." << std::endl; } else { std::cout << ", Failed." << std::endl; status = EXIT_FAILURE; } } std::cout << std::endl; std::cout << "Inverse Gaussian CDF" << std::endl; for (i = -5; i <= 5; ++i) { value = distributionFunction->EvaluateInverseCDF( expected1[i+5] ); diff = vcl_fabs(value - double(i)); std::cout << "Inverse Gaussian cdf at "; std::cout.width(22); std::cout << expected1[i+5] << " = "; std::cout.width(22); std::cout << value << ", expected value = "; std::cout.width(22); std::cout << double(i) << ", error = "; std::cout.width(22); std::cout << diff; if (diff < tol) { std::cout << ", Passed." << std::endl; } else { std::cout << ", Failed." << std::endl; status = EXIT_FAILURE; } } std::cout << std::endl; // do the same tests at a different mean/variance distributionFunction->SetMean( 5.0 ); distributionFunction->SetVariance( 2.0 ); std::cout << "Testing mean = " << distributionFunction->GetMean() << ", variance = " << distributionFunction->GetVariance() << std::endl; double expected2[] = {7.687298972140230e-013, 9.830802207714426e-011, 7.708628950140045e-009, 3.715491861707074e-007, 1.104524849929275e-005, 2.034760087224798e-004, 2.338867490523635e-003, 1.694742676234465e-002, 7.864960352514258e-002, 2.397500610934768e-001, 5.000000000000000e-001}; std::cout << "Gaussian CDF" << std::endl; for (i = -5; i <= 5; ++i) { x = static_cast<double>(i); value = distributionFunction->EvaluateCDF( x ); diff = vcl_fabs(value - expected2[i+5]); std::cout << "Gaussian cdf at "; std::cout.width(2); std::cout << x << " = "; std::cout.width(22); std::cout << value << ", expected value = "; std::cout.width(22); std::cout << expected2[i+5] << ", error = "; std::cout.width(22); std::cout << diff; if (diff < tol) { std::cout << ", Passed." << std::endl; } else { std::cout << ", Failed." << std::endl; status = EXIT_FAILURE; } } std::cout << std::endl; // same test but using the parameter vector API DistributionType::ParametersType params(2); params[0] = 5.0; params[1] = 2.0; std::cout << "Testing mean = " << params[0] << ", variance = " << params[1] << std::endl; distributionFunction->SetMean(0.0); // clear settings distributionFunction->SetVariance(1.0); // clear settings double expected3[] = {7.687298972140230e-013, 9.830802207714426e-011, 7.708628950140045e-009, 3.715491861707074e-007, 1.104524849929275e-005, 2.034760087224798e-004, 2.338867490523635e-003, 1.694742676234465e-002, 7.864960352514258e-002, 2.397500610934768e-001, 5.000000000000000e-001}; std::cout << "Gaussian CDF (parameter vector API)" << std::endl; for (i = -5; i <= 5; ++i) { x = static_cast<double>(i); value = distributionFunction->EvaluateCDF( x, params ); diff = vcl_fabs(value - expected3[i+5]); std::cout << "Gaussian cdf at "; std::cout.width(2); std::cout << x << " = "; std::cout.width(22); std::cout << value << ", expected value = "; std::cout.width(22); std::cout << expected3[i+5] << ", error = "; std::cout.width(22); std::cout << diff; if (diff < tol) { std::cout << ", Passed." << std::endl; } else { std::cout << ", Failed." << std::endl; status = EXIT_FAILURE; } } std::cout << std::endl; // same test but using the separate parameters std::cout << "Testing mean = " << params[0] << ", variance = " << params[1] << std::endl; double expected4[] = {7.687298972140230e-013, 9.830802207714426e-011, 7.708628950140045e-009, 3.715491861707074e-007, 1.104524849929275e-005, 2.034760087224798e-004, 2.338867490523635e-003, 1.694742676234465e-002, 7.864960352514258e-002, 2.397500610934768e-001, 5.000000000000000e-001}; std::cout << "Gaussian CDF (separate parameter API)" << std::endl; for (i = -5; i <= 5; ++i) { x = static_cast<double>(i); value = distributionFunction->EvaluateCDF( x, params[0], params[1] ); diff = vcl_fabs(value - expected4[i+5]); std::cout << "Gaussian cdf at "; std::cout.width(2); std::cout << x << " = "; std::cout.width(22); std::cout << value << ", expected value = "; std::cout.width(22); std::cout << expected4[i+5] << ", error = "; std::cout.width(22); std::cout << diff; if (diff < tol) { std::cout << ", Passed." << std::endl; } else { std::cout << ", Failed." << std::endl; status = EXIT_FAILURE; } } std::cout << std::endl; std::cout << "Inverse Gaussian CDF" << std::endl; // put the parameters back distributionFunction->SetParameters( params ); for (i = -5; i <= 5; ++i) { value = distributionFunction->EvaluateInverseCDF( expected2[i+5] ); diff = vcl_fabs(value - double(i)); std::cout << "Inverse Gaussian cdf at "; std::cout.width(22); std::cout << expected2[i+5] << " = "; std::cout.width(22); std::cout << value << ", expected value = "; std::cout.width(22); std::cout << double(i) << ", error = "; std::cout.width(22); std::cout << diff; if (diff < tol) { std::cout << ", Passed." << std::endl; } else { std::cout << ", Failed." << std::endl; status = EXIT_FAILURE; } } std::cout << std::endl; return status; }
28.476489
76
0.503192
dtglidden
cbc43e9f400cf5ef427d5ab87bcbbf3b48bd404f
602
cpp
C++
WonderMake/Graphics/Shader.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
3
2020-03-27T15:25:19.000Z
2022-01-18T14:12:25.000Z
WonderMake/Graphics/Shader.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
null
null
null
WonderMake/Graphics/Shader.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
null
null
null
#include "pch.h" #include "Shader.h" #include "Resources/AssetDatabase.h" _REGISTER_SYSTEM_IMPL(ResourceSystem<Shader<EShaderType::Fragment>>, Shader_Fragment); _REGISTER_SYSTEM_IMPL(ResourceSystem<Shader<EShaderType::Geometry>>, Shader_Geometry); _REGISTER_SYSTEM_IMPL(ResourceSystem<Shader<EShaderType::Vertex>>, Shader_Vertex); _REGISTER_SYSTEM_IMPL(AssetDatabase<Shader<EShaderType::Fragment>>, Shader_FragmentAsset); _REGISTER_SYSTEM_IMPL(AssetDatabase<Shader<EShaderType::Geometry>>, Shader_GeometryAsset); _REGISTER_SYSTEM_IMPL(AssetDatabase<Shader<EShaderType::Vertex>>, Shader_VertexAsset);
50.166667
90
0.845515
nicolasgustafsson
cbca1443612e8fc621aeb7b903fda5f75ac68adf
2,160
cpp
C++
src/editorLib/Render/EnvironmentModelRenderObserver.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/editorLib/Render/EnvironmentModelRenderObserver.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/editorLib/Render/EnvironmentModelRenderObserver.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <stdexcept> #include <mtt/editorLib/AsyncTasks/LoadEnvironmentModelTask.h> #include <mtt/editorLib/Objects/EnvironmentModel.h> #include <mtt/editorLib/Render/EnvironmentModelRenderObserver.h> #include <mtt/editorLib/EditorApplication.h> #include <mtt/utilities/Log.h> using namespace mtt; EnvironmentModelRenderObserver::EnvironmentModelRenderObserver( EnvironmentModel& object, CommonEditData& commonData) : Object3DRenderObserver(object, commonData), _object(object) { connect(&_object, &EnvironmentModel::filenameChanged, this, &EnvironmentModelRenderObserver::_updateModel, Qt::DirectConnection); _updateModel(); } void EnvironmentModelRenderObserver::_updateModel() noexcept { if(_drawModel != nullptr) { unregisterCulledDrawable(*_drawModel); fullTransformJoint().removeChild(*_drawModel); _drawModel.reset(); } QString filename = _object.filename(); if (!filename.isEmpty()) { try { auto callback = [&](std::unique_ptr<SlaveDrawModel> model) { try { model->addModificator(visibleFilter()); model->addModificator(uidSetter()); model->addModificator(selectionModificator()); _drawModel = std::move(model); registerCulledDrawable(*_drawModel); fullTransformJoint().addChild(*_drawModel); } catch (...) { unregisterCulledDrawable(*_drawModel); fullTransformJoint().removeChild(*_drawModel); _drawModel.reset(); throw; } }; std::unique_ptr<LoadEnvironmentModelTask> task( new LoadEnvironmentModelTask(filename, callback)); AsyncTaskQueue& queue = EditorApplication::instance().asyncTaskQueue; _uploadStopper = queue.addTaskWithStopper(std::move(task)); } catch(std::exception& error) { Log() << "Unable to load model: " << error.what(); } catch (...) { Log() << "Unable to load model: unknown error"; } } }
29.189189
80
0.623611
AluminiumRat
cbca53aa4a9bc04509a0051f70289e2d86aa1bae
4,011
cpp
C++
utl/tests/testinc_queue.cpp
mathiasrw/ptarmigan
69b26470310daa24f95cb83eefde8e539eff6d96
[ "Apache-2.0" ]
143
2017-07-22T12:12:00.000Z
2022-02-09T09:46:26.000Z
utl/tests/testinc_queue.cpp
mathiasrw/ptarmigan
69b26470310daa24f95cb83eefde8e539eff6d96
[ "Apache-2.0" ]
534
2017-09-02T13:45:32.000Z
2020-06-15T09:26:33.000Z
utl/tests/testinc_queue.cpp
mathiasrw/ptarmigan
69b26470310daa24f95cb83eefde8e539eff6d96
[ "Apache-2.0" ]
31
2017-09-29T00:11:33.000Z
2021-06-17T08:24:37.000Z
//////////////////////////////////////////////////////////////////////// //FAKE関数 //FAKE_VALUE_FUNC(int, external_function, int); //////////////////////////////////////////////////////////////////////// class queue: public testing::Test { protected: virtual void SetUp() { //RESET_FAKE(external_function) utl_dbg_malloc_cnt_reset(); } virtual void TearDown() { ASSERT_EQ(0, utl_dbg_malloc_cnt()); } public: static void DumpBin(const uint8_t *pData, uint16_t Len) { for (uint16_t lp = 0; lp < Len; lp++) { printf("%02x", pData[lp]); } printf("\n"); } }; //////////////////////////////////////////////////////////////////////// TEST_F(queue, push_and_pop) { utl_queue_t queue; ASSERT_TRUE(utl_queue_create(&queue, sizeof(uint32_t), 5)); uint32_t item_in = 0xabcd0123; uint32_t item_out; uint32_t item_expected = item_in; ASSERT_FALSE(utl_queue_pop(&queue, &item_in)); //push x 5 ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_FALSE(utl_queue_push(&queue, &item_in)); //pop x 5 ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_FALSE(utl_queue_pop(&queue, &item_out)); utl_queue_free(&queue); } TEST_F(queue, push_and_pop_and_push_and_pop) { utl_queue_t queue; ASSERT_TRUE(utl_queue_create(&queue, sizeof(uint32_t), 5)); uint32_t item_in = 0xabcd0123; uint32_t item_out; uint32_t item_expected = item_in; ASSERT_FALSE(utl_queue_pop(&queue, &item_in)); //push x 5 ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_FALSE(utl_queue_push(&queue, &item_in)); //pop x 3 ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; //push x 3 ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_TRUE(utl_queue_push(&queue, &item_in)); item_in++; ASSERT_FALSE(utl_queue_push(&queue, &item_in)); //pop x 5 ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_TRUE(utl_queue_pop(&queue, &item_out)); ASSERT_EQ(item_out, item_expected); item_expected++; ASSERT_FALSE(utl_queue_pop(&queue, &item_out)); utl_queue_free(&queue); }
26.562914
72
0.638993
mathiasrw
cbca8d65465fa1ac6996b7568e261f1919444d31
2,759
cpp
C++
test_deprecated/testUtil/example_tc_file.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
1
2019-09-05T07:25:51.000Z
2019-09-05T07:25:51.000Z
test_deprecated/testUtil/example_tc_file.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
null
null
null
test_deprecated/testUtil/example_tc_file.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
1
2021-05-21T09:59:06.000Z
2021-05-21T09:59:06.000Z
/** * Tencent is pleased to support the open source community by making Tars available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 "util/tc_file.h" #include <errno.h> #include <iterator> #include <sys/time.h> using namespace tars; /* int removeFile(const string &sFullFileName, bool bRecursive) { cout << sFullFileName << endl; string path = TC_File::simplifyDirectory(sFullFileName); struct stat f_stat; if (lstat(path.c_str(), &f_stat) == -1) { return -1; } if(S_ISDIR(f_stat.st_mode)) { if(bRecursive) { vector<string> files; TC_File::listDirectory(path, files, true, false); for(size_t i = 0; i < files.size(); i++) { removeFile(files[i], bRecursive); } if(path != "/") { if(::rmdir(path.c_str()) == -1) { return -1; } return 0; } } else { if(::rmdir(path.c_str()) == -1) { return -1; } } } else { if(::remove(path.c_str()) == -1) { return -1; } } return 0; } */ struct Out { void operator()(const string &n) { cout << n << endl; } }; int main(int argc, char *argv[]) { try { // cout << TC_File::getFileSize("./test_tc_file.cpp") << endl; // cout << TC_File::isFileExist("./test_tc_file.cpp", S_IFDIR) << endl; // cout << TC_File::makeDir("test") << endl; // cout << TC_File::simplifyDirectory("/.") << endl; // cout << TC_File::simplifyDirectory("/./ab/tt//t///t//../tt/") << endl; // TC_File::removeFile("./", true); // vector<string> v; // TC_File::listDirectory("/home/base.l", v, true); // for_each(v.begin(), v.end(), Out()); TC_File::copyFile("/data/shared/Tars/web/", "/home/tars/", true); // TC_File::removeFile("/home/base.l", false); } catch(exception &ex) { cout << ex.what() << endl; } return 0; }
24.633929
92
0.536064
SuckShit
cbcdb2ab26b8909fe19cd4642aebfcecd4daf6d1
130
cpp
C++
boilerplate/MainScreen.cpp
ManoShu/SGB
4590910743ad1e8bbcf9209325393059587592cd
[ "BSD-2-Clause" ]
5
2017-05-21T08:46:08.000Z
2020-04-22T13:21:39.000Z
boilerplate/MainScreen.cpp
ManoShu/SGB
4590910743ad1e8bbcf9209325393059587592cd
[ "BSD-2-Clause" ]
null
null
null
boilerplate/MainScreen.cpp
ManoShu/SGB
4590910743ad1e8bbcf9209325393059587592cd
[ "BSD-2-Clause" ]
null
null
null
#include "MainScreen.h" void MainScreen::LoadScreen() { } void MainScreen::ScreenShow() { } void MainScreen::Update() { }
6.842105
29
0.661538
ManoShu
cbce526d0fb1e7572492c86a1fc3ea25bda7d4e0
637
cpp
C++
Codeforces/469A_I wanna be the guy.cpp
lieahau/Online-Judge-Solution
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
[ "MIT" ]
1
2020-04-13T11:12:19.000Z
2020-04-13T11:12:19.000Z
Codeforces/469A_I wanna be the guy.cpp
lieahau/Online-Judge-Solution
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
[ "MIT" ]
null
null
null
Codeforces/469A_I wanna be the guy.cpp
lieahau/Online-Judge-Solution
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool arr[200]; int main() { int n, x, y, temp, ans = 0; scanf("%d", &n); scanf("%d", &x); for(int i = 0; i < x; i++) { scanf("%d", &temp); if(!arr[temp]){ arr[temp] = true; ans++; } } scanf("%d", &y); for(int i = 0; i < y; i++) { scanf("%d", &temp); if(!arr[temp]){ arr[temp] = true; ans++; } } if(ans == n) printf("I become the guy.\n"); else printf("Oh, my keyboard!\n"); return 0; }
17.216216
39
0.359498
lieahau
cbd0080c5d1a84d97fe411b045330ac57a204606
10,573
cpp
C++
source/owlcore/view.cpp
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
source/owlcore/view.cpp
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
source/owlcore/view.cpp
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1993, 1996 by Borland International, All Rights Reserved // /// \file /// Implementation of classes TView & TWindowView //---------------------------------------------------------------------------- #include <owl/pch.h> #include <owl/defs.h> #include <owl/docmanag.h> #include <owl/appdict.h> #include <owl/bardescr.h> #include <owl/docview.rh> #if defined(__BORLANDC__) # pragma option -w-ccc // Disable "Condition is always true/false" #endif namespace owl { OWL_DIAGINFO; DIAG_DECLARE_GROUP(OwlDocView); // General Doc/View diagnostic group const uint MinUniqueViewId = 0x8000; uint TView::NextViewId = MinUniqueViewId; // /// Constructs a TView object of the document associated with the view. Sets the /// private data member ViewId to NextViewId. Calls TDocument's private member /// function AttachView to attach the view to the associated document. // TView::TView(TDocument& doc) : Tag(0), ViewMenu(0), ViewBar(0) { ViewId = NextViewId; doc.AttachView(*this); } // /// Frees a TView object and calls TDocument's private member function DetachView to /// detach the view from the associated document. // TView::~TView() { delete ViewMenu; delete ViewBar; const auto ok = Doc != 0; WARN(!ok, _T("TView::~TView: Terminating due to failed precondition.")); if (!ok) std::terminate(); if (Doc->DetachView(*this)) { delete Doc; } } // // Detach the view from the current document and attach it to another. // (Added by Vidar Hasfjord, 2007-08-27.) // void TView::SetDocument(TDocument& new_doc) { if (&new_doc == Doc) return; // Guard against reassignment. // Detach and register whether the document should be deleted. // The actual deletion is postponed to later to avoid any side-effects // from the deletion that may affect the validity of the new document. TDocument* delete_doc = 0; if (Doc && Doc->DetachView(*this)) delete_doc = Doc; // Update the new document and existing views as if this was a new view. new_doc.AttachView(*this); CHECK(Doc == &new_doc); Doc->ReindexFrames(); // Deletion of the old doc should be safe now. if (delete_doc) delete delete_doc; } // // // void TView::SetViewMenu(TMenuDescr* menu) { delete ViewMenu; ViewMenu = menu; TDocTemplate* tpl = Doc->GetTemplate(); //if (tpl && ViewMenu && *ViewMenu->GetModule() == *tpl->GetModule()) // must check also if template is static becouse as module = 0; if (tpl && ViewMenu && !tpl->IsStatic() && *ViewMenu->GetModule() == *tpl->GetModule()) ViewMenu->SetModule(tpl->GetModule());// force same module alias as template } // /// Sets the menu descriptor for this view. This can be any existing TMenuDescr /// object. If no descriptor exists, ViewMenu is 0. // void TView::SetViewBar(TBarDescr* bar) { delete ViewBar; ViewBar = bar; } static const tchar* const TView_PropertyNames[] = { _T("View Class"), // ViewClass _T("View Name"), // ViewName }; static const int TView_PropertyFlags[] = { pfGetText|pfConstant, // ViewClass pfGetText|pfConstant, // ViewName }; // /// Returns the text name of the property given the index value. // const tchar* TView::PropertyName(int index) { if (index <= PrevProperty) { TRACEX(OwlDocView, 0, _T("PropertyName(): index <= PrevProperty!")); return 0; } else if (index < NextProperty) return TView_PropertyNames[index-PrevProperty-1]; else { TRACEX(OwlDocView, 0, _T("PropertyName(): index >= NextProperty!")); return 0; } } // /// Returns the attributes of a specified property given the index of the property /// whose attributes you want to retrieve. // int TView::PropertyFlags(int index) { if (index <= PrevProperty) { TRACEX(OwlDocView, 0, _T("PropertyFlags(): index <= PrevProperty!")); return 0; } else if (index < NextProperty) return TView_PropertyFlags[index-PrevProperty-1]; else { TRACEX(OwlDocView, 0, _T("PropertyFlags(): index >= NextProperty!")); return 0; } } // /// Gets the property index, given the property name (name). Returns 0 if the name /// is not found. // int TView::FindProperty(LPCTSTR name) { int i; for (i=0; i < NextProperty-PrevProperty-1; i++) if (_tcscmp(TView_PropertyNames[i], name) == 0) return i+PrevProperty+1; TRACEX(OwlDocView, 0, _T("FindProperty(): ") \ _T("index of [") << tstring(name).c_str() << _T("] not found") ); return 0; } // /// Retrieves the property identified by the given index. /// If the requested property is text, then `dest` should point to a text buffer, and `textlen` /// should specify the maximum number of characters the buffer can hold, excluding the terminating /// null-character, i.e. the buffer must have room for (`textlen` + 1) characters. /// /// If the requested property is numerical, then it may be requested either as text or in its /// binary form. To request the property as text, pass a text buffer as described above. To request /// the property in binary form, `dest` should point to storage of sufficent size, and `textlen` /// should be zero. /// /// Non-text properties without textual representation, e.g. file handles, may only be requested /// in binary form, i.e. `dest` must point to sufficient storage, and `textlen` must be zero. /// /// \return If the parameter `textlen` is non-zero, which means that the property is requested in /// string form, the function returns the length of the string, i.e. the character count excluding /// the terminating null-character. If the parameter `textlen` is zero, which means that property /// is requested in binary form, the return value is the size of the data in bytes. /// /// If the property is text, and `textlen` is zero, the function fails and returns 0. The function /// also fails and returns 0 if `textlen` is non-zero and the property requested can not be /// expressed as text. It also returns 0 if the property is not defined. /// /// \sa TView::TViewProp // int TView::GetProperty(int index, void * dest, int textlen) { LPCTSTR src; switch (index) { case ViewClass:{ _USES_CONVERSION; src = _A2W(_OBJ_FULLTYPENAME(this)); } break; case ViewName: src = GetViewName(); break; default: TRACEX(OwlDocView, 0, _T("GetProperty(): ") \ _T("invalid property [") << index << _T("] specified!") ); return 0; } if (!textlen) { TRACEX(OwlDocView, 0, _T("GetProperty(): 0-Length buffer specified!")); return 0; } int srclen = src ? static_cast<int>(::_tcslen(src)) : 0; if (textlen > srclen) textlen = srclen; if (textlen) memcpy(dest, src, textlen*sizeof(tchar)); *((tchar *)dest + textlen) = 0; return srclen; } // /// Increments an internal count used by the Doc/View subsystem to identify each /// view. // void TView::BumpNextViewId() { if (++NextViewId < MinUniqueViewId) NextViewId = MinUniqueViewId; } IMPLEMENT_ABSTRACT_STREAMABLE(TView); #if !defined(BI_NO_OBJ_STREAMING) // // // void* TView::Streamer::Read(ipstream& is, uint32 /*version*/) const { TView* o = GetObject(); bool hasViewMenu = is.readByte(); if (hasViewMenu) { o->ViewMenu = new TMenuDescr; is >> *o->ViewMenu; } else o->ViewMenu = 0; o->ViewBar = 0; is >> o->ViewId; is >> o->Doc; is >> o->NextView; return o; } // // // void TView::Streamer::Write(opstream& os) const { TView* o = GetObject(); os.writeByte(uint8(o->ViewMenu ? 1 : 0)); if (o->ViewMenu) os << *o->ViewMenu; os << o->ViewId; os << o->Doc; os << o->NextView; } #endif // BI_NO_OBJ_STREAMING //---------------------------------------------------------------------------- // TWindowView Implementation // DEFINE_RESPONSE_TABLE1(TWindowView, TWindow) EV_VN_ISWINDOW, END_RESPONSE_TABLE; // /// Constructs a TWindowView interface object associated with the window view. Sets /// ViewId to NextViewId. Calls the associated document's AttachView() function (a /// private TDocument function) to attach the view to the document. // TWindowView::TWindowView(TDocument& doc, TWindow* parent) : TWindow(parent, 0, doc.GetDocManager().GetApplication()), TView(doc) { } // IMPLEMENT_STREAMABLE2(TWindowView, TWindow, TView); #if !defined(BI_NO_OBJ_STREAMING) // // // void* TWindowView::Streamer::Read(ipstream& is, uint32 /*version*/) const { ReadBaseObject((TWindow*)GetObject(), is); ReadBaseObject((TView*)GetObject(), is); return GetObject(); } // // // void TWindowView::Streamer::Write(opstream& os) const { WriteBaseObject((TWindow*)GetObject(), os); WriteBaseObject((TView*)GetObject(), os); } #endif // BI_NO_OBJ_STREAMING //---------------------------------------------------------------------------- // TDialogView Implementation // DEFINE_RESPONSE_TABLE1(TDialogView, TDialog) EV_VN_ISWINDOW, END_RESPONSE_TABLE; // // // TDialogView::TDialogView(TDocument& doc, TWindow* parent, TResId resId, TModule* module) : TDialog(parent, resId, module), TView(doc) { } // TDialogView::TDialogView(TDocument& doc, TWindow* parent, const DLGTEMPLATE& dlgTemplate, TAutoDelete del, TModule* module) : TDialog(parent, dlgTemplate, del, module), TView(doc) { } // TDialogView::TDialogView(TDocument& doc, TWindow* parent, TModule* module, HGLOBAL hTemplate, TAutoDelete del) : TDialog(hTemplate, parent, del, module), TView(doc) { } // IMPLEMENT_STREAMABLE2(TDialogView, TDialog, TView); #if !defined(BI_NO_OBJ_STREAMING) // // // void* TDialogView::Streamer::Read(ipstream& is, uint32 /*version*/) const { ReadBaseObject((TDialog*)GetObject(), is); ReadBaseObject((TView*)GetObject(), is); return GetObject(); } // // // void TDialogView::Streamer::Write(opstream& os) const { WriteBaseObject((TDialog*)GetObject(), os); WriteBaseObject((TView*)GetObject(), os); } #endif // BI_NO_OBJ_STREAMING //---------------------------------------------------------------------------- } // OWL namespace /* ========================================================================== */
26.366584
100
0.626501
pierrebestwork
cbd2410a82d11ff7bc559271f3506a759f241e03
290
cpp
C++
src/Mementos/Memento.cpp
edusidsan/GameProg-OO
c74bedb6c592386a40eefbd61770184994a75aa6
[ "MIT" ]
null
null
null
src/Mementos/Memento.cpp
edusidsan/GameProg-OO
c74bedb6c592386a40eefbd61770184994a75aa6
[ "MIT" ]
null
null
null
src/Mementos/Memento.cpp
edusidsan/GameProg-OO
c74bedb6c592386a40eefbd61770184994a75aa6
[ "MIT" ]
null
null
null
#include "Memento.hpp" namespace OgrO // Namespace com o nome do jogo. { namespace Mementos { Memento::Memento() { } Memento::~Memento() { } nlohmann::json Memento::toJSON() { return ""; } } }
15.263158
47
0.444828
edusidsan
cbd9f4d23df19555182da1d6d25c2848becf0668
863
cpp
C++
Tankerfield/Tankerfield/Obj_Building.cpp
gamificalostudio/Tankerfield
f3801c5286ae836c0fd62392cc14be081b5c74e8
[ "MIT" ]
7
2019-03-11T11:31:36.000Z
2019-05-18T08:03:35.000Z
Tankerfield/Tankerfield/Obj_Building.cpp
gamificalostudio/Tankerfield
f3801c5286ae836c0fd62392cc14be081b5c74e8
[ "MIT" ]
86
2019-03-27T14:36:16.000Z
2019-06-10T18:43:52.000Z
Tankerfield/Tankerfield/Obj_Building.cpp
gamificalostudio/Tankerfield
f3801c5286ae836c0fd62392cc14be081b5c74e8
[ "MIT" ]
1
2019-09-10T17:37:44.000Z
2019-09-10T17:37:44.000Z
#include "PugiXml/src/pugiconfig.hpp" #include "PugiXml/src/pugixml.hpp" #include "app.h" #include "Obj_Building.h" #include "M_Textures.h" #include "M_Render.h" #include "M_Collision.h" #include "M_Input.h" #include "Log.h" #include "M_Map.h" #include "M_ObjManager.h" SDL_Texture * Obj_Building::texture = nullptr; Obj_Building::Obj_Building(fPoint pos) : Object(pos) { } Obj_Building::~Obj_Building() { } void Obj_Building::SetTexture(const char* path) { texture = app->tex->Load(path); curr_tex = texture; frame.x = 0; frame.y = 0; SDL_QueryTexture(texture, NULL, NULL, &frame.w, &frame.h);//Set the frame w & h to do sprite sorting correctly } void Obj_Building::SetCollider(const fRect & collider_rect) { coll = app->collision->AddCollider(collider_rect.pos, collider_rect.w, collider_rect.h, TAG::WALL, BODY_TYPE::STATIC, 0.f, this); }
20.069767
130
0.7219
gamificalostudio
cbdfd291270d68e0cc3fedcecb1210f83562805a
827
hpp
C++
src/LEDEffect/Effects/BaseEffect.hpp
Diaoul/LEDEffect
1524325597a5195f7a4d96bd6a9df712bcb8196c
[ "MIT" ]
7
2018-02-14T06:10:33.000Z
2022-01-01T09:56:27.000Z
src/LEDEffect/Effects/BaseEffect.hpp
Diaoul/LEDEffect
1524325597a5195f7a4d96bd6a9df712bcb8196c
[ "MIT" ]
1
2018-11-06T12:51:29.000Z
2019-07-21T04:58:08.000Z
src/LEDEffect/Effects/BaseEffect.hpp
Diaoul/LEDEffect
1524325597a5195f7a4d96bd6a9df712bcb8196c
[ "MIT" ]
1
2019-05-05T16:32:51.000Z
2019-05-05T16:32:51.000Z
#pragma once #include <ArduinoJson.h> #include <FastLED.h> #include "../Configuration.hpp" #ifndef LEDEFFECT_EFFECT_NAME_MAX_LENGTH #define LEDEFFECT_EFFECT_NAME_MAX_LENGTH 20 #endif class BaseEffect { public: char name[LEDEFFECT_EFFECT_NAME_MAX_LENGTH]; const size_t jsonBufferSize = 0; BaseEffect(const char* name, const size_t jsonBufferSize = 0) : jsonBufferSize(jsonBufferSize) { strncpy(this->name, name, LEDEFFECT_EFFECT_NAME_MAX_LENGTH); }; virtual void begin(CLEDController* controller) { LEDEFFECT_DEBUG_PRINT(F("BaseEffect: Beginning effect ")); LEDEFFECT_DEBUG_PRINTLN(name); _controller = controller; } virtual void deserialize(JsonObject& data) = 0; virtual void serialize(JsonObject& data) const = 0; virtual void loop() = 0; protected: CLEDController* _controller; };
24.323529
98
0.758162
Diaoul
cbe0f1ebebbb45a7844417707eebb67260279d3f
12,583
cpp
C++
libcaf_core/src/blocking_actor.cpp
samanbarghi/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
2
2020-08-25T15:22:08.000Z
2021-03-05T16:29:24.000Z
libcaf_core/src/blocking_actor.cpp
wujsy/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/src/blocking_actor.cpp
wujsy/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <utility> #include "caf/blocking_actor.hpp" #include "caf/logger.hpp" #include "caf/actor_system.hpp" #include "caf/actor_registry.hpp" #include "caf/detail/sync_request_bouncer.hpp" #include "caf/detail/invoke_result_visitor.hpp" #include "caf/detail/default_invoke_result_visitor.hpp" namespace caf { blocking_actor::receive_cond::~receive_cond() { // nop } bool blocking_actor::receive_cond::pre() { return true; } bool blocking_actor::receive_cond::post() { return true; } blocking_actor::accept_one_cond::~accept_one_cond() { // nop } bool blocking_actor::accept_one_cond::post() { return false; } blocking_actor::blocking_actor(actor_config& cfg) : extended_base(cfg.add_flag(local_actor::is_blocking_flag)) { // nop } blocking_actor::~blocking_actor() { // avoid weak-vtables warning } void blocking_actor::enqueue(mailbox_element_ptr ptr, execution_unit*) { CAF_ASSERT(ptr != nullptr); CAF_ASSERT(getf(is_blocking_flag)); CAF_LOG_TRACE(CAF_ARG(*ptr)); CAF_LOG_SEND_EVENT(ptr); auto mid = ptr->mid; auto src = ptr->sender; // returns false if mailbox has been closed if (!mailbox().synchronized_enqueue(mtx_, cv_, ptr.release())) { CAF_LOG_REJECT_EVENT(); if (mid.is_request()) { detail::sync_request_bouncer srb{exit_reason()}; srb(src, mid); } } else { CAF_LOG_ACCEPT_EVENT(); } } const char* blocking_actor::name() const { return "blocking_actor"; } void blocking_actor::launch(execution_unit*, bool, bool hide) { CAF_LOG_TRACE(CAF_ARG(hide)); CAF_ASSERT(getf(is_blocking_flag)); if (!hide) register_at_system(); home_system().inc_detached_threads(); std::thread([](strong_actor_ptr ptr) { // actor lives in its own thread auto this_ptr = ptr->get(); CAF_ASSERT(dynamic_cast<blocking_actor*>(this_ptr) != 0); auto self = static_cast<blocking_actor*>(this_ptr); CAF_SET_LOGGER_SYS(ptr->home_system); CAF_PUSH_AID_FROM_PTR(self); self->initialize(); error rsn; # ifndef CAF_NO_EXCEPTIONS try { self->act(); rsn = self->fail_state_; } catch (...) { rsn = exit_reason::unhandled_exception; } try { self->on_exit(); } catch (...) { // simply ignore exception } # else self->act(); rsn = self->fail_state_; self->on_exit(); # endif self->cleanup(std::move(rsn), self->context()); ptr->home_system->dec_detached_threads(); }, strong_actor_ptr{ctrl()}).detach(); } blocking_actor::receive_while_helper blocking_actor::receive_while(std::function<bool()> stmt) { return {this, std::move(stmt)}; } blocking_actor::receive_while_helper blocking_actor::receive_while(const bool& ref) { return receive_while([&] { return ref; }); } void blocking_actor::await_all_other_actors_done() { system().registry().await_running_count_equal(getf(is_registered_flag) ? 1 : 0); } void blocking_actor::act() { CAF_LOG_TRACE(""); if (initial_behavior_fac_) initial_behavior_fac_(this); } void blocking_actor::fail_state(error err) { fail_state_ = std::move(err); } namespace { class message_sequence { public: virtual ~message_sequence() { // nop } virtual bool at_end() = 0; virtual bool await_value(bool reset_timeout) = 0; virtual mailbox_element& value() = 0; virtual void advance() = 0; virtual void erase_and_advance() = 0; }; class cached_sequence : public message_sequence { public: using cache_type = local_actor::mailbox_type::cache_type; using iterator = cache_type::iterator; cached_sequence(cache_type& cache) : cache_(cache), i_(cache.continuation()), e_(cache.end()) { // iterater to the first un-marked element i_ = advance_impl(i_); } bool at_end() override { return i_ == e_; } void advance() override { CAF_ASSERT(i_->marked); i_->marked = false; i_ = advance_impl(i_.next()); } void erase_and_advance() override { CAF_ASSERT(i_->marked); i_ = advance_impl(cache_.erase(i_)); } bool await_value(bool) override { return true; } mailbox_element& value() override { CAF_ASSERT(i_->marked); return *i_; } public: iterator advance_impl(iterator i) { while (i != e_) { if (!i->marked) { i->marked = true; return i; } ++i; } return i; } cache_type& cache_; iterator i_; iterator e_; }; class mailbox_sequence : public message_sequence { public: mailbox_sequence(blocking_actor* self, duration rel_timeout) : self_(self), rel_tout_(rel_timeout) { next_timeout(); } bool at_end() override { return false; } void advance() override { if (ptr_) self_->push_to_cache(std::move(ptr_)); next_timeout(); } void erase_and_advance() override { ptr_.reset(); next_timeout(); } bool await_value(bool reset_timeout) override { if (!rel_tout_.valid()) { self_->await_data(); return true; } if (reset_timeout) next_timeout(); return self_->await_data(abs_tout_); } mailbox_element& value() override { ptr_ = self_->dequeue(); CAF_ASSERT(ptr_ != nullptr); return *ptr_; } private: void next_timeout() { abs_tout_ = std::chrono::high_resolution_clock::now(); abs_tout_ += rel_tout_; } blocking_actor* self_; duration rel_tout_; std::chrono::high_resolution_clock::time_point abs_tout_; mailbox_element_ptr ptr_; }; class message_sequence_combinator : public message_sequence { public: using pointer = message_sequence*; message_sequence_combinator(pointer first, pointer second) : ptr_(first), fallback_(second) { // nop } bool at_end() override { if (ptr_->at_end()) { if (fallback_ == nullptr) return true; ptr_ = fallback_; fallback_ = nullptr; return at_end(); } return false; } void advance() override { ptr_->advance(); } void erase_and_advance() override { ptr_->erase_and_advance(); } bool await_value(bool reset_timeout) override { return ptr_->await_value(reset_timeout); } mailbox_element& value() override { return ptr_->value(); } private: pointer ptr_; pointer fallback_; }; } // namespace <anonymous> void blocking_actor::receive_impl(receive_cond& rcc, message_id mid, detail::blocking_behavior& bhvr) { CAF_LOG_TRACE(CAF_ARG(mid)); // we start iterating the cache and iterating mailbox elements afterwards cached_sequence seq1{mailbox().cache()}; mailbox_sequence seq2{this, bhvr.timeout()}; message_sequence_combinator seq{&seq1, &seq2}; detail::default_invoke_result_visitor<blocking_actor> visitor{this}; // read incoming messages until we have a match or a timeout for (;;) { // check loop pre-condition if (!rcc.pre()) return; // mailbox sequence is infinite, but at_end triggers the // transition from seq1 to seq2 if we iterated our cache if (seq.at_end()) CAF_RAISE_ERROR("reached the end of an infinite sequence"); // reset the timeout each iteration if (!seq.await_value(true)) { // short-circuit "loop body" bhvr.handle_timeout(); if (!rcc.post()) return; continue; } // skip messages in the loop body until we have a match bool skipped; bool timed_out; do { skipped = false; timed_out = false; auto& x = seq.value(); CAF_LOG_RECEIVE_EVENT((&x)); // skip messages that don't match our message ID if ((mid.valid() && mid != x.mid) || (!mid.valid() && x.mid.is_response())) { skipped = true; CAF_LOG_SKIP_EVENT(); } else { // blocking actors can use nested receives => restore current_element_ auto prev_element = current_element_; current_element_ = &x; switch (bhvr.nested(visitor, x.content())) { case match_case::skip: skipped = true; CAF_LOG_SKIP_EVENT(); break; default: break; case match_case::no_match: { auto sres = bhvr.fallback(*current_element_); // when dealing with response messages, there's either a match // on the first handler or we produce an error to // get a match on the second (error) handler if (sres.flag != rt_skip) { visitor.visit(sres); CAF_LOG_FINALIZE_EVENT(); } else if (mid.valid()) { // invoke again with an unexpected_response error auto& old = *current_element_; auto err = make_error(sec::unexpected_response, old.move_content_to_message()); mailbox_element_view<error> tmp{std::move(old.sender), old.mid, std::move(old.stages), err}; current_element_ = &tmp; bhvr.nested(tmp.content()); CAF_LOG_FINALIZE_EVENT(); } else { skipped = true; CAF_LOG_SKIP_EVENT(); } } } current_element_ = prev_element; } if (skipped) { seq.advance(); if (seq.at_end()) CAF_RAISE_ERROR("reached the end of an infinite sequence"); if (!seq.await_value(false)) { timed_out = true; } } } while (skipped && !timed_out); if (timed_out) bhvr.handle_timeout(); else seq.erase_and_advance(); // check loop post condition if (!rcc.post()) return; } } void blocking_actor::await_data() { if (!has_next_message()) mailbox().synchronized_await(mtx_, cv_); } bool blocking_actor::await_data(timeout_type timeout) { if (has_next_message()) return true; return mailbox().synchronized_await(mtx_, cv_, timeout); } mailbox_element_ptr blocking_actor::dequeue() { return next_message(); } void blocking_actor::varargs_tup_receive(receive_cond& rcc, message_id mid, std::tuple<behavior&>& tup) { using namespace detail; auto& bhvr = std::get<0>(tup); if (bhvr.timeout().valid()) { auto tmp = after(bhvr.timeout()) >> [&] { bhvr.handle_timeout(); }; auto fun = make_blocking_behavior(&bhvr, std::move(tmp)); receive_impl(rcc, mid, fun); } else { auto fun = make_blocking_behavior(&bhvr); receive_impl(rcc, mid, fun); } } size_t blocking_actor::attach_functor(const actor& x) { return attach_functor(actor_cast<strong_actor_ptr>(x)); } size_t blocking_actor::attach_functor(const actor_addr& x) { return attach_functor(actor_cast<strong_actor_ptr>(x)); } size_t blocking_actor::attach_functor(const strong_actor_ptr& ptr) { using wait_for_atom = atom_constant<atom("waitFor")>; if (!ptr) return 0; actor self{this}; ptr->get()->attach_functor([=](const error&) { anon_send(self, wait_for_atom::value); }); return 1; } } // namespace caf
27.354348
80
0.591751
samanbarghi
cbe45efaba1f21c3417aefbc6c14b73b112d21f3
9,248
cpp
C++
cpp/openScenarioLib/src/parser/ParserHelper.cpp
RA-Consulting-GmbH/openscenario.api.test
4b8aa781fc51862cac382b312855d520ea61aaa7
[ "Apache-2.0" ]
27
2020-08-13T11:39:24.000Z
2022-02-13T06:21:16.000Z
cpp/openScenarioLib/src/parser/ParserHelper.cpp
RA-Consulting-GmbH/openscenario.api.test
4b8aa781fc51862cac382b312855d520ea61aaa7
[ "Apache-2.0" ]
62
2020-08-12T14:53:29.000Z
2022-02-21T14:39:23.000Z
cpp/openScenarioLib/src/parser/ParserHelper.cpp
ahege/openscenario.api.test
94cc39a6caad0418c71aadc6567fa200ded0ac65
[ "Apache-2.0" ]
4
2021-07-08T03:04:14.000Z
2022-01-11T11:16:43.000Z
/* * Copyright 2020 RA Consulting * * RA Consulting GmbH licenses this file 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 "ParserHelper.h" /** * Container for parameter values (name, type, value) * @author Andreas Hege - RA Consulting * */ namespace NET_ASAM_OPENSCENARIO { std::string ParserHelper::ParseString(IParserMessageLogger& messageLogger, std::string& xmlValue, Textmarker& textMarker) { return xmlValue; } uint32_t ParserHelper::ParseUnsignedInt(IParserMessageLogger& messageLogger, std::string& xmlValue, Textmarker& textMarker) { try { const auto kResult = std::stoll(xmlValue, nullptr, 0); if (kResult > UNSIGNED_INT_MAX_VALUE || kResult < 0) { auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to an unsignedInteger. Value must be in [0.." + std::to_string(UNSIGNED_INT_MAX_VALUE) + "].", ERROR, textMarker); messageLogger.LogMessage(msg); } else return kResult & 0xffffffff; } catch ( std::invalid_argument& e ) { (void)e; auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to an unsignedInteger. Number format error.", ERROR, textMarker); messageLogger.LogMessage(msg); } return 0; } int ParserHelper::ParseInt(IParserMessageLogger& messageLogger, std::string& xmlValue, Textmarker& textMarker) { try { const auto kResult = std::stoi(xmlValue, nullptr, 0); return kResult; } catch (std::invalid_argument& e) { (void)e; auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to an int. Number format error.", ERROR, textMarker); messageLogger.LogMessage(msg); } return 0; } double ParserHelper::ParseDouble(IParserMessageLogger& messageLogger, std::string& xmlValue, Textmarker& textMarker) { try { const auto kResult = std::stod(xmlValue); return kResult; } catch (std::invalid_argument& e) { (void)e; auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to a double. Number format error.", ERROR, textMarker); messageLogger.LogMessage(msg); } return 0; } uint16_t ParserHelper::ParseUnsignedShort(IParserMessageLogger& messageLogger, std::string& xmlValue, Textmarker& textMarker) { try { const auto kResult = std::stol(xmlValue, nullptr, 0); if (kResult > 2 * UNSIGNED_SHORT_MAX_VALUE || kResult < 0) { auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to an unsignedShort. Value must be in [0.." + std::to_string(UNSIGNED_SHORT_MAX_VALUE) + "].", ERROR, textMarker); messageLogger.LogMessage(msg); } else return kResult & 0xffff; } catch (std::invalid_argument& e) { (void)e; auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to an unsignedShort. Number format error.", ERROR, textMarker); messageLogger.LogMessage(msg); } return 0; } bool ParserHelper::ParseBoolean(IParserMessageLogger& messageLogger, std::string& xmlValue, Textmarker& textMarker) { bool result; // std::transform(xmlValue.begin(), xmlValue.end(), xmlValue.begin(), [](unsigned char c) { return std::tolower(c, std::locale()); }); for ( std::string::iterator it=xmlValue.begin(); it!=xmlValue.end(); ++it) *it = std::tolower(*it, std::locale()); if (xmlValue == "1" || xmlValue == "true") result = true; else if (xmlValue == "0" || xmlValue == "false") result = false; else { auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to a boolean. Number format error.", ERROR, textMarker); messageLogger.LogMessage(msg); return false; } return result; } DateTime ParserHelper::ParseDateTime(IParserMessageLogger& messageLogger, std::string& xmlValue, Textmarker& textMarker) { DateTime result{}; try { if(!DateTimeParser::ToDateTime(xmlValue, result)) { auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to a dateTime. Number format error.", ERROR, textMarker); messageLogger.LogMessage(msg); return {}; } } catch (...) { auto msg = FileContentMessage("Cannot convert '" + xmlValue + "' to a dateTime. Number format error.", ERROR, textMarker); messageLogger.LogMessage(msg); return {}; } return result; } void ParserHelper::ValidateUnsignedInt(std::string& xmlValue) { try { const auto kResult = std::stoll(xmlValue, nullptr, 0); if (kResult > UNSIGNED_INT_MAX_VALUE || kResult < 0) { const std::string kErrorMessage = "Cannot convert '" + xmlValue + "' to an unsignedInteger. Value must be in [0.." + std::to_string(UNSIGNED_INT_MAX_VALUE)+ "]."; throw std::range_error(kErrorMessage); } } catch (...) { throw std::runtime_error("Cannot convert '" + xmlValue + "' to an unsignedInteger. Number format error."); } } void ParserHelper::ValidateInt(std::string& xmlValue) { try { (void) std::stoi(xmlValue, nullptr, 0); } catch (...) { throw std::runtime_error("Cannot convert '" + xmlValue + "' to an int. Number format error."); } } void ParserHelper::ValidateDouble(std::string& xmlValue) { try { (void) std::stod(xmlValue); } catch (...) { throw std::runtime_error("Cannot convert '" + xmlValue + "' to a double. Number format error."); } } void ParserHelper::ValidateUnsignedShort(std::string& xmlValue) { try { const auto kResult = std::stol(xmlValue, nullptr, 0); if (kResult > 2 * UNSIGNED_SHORT_MAX_VALUE || kResult < 0) { const std::string kErrorMessage = "Cannot convert '" + xmlValue + "' to an unsignedShort. Value must be in [0.." + std::to_string(UNSIGNED_SHORT_MAX_VALUE) + "]."; throw std::range_error(kErrorMessage); } } catch (...) { throw std::runtime_error("Cannot convert '" + xmlValue + "' to an unsignedShort. Number format error."); } } void ParserHelper::ValidateBoolean(std::string& xmlValue) { auto xmlValueCpy = xmlValue; for (std::string::iterator it = xmlValueCpy.begin(); it != xmlValueCpy.end(); ++it) *it = std::tolower(*it, std::locale()); if (xmlValueCpy !="true" && xmlValueCpy != "false" && xmlValueCpy != "0" && xmlValueCpy != "1") throw std::runtime_error("Cannot convert '" + xmlValue + "' to a boolean. Illegal boolean value."); } void ParserHelper::ValidateDateTime(std::string& xmlValue) { try { DateTime result{}; if (!DateTimeParser::ToDateTime(xmlValue, result)) { if (xmlValue != "true" && xmlValue != "false" && xmlValue != "0" && xmlValue != "1") throw std::runtime_error("Cannot convert '" + xmlValue + "' to a dateTime. Illegal dateTime value."); } } catch (...) { throw std::runtime_error("Cannot convert '" + xmlValue + "' to a dateTime. Illegal dateTime value."); } } bool ParserHelper::IsParametrized(std::string& value) { // Only Dollar will result in "$" std::smatch base_match; const std::regex base_regex("^\\s*\\$[A-Za-z_][A-Za-z0-9_]*$"); bool result = std::regex_match(value, base_match, base_regex); if (result) { return true; } else { return false; } } bool ParserHelper::IsExpression(std::string& value) { // Only Dollar will result in "$" std::smatch base_match; const std::regex base_regex("^\\s*\\$\\s*\\{"); bool result = std::regex_search(value, base_match, base_regex); if (result) { return true; } else { return false; } } }
33.028571
179
0.566609
RA-Consulting-GmbH
cbe7337258c637ed4b28bb56247d1cc6035aac59
443
cpp
C++
solutions/572.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
solutions/572.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
solutions/572.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
class Solution { bool isSame(TreeNode* s, TreeNode* t) { if ((s and not t) or (t and not s)) { return false; } if (not s and not t) { return true; } return s->val == t->val and isSame(s->left, t->left) and isSame(s->right, t->right); } public: bool isSubtree(TreeNode* s, TreeNode* t) { return isSame(s, t) or (s and (isSubtree(s->left, t) or isSubtree(s->right, t))); } };
22.15
69
0.539503
tdakhran
cbeb31de7370fe009de6013e233972bf1e167f60
1,329
cc
C++
leetcode/234_panlindrome_linked_list.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
leetcode/234_panlindrome_linked_list.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
leetcode/234_panlindrome_linked_list.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
/* * ===================================================================================== * * Filename: 234_panlindrome_linked_list.cc * * Description: * * Version: 1.0 * Created: 09/02/2015 09:32:09 AM * Revision: none * Compiler: gcc * * Author: (Qi Liu), liuqi.edward@gmail.com * Organization: antq.com * * Copyright (c) 2015, Qi Liu. * All rights reserved. * ===================================================================================== */ #include <stdlib.h> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool isPalindrome(ListNode* node) { int length = 0; bool odd = false; ListNode* head = node,* next_node,* tail; while(head != NULL){ length += 1; head = head->next; } if(length == 1) return true; if(length & 1){ odd = true; } head = NULL; next_node = node; length /= 2; for(int i = 0; i < length; ++i){ tail = next_node->next; next_node->next = head; head = next_node; next_node = tail; } if(odd){ next_node = next_node->next; } while(head != NULL){ if(head->val != next_node->val){ return false; } head = head->next; next_node = next_node->next; } return true; } };
20.446154
88
0.483822
norlanliu
cbeb6cd455d5c3953a1434129c7024d386911ab9
2,179
cpp
C++
Vishv_GE/Framework/Physics/Src/Simulation.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
1
2021-12-19T02:06:12.000Z
2021-12-19T02:06:12.000Z
Vishv_GE/Framework/Physics/Src/Simulation.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
null
null
null
Vishv_GE/Framework/Physics/Src/Simulation.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
null
null
null
#include "Precompiled.h" #include "Simulation.h" //using namespace physx; /* namespace { std::unique_ptr<Vishv::Physics::Simulation> sInstance = nullptr; } void Vishv::Physics::Simulation::StaticInitialize() { VISHVASSERT(sInstance == nullptr, "[SamplerManager] already Initialized"); sInstance = std::make_unique<Vishv::Physics::Simulation>(); sInstance->Initialize(); } void Vishv::Physics::Simulation::StaticTerminate() { if (sInstance != nullptr) { sInstance->Terminate(); sInstance.reset(); } } Vishv::Physics::Simulation* Vishv::Physics::Simulation::Get() { VISHVASSERT(sInstance != nullptr, "[SamplerManager] not Initialized"); return sInstance.get(); } void Vishv::Physics::Simulation::Initialize() { mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, mAllocator, mErrorCallBack); mVisualDebugger = physx::PxCreatePvd(*mFoundation); physx::PxPvdTransport* transport = physx::PxDefaultPvdSocketTransportCreate(hostIP.c_str(), 5425, 10); //mVisualDebugger->connect(*transport, physx::PxPvdInstrumentationFlag::eALL); mPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *mFoundation, physx::PxTolerancesScale(), true, mVisualDebugger); physx::PxSceneDesc sceneDesc(mPhysics->getTolerancesScale()); sceneDesc.gravity = { 0.0f, -9.81f, 0.0f }; mDispatcher = physx::PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = mDispatcher; sceneDesc.filterShader = physx::PxDefaultSimulationFilterShader; mScene = mPhysics->createScene(sceneDesc); physx::PxPvdSceneClient* pvdClient = mScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(physx::PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(physx::PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(physx::PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } mMaterial = mPhysics->createMaterial(0.5f, 0.5f, 0.6f); // (0, 1, 0, 0); physx::PxRigidStatic* groundPlane = PxCreatePlane(*mPhysics, physx::PxPlane(0.0f, 1.0f, 0.0f, 0.0f), *mMaterial); mScene->addActor(*groundPlane); for (physx::PxU32 i = 0; i < 5; i++) { //physx::createstack(physx::PxTransform(physx::PxVec3(0, 0, stackZ -= 10.0f)), 10, 2.0f); } } */
30.690141
114
0.744837
InFaNsO
cbee31800a2529e86e15c8612b7bded1108d537c
8,640
hpp
C++
src/xalanc/XMLSupport/XalanFormatterWriter.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XMLSupport/XalanFormatterWriter.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XMLSupport/XalanFormatterWriter.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(XALANFORMATTERWRITER_HEADER_GUARD_1357924680) #define XALANFORMATTERWRITER_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/XMLSupport/XMLSupportDefinitions.hpp> #include <xercesc/sax/SAXException.hpp> #include <xalanc/PlatformSupport/DOMStringHelper.hpp> #include <xalanc/PlatformSupport/Writer.hpp> #include <xalanc/PlatformSupport/XalanMessageLoader.hpp> #include <xalanc/PlatformSupport/XalanOutputStream.hpp> XALAN_CPP_NAMESPACE_BEGIN XALAN_USING_XERCES(MemoryManager) class XalanFormatterWriter { public: template <class WriterType> class NewLineWriterFunctor { public: typedef WriterType writer_type; NewLineWriterFunctor(WriterType& writer) : m_writer(writer), m_newlineString(0), m_newlineStringLength(0) { XalanOutputStream* stream = writer.getStream(); if(stream != 0) { m_newlineString = stream->getNewlineString(); } else { m_newlineString = XalanOutputStream::defaultNewlineString(); } assert(m_newlineString != 0); m_newlineStringLength = length(m_newlineString); } void operator()() { assert(m_newlineString != 0 && length(m_newlineString) == m_newlineStringLength); m_writer.write(m_newlineString, m_newlineStringLength); } private: WriterType& m_writer; /** * The string of characters that represents the newline */ const XalanDOMChar* m_newlineString; /** * The length of the the string of characters that represents the newline */ XalanDOMString::size_type m_newlineStringLength; }; template<class WriterType> class WhiteSpaceWriterFunctor { typedef XalanDOMString::size_type size_type; typedef typename WriterType::value_type value_type; public: typedef WriterType writer_type; WhiteSpaceWriterFunctor(WriterType& writer) : m_writer(writer) { } void operator()(size_type count) { for ( size_type i = 0 ; i < count ; i++ ) { m_writer.write(value_type(XalanUnicode::charSpace)); } } private: WriterType& m_writer; }; class CommonRepresentableCharFunctor { public: CommonRepresentableCharFunctor(const XalanOutputStream* stream) : m_stream(stream) { assert(stream != 0); } bool operator()(unsigned int theChar) const { bool result = true; if( m_stream != 0) { result = m_stream->canTranscodeTo(theChar); } return result; } private: const XalanOutputStream* const m_stream; }; public: typedef XalanDOMString::size_type size_type; XalanFormatterWriter( Writer& theWriter, MemoryManager& theMemoryManager) : m_writer(theWriter), m_memoryManager(theMemoryManager), m_stringBuffer(5, 0, theMemoryManager) { const XalanOutputStream* const theStream = theWriter.getStream(); if (theStream == 0) { m_newlineString = XalanOutputStream::defaultNewlineString(); } else { m_newlineString = theStream->getNewlineString(); } assert(m_newlineString != 0); m_newlineStringLength = length(m_newlineString); assert(m_newlineString != 0); } MemoryManagerType& getMemoryManager() { return m_memoryManager; } virtual ~XalanFormatterWriter() { } Writer* getWriter() const { return &m_writer; } XalanOutputStream* getStream() { return m_writer.getStream(); } const XalanOutputStream* getStream() const { return m_writer.getStream(); } void flushWriter() { m_writer.flush(); } static bool isUTF16HighSurrogate(XalanDOMChar theChar) { return 0xD800u <= theChar && theChar <= 0xDBFFu ? true : false; } static bool isUTF16LowSurrogate(XalanDOMChar theChar) { return 0xDC00u <= theChar && theChar <= 0xDFFFu ? true : false; } static unsigned int decodeUTF16SurrogatePair( XalanDOMChar theHighSurrogate, XalanDOMChar theLowSurrogate, MemoryManager& theManager) { assert(isUTF16HighSurrogate(theHighSurrogate) == true); if (isUTF16LowSurrogate(theLowSurrogate) == false) { throwInvalidUTF16SurrogateException(theHighSurrogate, theLowSurrogate, theManager); } return ((theHighSurrogate - 0xD800u) << 10) + theLowSurrogate - 0xDC00u + 0x00010000u; } static void throwInvalidCharacterException( unsigned int ch, MemoryManager& theManager) { XalanDOMString theMessage(theManager); XalanDOMString theBuffer(theManager); XalanMessageLoader::getMessage( theMessage, XalanMessages::InvalidScalar_1Param, UnsignedLongToHexDOMString(ch, theBuffer)); XALAN_USING_XERCES(SAXException) throw SAXException(c_wstr(theMessage), &theManager); } static void throwInvalidUTF16SurrogateException( XalanDOMChar ch, XalanDOMChar next, MemoryManagerType& theManager) { XalanDOMString chStr(theManager); XalanDOMString nextStr(theManager); UnsignedLongToHexDOMString(ch, chStr); UnsignedLongToHexDOMString(next, nextStr); XalanDOMString theMessage(theManager); XalanMessageLoader::getMessage( theMessage, XalanMessages::InvalidSurrogatePair_2Param, theMessage, chStr, nextStr); XALAN_USING_XERCES(SAXException) throw SAXException(c_wstr(theMessage),&theManager); } protected: /** * The writer. */ Writer& m_writer; /** * The MemoryManager instance to use for any dynamically- * allocated memory. */ MemoryManager& m_memoryManager; XalanDOMString m_stringBuffer; /** * The string of characters that represents the newline */ const XalanDOMChar* m_newlineString; /** * The length of the the string of characters that represents the newline */ XalanDOMString::size_type m_newlineStringLength; /** * Format a code point as a numeric character reference. * * @param theChar A Unicode code point. */ const XalanDOMString& formatNumericCharacterReference(unsigned int theNumber) { clear(m_stringBuffer); m_stringBuffer.push_back(XalanDOMChar(XalanUnicode::charAmpersand)); m_stringBuffer.push_back(XalanDOMChar(XalanUnicode::charNumberSign)); UnsignedLongToDOMString(theNumber, m_stringBuffer); m_stringBuffer.push_back(XalanDOMChar(XalanUnicode::charSemicolon)); return m_stringBuffer; } private: // These are not implemented. XalanFormatterWriter(); XalanFormatterWriter& operator=(const XalanFormatterWriter&); }; XALAN_CPP_NAMESPACE_END #endif // XALANFORMATTERWRITER_HEADER_GUARD_1357924680
24.40678
96
0.59537
rherardi
cbf1a5980840a20f46f686bceca55f9fd75d9794
176
cpp
C++
allMatuCommit/1_输出n的1-5次方_2021010915012_20210920100509.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/1_输出n的1-5次方_2021010915012_20210920100509.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/1_输出n的1-5次方_2021010915012_20210920100509.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
#include<stdio.h> int main() { int n,m=1; scanf_s("%d",&n); for(int i=0 ; i<4 ; i++) { m *= n; printf("%d ",m); } printf("%d\n",m*n); return 0; }
11.733333
30
0.414773
BachWV
cbf238f9e0dc5bc6fba564525d792d90fa60867b
18,554
cpp
C++
vision/route_plan/route_plan.cpp
Eithwa/kym2019
192ba41a304f8c92cab5997e48b357718a84c08e
[ "Apache-2.0" ]
2
2019-06-24T13:33:14.000Z
2019-06-30T07:42:51.000Z
vision/route_plan/route_plan.cpp
eithwa/kym2019
192ba41a304f8c92cab5997e48b357718a84c08e
[ "Apache-2.0" ]
null
null
null
vision/route_plan/route_plan.cpp
eithwa/kym2019
192ba41a304f8c92cab5997e48b357718a84c08e
[ "Apache-2.0" ]
3
2020-05-26T14:10:07.000Z
2020-08-13T02:56:06.000Z
#include "route_plan.h" #define TEST ros::package::getPath("vision")+"/route_plan/image.png" #define TO_RAD M_PI/180.0 #define TO_DEG 180.0/M_PI Vision::Vision() { //image_sub = nh.subscribe(VISION_TOPIC, 1,static_cast<void (Vision::*)(const sensor_msgs::ImageConstPtr&)>(&Vision::imageCb),this); image_sub = nh.subscribe(VISION_TOPIC, 1, &Vision::imageCb, this); } Vision::Vision(string topic) { //image_sub = nh.subscribe(topic, 1, &Vision::imageCb, this); } Vision::~Vision() { Source.release(); destroyAllWindows(); } double Vision::Rate() { double ALPHA = 0.5; double dt; static int frame_counter = 0; static double frame_rate = 0.0; static double StartTime = ros::Time::now().toNSec(); double EndTime; frame_counter++; if (frame_counter == 10) { EndTime = ros::Time::now().toNSec(); dt = (EndTime - StartTime) / frame_counter; StartTime = EndTime; if (dt != 0) { frame_rate = (1000000000.0 / dt) * ALPHA + frame_rate * (1.0 - ALPHA); //cout << "FPS: " << frame_rate << endl; } frame_counter = 0; } return frame_rate; } //=============================影像接收======================================= void Vision::imageCb(const sensor_msgs::ImageConstPtr &msg) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); //convert image data if (!cv_ptr->image.empty()) { Source = cv_ptr->image.clone(); cv::flip(Source, Source, 1); // reverse image monitor = Source.clone(); threshold = Mat(Size(Source.cols, Source.rows), CV_8UC3, Scalar(0, 0, 0)); FrameRate = Rate(); Mat blackline = Black_Item(Source); cv::imshow("Image window", cv_ptr->image); //cv::imshow("blackline", blackline); cv::imshow("monitor", monitor); //cv::waitKey(10); } } catch (cv_bridge::Exception &e) { ROS_ERROR("Could not convert to image!"); return; } } cv::Mat Vision::Black_Item(const cv::Mat iframe) { //cv::Mat threshold(iframe.rows, iframe.cols, CV_8UC3, Scalar(0, 0, 0)); cv::Mat oframe(iframe.rows, iframe.cols, CV_8UC3, Scalar(0, 0, 0)); //======================threshold=================== for (int i = 0; i < iframe.rows; i++) { for (int j = 0; j < iframe.cols; j++) { int gray = (iframe.data[(i * iframe.cols * 3) + (j * 3) + 0] + iframe.data[(i * iframe.cols * 3) + (j * 3) + 1] + iframe.data[(i * iframe.cols * 3) + (j * 3) + 2]) / 3; if (gray <= BlackGrayMsg) { threshold.data[(i * threshold.cols * 3) + (j * 3) + 0] = 0; threshold.data[(i * threshold.cols * 3) + (j * 3) + 1] = 0; threshold.data[(i * threshold.cols * 3) + (j * 3) + 2] = 0; } else { threshold.data[(i * threshold.cols * 3) + (j * 3) + 0] = 255; threshold.data[(i * threshold.cols * 3) + (j * 3) + 1] = 255; threshold.data[(i * threshold.cols * 3) + (j * 3) + 2] = 255; } } } //=====================draw the scan line=========== oframe = threshold.clone(); Mat frame_ = Mat(Size(Source.cols, Source.rows), CV_8UC3, Scalar(0, 0, 0)); DetectedObject FIND_Item;//找障礙物位置 vector<DetectedObject> obj_item; deque<int> find_point; int color = 0; //cout<<BlackGrayMsg<<endl; int x, y; int x_, y_; int object_size; int dis, ang; for (int distance = InnerMsg; distance <= Magn_Far_StartMsg; distance += Magn_Near_GapMsg) { for (int angle = 0; angle < 360; angle += Angle_Interval(distance)) { int find_angle = Angle_Adjustment(angle); if ((find_angle >= Unscaned_Angle[0] && angle <= Unscaned_Angle[1]) || (find_angle >= Unscaned_Angle[2] && angle <= Unscaned_Angle[3]) || (find_angle >= Unscaned_Angle[4] && angle <= Unscaned_Angle[5]) || (find_angle >= Unscaned_Angle[6] && angle <= Unscaned_Angle[7])) { continue; } object_size = 0; FIND_Item.size = 0; x_ = distance * Angle_cos[find_angle]; y_ = distance * Angle_sin[find_angle]; x = Frame_Area(CenterXMsg + x_, frame_.cols); y = Frame_Area(CenterYMsg - y_, frame_.rows); if (threshold.data[(y * threshold.cols + x) * 3 + 0] == 0&& threshold.data[(y * threshold.cols + x) * 3 + 1] == 0&& threshold.data[(y * threshold.cols + x) * 3 + 2] == 0 ) { Mark_point(frame_, find_point, distance, find_angle, x, y, object_size, color); FIND_Item.dis_max = distance; FIND_Item.dis_min = distance; FIND_Item.ang_max = find_angle; FIND_Item.ang_min = find_angle; while (!find_point.empty()) { dis = find_point.front(); find_point.pop_front(); ang = find_point.front(); find_point.pop_front(); object_compare(FIND_Item, dis, ang); find_around_black(frame_, find_point, dis, ang, object_size, color); } FIND_Item.size = object_size; } find_point.clear(); if(FIND_Item.size>20) //if (!(FIND_Item.size < 100 && FIND_Item.distance < 50)) { obj_item.push_back(FIND_Item); } } } for(int i = 0; i < obj_item.size(); i++){ int x, y; int x_, y_; int angle_, distance_; int find_angle; angle_ = Angle_Adjustment((obj_item.at(i).ang_max + obj_item.at(i).ang_min) / 2); distance_ = obj_item.at(i).dis_min; find_angle = Angle_Adjustment(angle_); x_ = distance_ * Angle_cos[find_angle]; y_ = distance_ * Angle_sin[find_angle]; x = Frame_Area(CenterXMsg + x_, Source.cols); y = Frame_Area(CenterYMsg - y_, Source.rows); obj_item.at(i).x = x; obj_item.at(i).y = y; obj_item.at(i).distance = distance_; obj_item.at(i).angle = find_angle; draw_ellipse(monitor, obj_item.at(i), 5); circle(monitor, Point(x, y), 3, Scalar(0, 0, 200), -1); } cv::imshow("threshold", threshold); cv::imshow("frame_", frame_); cv::waitKey(10); return oframe; } void Vision::Mark_point(Mat &frame_, deque<int> &find_point, int distance, int angle, int x, int y, int &size, int color) { frame_.data[(y * frame_.cols + x) * 3 + 0] = 255; frame_.data[(y * frame_.cols + x) * 3 + 1] = 255; frame_.data[(y * frame_.cols + x) * 3 + 2] = 255; find_point.push_back(distance); find_point.push_back(angle); size += 1; } //判斷物件資料並且更新 void Vision::object_compare(DetectedObject &FIND_Item, int distance, int angle) { if (FIND_Item.dis_max < distance) { FIND_Item.dis_max = distance; } if (FIND_Item.dis_min > distance) { FIND_Item.dis_min = distance; } if (FIND_Item.ang_max < angle) { FIND_Item.ang_max = angle; } if (FIND_Item.ang_min > angle) { FIND_Item.ang_min = angle; } } void Vision::find_around_black(Mat &frame_, deque<int> &find_point, int distance, int angle, int &size, int color) { int x, y; int x_, y_; int dis_f, ang_f; double angle_f; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { dis_f = distance + i * Magn_Near_GapMsg; if (dis_f < Magn_Near_StartMsg) dis_f = Magn_Near_StartMsg; //dis_f = Frame_Area(dis_f, Magn_Far_EndMsg); if(dis_f>Magn_Far_StartMsg)break; ang_f = angle + j * Angle_Interval(dis_f); ang_f = ang_f - (ang_f % Angle_Interval(dis_f)); while ((Angle_Adjustment(ang_f) > Unscaned_Angle[0] && Angle_Adjustment(ang_f) < Unscaned_Angle[1]) || (Angle_Adjustment(ang_f) > Unscaned_Angle[2] && Angle_Adjustment(ang_f) < Unscaned_Angle[3]) || (Angle_Adjustment(ang_f) > Unscaned_Angle[4] && Angle_Adjustment(ang_f) < Unscaned_Angle[5]) || (Angle_Adjustment(ang_f) > Unscaned_Angle[6] && Angle_Adjustment(ang_f) < Unscaned_Angle[7])) { if (j < 0){ ang_f += -1 * Angle_Interval(dis_f); ang_f = ang_f - (ang_f % Angle_Interval(dis_f)); } else{ ang_f += 1 * Angle_Interval(dis_f); ang_f = ang_f + (Angle_Interval(dis_f) - (ang_f % Angle_Interval(dis_f)) ); } } angle_f = Angle_Adjustment(ang_f); x_ = dis_f * Angle_cos[angle_f]; y_ = dis_f * Angle_sin[angle_f]; x = Frame_Area(CenterXMsg + x_, frame_.cols); y = Frame_Area(CenterYMsg - y_, frame_.rows); if (threshold.data[(y * threshold.cols + x) * 3 + 0] == 0 && frame_.data[(y * frame_.cols + x) * 3 + 0] == 0) { Mark_point(frame_, find_point, dis_f, ang_f, x, y, size, color); } } } } void Vision::draw_ellipse(Mat &frame_, DetectedObject &obj_, int color) { ellipse(frame_, Point(CenterXMsg, CenterYMsg), Size(obj_.dis_min, obj_.dis_min), 0, 360 - obj_.ang_max, 360 - obj_.ang_min, Scalar(0, 255, 255), 1); ellipse(frame_, Point(CenterXMsg, CenterYMsg), Size(obj_.dis_max, obj_.dis_max), 0, 360 - obj_.ang_max, 360 - obj_.ang_min, Scalar(0, 255, 255), 1); draw_Line(frame_, obj_.dis_max, obj_.dis_min, obj_.ang_max, 5); draw_Line(frame_, obj_.dis_max, obj_.dis_min, obj_.ang_min, 5); circle(frame_, Point(obj_.x, obj_.y), 2, Scalar(0, 0, 0), -1); } void Vision::draw_Line(Mat &frame_, int obj_distance_max, int obj_distance_min, int obj_angle, int color) { int x_, y_; double angle_f; int x[2], y[2]; angle_f = Angle_Adjustment(obj_angle); x_ = obj_distance_min * Angle_cos[angle_f]; y_ = obj_distance_min * Angle_sin[angle_f]; x[0] = Frame_Area(CenterXMsg + x_, frame_.cols); y[0] = Frame_Area(CenterYMsg - y_, frame_.rows); x_ = obj_distance_max * Angle_cos[angle_f]; y_ = obj_distance_max * Angle_sin[angle_f]; x[1] = Frame_Area(CenterXMsg + x_, frame_.cols); y[1] = Frame_Area(CenterYMsg - y_, frame_.rows); line(frame_, Point(x[0], y[0]), Point(x[1], y[1]), Scalar(255, 255, 0), 1); if(color==5){ line(frame_, Point(x[0], y[0]), Point(x[1], y[1]), Scalar(0, 255, 255), 1); } } void Vision::draw_field() { Mat img = imread(TEST, CV_LOAD_IMAGE_COLOR); int center_x = img.cols/2; int center_y = img.rows/2; //=========draw robot========== int x = center_x+robot_x; int y = center_y-robot_y; circle(img, Point(x, y), 20, Scalar(0, 255, 255), 2); int x_= x+20 * cos(imu_angle * TO_RAD); int y_= y-20 * sin(imu_angle * TO_RAD); line(img, Point(x, y), Point(x_, y_), Scalar(0, 255, 255), 2); //============================== //=========draw obstacle======== for(int i=0; i<obstacle_info.size(); i+=4){ int distance = obstacle_info.at(i+0); int angle = obstacle_info.at(i+1)+imu_angle; int angle_right = obstacle_info.at(i+2)+imu_angle; int angle_left = obstacle_info.at(i+3)+imu_angle; if(angle_right > 180) angle_right = angle_right - 360; if(angle_right <-180) angle_right = angle_right + 360; if(angle_left > 180) angle_left = angle_left - 360; if(angle_left <-180) angle_left = angle_left + 360; if(angle_right < angle_left)angle_right = 360 + angle_right; //cout<<angle_right<<" "<<angle_left<<" "<<endl; int o_x = x + distance * cos(angle * TO_RAD); int o_y = y - distance * sin(angle * TO_RAD); if(abs(o_y-center_y)>200){ ellipse(img, Point(x, y), Size(distance, distance), 0, 360 - angle_right, 360 - angle_left, Scalar(0, 0, 255), 2); }else{ ellipse(img, Point(x, y), Size(distance, distance), 0, 360 - angle_right, 360 - angle_left, Scalar(0, 0, 0), 2); } circle(img, Point(o_x, o_y), 3, Scalar(0, 0, 255), -1); } int b_goal_x = 300+50; int b_goal_y = 0; circle(img, Point(center_x+b_goal_x, center_y-b_goal_y), 3, Scalar(0, 0, 255), -1); int g_ang = atan2(b_goal_y-robot_y, b_goal_x-robot_x)*TO_DEG - imu_angle; if(g_ang > 180) g_ang = g_ang - 360; if(g_ang <-180) g_ang = g_ang + 360; //cout<<b_ang<<" " <<imu_angle<<endl; int g_dis = sqrt(pow(b_goal_y-robot_y,2)+pow(b_goal_x-robot_x,2)); x_= x+g_dis * cos((imu_angle+g_ang) * TO_RAD); y_= y-g_dis * sin((imu_angle+g_ang) * TO_RAD); line(img, Point(x, y), Point(x_, y_), Scalar(255, 0, 0), 2); //============================== //========route_plan============ route_plan(robot_x, robot_y, obstacle_info, g_dis, g_ang); //============================== x_= x+120 * cos((imu_angle+v_ang) * TO_RAD); y_= y-120 * sin((imu_angle+v_ang) * TO_RAD); line(img, Point(x, y), Point(x_, y_), Scalar(0, 0, 255), 15); x_= x+40 * cos((imu_angle+v_yaw) * TO_RAD); y_= y-40 * sin((imu_angle+v_yaw) * TO_RAD); line(img, Point(x, y), Point(x_, y_), Scalar(255, 255, 0), 2); imshow("img",img); waitKey(10); } void Vision::route_plan(int r_x, int r_y, vector<int> obstacle_info, int goal_dis, int goal_ang) { //===========場外障礙過慮============ vector <int> obstacle_filter; for(int i=0; i<obstacle_info.size(); i+=4){ int distance = obstacle_info.at(i+0); int angle = obstacle_info.at(i+1)+imu_angle; int o_x = r_x + distance * cos(angle * TO_RAD); int o_y = -r_y - distance * sin(angle * TO_RAD); if(abs(o_y)<200){ obstacle_filter.push_back(obstacle_info.at(i+0)); obstacle_filter.push_back(obstacle_info.at(i+1)); obstacle_filter.push_back(obstacle_info.at(i+2)); obstacle_filter.push_back(obstacle_info.at(i+3)); } } //================================= //===========背向權重計算=========== int rf_x=0; int rf_y=0; int dis_threshold = 200; for(int i=0; i<obstacle_filter.size(); i+=4){ int distance = obstacle_filter.at(i+0); int angle = obstacle_filter.at(i+1)-180; if(angle<-180)angle = angle+360; if(distance<dis_threshold){ rf_x += (dis_threshold-distance)*cos(angle*TO_RAD); rf_y += (dis_threshold-distance)*sin(angle*TO_RAD); } } v_yaw = atan2(rf_y,rf_x)*TO_DEG; //cout<<v_yaw<<endl; //================================= //============避障路徑規劃========== vector <int> route_ang; route_ang.push_back(goal_ang); int ang_threshold = 180; int two_robot_dis = 40; //cout<<obstacle_filter.size()<<endl; for(int i=0; i<obstacle_filter.size(); i+=4){ int distance = obstacle_filter.at(i+0); int angle = obstacle_filter.at(i+1); if(abs(angle-goal_ang)<ang_threshold || abs(360-abs(angle-goal_ang))<ang_threshold){ int tmp = sqrt(pow(distance,2)-pow(two_robot_dis,2)); //cout<<distance<<endl; //cout<<tmp<<endl; int escape_ang = atan2(tmp, two_robot_dis)*TO_DEG; if(distance<=two_robot_dis+5 || escape_ang>70)escape_ang = 70; //cout<<escape_ang<<endl; int angle_right = angle+escape_ang; int angle_left = angle-escape_ang; if(angle_right > 180) angle_right = angle_right - 360; if(angle_right <-180) angle_right = angle_right + 360; if(angle_left > 180) angle_left = angle_left - 360; if(angle_left <-180) angle_left = angle_left + 360; route_ang.push_back(angle_right); route_ang.push_back(angle_left); //cout<<angle_right<<endl; //v_ang = angle_right; } } //清除被阻擋角度 vector <int> route_ang_filter; //cout<<"fuck "<<goal_ang<<" "<<route_ang.at(0)<<endl; cout<<"route "<<route_ang.size()<<endl; for(int j=0; j<route_ang.size(); j++){ bool cross_flag = true; cout<<route_ang.at(j)<<endl; for(int i=0; i<obstacle_filter.size(); i+=4){ int dis = obstacle_filter.at(i+0); int ang = obstacle_filter.at(i+1); int min_ang = (abs(route_ang.at(j)-ang) < abs(360-abs(route_ang.at(j)-ang)) )?abs(route_ang.at(j)-ang):abs(360-abs(route_ang.at(j)-ang)); int cross_dis = abs((double)(dis/(double)cos(min_ang*TO_RAD))*(double)sin(min_ang*TO_RAD)); //cout<<"dis "<<dis<<" "<<ang<<" cross dis "<<cross_dis<<" "<<min_ang<<endl; int angle = route_ang.at(j)+imu_angle; int x = r_x + 100 * cos(angle * TO_RAD); int y = -r_y - 100 * sin(angle * TO_RAD); if(cross_dis < two_robot_dis -10 && min_ang<90) cross_flag=false; //cout<<"x "<<x<<" y "<<y<<endl; if(abs(x)>300||abs(y)>200)cross_flag=false; } //cout<<endl; if(cross_flag ==true){ route_ang_filter.push_back(route_ang.at(j)); } } //找最小角度 int min_ang = 999; int good_ang; cout<<"filter "<<route_ang_filter.size()<<endl; if(!route_ang_filter.empty()){ for(int i=0; i<route_ang_filter.size(); i++){ int ang = (abs(route_ang_filter.at(i)-goal_ang) < abs(360-abs(route_ang_filter.at(i)-goal_ang)) )?abs(route_ang_filter.at(i)-goal_ang):abs(360-abs(route_ang_filter.at(i)-goal_ang)); //cout<<route_ang_filter.at(i)<<" "<<ang<<" "<<min_ang <<endl; if(ang<abs(min_ang)){ //cout<<min_ang<<" "<<ang<<endl; min_ang = ang; good_ang = route_ang_filter.at(i); } } } int final_route_ang = goal_ang; if(min_ang!=999){ final_route_ang = good_ang; } cout<<"final_route_ang " <<final_route_ang<<endl; v_ang = final_route_ang; }
37.108
193
0.54468
Eithwa
cbf55906feec3a8b2f95816ca1501bdd488c606a
3,438
cpp
C++
openstudiocore/src/utilities/core/CommandLine.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/utilities/core/CommandLine.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
null
null
null
openstudiocore/src/utilities/core/CommandLine.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY 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 "CommandLine.hpp" namespace openstudio{ // platform specific #ifdef _WINDOWS #include <Windows.h> // for SetConsoleOutputCP /** Manage the console. */ class ConsoleInitializer{ public: /** Initialize the console. */ ConsoleInitializer(); /** Restore the console. */ virtual ~ConsoleInitializer(); private: unsigned m_inputCP; unsigned m_outputCP; }; /** Initialize the console. */ ConsoleInitializer::ConsoleInitializer() : m_inputCP(GetConsoleCP()), m_outputCP(GetConsoleOutputCP()) { // http://msdn.microsoft.com/en-us/library/ms686036%28VS.85%29.aspx //bool b1 = SetConsoleCP(65001); // set to UTF-8 //bool b2 = SetConsoleOutputCP(65001); // set to UTF-8 //bool b1 = SetConsoleCP(1200); // set to UTF-16LE //bool b2 = SetConsoleOutputCP(1200); // set to UTF-16LE //unsigned inputCP = GetConsoleCP(); //unsigned outputCP = GetConsoleOutputCP(); } /** Restore the console. */ ConsoleInitializer::~ConsoleInitializer() { SetConsoleCP(m_inputCP); SetConsoleOutputCP(m_outputCP); } // Global ConsoleInitializer object static ConsoleInitializer GlobalConsoleOutputInitializer; #endif } // openstudio
44.649351
120
0.689354
hongyuanjia
cbf71ea3ae36b3169d4875526bbaf2c5844ee2f2
42,911
cc
C++
arcane/src/arcane/std/CartesianMeshGenerator.cc
grospelliergilles/framework
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
[ "Apache-2.0" ]
null
null
null
arcane/src/arcane/std/CartesianMeshGenerator.cc
grospelliergilles/framework
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
[ "Apache-2.0" ]
null
null
null
arcane/src/arcane/std/CartesianMeshGenerator.cc
grospelliergilles/framework
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
[ "Apache-2.0" ]
null
null
null
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* CartesianMeshGenerator.cc (C) 2000-2021 */ /* */ /* Service de génération de maillage cartésien. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arcane/std/CartesianMeshGenerator.h" #include "arcane/utils/Array.h" #include "arcane/utils/HashTableMap.h" #include "arcane/utils/PlatformUtils.h" #include "arcane/utils/ITraceMng.h" #include "arcane/utils/Real3.h" #include "arcane/utils/ValueConvert.h" #include "arcane/utils/CheckedConvert.h" #include "arcane/IMeshReader.h" #include "arcane/ISubDomain.h" #include "arcane/ICaseDocument.h" #include "arcane/XmlNode.h" #include "arcane/XmlNodeList.h" #include "arcane/XmlNodeIterator.h" #include "arcane/Service.h" #include "arcane/IParallelMng.h" #include "arcane/Item.h" #include "arcane/ItemGroup.h" #include "arcane/IMesh.h" #include "arcane/IMeshSubMeshTransition.h" #include "arcane/IItemFamily.h" #include "arcane/MeshVariable.h" #include "arcane/MeshUtils.h" #include "arcane/ItemPrinter.h" #include "arcane/FactoryService.h" #include "arcane/AbstractService.h" #include "arcane/Properties.h" #include "arcane/MeshPartInfo.h" #include "arcane/IMeshBuilder.h" #include "arcane/IMeshUniqueIdMng.h" #include "arcane/ICartesianMeshGenerationInfo.h" #include "arcane/std/Cartesian2DMeshGenerator_axl.h" #include "arcane/std/Cartesian3DMeshGenerator_axl.h" #include "arcane/std/internal/SodStandardGroupsBuilder.h" /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arcane { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void CartesianMeshGeneratorBuildInfo:: readOptionsFromXml(XmlNode cartesian_node) { XmlNode origine_node = cartesian_node.child("origine"); XmlNode nsd_node = cartesian_node.child("nsd"); XmlNodeList lx_node_list = cartesian_node.children("lx"); XmlNodeList ly_node_list = cartesian_node.children("ly"); XmlNodeList lz_node_list = cartesian_node.children("lz"); // On vérifie qu'on a bien au moins trois données x, y & z et une origine if (origine_node.null()) ARCANE_FATAL("No <origin> element found"); if (lx_node_list.size() == 0) ARCANE_FATAL("No <lx> elements found"); if (ly_node_list.size() == 0) ARCANE_FATAL("No <ly> elements found"); String origine_value = origine_node.value(); // On récupère l'origine bool is_bad_origin = builtInGetValue(m_origine, origine_value); // On regarde si on a un noeud en Z if (lz_node_list.size() == 0) { m_mesh_dimension = 2; // En 2D, on autorise l'origine a avoir 2 composantes if (is_bad_origin) { Real2 xy(0.0, 0.0); is_bad_origin = builtInGetValue(xy, origine_value); if (!is_bad_origin) { m_origine.x = xy.x; m_origine.y = xy.y; } } } else { m_mesh_dimension = 3; } if (is_bad_origin) ARCANE_FATAL("Element '{0}' : can not convert value '{1}' to type Real3", origine_node.xpathFullName(), origine_value); // On récupère les longueurs des blocs, + true pour throw_exception // On récupère aussi les nombres de mailles des blocs + true pour throw_exception // On récupère aussi les progressions géométriques // On met les progressions à 1.0 par défaut for (XmlNode& lx_node : lx_node_list) { m_bloc_lx.add(lx_node.valueAsReal(true)); m_bloc_nx.add(lx_node.attr("nx", true).valueAsInteger(true)); Real px = lx_node.attr("prx").valueAsReal(true); if (px == 0.0) px = 1.0; m_bloc_px.add(px); } for (XmlNode& ly_node : ly_node_list.range()) { m_bloc_ly.add(ly_node.valueAsReal(true)); m_bloc_ny.add(ly_node.attr("ny", true).valueAsInteger(true)); Real py = ly_node.attr("pry").valueAsReal(true); if (py == 0.0) py = 1.0; m_bloc_py.add(py); } if (m_mesh_dimension == 3) { for (XmlNode& lz_node : lz_node_list.range()) { m_bloc_lz.add(lz_node.valueAsReal(true)); m_bloc_nz.add(lz_node.attr("nz", true).valueAsInteger(true)); Real pz = lz_node.attr("prz").valueAsReal(true); if (pz == 0.0) pz = 1.0; m_bloc_pz.add(pz); } } // On récupère les nombres de sous-domaines + throw_exception String nsd_value = nsd_node.value(); IntegerUniqueArray nsd; if (builtInGetValue(nsd, nsd_value)) ARCANE_FATAL("Can not convert string '{0}' to Int[]", nsd_value); if (nsd.size() != m_mesh_dimension) ARCANE_FATAL("Number of sub-domain '<nsd>={0}' has to be equal to mesh dimension '{1}'", nsd.size(), m_mesh_dimension); m_nsdx = nsd[0]; m_nsdy = nsd[1]; m_nsdz = (m_mesh_dimension == 3) ? nsd[2] : 0; { XmlNode version_node = cartesian_node.child("face-numbering-version"); if (!version_node.null()){ Int32 v = version_node.valueAsInteger(true); if (v>=0) m_face_numbering_version = v; } } { XmlNode version_node = cartesian_node.child("edge-numbering-version"); if (!version_node.null()){ Int32 v = version_node.valueAsInteger(true); if (v>=0) m_edge_numbering_version = v; } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ CartesianMeshGenerator:: CartesianMeshGenerator(IPrimaryMesh* mesh) : TraceAccessor(mesh->traceMng()) , m_mesh(mesh) , m_my_mesh_part(mesh->parallelMng()->commRank()) { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ bool CartesianMeshGenerator:: readOptions(XmlNode cartesian_node) { m_build_info.readOptionsFromXml(cartesian_node); return _readOptions(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void CartesianMeshGenerator:: setBuildInfo(const CartesianMeshGeneratorBuildInfo& build_info) { m_build_info = build_info; _readOptions(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief readOptions */ bool CartesianMeshGenerator:: _readOptions() { Trace::Setter mci(traceMng(),"CartesianMeshGenerator"); m_mesh_dimension = m_build_info.m_mesh_dimension; Int32 nb_sub_domain = m_mesh->parallelMng()->commSize(); // On met les nombres de sous-domaines par défaut if (m_build_info.m_nsdx == 0 || nb_sub_domain == 1) m_build_info.m_nsdx = 1; if (m_build_info.m_nsdy == 0 || nb_sub_domain == 1) m_build_info.m_nsdy = 1; if (m_build_info.m_nsdz == 0 || nb_sub_domain == 1) m_build_info.m_nsdz = 1; // Synthèse des longueurs des blocs m_l.x = m_l.y = m_l.z = 0.; for (int i = 0; i < m_build_info.m_bloc_lx.size(); i += 1) m_l.x += m_build_info.m_bloc_lx.at(i); for (int i = 0; i < m_build_info.m_bloc_ly.size(); i += 1) m_l.y += m_build_info.m_bloc_ly.at(i); if (m_mesh_dimension == 3) for (int i = 0; i < m_build_info.m_bloc_lz.size(); i += 1) m_l.z += m_build_info.m_bloc_lz.at(i); // Synthèse des origines pour chaque bloc m_bloc_ox.add(m_build_info.m_origine.x); m_bloc_oy.add(m_build_info.m_origine.y); if (m_mesh_dimension == 3) m_bloc_oz.add(m_build_info.m_origine.z); for (int i = 0; i < m_build_info.m_bloc_lx.size(); i += 1) m_bloc_ox.add(m_bloc_ox.at(i) + m_build_info.m_bloc_lx.at(i)); for (int i = 0; i < m_build_info.m_bloc_ly.size(); i += 1) m_bloc_oy.add(m_bloc_oy.at(i) + m_build_info.m_bloc_ly.at(i)); if (m_mesh_dimension == 3) for (int i = 0; i < m_build_info.m_bloc_lz.size(); i += 1) m_bloc_oz.add(m_bloc_oz.at(i) + m_build_info.m_bloc_lz.at(i)); // Synthèse des nombres de mailles des blocs et en total m_nx = m_ny = m_nz = 0; for (int i = 0; i < m_build_info.m_bloc_nx.size(); ++i) m_nx += m_build_info.m_bloc_nx.at(i); for (int i = 0; i < m_build_info.m_bloc_ny.size(); ++i) m_ny += m_build_info.m_bloc_ny.at(i); if (m_mesh_dimension == 3) for (int i = 0; i < m_build_info.m_bloc_nz.size(); i += 1) m_nz += m_build_info.m_bloc_nz.at(i); else m_nz += 1; // On dump les infos récupérées jusque là info() << " mesh_name=" << m_mesh->name(); info() << " dimension=" << m_mesh_dimension; info() << " origin:" << m_build_info.m_origine; info() << " length x =" << m_l.x << "," << m_build_info.m_bloc_lx; info() << " length y=" << m_l.y << "," << m_build_info.m_bloc_ly; if (m_build_info.m_mesh_dimension == 3) info() << " length z=" << m_l.z << "," << m_build_info.m_bloc_lz; info() << "cells number:" << m_nx << "x" << m_ny << "x" << m_nz; info() << "progression x:" << m_build_info.m_bloc_px; info() << "progression y:" << m_build_info.m_bloc_py; if (m_mesh_dimension == 3) info() << "progression z:" << m_build_info.m_bloc_pz; info() << " nb_sub_domain:" << nb_sub_domain; info() << " decomposing the subdomains:" << m_build_info.m_nsdx << "x" << m_build_info.m_nsdy << "x" << m_build_info.m_nsdz; // Vérification du nombre de sous domaines vs ce qui a été spécifié if (m_build_info.m_nsdx * m_build_info.m_nsdy * m_build_info.m_nsdz != nb_sub_domain) ARCANE_FATAL("Specified partition {0}x{1}x{2} has to be equal to number of parts ({3})", m_build_info.m_nsdx,m_build_info.m_nsdy,m_build_info.m_nsdz,nb_sub_domain); return false; // false == ok } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ // ****************************************************************************** // * sd[X|Y|Z]Offset // ****************************************************************************** inline Integer CartesianMeshGenerator:: sdXOffset(Int32 this_sub_domain_id) { return this_sub_domain_id % m_build_info.m_nsdx; } inline Integer CartesianMeshGenerator:: sdYOffset(Int32 this_sub_domain_id) { return (this_sub_domain_id / m_build_info.m_nsdx) % m_build_info.m_nsdy; } inline Integer CartesianMeshGenerator:: sdZOffset(Int32 this_sub_domain_id) { return (this_sub_domain_id / (m_build_info.m_nsdx * m_build_info.m_nsdy)) % m_build_info.m_nsdz; } inline Integer CartesianMeshGenerator:: sdXOffset() { return sdXOffset(m_my_mesh_part); } inline Integer CartesianMeshGenerator:: sdYOffset() { return sdYOffset(m_my_mesh_part); } inline Integer CartesianMeshGenerator:: sdZOffset() { return sdZOffset(m_my_mesh_part); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ // ****************************************************************************** // * own[X|Y|Z]NbCell // ****************************************************************************** inline Int32 ownNbCell(Int64 n, Integer nsd, int sd_offset) { Int64 q = n / nsd; Int64 r = n % nsd; // Si on est en 'première approche', on a pas de reste if (r == 0) return CheckedConvert::toInt32(q); // Sinon, le reste des mailles est réparti sur les derniers sous domaines if (sd_offset < (nsd - r)) return CheckedConvert::toInt32(q); return CheckedConvert::toInt32(q + 1); } inline Int32 CartesianMeshGenerator:: ownXNbCell() { return ownNbCell(m_nx, m_build_info.m_nsdx, sdXOffset()); } inline Int32 CartesianMeshGenerator:: ownXNbCell(int isd) { return ownNbCell(m_nx, m_build_info.m_nsdx, sdXOffset(isd)); } inline Int32 CartesianMeshGenerator:: ownYNbCell() { return ownNbCell(m_ny, m_build_info.m_nsdy, sdYOffset()); } inline Int32 CartesianMeshGenerator:: ownYNbCell(int isd) { return ownNbCell(m_ny, m_build_info.m_nsdy, sdYOffset(isd)); } inline Int32 CartesianMeshGenerator:: ownZNbCell() { return ownNbCell(m_nz, m_build_info.m_nsdz, sdZOffset()); } inline Int32 CartesianMeshGenerator:: ownZNbCell(int isd) { return ownNbCell(m_nz, m_build_info.m_nsdz, sdZOffset(isd)); } // ****************************************************************************** // * iProgression // ****************************************************************************** inline Real iDelta(int iBloc, const RealArray& bloc_p, const Int32Array& bloc_n, const RealArray& bloc_l, const Real all_l, const Int64 all_n) { Real p = bloc_p.at(iBloc); Real n = (Real)bloc_n.at(iBloc); Real l = bloc_l.at(iBloc); if (p <= 1.0) return all_l / (Real)all_n; return (p - 1.0) / (math::pow(p, n) - 1.0) * l; } inline Real kDelta(Real k, int iBloc, const RealArray& bloc_p, const Int32Array& bloc_n, const RealArray& bloc_l, const Real all_l, const Int64 all_n) { ARCANE_UNUSED(all_l); ARCANE_UNUSED(all_n); Real p = bloc_p.at(iBloc); Real n = (Real)bloc_n.at(iBloc); Real l = bloc_l.at(iBloc); if (p == 1.0) return l * k / n; return l * (math::pow(p, k) - 1.0) / (math::pow(p, (Real)n) - 1.0); } inline Real CartesianMeshGenerator:: nxDelta(Real k, int iBloc) { return m_bloc_ox.at(iBloc) + kDelta(k, iBloc, m_build_info.m_bloc_px, m_build_info.m_bloc_nx, m_build_info.m_bloc_lx, m_l.x, m_nx); } inline Real CartesianMeshGenerator:: xDelta(int iBloc) { return iDelta(iBloc, m_build_info.m_bloc_px, m_build_info.m_bloc_nx, m_build_info.m_bloc_lx, m_l.x, m_nx); } inline Real CartesianMeshGenerator:: nyDelta(Real k, int iBloc) { return m_bloc_oy.at(iBloc) + kDelta(k, iBloc, m_build_info.m_bloc_py, m_build_info.m_bloc_ny, m_build_info.m_bloc_ly, m_l.y, m_ny); } inline Real CartesianMeshGenerator:: yDelta(int iBloc) { return iDelta(iBloc, m_build_info.m_bloc_py, m_build_info.m_bloc_ny, m_build_info.m_bloc_ly, m_l.y, m_ny); } inline Real CartesianMeshGenerator:: nzDelta(Real k, int iBloc) { return m_bloc_oz.at(iBloc) + kDelta(k, iBloc, m_build_info.m_bloc_pz, m_build_info.m_bloc_nz, m_build_info.m_bloc_lz, m_l.z, m_nz); } inline Real CartesianMeshGenerator:: zDelta(int iBloc) { return iDelta(iBloc, m_build_info.m_bloc_pz, m_build_info.m_bloc_nz, m_build_info.m_bloc_lz, m_l.z, m_nz); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ // ****************************************************************************** // * X scanning // ****************************************************************************** void CartesianMeshGenerator:: xScan(const Int64 all_nb_cell_x, IntegerArray& sd_x_ibl, IntegerArray& sd_x_obl, Int64Array& sd_x_nbl, Int64Array& sd_x_node_offset, Int64Array& sd_x_cell_offset) { sd_x_ibl.add(0); sd_x_obl.add(0); sd_x_nbl.add(0); sd_x_node_offset.add(0); sd_x_cell_offset.add(0); // Reset des indices, offset et frontières Int64 nsd = 0; Integer isd = 0; Integer ibl = 0; Integer obl = 0; Int64 nbl = 0; for (Int64 x = 0; x < all_nb_cell_x; ++x) { // Si on découvre la frontière d'un bloc if (x == (nbl + m_build_info.m_bloc_nx.at(ibl))) { nbl += m_build_info.m_bloc_nx.at(ibl); info(4) << "\t[CartesianMeshGenerator::xScan] Scan hit x bloc boundary: @ node " << nbl << ""; // On saute de bloc ibl += 1; // On reset l'offset de calcul dans le bloc obl = 0; } // Si on découvre la frontière d'un sous-domaine if (x == (nsd + ownXNbCell(isd))) { nsd += ownXNbCell(isd); info(4) << "\t[CartesianMeshGenerator::xScan] Scan hit x sub domain boundary: @ node " << nsd << ""; // On sauvegarde les infos nécessaire à la reprise par sous-domaine sd_x_ibl.add(ibl); sd_x_obl.add(obl); sd_x_nbl.add(nbl); sd_x_node_offset.add(nsd); sd_x_cell_offset.add(nsd); isd += 1; info(4) << "\t[CartesianMeshGenerator::xScan] Saving state: " << ", node_offset=" << sd_x_node_offset.at(isd) << ", cell_offset=" << sd_x_cell_offset.at(isd) << ", ibl=" << sd_x_ibl.at(isd) << ", nbl=" << sd_x_nbl.at(isd) << ""; } // On incrémente l'offset de calcul dans le bloc obl += 1; } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ // ****************************************************************************** // * Y scanning // ****************************************************************************** void CartesianMeshGenerator:: yScan(const Integer all_nb_cell_y, IntegerArray& sd_y_ibl, IntegerArray& sd_y_obl, Int64Array& sd_y_nbl, Int64Array& sd_y_node_offset, Int64Array& sd_y_cell_offset, Int64 all_nb_node_x, Int64 all_nb_cell_x) { sd_y_ibl.add(0); sd_y_obl.add(0); sd_y_nbl.add(0); sd_y_node_offset.add(0); sd_y_cell_offset.add(0); Int64 nsd = 0; Integer isd = 0; Integer ibl = 0; Integer obl = 0; Int64 nbl = 0; for (Int64 y = 0; y < all_nb_cell_y; ++y) { if (y == (nbl + m_build_info.m_bloc_ny.at(ibl))) { nbl += m_build_info.m_bloc_ny.at(ibl); info(4) << "\t[CartesianMeshGenerator::generateMesh] Scan hit y bloc boundary: @ node " << nbl << ""; ibl += 1; obl = 0; } if (y == (nsd + ownYNbCell(isd))) { nsd += ownYNbCell(isd); info(4) << "\t[CartesianMeshGenerator::generateMesh] Scan hit y sub domain boundary: @ node " << nsd << ""; sd_y_ibl.add(ibl); sd_y_obl.add(obl); sd_y_nbl.add(nbl * all_nb_node_x); sd_y_node_offset.add(nsd * all_nb_node_x); sd_y_cell_offset.add(nsd * all_nb_cell_x); isd += m_build_info.m_nsdx; } obl += 1; } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ // ****************************************************************************** // * Z scanning // ****************************************************************************** void CartesianMeshGenerator:: zScan(const Int64 all_nb_cell_z, IntegerArray& sd_z_ibl, IntegerArray& sd_z_obl, Int64Array& sd_z_nbl, Int64Array& sd_z_node_offset, Int64Array& sd_z_cell_offset, Int64 all_nb_node_xy, Int64 all_nb_cell_xy) { if (m_mesh_dimension != 3) return; sd_z_ibl.add(0); sd_z_obl.add(0); sd_z_nbl.add(0); sd_z_node_offset.add(0); sd_z_cell_offset.add(0); Int64 nsd = 0; Integer isd = 0; Integer ibl = 0; Integer obl = 0; Int64 nbl = 0; for (Int64 z = 0; z < all_nb_cell_z; ++z) { if (z == (nbl + m_build_info.m_bloc_nz.at(ibl))) { nbl += m_build_info.m_bloc_nz.at(ibl); ibl += 1; obl = 0; } if (z == (nsd + ownZNbCell(isd))) { nsd += ownZNbCell(isd); sd_z_ibl.add(ibl); sd_z_obl.add(obl); sd_z_nbl.add(nbl * all_nb_node_xy); sd_z_node_offset.add(nsd * all_nb_node_xy); sd_z_cell_offset.add(nsd * all_nb_cell_xy); isd += m_build_info.m_nsdx * m_build_info.m_nsdy; } obl += 1; } } // ****************************************************************************** // * generateMesh // ****************************************************************************** bool CartesianMeshGenerator:: generateMesh() { Trace::Setter mci(traceMng(),"CartesianMeshGenerator"); IPrimaryMesh* mesh = m_mesh; m_generation_info = ICartesianMeshGenerationInfo::getReference(mesh,true); info() << " decomposing the subdomains:" << m_build_info.m_nsdx << "x" << m_build_info.m_nsdy << "x" << m_build_info.m_nsdz; info() << "sub domain offset @ " << sdXOffset() << "x" << sdYOffset() << "x" << sdZOffset(); // All Cells Setup Integer all_nb_cell_x = m_nx; Integer all_nb_cell_y = m_ny; Integer all_nb_cell_z = m_nz; // Positionne des propriétés sur le maillage pour qu'il puisse connaître // le nombre de mailles dans chaque direction ainsi que l'offset du sous-domaine. // Cela est utilisé notammement par CartesianMesh. //Properties* mesh_properties = mesh->properties(); m_generation_info->setGlobalNbCells(all_nb_cell_x,all_nb_cell_y,all_nb_cell_z); m_generation_info->setSubDomainOffsets(sdXOffset(),sdYOffset(),sdZOffset()); m_generation_info->setNbSubDomains(m_build_info.m_nsdx,m_build_info.m_nsdy,m_build_info.m_nsdz); m_generation_info->setGlobalOrigin(m_build_info.m_origine); m_generation_info->setGlobalLength(m_l); Int64 all_nb_cell_xy = ((Int64)all_nb_cell_x) * ((Int64)all_nb_cell_y); Int64 all_nb_cell_xyz = ((Int64)all_nb_cell_xy) * ((Int64)all_nb_cell_z); info() << " all cells: " << all_nb_cell_x << "x" << all_nb_cell_y << "y" << all_nb_cell_z << "=" << all_nb_cell_xyz; // Own Cells Setup Int32 own_nb_cell_x = ownXNbCell(); Int32 own_nb_cell_y = ownYNbCell(); Int32 own_nb_cell_z = ownZNbCell(); m_generation_info->setOwnNbCells(own_nb_cell_x,own_nb_cell_y,own_nb_cell_z); Integer own_nb_cell_xy = CheckedConvert::multiply(own_nb_cell_x, own_nb_cell_y); Integer own_nb_cell_xyz = CheckedConvert::multiply(own_nb_cell_xy, own_nb_cell_z); info() << " own cells: " << own_nb_cell_x << "x" << own_nb_cell_y << "y" << own_nb_cell_z << "=" << own_nb_cell_xyz; // All Nodes Setup Integer all_nb_node_x = all_nb_cell_x + 1; Integer all_nb_node_y = all_nb_cell_y + 1; Int64 all_nb_node_xy = ((Int64)all_nb_node_x) * ((Int64)all_nb_node_y); // Own Nodes Setup Integer own_nb_node_x = own_nb_cell_x + 1; Integer own_nb_node_y = own_nb_cell_y + 1; Integer own_nb_node_z = (m_mesh_dimension == 3) ? own_nb_cell_z + 1 : own_nb_cell_z; Integer own_nb_node_xy = CheckedConvert::multiply(own_nb_node_x, own_nb_node_y); Integer own_nb_node_xyz = CheckedConvert::multiply(own_nb_node_xy, own_nb_node_z); info() << " own nodes: " << own_nb_node_x << "x" << own_nb_node_y << "y" << own_nb_node_z << "=" << own_nb_node_xyz; // Création hash-table des noeuds et préparation de leurs uid UniqueArray<Int64> nodes_unique_id(CheckedConvert::toInteger(own_nb_node_xyz)); HashTableMapT<Int64, NodeInfo> nodes_infos(CheckedConvert::toInteger(own_nb_node_xyz), true); // Calcule des infos blocs et des offset associés à tous les sub_domain_id IntegerUniqueArray sd_x_ibl, sd_x_obl; // Numéro et offset dans le bloc IntegerUniqueArray sd_y_ibl, sd_y_obl; IntegerUniqueArray sd_z_ibl, sd_z_obl; Int64UniqueArray sd_x_nbl, sd_y_nbl, sd_z_nbl; // Nombre dans le bloc Int64UniqueArray sd_x_node_offset; Int64UniqueArray sd_y_node_offset; Int64UniqueArray sd_z_node_offset; Int64UniqueArray sd_x_cell_offset; Int64UniqueArray sd_y_cell_offset; Int64UniqueArray sd_z_cell_offset; // Scan des sous domaines: i_ème (isd) et n_ème (nsd) noeud pour marquer la frontière sous domaine // Scan des des blocs: i_ème (ibl), o_ème offset (obl) et n_ème (nbl) noeud pour marquer la frontière bloc // Selon la direction X xScan(all_nb_cell_x, sd_x_ibl, sd_x_obl, sd_x_nbl, sd_x_node_offset, sd_x_cell_offset); // Selon la direction Y yScan(all_nb_cell_y, sd_y_ibl, sd_y_obl, sd_y_nbl, sd_y_node_offset, sd_y_cell_offset, all_nb_node_x, all_nb_cell_x); // Selon la direction Z zScan(all_nb_cell_z, sd_z_ibl, sd_z_obl, sd_z_nbl, sd_z_node_offset, sd_z_cell_offset, all_nb_node_xy, all_nb_cell_xy); // Calcule pour les mailles l'offset global du début de la grille pour chaque direction. { Int64 cell_offset_x = sd_x_cell_offset[sdXOffset()]; Int64 cell_offset_y = sd_y_cell_offset[sdYOffset()] / all_nb_cell_x; Int64 cell_offset_z = 0; if (m_mesh_dimension == 3) { cell_offset_z = sd_z_cell_offset[sdZOffset()] / all_nb_cell_xy; } info() << "OwnCellOffset info X=" << cell_offset_x << " Y=" << cell_offset_y << " Z=" << cell_offset_z; m_generation_info->setOwnCellOffsets(cell_offset_x,cell_offset_y,cell_offset_z); } // IBL, NBL info() << " sd_x_ibl=" << sd_x_ibl; info() << " sd_x_obl=" << sd_x_obl; info() << " sd_x_nbl=" << sd_x_nbl; info() << " sd_y_ibl=" << sd_y_ibl; info() << " sd_y_obl=" << sd_y_obl; info() << " sd_y_nbl=" << sd_y_nbl; info() << " sd_z_ibl=" << sd_z_ibl; info() << " sd_z_obl=" << sd_z_obl; info() << " sd_z_nbl=" << sd_z_nbl; // NODE OFFSET info() << " sd_x_node_offset=" << sd_x_node_offset; info() << " sd_y_node_offset=" << sd_y_node_offset; info() << " sd_z_node_offset=" << sd_z_node_offset; // CELL OFFSET info() << " sd_x_cell_offset=" << sd_x_cell_offset; info() << " sd_y_cell_offset=" << sd_y_cell_offset; info() << " sd_z_cell_offset=" << sd_z_cell_offset; // On calcule le premier node_local_id en fonction de notre sub_domain_id Integer node_local_id = 0; Int64 node_unique_id_offset = 0; info() << " sdXOffset=" << sdXOffset() << " sdYOffset=" << sdYOffset() << " sdZOffset=" << sdZOffset(); // On calcule l'offset en x des node_unique_id node_unique_id_offset += sd_x_node_offset.at(sdXOffset()); info() << " node_unique_id_offset=" << node_unique_id_offset; // On calcule l'offset en y des node_unique_id node_unique_id_offset += (sd_y_node_offset.at(sdYOffset())); info() << " node_unique_id_offset=" << node_unique_id_offset; if (m_mesh_dimension == 3) { // On calcule l'offset en z des node_unique_id node_unique_id_offset += (sd_z_node_offset.at(sdZOffset())); info() << " node_unique_id_offset=" << node_unique_id_offset; } Integer z_ibl = 0; Integer z_obl = 0; Int64 z_nbl = 0; if (m_mesh_dimension == 3) { z_ibl = sd_z_ibl.at(sdZOffset()); z_obl = sd_z_obl.at(sdZOffset()); z_nbl = sd_z_nbl.at(sdZOffset()); } for (Int64 z = 0; z < own_nb_node_z; ++z) { if (m_mesh_dimension == 3) { // On saute l'éventuelle dernière frontière bl coincidante avec les sd // Et si on découvre une frontière bloc, on reset les origines if (((z + 1) != own_nb_node_z) && ((z * all_nb_node_xy + sd_z_node_offset.at(sdZOffset())) == (z_nbl + m_build_info.m_bloc_nz.at(z_ibl) * all_nb_node_xy))) { info() << " Creation hit z bloc boundarz: @ node " << z; z_nbl += m_build_info.m_bloc_nz.at(z_ibl) * all_nb_node_xy; // On incrémente de bloc z_ibl += 1; z_obl = 0; } } Real nz = 0.0; if (m_mesh_dimension == 3) nz = nzDelta(z_obl, z_ibl); Integer y_ibl = sd_y_ibl.at(sdYOffset()); Integer y_obl = sd_y_obl.at(sdYOffset()); Int64 y_nbl = sd_y_nbl.at(sdYOffset()); for (Int64 y = 0; y < own_nb_node_y; ++y) { // On saute l'éventuelle dernière frontière bl coincidante avec les sd // Et si on découvre une frontière bloc, on reset les origines if (((y + 1) != own_nb_node_y) && ((y * all_nb_node_x + sd_y_node_offset.at(sdYOffset())) == (y_nbl + m_build_info.m_bloc_ny.at(y_ibl) * all_nb_node_x))) { info() << " Creation hit y bloc boundary: @ node " << y; y_nbl += m_build_info.m_bloc_ny.at(y_ibl) * all_nb_node_x; // On incrémente de bloc y_ibl += 1; y_obl = 0; } Real ny = nyDelta(y_obl, y_ibl); // Récupération du numéro de bloc courant Integer x_ibl = sd_x_ibl.at(sdXOffset()); // Récupération de l'offset dans le bloc courant Integer x_obl = sd_x_obl.at(sdXOffset()); // Récupération du nombre de noeuds dans le bloc courant Int64 x_nbl = sd_x_nbl.at(sdXOffset()); for (Int64 x = 0; x < own_nb_node_x; ++x) { Int64 node_unique_id = node_unique_id_offset + x + y * all_nb_node_x + z * all_nb_node_xy; nodes_unique_id[node_local_id] = node_unique_id; Int32 owner = m_my_mesh_part; // Si on est pas sur sur un sd des bords // Et si on touche aux noeuds des bords du sd de bord if (((sdXOffset() + 1) != m_build_info.m_nsdx) && ((x + 1) == own_nb_node_x)) owner += 1; if (((sdYOffset() + 1) != m_build_info.m_nsdy) && ((y + 1) == own_nb_node_y)) owner += m_build_info.m_nsdx; if (((sdZOffset() + 1) != m_build_info.m_nsdz) && ((z + 1) == own_nb_node_z)) owner += m_build_info.m_nsdx * m_build_info.m_nsdy; // On saute l'éventuelle dernière frontière bl coincidante avec les sd // Et si on découvre une frontière bloc, on reset les origines if (((x + 1) != own_nb_node_x) && ((x + sd_x_node_offset.at(sdXOffset())) == (x_nbl + m_build_info.m_bloc_nx.at(x_ibl)))) { info() << " Creation hit x bloc boundary: @ node " << x; x_nbl += m_build_info.m_bloc_nx.at(x_ibl); // On incrémente de bloc x_ibl += 1; x_obl = 0; } Real nx = nxDelta(x_obl, x_ibl); /*debug() << "[CartesianMeshGenerator::generateMesh] node @ "<<x<<"x"<<y<<"x"<<z <<":"<< ", uid=" << node_unique_id<< ", owned by " << owner << ",  coords=("<<nx<<","<<ny<<","<<nz<<")"<<"";*/ nodes_infos.nocheckAdd(node_unique_id, NodeInfo(owner, Real3(nx, ny, nz))); node_local_id += 1; x_obl += 1; } y_obl += 1; } z_obl += 1; } // Création des mailles // Infos pour la création des mailles // par maille: 1 pour son unique id, // 1 pour son type, // 8 pour chaque noeud Integer cell_local_id = 0; Int64 cell_unique_id_offset = 0; Int64UniqueArray cells_infos; if (m_mesh_dimension == 3) cells_infos.resize(own_nb_cell_xyz * (1 + 1 + 8)); if (m_mesh_dimension == 2) cells_infos.resize(own_nb_cell_xyz * (1 + 1 + 4)); // On calcule l'offset en x des cell_unique_id cell_unique_id_offset += sd_x_cell_offset.at(sdXOffset()); info() << "cell_unique_id_offset=" << cell_unique_id_offset; // On calcule l'offset en y des cell_unique_id cell_unique_id_offset += sd_y_cell_offset.at(sdYOffset()); info() << "cell_unique_id_offset=" << cell_unique_id_offset; if (m_mesh_dimension == 3) { // On calcule l'offset en z des cell_unique_id cell_unique_id_offset += sd_z_cell_offset.at(sdZOffset()); info() << "cell_unique_id_offset=" << cell_unique_id_offset; } Integer cells_infos_index = 0; info() << "cell_unique_id_offset=" << cell_unique_id_offset; m_generation_info->setFirstOwnCellUniqueId(cell_unique_id_offset); if (m_mesh_dimension == 3) { for (Integer z = 0; z < own_nb_cell_z; ++z) { for (Integer y = 0; y < own_nb_cell_y; ++y) { for (Integer x = 0; x < own_nb_cell_x; ++x) { Int64 cell_unique_id = cell_unique_id_offset + x + y * all_nb_cell_x + z * all_nb_cell_xy; /*debug() << "[CartesianMeshGenerator::generateMesh] cell @ " <<x<<"x"<<y<<"x"<<z<<":"<<", uid=" << cell_unique_id<< "";*/ cells_infos[cells_infos_index] = IT_Hexaedron8; ++cells_infos_index; cells_infos[cells_infos_index] = cell_unique_id; ++cells_infos_index; Integer node_lid = x + y * own_nb_node_x + z * own_nb_node_xy; cells_infos[cells_infos_index + 0] = nodes_unique_id[node_lid]; cells_infos[cells_infos_index + 1] = nodes_unique_id[node_lid + 1]; cells_infos[cells_infos_index + 2] = nodes_unique_id[node_lid + own_nb_node_x + 1]; cells_infos[cells_infos_index + 3] = nodes_unique_id[node_lid + own_nb_node_x + 0]; cells_infos[cells_infos_index + 4] = nodes_unique_id[node_lid + own_nb_node_xy]; cells_infos[cells_infos_index + 5] = nodes_unique_id[node_lid + own_nb_node_xy + 1]; cells_infos[cells_infos_index + 6] = nodes_unique_id[node_lid + own_nb_node_xy + own_nb_node_x + 1]; cells_infos[cells_infos_index + 7] = nodes_unique_id[node_lid + own_nb_node_xy + own_nb_node_x + 0]; /*debug() << "[CartesianMeshGenerator::generateMesh] cell #" << cell_unique_id <<", connected to nodes: " << cells_infos[cells_infos_index+0] << ", " << cells_infos[cells_infos_index+1] << ", " << cells_infos[cells_infos_index+2] << ", " << cells_infos[cells_infos_index+3] << ", " << cells_infos[cells_infos_index+4] << ", " << cells_infos[cells_infos_index+5] << ", " << cells_infos[cells_infos_index+6] << ", " << cells_infos[cells_infos_index+7]<< "";*/ cells_infos_index += 8; cell_local_id += 1; } } } } if (m_mesh_dimension == 2) { for (Integer y = 0; y < own_nb_cell_y; ++y) { for (Integer x = 0; x < own_nb_cell_x; ++x) { Int64 cell_unique_id = cell_unique_id_offset + x + y * all_nb_cell_x; //info() << "X=" << x << " y=" << y << " UID=" << cell_unique_id; /*debug() << "[CartesianMeshGenerator::generateMesh] cell @ " <<x<<"x"<<y<<":"<<", uid=" << cell_unique_id<< "";*/ cells_infos[cells_infos_index] = IT_Quad4; ++cells_infos_index; cells_infos[cells_infos_index] = cell_unique_id; ++cells_infos_index; Integer node_lid = x + y * own_nb_node_x; cells_infos[cells_infos_index + 0] = nodes_unique_id[node_lid]; cells_infos[cells_infos_index + 1] = nodes_unique_id[node_lid + 1]; cells_infos[cells_infos_index + 2] = nodes_unique_id[node_lid + own_nb_node_x + 1]; cells_infos[cells_infos_index + 3] = nodes_unique_id[node_lid + own_nb_node_x + 0]; /*debug() << "[CartesianMeshGenerator::generateMesh] cell #" << cell_unique_id <<", connected to nodes: " << cells_infos[cells_infos_index+0] << ", " << cells_infos[cells_infos_index+1] << ", " << cells_infos[cells_infos_index+2] << ", " << cells_infos[cells_infos_index+3] << "";*/ cells_infos_index += 4; cell_local_id += 1; } } } mesh->setDimension(m_mesh_dimension); info() << "FaceNumberingVersion = " << m_build_info.m_face_numbering_version; if (m_build_info.m_face_numbering_version>=0) mesh->meshUniqueIdMng()->setFaceBuilderVersion(m_build_info.m_face_numbering_version); info() << "EdgeNumberingVersion = " << m_build_info.m_edge_numbering_version; if (m_build_info.m_edge_numbering_version>=0) mesh->meshUniqueIdMng()->setEdgeBuilderVersion(m_build_info.m_edge_numbering_version); mesh->allocateCells(own_nb_cell_xyz, cells_infos, true); VariableNodeReal3& nodes_coord_var(mesh->nodesCoordinates()); { info() << "Fills the variable containing the coordinates of the nodes"; Int32UniqueArray nodes_local_id(nodes_unique_id.size()); IItemFamily* family = mesh->nodeFamily(); family->itemsUniqueIdToLocalId(nodes_local_id, nodes_unique_id); ItemInternalList nodes_internal(family->itemsInternal()); for (Integer i = 0; i < node_local_id; ++i) { const Node& node = nodes_internal[nodes_local_id[i]]; Int64 unique_id = nodes_unique_id[i]; nodes_coord_var[node] = nodes_infos.lookupValue(unique_id).m_coord; /*debug() << "[CartesianMeshGenerator::generateMesh] Set coord " << ItemPrinter(node) << " coord=" << nodes_coord_var[node]<< "";*/ } } nodes_coord_var.synchronize(); if (m_build_info.m_is_generate_sod_groups){ if (m_mesh_dimension==3){ SodStandardGroupsBuilder groups_builder(traceMng()); Real3 origin = m_build_info.m_origine; Real3 length(m_l.x,m_l.y,m_l.z); Real3 max_pos = origin + length; // TODO: Comme il peut y avoir des progressions geométriques il faut définir // le milieu à partir de la position de la maille d'offset le milieu // et pas à partir des coordonnées // Calculer middle_x comme position du milieu Real middle_x = (origin.x + max_pos.x) / 2.0; Real middle_height = (origin.y + max_pos.y) / 2.0; groups_builder.generateGroups(mesh,origin,origin+length,middle_x,middle_height); } } return false; // false == ok } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Service de génération de maillage cartésien en 2D. */ class Cartesian2DMeshGenerator : public ArcaneCartesian2DMeshGeneratorObject { public: Cartesian2DMeshGenerator(const ServiceBuildInfo& sbi) : ArcaneCartesian2DMeshGeneratorObject(sbi){} public: void fillMeshBuildInfo(MeshBuildInfo& build_info) override { ARCANE_UNUSED(build_info); info() << "Cartesian2DMeshGenerator: fillMeshBuildInfo()"; m_build_info.m_nsdx = options()->nbPartX(); m_build_info.m_nsdy = options()->nbPartY(); m_build_info.m_mesh_dimension = 2; Real2 origin = options()->origin; m_build_info.m_origine.x = origin.x; m_build_info.m_origine.y = origin.y; m_build_info.m_face_numbering_version = options()->faceNumberingVersion(); for( auto& o : options()->x() ){ m_build_info.m_bloc_lx.add(o->length); m_build_info.m_bloc_nx.add(o->n); m_build_info.m_bloc_px.add(o->progression); } for( auto& o : options()->y() ){ m_build_info.m_bloc_ly.add(o->length); m_build_info.m_bloc_ny.add(o->n); m_build_info.m_bloc_py.add(o->progression); } } void allocateMeshItems(IPrimaryMesh* pm) override { info() << "Cartesian2DMeshGenerator: allocateMeshItems()"; CartesianMeshGenerator g(pm); // Regarde s'il faut calculer dynamiquement le découpage auto [ x, y ] = _computePartition(pm,m_build_info.m_nsdx,m_build_info.m_nsdy); m_build_info.m_nsdx = x; m_build_info.m_nsdy = y; g.setBuildInfo(m_build_info); g.generateMesh(); } CartesianMeshGeneratorBuildInfo m_build_info; private: static std::tuple<Integer,Integer> _computePartition(IPrimaryMesh* pm,Integer nb_x,Integer nb_y) { Int32 nb_part = pm->meshPartInfo().nbPart(); // En séquentiel, ne tient pas compte des valeurs de jeu de données. if (nb_part==1) return {1,1}; // Si le découpage en X et en Y est spécifié, l'utilise directement. if (nb_x!=0 && nb_y!=0) return {nb_x, nb_y}; // Aucun découpage spécifié. Il faut que math::sqrt(nb_part) // soit un entier if (nb_x==0 && nb_y==0){ double s = math::sqrt((double)(nb_part)); Integer s_int = (Integer)(::floor(s)); if ((s_int*s_int) != nb_part) ARCANE_FATAL("Invalid number of part '{0}' for automatic partitioning: sqrt({1}) is not an integer", nb_part,nb_part); return {s_int,s_int}; } // Ici, on a un des deux découpages qui n'est pas spécifié. if (nb_x==0){ if ( (nb_part % nb_y) != 0 ) ARCANE_FATAL("Invalid number of Y part '{0}' for automatic partitioning: can not divide '{1}' by '{2}'", nb_y,nb_part,nb_y); nb_x = nb_part / nb_y; } else{ if ( (nb_part % nb_x) != 0 ) ARCANE_FATAL("Invalid number of X part '{0}' for automatic partitioning: can not divide '{1}' by '{2}'", nb_x,nb_part,nb_x); nb_y = nb_part / nb_x; } return {nb_x,nb_y}; } }; ARCANE_REGISTER_SERVICE_CARTESIAN2DMESHGENERATOR(Cartesian2D,Cartesian2DMeshGenerator); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Service de génération de maillage cartésien en en 3D. */ class Cartesian3DMeshGenerator : public ArcaneCartesian3DMeshGeneratorObject { public: Cartesian3DMeshGenerator(const ServiceBuildInfo& sbi) : ArcaneCartesian3DMeshGeneratorObject(sbi){} public: void fillMeshBuildInfo(MeshBuildInfo& build_info) override { ARCANE_UNUSED(build_info); info() << "Cartesian3DMeshGenerator: fillMeshBuildInfo()"; m_build_info.m_nsdx = options()->nbPartX(); m_build_info.m_nsdy = options()->nbPartY(); m_build_info.m_nsdz = options()->nbPartZ(); m_build_info.m_mesh_dimension = 3; Real3 origin = options()->origin; m_build_info.m_origine.x = origin.x; m_build_info.m_origine.y = origin.y; m_build_info.m_origine.z = origin.z; m_build_info.m_is_generate_sod_groups = options()->generateSodGroups(); m_build_info.m_face_numbering_version = options()->faceNumberingVersion(); m_build_info.m_edge_numbering_version = options()->edgeNumberingVersion(); for( auto& o : options()->x() ){ m_build_info.m_bloc_lx.add(o->length); m_build_info.m_bloc_nx.add(o->n); m_build_info.m_bloc_px.add(o->progression); } for( auto& o : options()->y() ){ m_build_info.m_bloc_ly.add(o->length); m_build_info.m_bloc_ny.add(o->n); m_build_info.m_bloc_py.add(o->progression); } for( auto& o : options()->z() ){ m_build_info.m_bloc_lz.add(o->length); m_build_info.m_bloc_nz.add(o->n); m_build_info.m_bloc_pz.add(o->progression); } } void allocateMeshItems(IPrimaryMesh* pm) override { info() << "Cartesian3DMeshGenerator: allocateMeshItems()"; CartesianMeshGenerator g(pm); g.setBuildInfo(m_build_info); g.generateMesh(); } CartesianMeshGeneratorBuildInfo m_build_info; }; ARCANE_REGISTER_SERVICE_CARTESIAN3DMESHGENERATOR(Cartesian3D,Cartesian3DMeshGenerator); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arcane /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
38.589029
133
0.599846
grospelliergilles
cbf8db15338b21a99b138ab68bf6f1de9237116a
2,445
cpp
C++
src/drawing/shadowed.cpp
aliefhooghe/View
95996a673815deca12a52928e76cf557d4063daa
[ "BSD-3-Clause" ]
null
null
null
src/drawing/shadowed.cpp
aliefhooghe/View
95996a673815deca12a52928e76cf557d4063daa
[ "BSD-3-Clause" ]
null
null
null
src/drawing/shadowed.cpp
aliefhooghe/View
95996a673815deca12a52928e76cf557d4063daa
[ "BSD-3-Clause" ]
1
2020-03-25T01:09:42.000Z
2020-03-25T01:09:42.000Z
#include "shadowed.h" namespace View { void shadowed_down_rounded_rect( NVGcontext *vg, float x, float y, float width, float height, float radius, NVGcolor surface) { const auto shadow = nvgRGB(0, 0, 0); const auto gradient = nvgBoxGradient(vg, x + 1.5f, y + 1.8f, width - 2.f, height- 2.f, radius, 2.f, surface, shadow); // Draw background (with shadow) nvgBeginPath(vg); nvgRoundedRect(vg, x, y, width, height, radius); nvgFillPaint(vg, gradient); nvgFill(vg); } void shadowed_up_rounded_rect( NVGcontext *vg, float x, float y, float width, float height, float radius, NVGcolor surface) { const auto background = nvgRGBA(0, 0, 0, 0); const auto shadow = nvgRGB(0, 0, 0); const auto gradient = nvgBoxGradient(vg, x + 1.5f, y + 1.8f, width - 1.f, height - 1.f, radius, 2.f, shadow, background); // Draw shadow nvgBeginPath(vg); nvgRect(vg, x + 1.f, y + 1.f, width + 4.f, height + 4.f); nvgFillPaint(vg, gradient); nvgFill(vg); // Draw background nvgBeginPath(vg); nvgRoundedRect(vg, x, y, width, height, radius); nvgFillColor(vg, surface); nvgFill(vg); } void shadowed_down_circle( NVGcontext *vg, float cx, float cy, float radius, NVGcolor surface) { const auto shadow = nvgRGB(0, 0, 0); const auto gradient = nvgRadialGradient(vg, cx + 0.8f, cy + 1.f, radius - 1.1f, radius - 1.2f, surface, shadow); // Draw background (with shadow) nvgBeginPath(vg); nvgCircle(vg, cx, cy, radius); nvgFillPaint(vg, gradient); nvgFill(vg); } void shadowed_up_circle( NVGcontext *vg, float cx, float cy, float radius, NVGcolor surface) { const auto background = nvgRGBA(0, 0, 0, 0); const auto shadow = nvgRGB(0, 0, 0); const auto gradient = nvgRadialGradient(vg, cx + 1.f, cy + 1.2f, radius - 3.f, radius, shadow, background); // Draw shadow nvgBeginPath(vg); nvgCircle(vg, cx, cy, radius + 4.f); nvgFillPaint(vg, gradient); nvgFill(vg); // Draw background nvgBeginPath(vg); nvgCircle(vg, cx, cy, radius); nvgFillColor(vg, surface); nvgFill(vg); } }
30.5625
111
0.561145
aliefhooghe
cbfbf2d393e72e338925886ece42cbfcace0decb
3,530
cpp
C++
sdk/src/layers/SignalKLayer.cpp
Fpepe943/fairwindplusplus
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
[ "Apache-2.0" ]
4
2021-07-07T10:42:53.000Z
2022-01-11T12:53:25.000Z
sdk/src/layers/SignalKLayer.cpp
Fpepe943/fairwindplusplus
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
[ "Apache-2.0" ]
2
2022-02-13T19:59:25.000Z
2022-03-25T01:02:17.000Z
sdk/src/layers/SignalKLayer.cpp
Fpepe943/fairwindplusplus
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
[ "Apache-2.0" ]
7
2021-06-07T07:12:55.000Z
2022-01-12T16:09:55.000Z
// // Created by Raffaele Montella on 05/05/21. // #include <FairWindSdk/FairWind.hpp> #include <FairWindSdk/layers/ItemSignalK.hpp> #include <FairWindSdk/layers/ItemAton.hpp> #include <FairWindSdk/layers/ItemVessel.hpp> #include <FairWindSdk/layers/ItemShoreBasestations.hpp> #include <FairWindSdk/layers/ItemDefault.hpp> #include "FairWindSdk/layers/SignalKLayer.hpp" fairwind::layers::SignalKLayer::SignalKLayer() { setName("Signal K Layer"); setDescription("Generic Layer Holding Signal K elements"); qDebug() << "SignalKLayer::SignalKLayer() " << getName() << " " << getDescription(); } fairwind::layers::SignalKLayer::SignalKLayer(const SignalKLayer &other) { qDebug() << "SignalKLayer::SignalKLayer(const SignalKLayer &other)"; } fairwind::layers::SignalKLayer::~SignalKLayer() { qDebug() << "SignalKLayer::~SignalKLayer()"; } QImage fairwind::layers::SignalKLayer::getIcon() const { return QImage(":resources/images/icons/layer_signalk_icon.png"); } QWidget *fairwind::layers::SignalKLayer::onLegenda() { return nullptr; } QWidget *fairwind::layers::SignalKLayer::onSettings() { return nullptr; } void fairwind::layers::SignalKLayer::onInit(QMap<QString, QVariant> params) { qDebug() << "SignalKLayer::onInit(" << params << ")"; // Set the layer's name from the parameters if (params.contains("name")) { setName(params["name"].toString()); } // Set the layer's description from the parameters if (params.contains("description")) { setDescription(params["description"].toString()); } // Get the FairWind singleton auto fairWind = fairwind::FairWind::getInstance(); // Get the signalkdocument from the FairWind singleton itself auto signalKDocument = fairWind->getSignalKDocument(); // Get the self key from the document auto self = signalKDocument->getSelf(); // Check if a fullPath has been provided if (params.contains("fullPath")) { // Get the path QString fullPath=params["fullPath"].toString(); // Get the items to display on the layer QJsonValue itemsValue = signalKDocument->subtree(fullPath); // Check if there is at least one valid item if (!itemsValue.isNull() && itemsValue.isObject()) { QJsonObject itemsObject = itemsValue.toObject(); for (const auto& uuid: itemsObject.keys()) { QString context=fullPath+"."+uuid; ItemSignalK *itemSignalK = nullptr; if ( fullPath.endsWith("atons")) { itemSignalK = new ItemAton(context); } else if ( fullPath.endsWith("shore.basestations")) { itemSignalK = new ItemShoreBasestations(context); } else if ( fullPath.endsWith("vessels")) { if (self.indexOf(uuid)<0) { itemSignalK = new ItemVessel(context); } } else { itemSignalK = new ItemDefault(context); } if (itemSignalK) { addItem(itemSignalK); } } } } else { // Directly add the vessel to the layer addItem(new ItemVessel(self)); } } fairwind::layers::ILayer *fairwind::layers::SignalKLayer::getNewInstance() { return static_cast<ILayer *>(new fairwind::layers::SignalKLayer()); } QString fairwind::layers::SignalKLayer::getClassName() const { return this->metaObject()->className(); }
35.3
88
0.633428
Fpepe943
02000471835b079c0789c5385a2c65db43f2dc68
576
cpp
C++
src/shows/solidColour.cpp
reubn/symfonisk
559ae842a159734ab5f1dc33b80a394577b3b576
[ "MIT" ]
1
2020-05-14T20:52:56.000Z
2020-05-14T20:52:56.000Z
src/shows/solidColour.cpp
reubn/symfonisk
559ae842a159734ab5f1dc33b80a394577b3b576
[ "MIT" ]
null
null
null
src/shows/solidColour.cpp
reubn/symfonisk
559ae842a159734ab5f1dc33b80a394577b3b576
[ "MIT" ]
null
null
null
#include <vector> #include "../main.hpp" #include "../ringLEDs/main.hpp" #include "solidColour.hpp" void loopSolidColour(ConfigurableSettings& settings, bool first) { static float msBetweenFrames = 1000 / 60; // 60FPS static unsigned long lastExecution = millis(); static RgbColor lastColour = RgbColor(0, 0, 0); if(!first && lastColour == settings.colour) return; if(millis() < lastExecution + msBetweenFrames) return; for(auto& ringLED : allLEDs) LEDStrip.SetPixelColor(ringLED.index, settings.colour); lastColour = settings.colour; LEDStrip.Show(); }
26.181818
86
0.725694
reubn
020d1b199e5acee493685ee3ecaca2842bbaac55
8,395
cpp
C++
cpp-projects/exvr-export/main.cpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
cpp-projects/exvr-export/main.cpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
cpp-projects/exvr-export/main.cpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
/*********************************************************************************** ** exvr-export ** ** MIT License ** ** Copyright (c) [2018] [Florian Lance][EPFL-LNCO] ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ************************************************************************************/ #include <iostream> //#include "body_capture_export.hpp" #include <thread> #include <chrono> #include <iostream> #include <vector> #include <map> #include <any> //#include "socket_communication_export.hpp" //#include "scaner_video_file_export.hpp" int main(int argc, char *argv[]){ // auto scaner = create_scaner_video_file(); // auto loaded = load_scaner_video_file(scaner, "G:/vid1.kvid"); // if(!loaded){ // std::cerr << "Cannot load file.\n"; // return -1; // } // int duration = get_duration_ms_scaner_video_file(scaner); // int nbCameras = get_camera_nb_scaner_video_file(scaner); // std::cout << "Duration: " << duration << "\n"; // std::cout << "nbCameras: " << nbCameras << "\n"; // for(int ii = 0; ii < nbCameras; ++ii){ // int size = get_camera_cloud_size_video_file(scaner, ii); // std::cout << "Cam " << ii << " has cloud size of " << size << "\n"; // } // std::vector<float> vertices(512*424*3); // std::vector<float> colors(512*424*4); // for(int ii = 0; ii < duration; ii+=300){ // std::cout << "Time: " << ii << "\n"; // for(int jj = 0; jj < nbCameras; ++jj){ // update_cloud_data_scaner_video_file(scaner, jj, ii, 300, false, vertices.data(), colors.data()); // } // } // delete scaner; // DECL_EXPORT int get_duration_ms_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile); // DECL_EXPORT int get_camera_nb_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile); // DECL_EXPORT int get_camera_cloud_size_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC); // DECL_EXPORT void get_cloud_model_transform_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, float *model); // DECL_EXPORT int update_cloud_data_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, int timeMs, int maxDiffMs, int loop, float *vertices, float *colors); // DECL_EXPORT int get_nb_bodies_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC); // DECL_EXPORT int is_body_tracked_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, int idBody); // DECL_EXPORT int is_body_restricted_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, int idBody); // DECL_EXPORT int is_body_hand_detected_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, int idBody, int leftHand); // DECL_EXPORT int is_body_hand_confident_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, int idBody, int leftHand); // DECL_EXPORT void body_joints_positions_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, int idBody, float *positions); // DECL_EXPORT void body_joints_rotations_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, int idBody, float *rotations); // DECL_EXPORT void body_joints_states_scaner_video_file(tool::camera::ScanerVideoFile *scanerVideoFile, int idC, int idBody, int *states); // ScanerVideoFile video; //// std::string name = "L:/Users/Florian/_VIDEOS/7-kinects.kvid"; // std::string name = "G:/vid1.kvid"; //// std::string name = "G:/7-kinects.kvid"; //// std::string name = "C:/Users/lance/Desktop/test.kvid"; // std::cout << "Load video " << name << "\n"; // if(!video.load(name)){ // std::cout << "Cannot load video : " << name << "\n"; // return -1; // } // const bool displayModelMatrix = false; // std::cout << "#### Video: " << name << "\n"; // std::cout << "Duration: " << video.duration.count()*0.000001 << "ms\n";// (start: " << video.startingTimeStamp << " end: " << video.endingTimeStamp << " )\n"; // std::cout << "Nb Cameras: " << video.nbCameras << ", cloud nb: " << video.nbClouds << "\n"; // for(size_t ii = 0; ii < video.nbCameras; ++ii){ // std::cout << "\nCamera " << ii << "\n"; // const size_t sizeCloud = (video.data.count(ii) == 0) ? 0 : video.data[ii].size(); // const bool hasIntrincis = video.intrinsics.count(ii) != 0; // const bool hasModel = video.models.count(ii) != 0; // const size_t sizeBodiesId = (video.bodiesId.count(ii) == 0) ? 0 : video.bodiesId[ii].size(); // std::cout << "Nb clouds : " << sizeCloud << "\n"; // if(hasIntrincis){ // const auto &vInt = video.intrinsics[ii]; // std::cout << "Intrinsics : " << vInt[0] << " " << vInt[1] << " " << vInt[2] << " " << vInt[3] << "\n"; // }else{ // std::cout << "No intrinsics\n"; // } // if(hasModel){ // if(displayModelMatrix){ // std::cout << "Model maxtrix:\n" << video.models[ii] << "\n"; // }else{ // std::cout << "Has model matrix\n"; // } // }else{ // std::cout << "No model matrix\n"; // } // std::cout << "Nb bodies id : " << sizeBodiesId << "\n"; // std::cout << "## Cloud data ##\n"; // size_t firstCloudId = 0; // std::int64_t firstTimeStamp = 0; // for(size_t jj = 0; jj < sizeCloud; ++jj){ // auto &cloud = video.data[ii][jj]; // if(jj == 0){ // firstCloudId = cloud.id; // firstTimeStamp = cloud.timeStamp; // std::cout << cloud.id-firstCloudId << " " << cloud.timeStamp-firstTimeStamp << "\n"; // }else{ // auto &pCloud = video.data[ii][jj-1]; // std::cout << "Frame: " << cloud.id << " -> " << (cloud.id - pCloud.id) << " " << duration_cast<milliseconds>(nanoseconds(cloud.timeStamp-pCloud.timeStamp)).count() << "ms " << cloud.colors.size() << " " << cloud.depth.size() << "\n"; // } // } // } // auto durationMs = video.duration.count()*0.000001; // for(size_t ii = 0; ii < video.nbCameras; ++ii){ // // std::cout << "\nCamera " << ii << "\n"; // if(video.data[ii].size() > 0){ // auto t1 = video.data[ii][0].timeStamp; // auto t2 = video.data[ii][video.data[ii].size()-1].timeStamp; // std::cout << "Diff " << (t2-t1)*0.00001 << "ms\n"; // } // for(int jj = 0; jj < durationMs; jj+=30){ // auto frame = video.get_data(ii, jj); // std::cout << "Time wanted: " << jj << "ms, cloud id " << frame.idCloud << " with found time " << frame.foundTimeMs << "\n"; // } // } return 0; }
46.899441
254
0.562716
FlorianLance
020ef38e27ef5d971b32cfb9f2f3f9cf42149ebe
22,993
cpp
C++
Engine3D/Core/ModuleEditor.cpp
MaxLlovera/ManyoEngineCp2.0
5027439063153dfb55d9eef621d2eeb7136c9603
[ "MIT" ]
null
null
null
Engine3D/Core/ModuleEditor.cpp
MaxLlovera/ManyoEngineCp2.0
5027439063153dfb55d9eef621d2eeb7136c9603
[ "MIT" ]
null
null
null
Engine3D/Core/ModuleEditor.cpp
MaxLlovera/ManyoEngineCp2.0
5027439063153dfb55d9eef621d2eeb7136c9603
[ "MIT" ]
null
null
null
#include "Globals.h" //Modules #include "Application.h" #include "ModuleEditor.h" #include "ModuleWindow.h" #include "ModuleFileSystem.h" #include "ModuleRenderer3D.h" #include "ModuleInput.h" #include "ModuleImport.h" #include "ModuleScene.h" #include "ModuleViewportFrameBuffer.h" #include "ModuleCamera3D.h" #include "ModuleTextures.h" #include "ModuleClock.h" #include "ComponentMaterial.h" #include "ComponentMesh.h" #include "ComponentTransform.h" //Tools #include <string> #include <stack> #include "ImGui/imgui_impl_opengl3.h" #include "ImGui/imgui_impl_sdl.h" #include "ImGui/imgui_internal.h" #include "glew.h" #include <gl/GL.h> ModuleEditor::ModuleEditor(Application* app, bool start_enabled) : Module(app, start_enabled) { showDemoWindow = false; showAnotherWindow = false; showAboutWindow = false; showConfWindow = true; showConsoleWindow = true; showHierarchyWindow = true; showInspectorWindow = true; showGameWindow = true; showSceneWindow = true; showTextures = true; showExplorer = true; currentColor = { 1.0f, 1.0f, 1.0f, 1.0f }; gameobjectSelected = nullptr; } // Destructor ModuleEditor::~ModuleEditor() { } bool ModuleEditor::Init() { bool ret = true; return ret; } // Called before render is available bool ModuleEditor::Start() { bool ret = true; // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; sceneWindow |= ImGuiWindowFlags_NoScrollbar; // Setup ImGui style by default ImGui::StyleColorsDark(); // Setup Platform/Renderer bindings ImGui_ImplOpenGL3_Init(); ImGui_ImplSDL2_InitForOpenGL(App->window->window, App->renderer3D->context); CreateGridBuffer(); return ret; } update_status ModuleEditor::PreUpdate(float dt) { // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(App->window->window); ImGui::NewFrame(); return UPDATE_CONTINUE; } // PreUpdate: clear buffer update_status ModuleEditor::Update(float dt) { DrawGrid(); //Creating MenuBar item as a root for docking windows if (DockingRootItem("Viewport", ImGuiWindowFlags_MenuBar)) { MenuBar(); ImGui::End(); } //Update status of each window and shows ImGui elements UpdateWindowStatus(); return UPDATE_CONTINUE; } update_status ModuleEditor::PostUpdate(float dt) { ImGuiIO& io = ImGui::GetIO(); (void)io; // Rendering ImGui::Render(); glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // Update and Render additional Platform Windows // (Platform functions may change the current OpenGL context, so we save/restore it to make it easier to paste this code elsewhere. // For this specific demo app we could also call SDL_GL_MakeCurrent(window, gl_context) directly) if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { SDL_Window* backup_current_window = SDL_GL_GetCurrentWindow(); SDL_GLContext backup_current_context = SDL_GL_GetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); SDL_GL_MakeCurrent(backup_current_window, backup_current_context); } ImGui::EndFrame(); return UPDATE_CONTINUE; } // Called before quitting bool ModuleEditor::CleanUp() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); return true; } void ModuleEditor::CreateGridBuffer() { std::vector<float3> vertices; std::vector<uint> indices; constexpr int slices = 200; constexpr float size = 2000.f; constexpr float halfSize = size * .5f; constexpr float sliceSize = size / static_cast<float>(slices); for (int i = 0; i < slices; ++i) { const float x = -halfSize + static_cast<float>(i) * sliceSize; if (x > 0.01f || x < -0.01f) { vertices.push_back(float3(x, 0.f, -halfSize)); vertices.push_back(float3(x, 0.f, halfSize)); indices.push_back(vertices.size() - 2); indices.push_back(vertices.size() - 1); } const float z = -halfSize + static_cast<float>(i) * sliceSize; if (z > 0.01f || z < -0.01f) { vertices.push_back(float3(-halfSize, 0.f, z)); vertices.push_back(float3(halfSize, 0.f, z)); indices.push_back(vertices.size() - 2); indices.push_back(vertices.size() - 1); } } glGenVertexArrays(1, &grid.VAO); glBindVertexArray(grid.VAO); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float3), &vertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); GLuint ibo; glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(uint), &indices[0], GL_STATIC_DRAW); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); grid.length = (GLuint)indices.size() * 4; } void ModuleEditor::DrawGrid() { GLboolean isLightingOn, isDepthTestOn; glGetBooleanv(GL_LIGHTING, &isLightingOn); glGetBooleanv(GL_DEPTH_TEST, &isDepthTestOn); glEnable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glBindVertexArray(grid.VAO); glColor3f(.5f, .5f, .5f); glDrawElements(GL_LINES, grid.length, GL_UNSIGNED_INT, NULL); glBindVertexArray(0); glBegin(GL_LINES); //x Axis glColor3f(1.f, 0.f, 0.f); glVertex3f(0.f, 0.0f, 0.f); glColor3f(1.f, 0.f, 0.f); glVertex3f(1000.f, 0.0f, 0.f); glColor3f(.2f, 0.f, 0.f); glVertex3f(0.f, 0.0f, 0.f); glColor3f(.2f, 0.f, 0.f); glVertex3f(-1000.f, 0.0f, 0.f); //z Axis glColor3f(0.f, 0.f, 1.f); glVertex3f(0.f, 0.0f, 0.f); glColor3f(0.f, 0.f, 1.f); glVertex3f(0.f, 0.0f, 1000.f); glColor3f(0.f, 0.f, .2f); glVertex3f(0.f, 0.0f, 0.f); glColor3f(0.f, 0.f, .2f); glVertex3f(0.f, 0.0f, -1000.f); glEnd(); isLightingOn ? glEnable(GL_LIGHTING) : 0; !isDepthTestOn ? glDisable(GL_DEPTH_TEST) : 0; } void ModuleEditor::About_Window() { ImGui::Begin("About ManyoEngineCp", &showAboutWindow); ImGui::Separator(); ImGui::Text("ManyoEngineCp\n"); ImGui::Separator(); ImGui::Text("3rd Party Libraries used: "); ImGui::BulletText("SDL v2.0.12"); ImGui::BulletText("Glew v2.1.0"); ImGui::BulletText("OpenGL v3.1.0"); ImGui::BulletText("ImGui v1.78"); ImGui::BulletText("MathGeoLib v1.5"); ImGui::BulletText("PhysFS v3.0.2"); ImGui::BulletText("DevIL v1.7.8"); ImGui::BulletText("Assimp v3.1.1"); ImGui::Separator(); ImGui::Text("LICENSE\n"); ImGui::Separator(); ImGui::Text("MIT License\n\n"); ImGui::Text("Permission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the 'Software'), to deal\n"); ImGui::Text("in the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and /or sell\n"); ImGui::Text("copies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions : \n"); ImGui::Text("\n"); ImGui::Text("The above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n"); ImGui::Text("\n"); ImGui::Text("THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n"); ImGui::Text("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"); ImGui::Text("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n"); ImGui::Text("SOFTWARE.\n"); //ImGui::Separator(); ImGui::End(); } void ModuleEditor::UpdateText(const char* text) { consoleText.appendf(text); } bool ModuleEditor::DockingRootItem(char* id, ImGuiWindowFlags winFlags) { //Setting windows as viewport size ImGuiViewport* viewport = ImGui::GetWindowViewport(); ImGui::SetNextWindowPos(viewport->Pos); ImGui::SetNextWindowSize(viewport->Size); ImGui::SetNextWindowViewport(viewport->ID); //Setting window style ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, .0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, .0f); //Viewport window flags just to have a non interactable white space where we can dock the rest of windows winFlags |= ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoTitleBar; winFlags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoBackground; bool temp = true; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); temp = ImGui::Begin(id, &temp, winFlags); ImGui::PopStyleVar(3); BeginDock(id, ImGuiDockNodeFlags_PassthruCentralNode); return temp; } void ModuleEditor::BeginDock(char* dockSpaceId, ImGuiDockNodeFlags dockFlags, ImVec2 size) { // DockSpace ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dock = ImGui::GetID(dockSpaceId); ImGui::DockSpace(dock, size, dockFlags); } } void ModuleEditor::MenuBar() { /* ---- MAIN MENU BAR DOCKED ----*/ if (ImGui::BeginMainMenuBar()) { /* ---- FILE ---- */ if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Save", "Ctrl + S")) //DO SOMETHING { App->scene->saveScene(); } ImGui::Separator(); if (ImGui::MenuItem("Exit", "(Alt+F4)")) App->closeEngine = true; ImGui::EndMenu(); } /* ---- GAMEOBJECTS ---- */ if (ImGui::BeginMenu("GameObject")) { if (ImGui::MenuItem("Create empty GameObject")) { App->scene->CreateGameObject(); } if (ImGui::MenuItem("Create Camera")) { GameObject* newGameObject = App->scene->CreateGameObject("Camera"); ComponentCamera* newCamera = new ComponentCamera(newGameObject); } if (ImGui::BeginMenu("3D Objects")) { if (ImGui::MenuItem("Cube")) { GameObject* newGameObject = App->scene->CreateGameObject("Cube"); ComponentMesh* newMesh = new ComponentMesh(newGameObject, ComponentMesh::Shape::CUBE); esfera = true; } if (ImGui::MenuItem("Sphere")) { GameObject* newGameObject = App->scene->CreateGameObject("Sphere"); ComponentMesh* newMesh = new ComponentMesh(newGameObject, ComponentMesh::Shape::SPHERE); } if (ImGui::MenuItem("Cylinder")) { GameObject* newGameObject = App->scene->CreateGameObject("Cylinder"); ComponentMesh* newMesh = new ComponentMesh(newGameObject, ComponentMesh::Shape::CYLINDER); } ImGui::EndMenu(); } ImGui::EndMenu(); } /* ---- WINDOW ----*/ if (ImGui::BeginMenu("Window")) { if (ImGui::MenuItem("Examples")) showDemoWindow = !showDemoWindow; ImGui::Separator(); if (ImGui::BeginMenu("Workspace Style")) { if (ImGui::MenuItem("Dark")) ImGui::StyleColorsDark(); if (ImGui::MenuItem("Classic")) ImGui::StyleColorsClassic(); if (ImGui::MenuItem("Light")) ImGui::StyleColorsLight(); if (ImGui::MenuItem("Custom")) ImGui::StyleColorsCustom(); ImGui::EndMenu(); } ImGui::Separator(); if (ImGui::MenuItem("Hierarchy")) showHierarchyWindow = !showHierarchyWindow; if (ImGui::MenuItem("Inspector")) showInspectorWindow = !showInspectorWindow; if (ImGui::MenuItem("Scene")) showSceneWindow = !showSceneWindow; if (ImGui::MenuItem("Game")) showGameWindow = !showGameWindow; if (ImGui::MenuItem("Console")) showConsoleWindow = !showConsoleWindow; if (ImGui::MenuItem("Textures")) showTextures = !showTextures; if (ImGui::MenuItem("Timer")) showTimer = !showTimer; if (ImGui::MenuItem("Explorer")) showExplorer = !showExplorer; ImGui::Separator(); if (ImGui::MenuItem("Configuration")) showConfWindow = !showConfWindow; ImGui::EndMenu(); } /* ---- HELP ----*/ if (ImGui::BeginMenu("Help")) { if (ImGui::MenuItem("About")) showAboutWindow = !showAboutWindow; ImGui::EndMenu(); } } ImGui::EndMainMenuBar(); } void ModuleEditor::UpdateWindowStatus() { //Demo if (showDemoWindow) ImGui::ShowDemoWindow(&showDemoWindow); //About info if (showAboutWindow) About_Window(); //Config if (showConfWindow) { ImGui::Begin("Configuration", &showConfWindow); App->OnGui(); ImGui::End(); } if (showTextures) { ImGui::Begin("Textures", &showTextures); for (auto& t : App->textures->textures) { ImGui::Image((ImTextureID)t.second.id, ImVec2(128, 128), ImVec2(0, 1), ImVec2(1, 0)); ImGui::SameLine(); ImGui::PushID(t.second.id); if (ImGui::Button("Assign to selected")) { if (gameobjectSelected) { ComponentMaterial* material = gameobjectSelected->GetComponent<ComponentMaterial>(); if (material) { std::string normPathShortTexture = "Assets/Textures/" + App->fileSystem->SetNormalName(t.second.name.c_str()); material->texturePath = normPathShortTexture; material->SetTexture(t.second); } } } ImGui::PopID(); } ImGui::End(); } if (showTimer) { ImGui::Begin("Timer", &showTimer); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, { 1,0,0,1 }); if (ImGui::Button("Play", { 60,20 })) { if (App->clock->CheckPause()) { App->clock->Resume(); } //else //{ // App->clock->Play(); //} } ImGui::SameLine(); if (ImGui::Button("Pause", { 60,20 })) { if (!App->clock->CheckPause()) { App->clock->Pause(); } } ImGui::SameLine(); if (ImGui::Button("Stop", { 60,20 })) { App->clock->Stop(); } ImGui::PopStyleColor(); ImGui::SliderFloat("Speed UP/DOWN", App->clock->GetScale(), 0.1f, 2.0f, "%.1f"); ImGui::Text("Real Time: %.1f", App->clock->GetRealTimeSeconds()); ImGui::Text("Game Time: %.1f", App->clock->GetSecondsSinceGameStart()); ImGui::Text("Delta Time: %.3f", App->clock->GetDeltaTimeGame()); ImGui::End(); } //Console if (showConsoleWindow) { ImGui::Begin("Console", &showConsoleWindow); ImGui::TextUnformatted(consoleText.begin(), consoleText.end()); ImGui::SetScrollHere(1.0f); ImGui::End(); } //Inspector if (showInspectorWindow) { ImGui::Begin("Inspector", &showInspectorWindow); //Only shows info if any gameobject selected if (gameobjectSelected != nullptr) InspectorGameObject(); ImGui::End(); } //Explorer if (showExplorer) { ImGui::Begin("Explorer", &showExplorer); std::stack<File*> explorer; explorer.push(App->scene->assets); while (!explorer.empty()) { File* go = explorer.top(); explorer.pop(); if (ImGui::TreeNodeEx(go->name.c_str(), ImGuiTreeNodeFlags_Selected)) { for (File* child : go->children) { explorer.push(child); } ImGui::TreePop(); } } ImGui::End(); } //Hierarchy if (showHierarchyWindow) { ImGui::Begin("Hierarchy", &showHierarchyWindow); if (App->input->GetKey(SDL_SCANCODE_DELETE) == KEY_UP) { if (App->editor->gameobjectSelected != nullptr) { LOG("Deleted gameobject %s", App->editor->gameobjectSelected->name.c_str()); for (int i = 0; i < App->scene->root->children.size(); i++) { if (App->scene->root->children.at(i) == App->editor->gameobjectSelected) { std::vector<GameObject*> lenght; for (int i = 0; i < App->scene->root->children.size(); i++) { if (App->scene->root->children.at(i) != App->editor->gameobjectSelected) { lenght.push_back(App->scene->root->children.at(i)); } } App->editor->gameobjectSelected = nullptr; App->scene->root->children.clear(); for (int i = 0; i < lenght.size(); i++) { App->scene->root->children.push_back(lenght.at(i)); } } } } } //Just cleaning gameObjects(not textures,buffers...) if (ImGui::Button("Clear", { 60,20 })) { App->editor->gameobjectSelected = nullptr; App->scene->CleanUp(); //Clean GameObjects } ImGui::SameLine(); if (ImGui::Button("New", { 60,20 })) { App->scene->CreateGameObject(); } std::stack<GameObject*> S; std::stack<uint> indents; S.push(App->scene->root); indents.push(0); while (!S.empty()) { GameObject* go = S.top(); uint indentsAmount = indents.top(); S.pop(); indents.pop(); ImGuiTreeNodeFlags nodeFlags = 0; if (go->isSelected) nodeFlags |= ImGuiTreeNodeFlags_Selected; if (go->children.size() == 0) nodeFlags |= ImGuiTreeNodeFlags_Leaf; for (uint i = 0; i < indentsAmount; ++i) { ImGui::Indent(); } if (ImGui::TreeNodeEx(go->name.c_str(), nodeFlags)) { if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { ImGui::SetDragDropPayload("DragDropHierarchy", &go, sizeof(GameObject*), ImGuiCond_Once); ImGui::Text("%s", go->name.c_str()); ImGui::EndDragDropSource(); } if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DragDropHierarchy")) { IM_ASSERT(payload->DataSize == sizeof(GameObject*)); GameObject* droppedGo = (GameObject*)*(const int*)payload->Data; if (droppedGo) { droppedGo->parent->RemoveChild(droppedGo); go->AttachChild(droppedGo); } } ImGui::EndDragDropTarget(); } if (ImGui::IsItemClicked()) { gameobjectSelected ? gameobjectSelected->isSelected = !gameobjectSelected->isSelected : 0; gameobjectSelected = go; gameobjectSelected->isSelected = !gameobjectSelected->isSelected; if (gameobjectSelected->isSelected) { LOG("GameObject selected name: %s", gameobjectSelected->name.c_str()); } else { LOG("GameObject unselected name: %s", gameobjectSelected->name.c_str()); } } for (GameObject* child : go->children) { S.push(child); indents.push(indentsAmount + 1); } for (uint i = 0; i < indentsAmount; ++i) { ImGui::Unindent(); } ImGui::TreePop(); } } ImGui::End(); } if (showGameWindow) { ImGui::Begin("Game", &showGameWindow, ImGuiWindowFlags_::ImGuiWindowFlags_NoScrollbar); ImVec2 viewportSize = ImGui::GetCurrentWindow()->Size; if (viewportSize.x != lastViewportSize.x || viewportSize.y != lastViewportSize.y) { App->camera->aspectRatio = viewportSize.x / viewportSize.y; App->scene->camera->GetComponent<ComponentCamera>()->aspectRatio = viewportSize.x / viewportSize.y; App->scene->camera->GetComponent<ComponentCamera>()->RecalculateProjection(); } lastViewportSize = viewportSize; ImGui::Image((ImTextureID)App->viewportBufferGame->texture, viewportSize, ImVec2(0, 1), ImVec2(1, 0)); ImGui::End(); } if (showSceneWindow) { ImGui::Begin("Scene", &showSceneWindow, ImGuiWindowFlags_NoScrollbar); ImVec2 viewportSize = ImGui::GetCurrentWindow()->Size; if (viewportSize.x != lastViewportSize.x || viewportSize.y != lastViewportSize.y) { App->camera->aspectRatio = viewportSize.x / viewportSize.y; App->camera->RecalculateProjection(); } lastViewportSize = viewportSize; ImGui::Image((ImTextureID)App->viewportBuffer->texture, viewportSize, ImVec2(0, 1), ImVec2(1, 0)); ImGui::End(); } } void ModuleEditor::InspectorGameObject() { if (gameobjectSelected) gameobjectSelected->OnGui(); } ModuleEditor::Grid::~Grid() { glDeleteBuffers(1, &VAO); }
31.540466
179
0.578089
MaxLlovera
0211fa687bd49a6ebd17ff11581e32c053a2a372
3,161
cpp
C++
Chapter6/Util01_FilterEnvmap/src/main.cpp
adoug/3D-Graphics-Rendering-Cookbook
dabffed670b8be5a619f0f62b10e0cc8ccdd5a36
[ "MIT" ]
399
2021-06-03T02:42:20.000Z
2022-03-27T23:23:15.000Z
Chapter6/Util01_FilterEnvmap/src/main.cpp
adoug/3D-Graphics-Rendering-Cookbook
dabffed670b8be5a619f0f62b10e0cc8ccdd5a36
[ "MIT" ]
7
2021-07-13T02:36:01.000Z
2022-03-26T03:46:37.000Z
Chapter6/Util01_FilterEnvmap/src/main.cpp
adoug/3D-Graphics-Rendering-Cookbook
dabffed670b8be5a619f0f62b10e0cc8ccdd5a36
[ "MIT" ]
53
2021-06-02T20:02:24.000Z
2022-03-29T15:36:30.000Z
#include <imgui/imgui.h> #include "shared/vkFramework/VulkanApp.h" #include "stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" // Image_Resize's implementation is included in UtilsVulkan.cpp #include "stb_image_resize.h" int numPoints = 1024; /// From Henry J. Warren's "Hacker's Delight" float radicalInverse_VdC(uint32_t bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10f; // / 0x100000000 } // The i-th point is then computed by /// From http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html vec2 hammersley2d(uint32_t i, uint32_t N) { return vec2(float(i)/float(N), radicalInverse_VdC(i)); } void convolveDiffuse(const vec3* data, int srcW, int srcH, int dstW, int dstH, vec3* output, int numMonteCarloSamples) { // only equirectangular maps are supported assert(srcW == 2 * srcH); if (srcW != 2 * srcH) return; std::vector<vec3> tmp(dstW * dstH); stbir_resize_float_generic( reinterpret_cast<const float*>(data), srcW, srcH, 0, reinterpret_cast<float*>(tmp.data()), dstW, dstH, 0, 3, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_FILTER_CUBICBSPLINE, STBIR_COLORSPACE_LINEAR, nullptr); const vec3* scratch = tmp.data(); srcW = dstW; srcH = dstH; for (int y = 0; y != dstH; y++) { printf("Line %i...\n", y); const float theta1 = float(y) / float(dstH) * Math::PI; for (int x = 0; x != dstW; x++) { const float phi1 = float(x) / float(dstW) * Math::TWOPI; const vec3 V1 = vec3(sin(theta1) * cos(phi1), sin(theta1) * sin(phi1), cos(theta1)); vec3 color = vec3(0.0f); float weight = 0.0f; for (int i = 0; i != numMonteCarloSamples; i++) { const vec2 h = hammersley2d(i, numMonteCarloSamples); const int x1 = int(floor(h.x * srcW)); const int y1 = int(floor(h.y * srcH)); const float theta2 = float(y1) / float(srcH) * Math::PI; const float phi2 = float(x1) / float(srcW) * Math::TWOPI; const vec3 V2 = vec3(sin(theta2) * cos(phi2), sin(theta2) * sin(phi2), cos(theta2)); const float D = std::max(0.0f, glm::dot(V1, V2)); if (D > 0.01f) { color += scratch[y1 * srcW + x1] * D; weight += D; } } output[y * dstW + x] = color / weight; } } } void process_cubemap(const char* filename, const char* outFilename) { int w, h, comp; const float* img = stbi_loadf(filename, &w, &h, &comp, 3); if (!img) { printf("Failed to load [%s] texture\n", filename); fflush(stdout); return; } const int dstW = 256; const int dstH = 128; std::vector<vec3> out(dstW * dstH); convolveDiffuse((vec3*)img, w, h, dstW, dstH, out.data(), numPoints); stbi_image_free((void*)img); stbi_write_hdr(outFilename, dstW, dstH, 3, (float*)out.data()); } int main() { process_cubemap("data/piazza_bologni_1k.hdr", "data/piazza_bologni_1k_irradiance.hdr"); return 0; }
29
118
0.649478
adoug
0212268ff1b50f209a304b1f270601fe53f73b7d
181
cpp
C++
lib/Experimental/Cmdline/GetOptIncW.cpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
8
2015-01-23T05:41:46.000Z
2019-11-20T05:10:27.000Z
lib/Experimental/Cmdline/GetOptIncW.cpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
null
null
null
lib/Experimental/Cmdline/GetOptIncW.cpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
4
2015-05-05T05:15:43.000Z
2020-03-07T11:10:56.000Z
//getopt unicode #ifndef UNICODE #define UNICODE #endif #ifndef _UNICODE #define _UNICODE #endif #ifdef _MBCS #undef _MBCS #endif #include "GetOptInc.h" #include "GetOptInc.inc"
12.066667
24
0.762431
fstudio
0215bdfe6153c72511b61d5994c9319daeb1eea0
6,428
hpp
C++
include/System/Linq/Expressions/InvocationExpression0.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Linq/Expressions/InvocationExpression0.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Linq/Expressions/InvocationExpression0.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Linq.Expressions.InvocationExpression #include "System/Linq/Expressions/InvocationExpression.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Linq::Expressions namespace System::Linq::Expressions { // Skipping declaration: Expression because it is already included! } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: System.Linq.Expressions namespace System::Linq::Expressions { // Forward declaring type: InvocationExpression0 class InvocationExpression0; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Linq::Expressions::InvocationExpression0); DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Expressions::InvocationExpression0*, "System.Linq.Expressions", "InvocationExpression0"); // Type namespace: System.Linq.Expressions namespace System::Linq::Expressions { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: System.Linq.Expressions.InvocationExpression0 // [TokenAttribute] Offset: FFFFFFFF class InvocationExpression0 : public ::System::Linq::Expressions::InvocationExpression { public: // public override System.Int32 get_ArgumentCount() // Offset: 0xF1F2D0 // Implemented from: System.Linq.Expressions.InvocationExpression // Base method: System.Int32 InvocationExpression::get_ArgumentCount() int get_ArgumentCount(); // public System.Void .ctor(System.Linq.Expressions.Expression lambda, System.Type returnType) // Offset: 0xF1F278 // Implemented from: System.Linq.Expressions.InvocationExpression // Base method: System.Void InvocationExpression::.ctor(System.Linq.Expressions.Expression lambda, System.Type returnType) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static InvocationExpression0* New_ctor(::System::Linq::Expressions::Expression* lambda, ::System::Type* returnType) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::InvocationExpression0::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<InvocationExpression0*, creationType>(lambda, returnType))); } // public override System.Linq.Expressions.Expression GetArgument(System.Int32 index) // Offset: 0xF1F27C // Implemented from: System.Linq.Expressions.InvocationExpression // Base method: System.Linq.Expressions.Expression InvocationExpression::GetArgument(System.Int32 index) ::System::Linq::Expressions::Expression* GetArgument(int index); // override System.Linq.Expressions.InvocationExpression Rewrite(System.Linq.Expressions.Expression lambda, System.Linq.Expressions.Expression[] arguments) // Offset: 0xF1F2D8 // Implemented from: System.Linq.Expressions.InvocationExpression // Base method: System.Linq.Expressions.InvocationExpression InvocationExpression::Rewrite(System.Linq.Expressions.Expression lambda, System.Linq.Expressions.Expression[] arguments) ::System::Linq::Expressions::InvocationExpression* Rewrite(::System::Linq::Expressions::Expression* lambda, ::ArrayW<::System::Linq::Expressions::Expression*> arguments); }; // System.Linq.Expressions.InvocationExpression0 #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Linq::Expressions::InvocationExpression0::get_ArgumentCount // Il2CppName: get_ArgumentCount template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::InvocationExpression0::*)()>(&System::Linq::Expressions::InvocationExpression0::get_ArgumentCount)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::InvocationExpression0*), "get_ArgumentCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::InvocationExpression0::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Linq::Expressions::InvocationExpression0::GetArgument // Il2CppName: GetArgument template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::Expression* (System::Linq::Expressions::InvocationExpression0::*)(int)>(&System::Linq::Expressions::InvocationExpression0::GetArgument)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::InvocationExpression0*), "GetArgument", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::InvocationExpression0::Rewrite // Il2CppName: Rewrite template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::InvocationExpression* (System::Linq::Expressions::InvocationExpression0::*)(::System::Linq::Expressions::Expression*, ::ArrayW<::System::Linq::Expressions::Expression*>)>(&System::Linq::Expressions::InvocationExpression0::Rewrite)> { static const MethodInfo* get() { static auto* lambda = &::il2cpp_utils::GetClassFromName("System.Linq.Expressions", "Expression")->byval_arg; static auto* arguments = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System.Linq.Expressions", "Expression"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::InvocationExpression0*), "Rewrite", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{lambda, arguments}); } };
63.019608
331
0.765557
v0idp
021774de25eaf6eed0b8b73024ee66825bc8903d
2,883
cc
C++
viewer/colors/solarized.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
1
2019-04-14T11:40:28.000Z
2019-04-14T11:40:28.000Z
viewer/colors/solarized.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
5
2018-04-18T13:54:29.000Z
2019-08-22T20:04:17.000Z
viewer/colors/solarized.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
1
2018-12-24T03:45:47.000Z
2018-12-24T03:45:47.000Z
#include "viewer/colors/solarized.hh" #include <map> namespace viewer { // I've got a case of the jeepy-jeekies void solarized_string_from_enum(const SolarizedColor color) { const std::vector<std::string> string_from_enum = { "Base03", // "Base02", // "Base01", // "Base00", // "Base0", // "Base1", // "Base2", // "Base3", // "Yellow", // "Orange", // "Red", // "Magenta", // "Violet", // "Blue", // "Cyan", // "Green" // }; const int index = static_cast<int>(color); JASSERT_LT(static_cast<int>(color), static_cast<int>(SolarizedColor::SIZE), "Out of range!"); return string_from_enum.at(index); } void solarized_enum_from_string(const std::string& color_name) { const std::map<std::string, SolarizedColor> enum_from_string = { {"Base03", SolarizedColor::Base03}, // {"Base02", SolarizedColor::Base02}, // {"Base01", SolarizedColor::Base01}, // {"Base00", SolarizedColor::Base00}, // {"Base0", SolarizedColor::Base0}, // {"Base1", SolarizedColor::Base1}, // {"Base2", SolarizedColor::Base2}, // {"Base3", SolarizedColor::Base3}, // {"Yellow", SolarizedColor::Yellow}, // {"Orange", SolarizedColor::Orange}, // {"Red", SolarizedColor::Red}, // {"Magenta", SolarizedColor::Magenta}, // {"Violet", SolarizedColor::Violet}, // {"Blue", SolarizedColor::Blue}, // {"Cyan", SolarizedColor::Cyan}, // {"Green", SolarizedColor::Green} // }; return enum_from_string.at(color_name); } jcc::Vec4 solarized_color(const std::string& name) { const SolarizedColor id = solarized_enum_from_string(name); return solarized_color(id); } jcc::Vec4 solarized_color(const SolarizedColor id) { const std::map<SolarizedColor, uint32_t> color_from_enum = { {Base03, 0x002b36}, // {Base02, 0x073642}, // {Base01, 0x586e75}, // {Base00, 0x657b83}, // {Base0, 0x839496}, // {Base1, 0x93a1a1}, // {Base2, 0xeee8d5}, // {Base3, 0xfdf6e3}, // {Yellow, 0xb58900}, // {Orange, 0xcb4b16}, // {Red, 0xdc322f}, // {Magenta, 0xd33682}, // {Violet, 0x6c71c4}, // {Blue, 0x268bd2}, // {Cyan, 0x2aa198}, // {Green, 0x859900} // }; const uint32_t color_hex = color_from_enum.at(id); jcc::Vec3 color; // Some people just want to fill the world with silly bit-shifts color[0] = static_cast<double>((color_hex >> (8 * 2)) & 0xff) / 255.0; color[1] = static_cast<double>((color_hex >> (8 * 1)) & 0xff) / 255.0; color[2] = static_cast<double>((color_hex >> (8 * 0)) & 0xff) / 255.0; return color; } } // namespace viewer
31.681319
77
0.554284
jpanikulam
021a8c7ce8fb1855366b06ad121cca5381f6fb65
7,416
cpp
C++
src/ExtLib/Bento4/Core/Ap4Movie.cpp
chinajeffery/MPC-BE--1.2.3
2229fde5535f565ba4a496a7f73267bd2c1ad338
[ "MIT" ]
null
null
null
src/ExtLib/Bento4/Core/Ap4Movie.cpp
chinajeffery/MPC-BE--1.2.3
2229fde5535f565ba4a496a7f73267bd2c1ad338
[ "MIT" ]
1
2019-11-14T04:18:32.000Z
2019-11-14T04:18:32.000Z
src/ExtLib/Bento4/Core/Ap4Movie.cpp
chinajeffery/MPC-BE--1.2.3
2229fde5535f565ba4a496a7f73267bd2c1ad338
[ "MIT" ]
null
null
null
/***************************************************************** | | AP4 - Movie | | Copyright 2002-2005 Gilles Boccon-Gibod | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL 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, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4.h" #include "Ap4File.h" #include "Ap4Atom.h" #include "Ap4TrakAtom.h" #include "Ap4MoovAtom.h" #include "Ap4MvhdAtom.h" #include "Ap4AtomFactory.h" #include "Ap4Movie.h" /*---------------------------------------------------------------------- | AP4_TrackFinderById +---------------------------------------------------------------------*/ class AP4_TrackFinderById : public AP4_List<AP4_Track>::Item::Finder { public: AP4_TrackFinderById(AP4_UI32 track_id) : m_TrackId(track_id) {} AP4_Result Test(AP4_Track* track) const { return track->GetId() == m_TrackId ? AP4_SUCCESS : AP4_FAILURE; } private: AP4_UI32 m_TrackId; }; /*---------------------------------------------------------------------- | AP4_TrackFinderByType +---------------------------------------------------------------------*/ class AP4_TrackFinderByType : public AP4_List<AP4_Track>::Item::Finder { public: AP4_TrackFinderByType(AP4_Track::Type type, AP4_Ordinal index = 0) : m_Type(type), m_Index(index) {} AP4_Result Test(AP4_Track* track) const { if (track->GetType() == m_Type && m_Index-- == 0) { return AP4_SUCCESS; } else { return AP4_FAILURE; } } private: AP4_Track::Type m_Type; mutable AP4_Ordinal m_Index; }; /*---------------------------------------------------------------------- | AP4_Movie::AP4_Movie +---------------------------------------------------------------------*/ AP4_Movie::AP4_Movie(AP4_UI32 time_scale) { m_MoovAtom = new AP4_MoovAtom(); m_MvhdAtom = new AP4_MvhdAtom(0, 0, time_scale, 0, 0x00010000, 0x0100); m_MoovAtom->AddChild(m_MvhdAtom); } /*---------------------------------------------------------------------- | AP4_Movie::AP4_Moovie +---------------------------------------------------------------------*/ AP4_Movie::AP4_Movie(AP4_MoovAtom* moov, AP4_ByteStream& mdat) : m_MoovAtom(moov) { // ignore null atoms if (moov == NULL) return; // get the time scale AP4_UI32 time_scale; m_MvhdAtom = dynamic_cast<AP4_MvhdAtom*>(moov->GetChild(AP4_ATOM_TYPE_MVHD)); if (m_MvhdAtom) { time_scale = m_MvhdAtom->GetTimeScale(); } else { time_scale = 0; } // get all tracks AP4_List<AP4_TrakAtom>* trak_atoms; trak_atoms = &moov->GetTrakAtoms(); AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem(); while (item) { AP4_Track* track = new AP4_Track(*item->GetData(), mdat, time_scale); m_Tracks.Add(track); item = item->GetNext(); } } /*---------------------------------------------------------------------- | AP4_Movie::~AP4_Movie +---------------------------------------------------------------------*/ AP4_Movie::~AP4_Movie() { m_Tracks.DeleteReferences(); delete m_MoovAtom; } /*---------------------------------------------------------------------- | AP4_Movie::Inspect +---------------------------------------------------------------------*/ AP4_Result AP4_Movie::Inspect(AP4_AtomInspector& inspector) { // dump the moov atom return m_MoovAtom->Inspect(inspector); } /*---------------------------------------------------------------------- | AP4_Movie::GetTrack +---------------------------------------------------------------------*/ AP4_Track* AP4_Movie::GetTrack(AP4_UI32 track_id) { AP4_Track* track = NULL; if (AP4_SUCCEEDED(m_Tracks.Find(AP4_TrackFinderById(track_id), track))) { return track; } else { return NULL; } } /*---------------------------------------------------------------------- | AP4_Movie::GetTrack +---------------------------------------------------------------------*/ AP4_Track* AP4_Movie::GetTrack(AP4_Track::Type track_type, AP4_Ordinal index) { AP4_Track* track = NULL; if (AP4_SUCCEEDED(m_Tracks.Find(AP4_TrackFinderByType(track_type, index), track))) { return track; } else { return NULL; } } /*---------------------------------------------------------------------- | AP4_Movie::AddTrack +---------------------------------------------------------------------*/ AP4_Result AP4_Movie::AddTrack(AP4_Track* track) { // assign an ID to the track unless it already has one if (track->GetId() == 0) { track->SetId(m_Tracks.ItemCount()+1); } // if we don't have a time scale, use the one from the track if (m_MvhdAtom->GetTimeScale() == 0) { m_MvhdAtom->SetTimeScale(track->GetMediaTimeScale()); } // adjust the parent time scale of the track track->SetMovieTimeScale(m_MvhdAtom->GetTimeScale()); // update the movie duration if (m_MvhdAtom->GetDuration() < track->GetDuration()) { m_MvhdAtom->SetDuration(track->GetDuration()); } // attach the track as a child m_MoovAtom->AddChild(track->GetTrakAtom()); m_Tracks.Add(track); return AP4_SUCCESS; } /*---------------------------------------------------------------------- | AP4_Movie::GetTimeScale +---------------------------------------------------------------------*/ AP4_UI32 AP4_Movie::GetTimeScale() { if (m_MvhdAtom) { return m_MvhdAtom->GetTimeScale(); } else { return 0; } } /*---------------------------------------------------------------------- | AP4_Movie::GetDuration +---------------------------------------------------------------------*/ AP4_UI64 AP4_Movie::GetDuration() { if (m_MvhdAtom) { return m_MvhdAtom->GetDuration(); } else { return 0; } } /*---------------------------------------------------------------------- | AP4_Movie::GetDurationMs +---------------------------------------------------------------------*/ AP4_Duration AP4_Movie::GetDurationMs() { if (m_MvhdAtom) { return m_MvhdAtom->GetDurationMs(); } else { return 0; } }
31.423729
88
0.459547
chinajeffery