hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cc4c1e622103d64a277e9407f9a7896871adc7de | 7,071 | cpp | C++ | environment_wrapper/EnvironmentWrapper.cpp | gkhaos/ICC | 20bcbcbfb25e06691f0408bae93426ecc8b0d4ed | [
"Apache-2.0"
] | 46 | 2020-03-16T14:18:59.000Z | 2021-12-14T14:11:41.000Z | environment_wrapper/EnvironmentWrapper.cpp | gkhaos/ICC | 20bcbcbfb25e06691f0408bae93426ecc8b0d4ed | [
"Apache-2.0"
] | 5 | 2020-06-19T10:44:57.000Z | 2021-01-07T15:10:25.000Z | environment_wrapper/EnvironmentWrapper.cpp | gkhaos/ICC | 20bcbcbfb25e06691f0408bae93426ecc8b0d4ed | [
"Apache-2.0"
] | 7 | 2020-03-18T18:11:14.000Z | 2021-02-17T01:05:07.000Z | #include "EnvironmentWrapper.h"
#include <omp.h>
#include <iostream>
#include "dart/dart.hpp"
#include "Utils.h"
#include "Configurations.h"
EnvironmentWrapper::
EnvironmentWrapper(std::string configuration_filepath, int num_slaves)
{
ICC::Configurations::instance().LoadConfigurations(configuration_filepath);
this->mNumSlaves = num_slaves;
dart::math::seedRand();
omp_set_num_threads(this->mNumSlaves);
for(int id = 0; id < this->mNumSlaves; id++){
this->mSlaves.emplace_back(new ICC::Environment());
}
this->mStateSize = this->mSlaves[0]->getStateSize();
this->mActionSize = this->mSlaves[0]->getActionSize();
}
//For general properties
int
EnvironmentWrapper::
getStateSize()
{
return this->mStateSize;
}
int
EnvironmentWrapper::
getActionSize()
{
return this->mActionSize;
}
//For each slave
void
EnvironmentWrapper::
step(int id, bool record)
{
this->mSlaves[id]->step(record);
}
void
EnvironmentWrapper::
reset(int id, double time)
{
this->mSlaves[id]->reset(time);
}
bool
EnvironmentWrapper::
isTerminal(int id)
{
return this->mSlaves[id]->isTerminal();
}
p::tuple
EnvironmentWrapper::
isNanAtTerminal(int id)
{
bool t = mSlaves[id]->isTerminal();
bool n = mSlaves[id]->isNanAtTerminal();
bool e = mSlaves[id]->isEndOfTrajectory();
return p::make_tuple(t, n, e);
}
np::ndarray
EnvironmentWrapper::
getState(int id)
{
return ICC::Utils::toNumPyArray(this->mSlaves[id]->getState());
}
void
EnvironmentWrapper::
setAction(int id, np::ndarray np_array)
{
this->mSlaves[id]->setAction(ICC::Utils::toEigenVector(np_array, this->mActionSize));
}
np::ndarray
EnvironmentWrapper::
getReward(int id)
{
return ICC::Utils::toNumPyArray(this->mSlaves[id]->getReward());
}
//For all slaves
void
EnvironmentWrapper::
steps(bool record)
{
if( this->mNumSlaves == 1){
this->step(0, record);
}
else{
#pragma omp parallel for
for (int id = 0; id < this->mNumSlaves; id++){
this->step(id, record);
}
}
}
void
EnvironmentWrapper::
resets()
{
for (int id = 0; id < this->mNumSlaves; id++){
this->reset(id, 0);
}
}
np::ndarray
EnvironmentWrapper::
isTerminals()
{
std::vector<bool> is_terminate_vector(this->mNumSlaves);
for(int id = 0; id < this->mNumSlaves; id++){
is_terminate_vector[id] = this->isTerminal(id);
}
return ICC::Utils::toNumPyArray(is_terminate_vector);
}
np::ndarray
EnvironmentWrapper::
getStates()
{
std::vector<Eigen::VectorXd> states(this->mNumSlaves);
for (int id = 0; id < this->mNumSlaves; id++){
states[id] = this->mSlaves[id]->getState();
}
return ICC::Utils::toNumPyArray(states);
}
void
EnvironmentWrapper::
setActions(np::ndarray np_array)
{
Eigen::MatrixXd action = ICC::Utils::toEigenMatrix(np_array, this->mNumSlaves, this->mActionSize);
for (int id = 0; id < this->mNumSlaves; id++){
this->mSlaves[id]->setAction(action.row(id));
}
}
np::ndarray
EnvironmentWrapper::
getRewards()
{
std::vector<std::vector<double>> rewards(this->mNumSlaves);
for (int id = 0; id < this->mNumSlaves; id++){
rewards[id] = this->mSlaves[id]->getReward();
}
return ICC::Utils::toNumPyArray(rewards);
}
void
EnvironmentWrapper::
setReferenceTrajectory(int id, int frame, np::ndarray ref_trajectory)
{
Eigen::MatrixXd mat = ICC::Utils::toEigenMatrix(ref_trajectory, frame, ICC::Configurations::instance().getTCMotionSize());
std::vector<Eigen::VectorXd> converted_traj;
converted_traj.resize(mat.rows());
for(int i = 0; i < mat.rows(); i++){
converted_traj[i] = ICC::Utils::convertMGToTC(mat.row(i), this->mSlaves[id]->getActor()->getSkeleton());
}
this->mSlaves[id]->setReferenceTrajectory(converted_traj);
}
void
EnvironmentWrapper::
setReferenceTrajectories(int frame, np::ndarray ref_trajectory)
{
Eigen::MatrixXd mat = ICC::Utils::toEigenMatrix(ref_trajectory, frame, ICC::Configurations::instance().getTCMotionSize());
std::vector<Eigen::VectorXd> converted_traj;
converted_traj.resize(mat.rows());
for(int i = 0; i < mat.rows(); i++){
converted_traj[i] = ICC::Utils::convertMGToTC(mat.row(i), this->mSlaves[0]->getActor()->getSkeleton());
}
#pragma omp parallel for
for(int id = 0; id < this->mNumSlaves; id++){
this->mSlaves[id]->setReferenceTrajectory(converted_traj);
}
}
void
EnvironmentWrapper::
setReferenceTargetTrajectory(int id, int frame, np::ndarray target_trajectory)
{
Eigen::MatrixXd mat = ICC::Utils::toEigenMatrix(target_trajectory, frame, 2);
std::vector<Eigen::Vector3d> converted_traj;
converted_traj.resize(mat.rows());
for(int i = 0; i < mat.rows(); i++){
converted_traj[i] << mat(i,0), 0, mat(i,1);
}
this->mSlaves[id]->setReferenceTargetTrajectory(converted_traj);
}
void
EnvironmentWrapper::
setReferenceTargetTrajectories(int frame, np::ndarray ref_trajectory)
{
Eigen::MatrixXd mat = ICC::Utils::toEigenMatrix(ref_trajectory, frame, 2);
std::vector<Eigen::Vector3d> converted_traj;
converted_traj.resize(mat.rows());
for(int i = 0; i < mat.rows(); i++){
converted_traj[i] << mat(i,0), 0, mat(i,1);
}
#pragma omp parallel for
for(int id = 0; id < this->mNumSlaves; id++){
this->mSlaves[id]->setReferenceTargetTrajectory(converted_traj);
}
}
void
EnvironmentWrapper::
followReference(int id)
{
this->mSlaves[id]->followReference();
}
void
EnvironmentWrapper::
followReferences()
{
for (int id = 0; id < this->mNumSlaves; id++)
this->mSlaves[id]->followReference();
}
void
EnvironmentWrapper::
writeRecords(std::string path)
{
for (int id = 0; id < this->mNumSlaves; id++){
mSlaves[id]->writeRecords(path + std::to_string(id) + ".rec");
// mSlaves[id]->writeFullRecords(path + std::to_string(id) + "_full.rec");
}
}
using namespace boost::python;
BOOST_PYTHON_MODULE(environment_wrapper)
{
Py_Initialize();
np::initialize();
class_<EnvironmentWrapper>("environment",init<std::string, int>())
.def("getStateSize",&EnvironmentWrapper::getStateSize)
.def("getActionSize",&EnvironmentWrapper::getActionSize)
.def("step",&EnvironmentWrapper::step)
.def("reset",&EnvironmentWrapper::reset)
.def("isTerminal",&EnvironmentWrapper::isTerminal)
.def("isNanAtTerminal",&EnvironmentWrapper::isNanAtTerminal)
.def("getState",&EnvironmentWrapper::getState)
.def("setAction",&EnvironmentWrapper::setAction)
.def("getReward",&EnvironmentWrapper::getReward)
.def("steps",&EnvironmentWrapper::steps)
.def("resets",&EnvironmentWrapper::resets)
.def("isTerminals",&EnvironmentWrapper::isTerminals)
.def("getStates",&EnvironmentWrapper::getStates)
.def("setActions",&EnvironmentWrapper::setActions)
.def("getRewards",&EnvironmentWrapper::getRewards)
.def("setReferenceTrajectory",&EnvironmentWrapper::setReferenceTrajectory)
.def("setReferenceTrajectories",&EnvironmentWrapper::setReferenceTrajectories)
.def("setReferenceTargetTrajectory",&EnvironmentWrapper::setReferenceTargetTrajectory)
.def("setReferenceTargetTrajectories",&EnvironmentWrapper::setReferenceTargetTrajectories)
.def("followReference",&EnvironmentWrapper::followReference)
.def("followReferences",&EnvironmentWrapper::followReferences)
.def("writeRecords",&EnvironmentWrapper::writeRecords);
} | 25.074468 | 123 | 0.726347 | gkhaos |
cc4d57af26e28ae0b6b38778af047c3a67388d3f | 83,476 | cc | C++ | optickscore/OpticksEvent.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 11 | 2020-07-05T02:39:32.000Z | 2022-03-20T18:52:44.000Z | optickscore/OpticksEvent.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | null | null | null | optickscore/OpticksEvent.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 4 | 2020-09-03T20:36:32.000Z | 2022-01-19T07:42:21.000Z | /*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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.
*/
#ifdef _MSC_VER
// 'ViewNPY': object allocated on the heap may not be aligned 16
// https://github.com/g-truc/glm/issues/235
// apparently fixed by 0.9.7.1 Release : currently on 0.9.6.3
#pragma warning( disable : 4316 )
#endif
#include <climits>
#include <cassert>
#include <sstream>
#include <cstring>
#include <csignal>
#include <iomanip>
// brap-
#include "BTimes.hh"
#include "BStr.hh"
#include "BTime.hh"
#include "BFile.hh"
#include "BOpticksResource.hh"
#include "BOpticksEvent.hh"
#include "BMeta.hh"
// npy-
#include "uif.h"
#include "NGLM.hpp"
#include "NPY.hpp"
#include "NLoad.hpp"
#include "NPYSpec.hpp"
#include "NLookup.hpp"
#include "NGeoTestConfig.hpp"
#include "ViewNPY.hpp"
#include "MultiViewNPY.hpp"
#include "TrivialCheckNPY.hpp"
#include "GLMFormat.hpp"
#include "Index.hpp"
#include "Report.hpp"
#include "BTimeKeeper.hh"
#include "BTimes.hh"
#include "BTimesTable.hh"
#include "OKConf.hh"
// okc-
#include "Opticks.hh"
#include "OpticksProfile.hh"
#include "OpticksSwitches.h"
#include "OpticksPhoton.h"
#include "OpticksGenstep.hh"
#include "OpticksConst.hh"
#include "OpticksDomain.hh"
#include "OpticksFlags.hh"
#include "OpticksEventInstrument.hh"
#include "OpticksEvent.hh"
#include "OpticksMode.hh"
#include "OpticksBufferSpec.hh"
#include "OpticksBufferControl.hh"
#include "OpticksActionControl.hh"
#include "Indexer.hh"
#include "PLOG.hh"
const plog::Severity OpticksEvent::LEVEL = PLOG::EnvLevel("OpticksEvent", "DEBUG") ;
const char* OpticksEvent::TIMEFORMAT = "%Y%m%d_%H%M%S" ;
const char* OpticksEvent::PARAMETERS_NAME = "parameters.json" ;
const char* OpticksEvent::PARAMETERS_STEM = "parameters" ;
const char* OpticksEvent::PARAMETERS_EXT = ".json" ;
std::string OpticksEvent::timestamp()
{
std::string timestamp = BTime::now(TIMEFORMAT, 0);
return timestamp ;
}
const char* OpticksEvent::fdom_ = "fdom" ;
const char* OpticksEvent::idom_ = "idom" ;
const char* OpticksEvent::genstep_ = "genstep" ;
const char* OpticksEvent::nopstep_ = "nopstep" ;
const char* OpticksEvent::photon_ = "photon" ;
const char* OpticksEvent::debug_ = "debug" ;
const char* OpticksEvent::way_ = "way" ;
const char* OpticksEvent::source_ = "source" ;
const char* OpticksEvent::record_ = "record" ;
const char* OpticksEvent::deluxe_ = "deluxe" ; // double precision version of the record buffer used for g4evt
const char* OpticksEvent::phosel_ = "phosel" ;
const char* OpticksEvent::recsel_ = "recsel" ;
const char* OpticksEvent::sequence_ = "sequence" ;
const char* OpticksEvent::boundary_ = "boundary" ;
const char* OpticksEvent::seed_ = "seed" ;
const char* OpticksEvent::hit_ = "hit" ;
const char* OpticksEvent::hiy_ = "hiy" ;
OpticksEvent* OpticksEvent::Make(OpticksEventSpec* spec, unsigned tagoffset) // static
{
OpticksEventSpec* offspec = spec->clone(tagoffset);
return new OpticksEvent(offspec) ;
}
Opticks* OpticksEvent::getOpticks() const { return m_ok ; }
OpticksProfile* OpticksEvent::getProfile() const { return m_profile ; }
const char* OpticksEvent::PRELAUNCH_LABEL = "OpticksEvent_prelaunch" ;
const char* OpticksEvent::LAUNCH_LABEL = "OpticksEvent_launch" ;
OpticksEvent::OpticksEvent(OpticksEventSpec* spec)
:
OpticksEventSpec(spec),
//m_event_spec(spec),
m_ok(NULL), // set by Opticks::makeEvent
m_profile(NULL),
m_noload(false),
m_loaded(false),
m_versions(NULL),
m_parameters(NULL),
m_report(NULL),
m_domain(NULL),
m_prelaunch_times(new BTimes(PRELAUNCH_LABEL)),
m_launch_times(new BTimes(LAUNCH_LABEL)),
m_geopath(NULL),
m_genstep_data(NULL),
m_nopstep_data(NULL),
m_photon_data(NULL),
m_debug_data(NULL),
m_way_data(NULL),
m_source_data(NULL),
m_record_data(NULL),
m_deluxe_data(NULL),
m_phosel_data(NULL),
m_recsel_data(NULL),
m_sequence_data(NULL),
m_boundary_data(NULL),
m_seed_data(NULL),
m_hit_data(NULL),
m_hiy_data(NULL),
m_photon_ctrl(NULL),
m_source_ctrl(NULL),
m_seed_ctrl(NULL),
m_genstep_vpos(NULL),
m_genstep_attr(NULL),
m_nopstep_attr(NULL),
m_photon_attr(NULL),
m_source_attr(NULL),
m_record_attr(NULL),
m_deluxe_attr(NULL),
m_phosel_attr(NULL),
m_recsel_attr(NULL),
m_sequence_attr(NULL),
m_boundary_attr(NULL),
m_seed_attr(NULL),
m_hit_attr(NULL),
m_hiy_attr(NULL),
m_records(NULL),
m_photons(NULL),
m_bnd(NULL),
m_num_gensteps(0),
m_num_nopsteps(0),
m_num_photons(0),
m_num_source(0),
m_seqhis(NULL),
m_seqmat(NULL),
m_bndidx(NULL),
m_fdom_spec(NULL),
m_idom_spec(NULL),
m_genstep_spec(NULL),
m_nopstep_spec(NULL),
m_photon_spec(NULL),
m_debug_spec(NULL),
m_way_spec(NULL),
m_source_spec(NULL),
m_record_spec(NULL),
m_deluxe_spec(NULL),
m_phosel_spec(NULL),
m_recsel_spec(NULL),
m_sequence_spec(NULL),
m_boundary_spec(NULL),
m_seed_spec(NULL),
m_hit_spec(NULL),
m_hiy_spec(NULL),
m_sibling(NULL),
m_geotestconfig(NULL),
m_fake_nopstep_path(NULL),
m_skipahead(0)
{
init();
}
BTimes* OpticksEvent::getPrelaunchTimes()
{
return m_prelaunch_times ;
}
BTimes* OpticksEvent::getLaunchTimes()
{
return m_launch_times ;
}
void OpticksEvent::setSkipAhead(unsigned skipahead) // TODO: move to unsigned long long
{
m_skipahead = skipahead ;
}
unsigned OpticksEvent::getSkipAhead() const
{
return m_skipahead ;
}
void OpticksEvent::setSibling(OpticksEvent* sibling)
{
m_sibling = sibling ;
}
OpticksEvent* OpticksEvent::getSibling()
{
return m_sibling ;
}
bool OpticksEvent::isNoLoad() const
{
return m_noload ;
}
bool OpticksEvent::isLoaded() const
{
return m_loaded ;
}
bool OpticksEvent::isStep() const
{
return true ;
}
bool OpticksEvent::isFlat() const
{
return false ;
}
unsigned int OpticksEvent::getNumGensteps()
{
return m_num_gensteps ;
}
unsigned int OpticksEvent::getNumNopsteps()
{
return m_num_nopsteps ;
}
void OpticksEvent::resizeToZero()
{
bool resize_ = true ;
setNumPhotons(0, resize_);
}
void OpticksEvent::setNumPhotons(unsigned int num_photons, bool resize_) // resize_ default true
{
m_num_photons = num_photons ;
if(resize_)
{
LOG(LEVEL) << "RESIZING " << num_photons ;
resize();
}
else
{
LOG(LEVEL) << "NOT RESIZING " << num_photons ;
}
}
/**
OpticksEvent::getNumPhotonsFromPhotonArraySize
-----------------------------------------------
Hmm why the m_num_photons ? Maybe because can declare a number without paying memory for them.
But that happens (lazy allocation) at NPY level anyhow.
TODO: try to eliminate m_num_photons
**/
unsigned int OpticksEvent::getNumPhotonsFromPhotonArraySize() const
{
return m_photon_data ? m_photon_data->getNumItems() : 0 ;
}
void OpticksEvent::updateNumPhotonsFromPhotonArraySize()
{
unsigned num_photons = m_num_photons ;
m_num_photons = getNumPhotonsFromPhotonArraySize() ;
LOG(LEVEL) << " num_photons update " << num_photons << " -> " << m_num_photons ;
}
unsigned int OpticksEvent::getNumPhotons() const
{
return m_num_photons ;
}
unsigned int OpticksEvent::getNumSource() const
{
return m_num_source ;
}
unsigned int OpticksEvent::getNumRecords() const
{
unsigned int maxrec = getMaxRec();
return m_num_photons * maxrec ;
}
unsigned int OpticksEvent::getNumDeluxe() const
{
return getNumRecords();
}
bool OpticksEvent::hasGenstepData() const
{
return m_genstep_data && m_genstep_data->hasData() ;
}
bool OpticksEvent::hasSourceData() const
{
return m_source_data && m_source_data->hasData() ;
}
bool OpticksEvent::hasPhotonData() const
{
return m_photon_data && m_photon_data->hasData() ;
}
bool OpticksEvent::hasDebugData() const
{
return m_debug_data && m_debug_data->hasData() ;
}
bool OpticksEvent::hasWayData() const
{
return m_way_data && m_way_data->hasData() ;
}
bool OpticksEvent::hasRecordData() const
{
return m_record_data && m_record_data->hasData() ;
}
bool OpticksEvent::hasDeluxeData() const
{
return m_deluxe_data && m_deluxe_data->hasData() ;
}
NPY<float>* OpticksEvent::getGenstepData() const
{
return m_genstep_data ;
}
NPY<float>* OpticksEvent::getNopstepData() const
{
return m_nopstep_data ;
}
NPY<float>* OpticksEvent::getPhotonData() const
{
return m_photon_data ;
}
NPY<float>* OpticksEvent::getDebugData() const
{
return m_debug_data ;
}
NPY<float>* OpticksEvent::getWayData() const
{
return m_way_data ;
}
NPY<float>* OpticksEvent::getSourceData() const
{
return m_source_data ;
}
NPY<short>* OpticksEvent::getRecordData() const
{
return m_record_data ;
}
NPY<double>* OpticksEvent::getDeluxeData() const
{
return m_deluxe_data ;
}
NPY<unsigned char>* OpticksEvent::getPhoselData() const
{
return m_phosel_data ;
}
NPY<unsigned char>* OpticksEvent::getRecselData() const
{
return m_recsel_data ;
}
NPY<unsigned long long>* OpticksEvent::getSequenceData() const // aka History Buffer with seqhis/seqmat
{
return m_sequence_data ;
}
NPY<unsigned>* OpticksEvent::getBoundaryData() const // aka seqbnd
{
return m_boundary_data ;
}
NPY<unsigned>* OpticksEvent::getSeedData() const
{
return m_seed_data ;
}
NPY<float>* OpticksEvent::getHitData() const
{
return m_hit_data ;
}
NPY<float>* OpticksEvent::getHiyData() const
{
return m_hiy_data ;
}
MultiViewNPY* OpticksEvent::getGenstepAttr(){ return m_genstep_attr ; }
MultiViewNPY* OpticksEvent::getNopstepAttr(){ return m_nopstep_attr ; }
MultiViewNPY* OpticksEvent::getPhotonAttr(){ return m_photon_attr ; }
MultiViewNPY* OpticksEvent::getSourceAttr(){ return m_source_attr ; }
MultiViewNPY* OpticksEvent::getRecordAttr(){ return m_record_attr ; }
MultiViewNPY* OpticksEvent::getDeluxeAttr(){ return m_deluxe_attr ; }
MultiViewNPY* OpticksEvent::getPhoselAttr(){ return m_phosel_attr ; }
MultiViewNPY* OpticksEvent::getRecselAttr(){ return m_recsel_attr ; }
MultiViewNPY* OpticksEvent::getSequenceAttr(){ return m_sequence_attr ; }
MultiViewNPY* OpticksEvent::getBoundaryAttr(){ return m_boundary_attr ; }
MultiViewNPY* OpticksEvent::getSeedAttr(){ return m_seed_attr ; }
MultiViewNPY* OpticksEvent::getHitAttr(){ return m_hit_attr ; }
MultiViewNPY* OpticksEvent::getHiyAttr(){ return m_hiy_attr ; }
void OpticksEvent::setRecordsNPY(RecordsNPY* records)
{
m_records = records ;
}
RecordsNPY* OpticksEvent::getRecordsNPY()
{
if(m_records == NULL)
{
m_records = OpticksEventInstrument::CreateRecordsNPY(this) ;
if(!m_records)
LOG(error) << "failed to CreateRecordsNPY "
;
//assert( m_records );
}
return m_records ;
}
void OpticksEvent::setPhotonsNPY(PhotonsNPY* photons)
{
m_photons = photons ;
}
PhotonsNPY* OpticksEvent::getPhotonsNPY()
{
return m_photons ;
}
void OpticksEvent::setBoundariesNPY(BoundariesNPY* bnd)
{
m_bnd = bnd ;
}
BoundariesNPY* OpticksEvent::getBoundariesNPY()
{
return m_bnd ;
}
//////////////// m_domain related ///////////////////////////////////
void OpticksEvent::setFDomain(NPY<float>* fdom) { m_domain->setFDomain(fdom) ; }
void OpticksEvent::setIDomain(NPY<int>* idom) { m_domain->setIDomain(idom) ; }
NPY<float>* OpticksEvent::getFDomain() const { return m_domain->getFDomain() ; }
NPY<int>* OpticksEvent::getIDomain() const { return m_domain->getIDomain() ; }
// below set by Opticks::makeEvent
void OpticksEvent::setSpaceDomain(const glm::vec4& space_domain) { m_domain->setSpaceDomain(space_domain) ; }
void OpticksEvent::setTimeDomain(const glm::vec4& time_domain) { m_domain->setTimeDomain(time_domain) ; }
void OpticksEvent::setWavelengthDomain(const glm::vec4& wavelength_domain) { m_domain->setWavelengthDomain(wavelength_domain) ; }
const glm::vec4& OpticksEvent::getSpaceDomain() const { return m_domain->getSpaceDomain() ; }
const glm::vec4& OpticksEvent::getTimeDomain() const { return m_domain->getTimeDomain() ; }
const glm::vec4& OpticksEvent::getWavelengthDomain() const { return m_domain->getWavelengthDomain() ; }
/**
OpticksEvent::getMaxRec
-------------------------
Domain configured a.idom[0,0,3] (.w) maximum number of photon steps to record into the record buffer,
default is 10 but it can be increased up to 16 via option.
**/
unsigned OpticksEvent::getMaxRec() const { return m_domain->getMaxRec() ; }
/**
OpticksEvent::getMaxBounce
---------------------------
Domain configured a.idom[0,0,2] (.z) maximum number of bounces prior to truncation.
Default is 9, one less than the getMaxRec default for alignment/debugging clarity but it does not need to be.
Can bounce much more than is practical to record if necessary.
TODO: get rid of confusingly similarly named getBounceMax which comes from parameters
**/
unsigned OpticksEvent::getMaxBounce() const { return m_domain->getMaxBounce() ; }
unsigned OpticksEvent::getMaxRng() const { return m_domain->getMaxRng() ; }
void OpticksEvent::setMaxRec(unsigned maxrec) { m_domain->setMaxRec(maxrec); }
void OpticksEvent::setMaxBounce(unsigned maxbounce) { m_domain->setMaxBounce(maxbounce); }
void OpticksEvent::setMaxRng(unsigned maxrng) { m_domain->setMaxRng(maxrng); }
void OpticksEvent::dumpDomains(const char* msg)
{
m_domain->dump(msg);
}
void OpticksEvent::updateDomainsBuffer()
{
m_domain->updateBuffer();
}
void OpticksEvent::importDomainsBuffer() // invoked by OpticksEvent::loadBuffers
{
m_domain->importBuffer();
}
void OpticksEvent::saveDomains() // invoked by OpticksEvent::save
{
updateDomainsBuffer();
NPY<float>* fdom = getFDomain();
if(fdom) fdom->save(m_pfx, fdom_, m_typ, m_tag, m_udet);
NPY<int>* idom = getIDomain();
if(idom) idom->save(m_pfx, idom_, m_typ, m_tag, m_udet);
}
////////////////////////////////////////////////////////////////////////////////////
void OpticksEvent::setMode(OpticksMode* mode)
{
m_mode = mode ;
}
bool OpticksEvent::isInterop()
{
return m_mode->isInterop();
}
bool OpticksEvent::isCompute()
{
return m_mode->isCompute();
}
void OpticksEvent::setBoundaryIndex(Index* bndidx)
{
// called from OpIndexer::indexBoundaries
m_bndidx = bndidx ;
}
void OpticksEvent::setHistoryIndex(Index* seqhis)
{
// called from OpIndexer::indexSequenceLoaded
m_seqhis = seqhis ;
}
void OpticksEvent::setMaterialIndex(Index* seqmat)
{
// called from OpIndexer::indexSequenceLoaded
m_seqmat = seqmat ;
}
Index* OpticksEvent::getHistoryIndex()
{
return m_seqhis ;
}
Index* OpticksEvent::getMaterialIndex()
{
return m_seqmat ;
}
Index* OpticksEvent::getBoundaryIndex()
{
return m_bndidx ;
}
BMeta* OpticksEvent::getParameters()
{
return m_parameters ;
}
void OpticksEvent::pushNames(std::vector<std::string>& names)
{
names.push_back(genstep_);
names.push_back(nopstep_);
names.push_back(photon_);
names.push_back(debug_);
names.push_back(way_);
names.push_back(source_);
names.push_back(record_);
names.push_back(deluxe_);
names.push_back(phosel_);
names.push_back(recsel_);
names.push_back(sequence_);
names.push_back(boundary_);
names.push_back(seed_);
names.push_back(hit_);
}
/**
OpticksEvent::init
-------------------
From ipython ab.py testing::
In [1]: a.metadata.parameters
Out[1]:
{u'BounceMax': 9,
u'Cat': u'tboolean-box',
u'Creator': u'/home/blyth/local/opticks/lib/OKG4Test',
u'Detector': u'tboolean-box',
u'EntryCode': u'G',
u'EntryName': u'GENERATE',
u'GEOCACHE': u'/home/blyth/local/opticks/geocache/OKX4Test_lWorld0x4bc2710_PV_g4live/g4ok_gltf/f6cc352e44243f8fa536ab483ad390ce/1',
u'Id': 1,
u'KEY': u'OKX4Test.X4PhysicalVolume.lWorld0x4bc2710_PV.f6cc352e44243f8fa536ab483ad390ce',
u'NumGensteps': 1,
**/
void OpticksEvent::init()
{
m_versions = new BMeta ;
m_parameters = new BMeta ;
m_report = new Report ;
m_domain = new OpticksDomain ;
m_versions->add<int>("OptiXVersion", OKConf::OptiXVersionInteger() );
m_versions->add<int>("CUDAVersion", OKConf::CUDAVersionInteger() );
m_versions->add<int>("ComputeVersion", OKConf::ComputeCapabilityInteger() );
m_versions->add<int>("Geant4Version", OKConf::Geant4VersionInteger() );
m_parameters->add<std::string>("TimeStamp", timestamp() );
m_parameters->add<std::string>("Type", m_typ );
m_parameters->add<std::string>("Tag", m_tag );
m_parameters->add<std::string>("Detector", m_det );
if(m_cat) m_parameters->add<std::string>("Cat", m_cat );
m_parameters->add<std::string>("UDet", getUDet() );
std::string switches = OpticksSwitches();
m_parameters->add<std::string>("Switches", switches );
pushNames(m_data_names);
m_abbrev[genstep_] = "gs" ; // input gs are named: cerenkov, scintillation but for posterity need common output tag
m_abbrev[nopstep_] = "no" ; // non optical particle steps obtained from G4 eg with g4gun
m_abbrev[photon_] = "ox" ; // photon final step uncompressed
m_abbrev[debug_] = "dg" ; // photon level debug
m_abbrev[way_] = "wy" ; // extra photon level info analogous to JUNO NormalAnaMgr info recording configurable points and times from photon history
m_abbrev[source_] = "so" ; // input photon
m_abbrev[record_] = "rx" ; // photon step compressed record
m_abbrev[deluxe_] = "dx" ; // double precision photon step record
m_abbrev[phosel_] = "ps" ; // photon selection index
m_abbrev[recsel_] = "rs" ; // record selection index
m_abbrev[sequence_] = "ph" ; // (unsigned long long) photon seqhis/seqmat
m_abbrev[boundary_] = "bn" ; // (unsigned) uint4 encoding of 16 signed char boundary, aka seqbnd
m_abbrev[seed_] = "se" ; // (short) genstep id used for photon seeding
m_abbrev[hit_] = "ht" ; // hits, subset of ox with photons flags fullfilling the hit mask
m_abbrev[hiy_] = "hy" ; // hiys, subset of wy with photons flags fullfilling the hit mask
}
void OpticksEvent::deleteMeta()
{
delete m_versions ;
delete m_parameters ;
delete m_report ;
delete m_domain ;
delete m_prelaunch_times ;
delete m_launch_times ;
free((char*)m_geopath);
}
void OpticksEvent::deleteCtrl()
{
delete m_photon_ctrl ;
delete m_source_ctrl ;
delete m_seed_ctrl ;
}
void OpticksEvent::deleteIndex()
{
delete m_seqhis ;
delete m_seqmat ;
delete m_bndidx ;
}
NPYBase* OpticksEvent::getData(const char* name)
{
NPYBase* data = NULL ;
if( strcmp(name, genstep_)==0) data = static_cast<NPYBase*>(m_genstep_data) ;
else if(strcmp(name, nopstep_)==0) data = static_cast<NPYBase*>(m_nopstep_data) ;
else if(strcmp(name, photon_)==0) data = static_cast<NPYBase*>(m_photon_data) ;
else if(strcmp(name, debug_)==0) data = static_cast<NPYBase*>(m_debug_data) ;
else if(strcmp(name, way_)==0) data = static_cast<NPYBase*>(m_way_data) ;
else if(strcmp(name, source_)==0) data = static_cast<NPYBase*>(m_source_data) ;
else if(strcmp(name, record_)==0) data = static_cast<NPYBase*>(m_record_data) ;
else if(strcmp(name, deluxe_)==0) data = static_cast<NPYBase*>(m_deluxe_data) ;
else if(strcmp(name, phosel_)==0) data = static_cast<NPYBase*>(m_phosel_data) ;
else if(strcmp(name, recsel_)==0) data = static_cast<NPYBase*>(m_recsel_data) ;
else if(strcmp(name, sequence_)==0) data = static_cast<NPYBase*>(m_sequence_data) ;
else if(strcmp(name, boundary_)==0) data = static_cast<NPYBase*>(m_boundary_data) ;
else if(strcmp(name, seed_)==0) data = static_cast<NPYBase*>(m_seed_data) ;
else if(strcmp(name, hit_)==0) data = static_cast<NPYBase*>(m_hit_data) ;
return data ;
}
NPYSpec* OpticksEvent::getSpec(const char* name)
{
NPYSpec* spec = NULL ;
if( strcmp(name, genstep_)==0) spec = static_cast<NPYSpec*>(m_genstep_spec) ;
else if(strcmp(name, nopstep_)==0) spec = static_cast<NPYSpec*>(m_nopstep_spec) ;
else if(strcmp(name, photon_)==0) spec = static_cast<NPYSpec*>(m_photon_spec) ;
else if(strcmp(name, debug_)==0) spec = static_cast<NPYSpec*>(m_debug_spec) ;
else if(strcmp(name, way_)==0) spec = static_cast<NPYSpec*>(m_way_spec) ;
else if(strcmp(name, source_)==0) spec = static_cast<NPYSpec*>(m_source_spec) ;
else if(strcmp(name, record_)==0) spec = static_cast<NPYSpec*>(m_record_spec) ;
else if(strcmp(name, deluxe_)==0) spec = static_cast<NPYSpec*>(m_deluxe_spec) ;
else if(strcmp(name, phosel_)==0) spec = static_cast<NPYSpec*>(m_phosel_spec) ;
else if(strcmp(name, recsel_)==0) spec = static_cast<NPYSpec*>(m_recsel_spec) ;
else if(strcmp(name, sequence_)==0) spec = static_cast<NPYSpec*>(m_sequence_spec) ;
else if(strcmp(name, boundary_)==0) spec = static_cast<NPYSpec*>(m_boundary_spec) ;
else if(strcmp(name, seed_)==0) spec = static_cast<NPYSpec*>(m_seed_spec) ;
else if(strcmp(name, hit_)==0) spec = static_cast<NPYSpec*>(m_hit_spec) ;
else if(strcmp(name, fdom_)==0) spec = static_cast<NPYSpec*>(m_fdom_spec) ;
else if(strcmp(name, idom_)==0) spec = static_cast<NPYSpec*>(m_idom_spec) ;
return spec ;
}
std::string OpticksEvent::getShapeString()
{
std::stringstream ss ;
for(std::vector<std::string>::const_iterator it=m_data_names.begin() ; it != m_data_names.end() ; it++)
{
std::string name = *it ;
NPYBase* data = getData(name.c_str());
ss << " " << name << " " << ( data ? data->getShapeString() : "NULL" ) ;
}
return ss.str();
}
void OpticksEvent::setOpticks(Opticks* ok)
{
m_ok = ok ;
m_profile = ok->getProfile();
}
int OpticksEvent::getId()
{
return m_parameters->get<int>("Id");
}
void OpticksEvent::setId(int id)
{
m_parameters->add<int>("Id", id);
}
void OpticksEvent::setCreator(const char* executable)
{
m_parameters->add<std::string>("Creator", executable ? executable : "NULL" );
}
std::string OpticksEvent::getCreator()
{
return m_parameters->get<std::string>("Creator", "NONE");
}
void OpticksEvent::setTestCSGPath(const char* testcsgpath)
{
m_parameters->add<std::string>("TestCSGPath", testcsgpath ? testcsgpath : "" );
}
std::string OpticksEvent::getTestCSGPath()
{
return m_parameters->get<std::string>("TestCSGPath", "");
}
void OpticksEvent::setTestConfigString(const char* testconfig)
{
m_parameters->add<std::string>("TestConfig", testconfig ? testconfig : "" );
}
std::string OpticksEvent::getTestConfigString()
{
return m_parameters->get<std::string>("TestConfig", "");
}
NGeoTestConfig* OpticksEvent::getTestConfig()
{
if(m_geotestconfig == NULL)
{
std::string gtc = getTestConfigString() ;
LOG(info) << " gtc " << gtc ;
m_geotestconfig = gtc.empty() ? NULL : new NGeoTestConfig( gtc.c_str() );
}
return m_geotestconfig ;
}
void OpticksEvent::setNote(const char* note)
{
m_parameters->add<std::string>("Note", note ? note : "NULL" );
}
void OpticksEvent::appendNote(const char* note)
{
std::string n = note ? note : "" ;
m_parameters->appendString("Note", n );
}
std::string OpticksEvent::getNote()
{
return m_parameters->get<std::string>("Note", "");
}
const char* OpticksEvent::getGeoPath()
{
if(m_geopath == NULL)
{
// only test geopath for now
std::string testcsgpath_ = getTestCSGPath();
const char* testcsgpath = testcsgpath_.empty() ? NULL : testcsgpath_.c_str() ;
const char* dbgcsgpath = m_ok->getDbgCSGPath();
const char* geopath = testcsgpath ? testcsgpath : ( dbgcsgpath ? dbgcsgpath : NULL ) ;
if( testcsgpath && dbgcsgpath && strcmp(testcsgpath, dbgcsgpath) != 0)
{
LOG(warning) << "OpticksEvent::getGeoPath"
<< " BOTH testcsgpath and dbgcsgpath DEFINED AND DIFFERENT "
<< " testcsgpath " << testcsgpath
<< " dbgcsgpath " << dbgcsgpath
<< " geopath " << geopath
;
}
m_geopath = geopath ? strdup(geopath) : NULL ;
if( geopath == NULL )
{
LOG(warning) << "OpticksEvent::getGeoPath"
<< " FAILED TO RESOLVE GeoPath "
<< " WORKAROUND EG USE --dbgcsgpath "
;
}
}
return m_geopath ;
}
void OpticksEvent::setEntryCode(char entryCode)
{
m_parameters->add<char>("EntryCode", entryCode );
}
char OpticksEvent::getEntryCode()
{
return m_parameters->get<char>("EntryCode", "0");
}
void OpticksEvent::setDynamic(int dynamic)
{
m_parameters->add<int>("Dynamic", dynamic );
}
int OpticksEvent::getDynamic() const
{
return m_parameters->get<int>("Dynamic", "-1");
}
void OpticksEvent::setAligned(int aligned)
{
m_parameters->add<int>("Aligned", aligned );
}
int OpticksEvent::getAligned() const
{
return m_parameters->get<int>("Aligned", "-1");
}
void OpticksEvent::setTimeStamp(const char* tstamp)
{
m_parameters->set<std::string>("TimeStamp", tstamp);
}
std::string OpticksEvent::getTimeStamp()
{
return m_parameters->get<std::string>("TimeStamp");
}
unsigned int OpticksEvent::getBounceMax() const
{
return m_parameters->get<unsigned int>("BounceMax");
}
unsigned int OpticksEvent::getRngMax() const
{
return m_parameters->get<unsigned int>("RngMax", "0");
}
void OpticksEvent::setRngMax(unsigned int rng_max)
{
m_parameters->add<unsigned int>("RngMax", rng_max );
}
ViewNPY* OpticksEvent::operator [](const char* spec)
{
std::vector<std::string> elem ;
BStr::split(elem, spec, '.');
if(elem.size() != 2 ) assert(0);
MultiViewNPY* mvn(NULL);
if( elem[0] == genstep_) mvn = m_genstep_attr ;
else if(elem[0] == nopstep_) mvn = m_nopstep_attr ;
else if(elem[0] == photon_) mvn = m_photon_attr ;
else if(elem[0] == source_) mvn = m_source_attr ;
else if(elem[0] == record_) mvn = m_record_attr ;
else if(elem[0] == deluxe_) mvn = m_deluxe_attr ;
else if(elem[0] == phosel_) mvn = m_phosel_attr ;
else if(elem[0] == recsel_) mvn = m_recsel_attr ;
else if(elem[0] == sequence_) mvn = m_sequence_attr ;
else if(elem[0] == boundary_) mvn = m_boundary_attr ;
else if(elem[0] == seed_) mvn = m_seed_attr ;
else if(elem[0] == hit_) mvn = m_hit_attr ;
assert(mvn);
return (*mvn)[elem[1].c_str()] ;
}
NPYSpec* OpticksEvent::GenstepSpec(bool compute)
{
return new NPYSpec(genstep_ , 0,6,4,0,0, NPYBase::FLOAT , OpticksBufferSpec::Get(genstep_, compute)) ;
}
NPYSpec* OpticksEvent::SeedSpec(bool compute)
{
return new NPYSpec(seed_ , 0,1,1,0,0, NPYBase::UINT , OpticksBufferSpec::Get(seed_, compute)) ;
}
NPYSpec* OpticksEvent::SourceSpec(bool compute)
{
return new NPYSpec(source_ , 0,4,4,0,0, NPYBase::FLOAT , OpticksBufferSpec::Get(source_, compute)) ;
}
void OpticksEvent::createSpec()
{
// invoked by Opticks::makeEvent or OpticksEvent::load
unsigned int maxrec = getMaxRec();
bool compute = isCompute();
m_genstep_spec = GenstepSpec(compute);
m_seed_spec = SeedSpec(compute);
m_source_spec = SourceSpec(compute);
m_hit_spec = new NPYSpec(hit_ , 0,4,4,0,0, NPYBase::FLOAT , OpticksBufferSpec::Get(hit_, compute));
m_hiy_spec = new NPYSpec(hiy_ , 0,2,4,0,0, NPYBase::FLOAT , OpticksBufferSpec::Get(hiy_, compute));
m_photon_spec = new NPYSpec(photon_ , 0,4,4,0,0, NPYBase::FLOAT , OpticksBufferSpec::Get(photon_, compute)) ;
m_debug_spec = new NPYSpec(debug_ , 0,1,4,0,0, NPYBase::FLOAT , OpticksBufferSpec::Get(debug_, compute)) ;
m_way_spec = new NPYSpec(way_ , 0,2,4,0,0, NPYBase::FLOAT , OpticksBufferSpec::Get(way_, compute)) ;
m_record_spec = new NPYSpec(record_ , 0,maxrec,2,4,0, NPYBase::SHORT , OpticksBufferSpec::Get(record_, compute)) ;
// SHORT -> RT_FORMAT_SHORT4 and size set to num_quads = num_photons*maxrec*2
m_deluxe_spec = new NPYSpec(deluxe_ , 0,maxrec,2,4,0, NPYBase::DOUBLE , OpticksBufferSpec::Get(deluxe_, compute)) ;
m_boundary_spec = new NPYSpec(boundary_ , 0,1,4,0,0, NPYBase::UINT , OpticksBufferSpec::Get(boundary_, compute)) ;
m_sequence_spec = new NPYSpec(sequence_ , 0,1,2,0,0, NPYBase::ULONGLONG , OpticksBufferSpec::Get(sequence_, compute)) ;
// ULONGLONG -> RT_FORMAT_USER and size set to ni*nj*nk = num_photons*1*2
m_nopstep_spec = new NPYSpec(nopstep_ , 0,4,4,0,0, NPYBase::FLOAT , OpticksBufferSpec::Get(nopstep_, compute) ) ;
m_phosel_spec = new NPYSpec(phosel_ , 0,1,4,0,0, NPYBase::UCHAR , OpticksBufferSpec::Get(phosel_, compute) ) ;
m_recsel_spec = new NPYSpec(recsel_ , 0,maxrec,1,4,0, NPYBase::UCHAR , OpticksBufferSpec::Get(recsel_, compute) ) ;
m_fdom_spec = new NPYSpec(fdom_ , 3,1,4,0,0, NPYBase::FLOAT , "" ) ;
m_idom_spec = new NPYSpec(idom_ , 1,1,4,0,0, NPYBase::INT , "" ) ;
}
void OpticksEvent::dumpSpec()
{
LOG(info) << "m_genstep_spec " << m_genstep_spec ;
LOG(info) << "m_seed_spec " << m_seed_spec ;
LOG(info) << "m_source_spec " << m_source_spec ;
LOG(info) << "m_hit_spec " << m_hit_spec ;
LOG(info) << "m_hiy_spec " << m_hiy_spec ;
LOG(info) << "m_photon_spec " << m_photon_spec ;
LOG(info) << "m_debug_spec " << m_debug_spec ;
LOG(info) << "m_way_spec " << m_way_spec ;
LOG(info) << "m_record_spec " << m_record_spec ;
LOG(info) << "m_deluxe_spec " << m_deluxe_spec ;
LOG(info) << "m_sequence_spec " << m_sequence_spec ;
LOG(info) << "m_boundary_spec " << m_boundary_spec ;
LOG(info) << "m_nopstep_spec " << m_nopstep_spec ;
LOG(info) << "m_phosel_spec " << m_phosel_spec ;
LOG(info) << "m_recsel_spec " << m_recsel_spec ;
LOG(info) << "m_fdom_spec " << m_fdom_spec ;
LOG(info) << "m_idom_spec " << m_idom_spec ;
}
void OpticksEvent::deleteSpec()
{
//dumpSpec();
delete m_genstep_spec ;
delete m_seed_spec ;
delete m_source_spec ;
delete m_hit_spec ;
delete m_hiy_spec ;
delete m_photon_spec ;
delete m_debug_spec ;
delete m_way_spec ;
delete m_record_spec ;
delete m_deluxe_spec ;
delete m_sequence_spec ;
delete m_boundary_spec ;
delete m_nopstep_spec ;
delete m_phosel_spec ;
delete m_recsel_spec ;
delete m_fdom_spec ;
delete m_idom_spec ;
}
OpticksEvent::~OpticksEvent()
{
deleteMeta();
deleteCtrl();
deleteIndex();
deleteSpec();
deleteBuffers();
deleteAttr();
}
void OpticksEvent::addBufferControl(const char* name, const char* ctrl_)
{
NPYBase* npy = getData(name);
assert(npy);
OpticksBufferControl ctrl(npy->getBufferControlPtr());
ctrl.add(ctrl_);
LOG(info) << "OpticksEvent::addBufferControl"
<< " name " << name
<< " adding " << ctrl_
<< " " << ctrl.description("result:")
;
}
/**
OpticksEvent::setBufferControl
-------------------------------
The OpticksBufferControl argument is a pointer to 64-bit int
living inside the NPYBase which has its contents
defined by the below depending on the OpticksBufferSpec::Get ctrl
string lodged into the spec.
**/
void OpticksEvent::setBufferControl(NPYBase* data)
{
const NPYSpec* spec = data->getBufferSpec();
const char* name = data->getBufferName();
if(!spec)
{
LOG(fatal) << "OpticksEvent::setBufferControl"
<< " SKIPPED FOR " << name
<< " AS NO spec "
;
BMeta* param = data->getParameters();
if(param)
param->dump("OpticksEvent::setBufferControl FATAL: BUFFER LACKS SPEC");
assert(0);
return ;
}
OpticksBufferControl ctrl(data->getBufferControlPtr());
ctrl.add(spec->getCtrl());
if(isCompute()) ctrl.add(OpticksBufferControl::COMPUTE_MODE_) ;
if(isInterop()) ctrl.add(OpticksBufferControl::INTEROP_MODE_) ;
if(ctrl("VERBOSE_MODE"))
LOG(verbose)
<< std::setw(10) << name
<< " : " << ctrl.description("(spec)")
<< " : " << brief()
;
}
/**
OpticksEvent::createBuffers
-----------------------------
Invoked by Opticks::makeEvent
NB allocation is deferred until zeroing and they start at 0 items anyhow
**/
void OpticksEvent::createBuffers()
{
NPY<float>* nop = NPY<float>::make(m_nopstep_spec);
bool clone_ = false ;
setNopstepData(nop, clone_);
NPY<float>* pho = NPY<float>::make(m_photon_spec); // must match GPU side photon.h:PNUMQUAD
setPhotonData(pho);
NPY<float>* dbg = NPY<float>::make(m_debug_spec);
setDebugData(dbg);
NPY<float>* way = NPY<float>::make(m_way_spec);
setWayData(way);
NPY<unsigned long long>* seq = NPY<unsigned long long>::make(m_sequence_spec);
setSequenceData(seq);
NPY<unsigned>* bnd = NPY<unsigned>::make(m_boundary_spec);
setBoundaryData(bnd);
NPY<unsigned>* seed = NPY<unsigned>::make(m_seed_spec);
setSeedData(seed);
NPY<float>* hit = NPY<float>::make(m_hit_spec);
setHitData(hit);
NPY<float>* hiy = NPY<float>::make(m_hiy_spec);
setHiyData(hiy);
NPY<unsigned char>* phosel = NPY<unsigned char>::make(m_phosel_spec);
setPhoselData(phosel);
NPY<unsigned char>* recsel = NPY<unsigned char>::make(m_recsel_spec);
setRecselData(recsel);
NPY<short>* rec = NPY<short>::make(m_record_spec);
setRecordData(rec);
NPY<double>* dx = NPY<double>::make(m_deluxe_spec);
setDeluxeData(dx);
NPY<float>* fdom = NPY<float>::make(m_fdom_spec);
fdom->zero(); // allocate small buffer immediately
setFDomain(fdom);
NPY<int>* idom = NPY<int>::make(m_idom_spec);
idom->zero(); // alloc small buffer immediately
setIDomain(idom);
}
void OpticksEvent::reset()
{
resetBuffers();
}
void OpticksEvent::resetBuffers()
{
LOG(LEVEL) << "[ itag " << getITag() ;
if(m_genstep_data) m_genstep_data->reset();
if(m_nopstep_data) m_nopstep_data->reset();
if(m_photon_data) m_photon_data->reset();
if(m_debug_data) m_debug_data->reset();
if(m_way_data) m_way_data->reset();
if(m_source_data) m_source_data->reset();
if(m_record_data) m_record_data->reset();
if(m_deluxe_data) m_deluxe_data->reset();
if(m_phosel_data) m_phosel_data->reset();
if(m_recsel_data) m_recsel_data->reset();
if(m_sequence_data) m_sequence_data->reset();
if(m_boundary_data) m_boundary_data->reset();
if(m_seed_data) m_seed_data->reset();
if(m_hit_data) m_hit_data->reset();
if(m_hiy_data) m_hiy_data->reset();
LOG(LEVEL) << "]" ;
}
void OpticksEvent::deleteBuffers()
{
delete m_genstep_data ; m_genstep_data = NULL ;
delete m_nopstep_data ; m_nopstep_data = NULL ;
delete m_photon_data ; m_photon_data = NULL ;
delete m_debug_data ; m_debug_data = NULL ;
delete m_way_data ; m_way_data = NULL ;
delete m_source_data ; m_source_data = NULL ;
delete m_record_data ; m_record_data = NULL ;
delete m_deluxe_data ; m_deluxe_data = NULL ;
delete m_phosel_data ; m_phosel_data = NULL ;
delete m_recsel_data ; m_recsel_data = NULL ;
delete m_sequence_data ; m_sequence_data = NULL ;
delete m_boundary_data ; m_boundary_data = NULL ;
delete m_seed_data ; m_seed_data = NULL ;
delete m_hit_data ; m_hit_data = NULL ;
delete m_hiy_data ; m_hiy_data = NULL ;
}
void OpticksEvent::deleteAttr()
{
delete m_genstep_attr ; m_genstep_attr = NULL ;
delete m_seed_attr ; m_seed_attr = NULL ;
delete m_hit_attr ; m_hit_attr = NULL ;
delete m_hiy_attr ; m_hiy_attr = NULL ;
delete m_photon_attr ; m_photon_attr = NULL ;
delete m_source_attr ; m_source_attr = NULL ;
delete m_nopstep_attr ; m_nopstep_attr = NULL ;
delete m_record_attr ; m_record_attr = NULL ;
delete m_deluxe_attr ; m_deluxe_attr = NULL ;
delete m_phosel_attr ; m_phosel_attr = NULL ;
delete m_recsel_attr ; m_recsel_attr = NULL ;
delete m_sequence_attr ; m_sequence_attr = NULL ;
delete m_boundary_attr ; m_boundary_attr = NULL ;
}
/**
OpticksEvent::resize
---------------------
For dynamically recorded g4evt the photon, sequence and record
buffers are grown during the instrumented Geant4 stepping, a
subsequent resize makes no difference to those buffers but pulls
up the counts for phosel and recsel (and seed) ready to
hold the CPU indices.
* all photon level qtys have num_photons for the first dimension
including recsel and record thanks to structured arrays (num_photons, maxrec, ...)
* note that NPY arrays are allocated lazily so setting NumItems for sometimes
unused arrays such as m_debug_data and m_way_data does not cost memory
**/
void OpticksEvent::resize()
{
assert(m_photon_data);
assert(m_sequence_data);
assert(m_boundary_data);
assert(m_phosel_data);
assert(m_recsel_data);
assert(m_record_data);
assert(m_deluxe_data);
assert(m_seed_data);
assert(m_debug_data);
assert(m_way_data);
unsigned int num_photons = getNumPhotons();
unsigned int num_records = getNumRecords();
unsigned int maxrec = getMaxRec();
unsigned rng_max = getRngMax();
bool enoughRng = num_photons <= rng_max ;
if(!enoughRng)
LOG(fatal)
<< "NOT ENOUGH RNG : USE OPTION --rngmax 3/10/100 "
<< " num_photons " << num_photons
<< " rng_max " << rng_max
;
assert(enoughRng && " need to prepare and persist more RNG states up to maximual per propagation number" );
LOG(LEVEL)
<< " num_photons " << num_photons
<< " num_records " << num_records
<< " maxrec " << maxrec
<< " " << getDir()
;
m_photon_data->setNumItems(num_photons);
m_sequence_data->setNumItems(num_photons);
m_boundary_data->setNumItems(num_photons);
m_record_data->setNumItems(num_photons);
m_deluxe_data->setNumItems(num_photons);
m_seed_data->setNumItems(num_photons);
m_phosel_data->setNumItems(num_photons);
m_recsel_data->setNumItems(num_photons);
m_debug_data->setNumItems(num_photons);
m_way_data->setNumItems(num_photons);
}
/**
OpticksEvent::setMetadataNum
------------------------------
Invoked by OpticksEvent::save, sets metadata m_parameters : NumGensteps, NumPhotons, NumRecords
from corresponding getters.
**/
void OpticksEvent::setMetadataNum()
{
m_parameters->add<unsigned int>("NumGensteps", getNumGensteps());
m_parameters->add<unsigned int>("NumPhotons", getNumPhotons());
m_parameters->add<unsigned int>("NumRecords", getNumRecords());
}
void OpticksEvent::zero()
{
if(m_photon_data) m_photon_data->zero();
if(m_sequence_data) m_sequence_data->zero();
if(m_boundary_data) m_boundary_data->zero();
if(m_record_data) m_record_data->zero();
if(m_deluxe_data) m_deluxe_data->zero();
if(m_debug_data) m_debug_data->zero();
// when operating CPU side phosel and recsel are derived from sequence data
// when operating GPU side they need not ever come to CPU
//if(m_phosel_data) m_phosel_data->zero();
//if(m_recsel_data) m_recsel_data->zero();
}
/**
OpticksEvent::setGenstepData
---------------------------------
Called for OpticksRun::m_g4evt from OpticksRun::setGensteps by OKMgr::propagate
oac_label
adds to the OpticksActionControl to customize the import for different genstep types
**/
void OpticksEvent::setGenstepData(NPY<float>* genstep_data_, bool resize_, bool clone_ )
{
OK_PROFILE("_OpticksEvent::setGenstepData");
NPY<float>* genstep_data = clone_ ? genstep_data_->clone() : genstep_data_ ;
int nitems = NPYBase::checkNumItems(genstep_data); // -1 for genstep_data NULL
if(nitems < 1)
{
LOG(warning)
<< " SKIP "
<< " nitems " << nitems
;
return ;
}
setBufferControl(genstep_data);
m_genstep_data = genstep_data ;
m_parameters->add<std::string>("genstepDigest", m_genstep_data->getDigestString() );
// j k l sz type norm iatt item_from_dim
ViewNPY* vpos = new ViewNPY("vpos",m_genstep_data,1,0,0,4,ViewNPY::FLOAT,false,false, 1); // (x0, t0) 2nd GenStep quad
ViewNPY* vdir = new ViewNPY("vdir",m_genstep_data,2,0,0,4,ViewNPY::FLOAT,false,false, 1); // (DeltaPosition, step_length) 3rd GenStep quad
m_genstep_vpos = vpos ;
m_genstep_attr = new MultiViewNPY("genstep_attr");
m_genstep_attr->add(vpos);
m_genstep_attr->add(vdir);
{
m_num_gensteps = m_genstep_data->getShape(0) ;
unsigned int num_photons = m_genstep_data->getUSum(0,3);
setNumPhotons(num_photons, resize_); // triggers a resize <<<<<<<<<<<<< SPECIAL HANDLING OF GENSTEP <<<<<<<<<<<<<<
}
OK_PROFILE("OpticksEvent::setGenstepData");
}
const glm::vec4& OpticksEvent::getGenstepCenterExtent()
{
assert(m_genstep_vpos && "check hasGenstepData() before getGenstepCenterExtent");
return m_genstep_vpos->getCenterExtent() ;
}
bool OpticksEvent::isTorchType()
{
return strcmp(m_typ, OpticksGenstep::TORCH_) == 0 ;
}
bool OpticksEvent::isMachineryType()
{
return strcmp(m_typ, OpticksGenstep::MACHINERY_) == 0 ;
}
OpticksBufferControl* OpticksEvent::getSeedCtrl()
{
return m_seed_ctrl ;
}
void OpticksEvent::setSeedData(NPY<unsigned>* seed_data)
{
m_seed_data = seed_data ;
if(!seed_data)
{
LOG(debug) << "OpticksEvent::setSeedData seed_data NULL " ;
return ;
}
setBufferControl(seed_data);
m_seed_ctrl = new OpticksBufferControl(m_seed_data->getBufferControlPtr());
m_seed_attr = new MultiViewNPY("seed_attr");
}
void OpticksEvent::setHitData(NPY<float>* hit_data)
{
m_hit_data = hit_data ;
if(!hit_data)
{
LOG(debug) << "OpticksEvent::setHitData hit_data NULL " ;
return ;
}
setBufferControl(hit_data);
m_hit_attr = new MultiViewNPY("hit_attr");
}
void OpticksEvent::setHiyData(NPY<float>* hiy_data)
{
m_hiy_data = hiy_data ;
if(!hiy_data)
{
LOG(debug) << "OpticksEvent::setHiyData hiy_data NULL " ;
return ;
}
setBufferControl(hiy_data);
m_hiy_attr = new MultiViewNPY("hiy_attr");
}
void OpticksEvent::setDebugData(NPY<float>* debug_data)
{
m_debug_data = debug_data ;
if(!debug_data)
{
LOG(debug) << "OpticksEvent::setDebugData debug_data NULL " ;
return ;
}
setBufferControl(debug_data);
}
void OpticksEvent::setWayData(NPY<float>* way_data)
{
m_way_data = way_data ;
if(!way_data)
{
LOG(debug) << "OpticksEvent::setWayData way_data NULL " ;
return ;
}
setBufferControl(way_data);
}
OpticksBufferControl* OpticksEvent::getPhotonCtrl()
{
return m_photon_ctrl ;
}
OpticksBufferControl* OpticksEvent::getSourceCtrl()
{
return m_source_ctrl ;
}
void OpticksEvent::setPhotonData(NPY<float>* photon_data)
{
setBufferControl(photon_data);
m_photon_data = photon_data ;
m_photon_ctrl = new OpticksBufferControl(m_photon_data->getBufferControlPtr());
if(m_num_photons == 0)
{
m_num_photons = photon_data->getShape(0) ;
LOG(debug) << "OpticksEvent::setPhotonData"
<< " setting m_num_photons from shape(0) " << m_num_photons
;
}
else
{
assert(m_num_photons == photon_data->getShape(0));
}
m_photon_data->setDynamic(); // need to update with seeding so GL_DYNAMIC_DRAW needed
m_photon_attr = new MultiViewNPY("photon_attr");
// j k l,sz type norm iatt item_from_dim
m_photon_attr->add(new ViewNPY("vpos",m_photon_data,0,0,0,4,ViewNPY::FLOAT, false, false, 1)); // 1st quad
m_photon_attr->add(new ViewNPY("vdir",m_photon_data,1,0,0,4,ViewNPY::FLOAT, false, false, 1)); // 2nd quad
m_photon_attr->add(new ViewNPY("vpol",m_photon_data,2,0,0,4,ViewNPY::FLOAT, false, false, 1)); // 3rd quad
m_photon_attr->add(new ViewNPY("iflg",m_photon_data,3,0,0,4,ViewNPY::INT , false, true , 1)); // 4th quad
//
// photon array
// ~~~~~~~~~~~~~
//
// vpos xxxx yyyy zzzz wwww position, time [:,0,:4]
// vdir xxxx yyyy zzzz wwww direction, wavelength [:,1,:4]
// vpol xxxx yyyy zzzz wwww polarization weight [:,2,:4]
// iflg xxxx yyyy zzzz wwww [:,3,:4]
//
//
// record array
// ~~~~~~~~~~~~~~
//
// 4*short(snorm)
// ________
// rpos xxyyzzww
// rpol-> xyzwaabb <-rflg
// ----^^^^
// 4*ubyte 2*ushort
// (unorm) (iatt)
//
//
//
// corresponds to GPU side cu/photon.h:psave and rsave
//
}
void OpticksEvent::setSourceData(NPY<float>* source_data_, bool clone_ )
{
OK_PROFILE("_OpticksEvent::setSourceData");
if(!source_data_) return ;
NPY<float>* source_data = clone_ ? source_data_->clone() : source_data_ ;
source_data->setBufferSpec(m_source_spec);
setBufferControl(source_data);
m_source_data = source_data ;
m_source_ctrl = new OpticksBufferControl(m_source_data->getBufferControlPtr());
if(m_num_source == 0)
{
m_num_source = source_data->getShape(0) ;
LOG(debug) << "OpticksEvent::setSourceData"
<< " setting m_num_source from shape(0) " << m_num_source
;
}
else
{
assert(m_num_source == source_data->getShape(0));
}
OK_PROFILE("_OpticksEvent::setSourceData_MultiViewNPY"); // NB dont use "." in the labels it messes up the ini
//m_source_data->setDynamic(); // need to update with seeding so GL_DYNAMIC_DRAW needed
m_source_attr = new MultiViewNPY("source_attr");
// j k l,sz type norm iatt item_from_dim
m_source_attr->add(new ViewNPY("vpos",m_source_data,0,0,0,4,ViewNPY::FLOAT, false, false, 1)); // 1st quad
m_source_attr->add(new ViewNPY("vdir",m_source_data,1,0,0,4,ViewNPY::FLOAT, false, false, 1)); // 2nd quad
m_source_attr->add(new ViewNPY("vpol",m_source_data,2,0,0,4,ViewNPY::FLOAT, false, false, 1)); // 3rd quad
m_source_attr->add(new ViewNPY("iflg",m_source_data,3,0,0,4,ViewNPY::INT , false, true , 1)); // 4th quad
OK_PROFILE("OpticksEvent::setSourceData_MultiViewNPY");
OK_PROFILE("OpticksEvent::setSourceData");
}
void OpticksEvent::setNopstepData(NPY<float>* nopstep_data_ , bool clone_ )
{
OK_PROFILE("_OpticksEvent::setNopstepData");
if(!nopstep_data_) return ;
m_nopstep_data = clone_ ? nopstep_data_->clone() : nopstep_data_ ;
setBufferControl(m_nopstep_data);
m_num_nopsteps = m_nopstep_data->getShape(0) ;
LOG(debug) << "OpticksEvent::setNopstepData"
<< " shape " << m_nopstep_data->getShapeString()
;
// j k l sz type norm iatt item_from_dim
ViewNPY* vpos = new ViewNPY("vpos",m_nopstep_data,0,0,0,4,ViewNPY::FLOAT ,false, false, 1);
ViewNPY* vdir = new ViewNPY("vdir",m_nopstep_data,1,0,0,4,ViewNPY::FLOAT ,false, false, 1);
ViewNPY* vpol = new ViewNPY("vpol",m_nopstep_data,2,0,0,4,ViewNPY::FLOAT ,false, false, 1);
m_nopstep_attr = new MultiViewNPY("nopstep_attr");
m_nopstep_attr->add(vpos);
m_nopstep_attr->add(vdir);
m_nopstep_attr->add(vpol);
OK_PROFILE("OpticksEvent::setNopstepData");
}
/**
OpticksEvent::setRecordData
------------------------------
NB that the ViewNPY::TYPE need not match the NPY<T>,
OpenGL shaders will view the data as of the ViewNPY::TYPE,
informed via glVertexAttribPointer/glVertexAttribIPointer
in oglrap-/Rdr::address(ViewNPY* vnpy)
* see ggv-/issues/gui_broken_photon_record_colors.rst
* note the shift of one to the right of the (j,k,l)
NB search the oglrap/gl/ shaders for the names "rpol" "rflg" to see how used
rpos
photon step records stored as domain compressed shorts -32767,+32767
with norm=true, so within the shaders rpos values are mapped to -1.f:1.f
rflq
**/
void OpticksEvent::setRecordData(NPY<short>* record_data)
{
setBufferControl(record_data);
m_record_data = record_data ;
// j k l sz type norm iatt item_from_dim
ViewNPY* rpos = new ViewNPY("rpos",m_record_data,0,0,0 ,4,ViewNPY::SHORT ,true, false, 2);
ViewNPY* rpol = new ViewNPY("rpol",m_record_data,0,1,0 ,4,ViewNPY::UNSIGNED_BYTE ,true, false, 2);
ViewNPY* rflg = new ViewNPY("rflg",m_record_data,0,1,2 ,2,ViewNPY::UNSIGNED_SHORT ,false, true, 2);
// NB l=2, value offset from which to start accessing data to fill the shaders uvec4 x y (z, w)
ViewNPY* rflq = new ViewNPY("rflq",m_record_data,0,1,2 ,4,ViewNPY::UNSIGNED_BYTE ,false, true, 2);
// NB l=2 again : UBYTE view of the same data for access to m1,m2,boundary,flag
m_record_attr = new MultiViewNPY("record_attr");
m_record_attr->add(rpos);
m_record_attr->add(rpol);
m_record_attr->add(rflg);
m_record_attr->add(rflq);
}
void OpticksEvent::setDeluxeData(NPY<double>* deluxe_data)
{
m_deluxe_data = deluxe_data ;
if(!deluxe_data) return ;
setBufferControl(deluxe_data);
m_deluxe_attr = new MultiViewNPY("deluxe_attr");
}
void OpticksEvent::setPhoselData(NPY<unsigned char>* phosel_data)
{
m_phosel_data = phosel_data ;
if(!m_phosel_data) return ;
setBufferControl(m_phosel_data);
// j k l sz type norm iatt item_from_dim
ViewNPY* psel = new ViewNPY("psel",m_phosel_data,0,0,0,4,ViewNPY::UNSIGNED_BYTE,false, true, 1);
m_phosel_attr = new MultiViewNPY("phosel_attr");
m_phosel_attr->add(psel);
}
void OpticksEvent::setRecselData(NPY<unsigned char>* recsel_data)
{
m_recsel_data = recsel_data ;
if(!m_recsel_data) return ;
setBufferControl(m_recsel_data);
// j k l sz type norm iatt item_from_dim
ViewNPY* rsel = new ViewNPY("rsel",m_recsel_data,0,0,0,4,ViewNPY::UNSIGNED_BYTE,false, true, 2);
// structured recsel array, means the count needs to come from product of 1st two dimensions,
m_recsel_attr = new MultiViewNPY("recsel_attr");
m_recsel_attr->add(rsel);
/*
delta:gl blyth$ find . -type f -exec grep -H rsel {} \;
./altrec/vert.glsl:layout(location = 3) in ivec4 rsel;
./altrec/vert.glsl: sel = rsel ;
./devrec/vert.glsl:layout(location = 3) in ivec4 rsel;
./devrec/vert.glsl: sel = rsel ;
./rec/vert.glsl:layout(location = 3) in ivec4 rsel;
./rec/vert.glsl: sel = rsel ;
*/
}
void OpticksEvent::setBoundaryData(NPY<unsigned>* boundary_data)
{
m_boundary_data = boundary_data ;
if(boundary_data == nullptr) return ;
setBufferControl(m_boundary_data);
m_boundary_attr = new MultiViewNPY("boundary_attr");
}
void OpticksEvent::setSequenceData(NPY<unsigned long long>* sequence_data)
{
setBufferControl(sequence_data);
m_sequence_data = sequence_data ;
assert(sizeof(unsigned long long) == 4*sizeof(unsigned short));
//
// 64 bit uint used to hold the sequence flag sequence
// is presented to OpenGL shaders as 4 *16bit ushort
// as intend to reuse the sequence bit space for the indices and count
// via some diddling
//
// Have not taken the diddling route,
// instead using separate Recsel/Phosel buffers for the indices
//
// j k l sz type norm iatt item_from_dim
ViewNPY* phis = new ViewNPY("phis",m_sequence_data,0,0,0,4,ViewNPY::UNSIGNED_SHORT,false, true, 1);
ViewNPY* pmat = new ViewNPY("pmat",m_sequence_data,0,1,0,4,ViewNPY::UNSIGNED_SHORT,false, true, 1);
m_sequence_attr = new MultiViewNPY("sequence_attr");
m_sequence_attr->add(phis);
m_sequence_attr->add(pmat);
/*
Looks like the raw photon level sequence data is not used in shaders, instead the rsel (popularity index)
that is derived from the sequence data by indexing is used::
delta:gl blyth$ find . -type f -exec grep -H phis {} \;
delta:gl blyth$ find . -type f -exec grep -H pmat {} \;
*/
}
void OpticksEvent::Summary(const char* msg)
{
LOG(info) << desc(msg) ;
}
std::string OpticksEvent::brief() // cannot be const, due to OpticksEventSpec::formDir
{
std::stringstream ss ;
ss << "Evt "
<< getDir()
<< " " << getTimeStamp()
<< " " << getCreator()
;
return ss.str();
}
std::string OpticksEvent::desc(const char* msg)
{
std::stringstream ss ;
if(msg) ss << msg << " " ;
ss
<< " id: " << getId()
<< " typ: " << m_typ
<< " tag: " << m_tag
<< " det: " << m_det
<< " cat: " << ( m_cat ? m_cat : "NULL" )
<< " udet: " << getUDet()
<< " num_photons: " << m_num_photons
<< " num_source : " << m_num_source
;
//if(m_genstep_data) ss << m_genstep_data->description("m_genstep_data") ;
//if(m_photon_data) ss << m_photon_data->description("m_photon_data") ;
return ss.str();
}
void OpticksEvent::recordDigests()
{
NPY<float>* ox = getPhotonData() ;
if(ox && ox->hasData())
m_parameters->add<std::string>("photonData", ox->getDigestString() );
NPY<short>* rx = getRecordData() ;
if(rx && rx->hasData())
m_parameters->add<std::string>("recordData", rx->getDigestString() );
NPY<double>* dx = getDeluxeData() ;
if(dx && dx->hasData())
m_parameters->add<std::string>("deluxeData", dx->getDigestString() );
NPY<unsigned long long>* ph = getSequenceData() ;
if(ph && ph->hasData())
m_parameters->add<std::string>("sequenceData", ph->getDigestString() );
}
bool OpticksEvent::CanAnalyse(OpticksEvent* evt)
{
return evt && evt->hasRecordData() ;
}
/**
OpticksEvent::save
---------------------
Canonically invoked by OpticksRun::saveEvent which is
invoked from top level managers such as OKMgr::propagate.
::
frame #3: 0x0000000106d45f96 libOpticksCore.dylib`OpticksEvent::save(this=0x0000000130c8c1d0) at OpticksEvent.cc:1619
frame #4: 0x0000000106d512dd libOpticksCore.dylib`OpticksRun::saveEvent(this=0x000000010f018ca0) at OpticksRun.cc:305
frame #5: 0x0000000106391cee libOKOP.dylib`OpMgr::propagate(this=0x0000000119540c20) at OpMgr.cc:133
frame #6: 0x00000001000e81a8 libG4OK.dylib`G4Opticks::propagateOpticalPhotons(this=0x000000010f15e450, eventID=0) at G4Opticks.cc:806
frame #7: 0x000000010001299c G4OKTest`G4OKTest::propagate(this=0x00007ffeefbfe920, eventID=0) at G4OKTest.cc:248
frame #8: 0x0000000100012bc2 G4OKTest`main(argc=1, argv=0x00007ffeefbfe978) at G4OKTest.cc:276
In "--production" mode skips saving the arrays.
Formerly skipped saving when no records resulting in CanAnalyse false,
* this avoids writing the G4 evt domains, when running without
--okg4 that leads to unhealthy mixed timestamp event loads in evt.py.
* Different timestamps for ab.py between A and B
is tolerated, although if too much time, divergence is to be expected.
**/
void OpticksEvent::save()
{
//std::raise(SIGINT);
//const char* dir = m_event_spec->getDir() ;
setMetadataNum();
const char* dir = getDir() ;
LOG(info) << dir ;
OK_PROFILE("_OpticksEvent::save");
LOG(LEVEL)
<< desc() << " " << getShapeString()
<< " dir " << dir
;
bool production = m_ok->isProduction() ;
if(production)
{
if(m_ok->hasOpt("savehit")) saveHitData(); // FOR production hit check
saveTimes();
}
else
{
saveHitData();
saveHiyData();
saveNopstepData();
saveGenstepData();
savePhotonData();
saveSourceData();
saveRecordData();
saveDeluxeData();
saveSequenceData();
saveBoundaryData();
saveDebugData();
saveWayData();
//saveSeedData();
saveIndex();
recordDigests();
saveDomains();
saveParameters();
}
OK_PROFILE("OpticksEvent::save");
if(!production)
{
makeReport(false); // after timer save, in order to include that in the report
saveReport();
}
}
/**
OpticksEvent::saveHitData
--------------------------
Writes hit buffer even when empty, otherwise get inconsistent
buffer time stamps when changes makes hits go away and are writing
into the same directory.
Argument form allows externals like G4Opticks to save Geant4 sourced
hit data collected with CPhotonCollector into an event dir
with minimal fuss.
**/
void OpticksEvent::saveHitData() const
{
NPY<float>* ht = getHitData();
saveHitData(ht);
}
void OpticksEvent::saveHitData(NPY<float>* ht) const
{
if(ht)
{
unsigned num_hit = ht->getNumItems();
ht->save(m_pfx, "ht", m_typ, m_tag, m_udet); // even when zero hits
LOG(LEVEL)
<< " num_hit " << num_hit
<< " ht " << ht->getShapeString()
<< " tag " << m_tag
;
}
}
/**
OpticksEvent::saveHiyData
--------------------------
Writes hiy buffer even when empty, otherwise get inconsistent
buffer time stamps when changes makes hits go away and are writing
into the same directory.
**/
void OpticksEvent::saveHiyData() const
{
NPY<float>* hy = getHiyData();
saveHiyData(hy);
}
void OpticksEvent::saveHiyData(NPY<float>* hy) const
{
if(hy)
{
unsigned num_hiy = hy->getNumItems();
hy->save(m_pfx, "hy", m_typ, m_tag, m_udet); // even when zero hits
LOG(LEVEL)
<< " num_hiy " << num_hiy
<< " hy " << hy->getShapeString()
<< " tag " << m_tag
;
}
}
void OpticksEvent::saveNopstepData()
{
NPY<float>* no = getNopstepData();
if(no)
{
unsigned num_nop = no->getNumItems();
if(num_nop > 0) no->save(m_pfx, "no", m_typ, m_tag, m_udet);
if(num_nop == 0) LOG(debug) << "saveNopstepData zero nop " ;
//if(num_nop > 0) no->dump("OpticksEvent::save (nopstep)");
NPY<int>* idom = getIDomain();
assert(idom && "OpticksEvent::save non-null nopstep BUT HAS NULL IDOM ");
}
}
void OpticksEvent::saveGenstepData()
{
// genstep were formally not saved as they exist already elsewhere,
// however recording the gs in use for posterity makes sense
//
NPY<float>* gs = getGenstepData();
if(gs) gs->save(m_pfx, "gs", m_typ, m_tag, m_udet);
}
void OpticksEvent::savePhotonData()
{
NPY<float>* ox = getPhotonData();
if(ox) ox->save(m_pfx, "ox", m_typ, m_tag, m_udet);
}
void OpticksEvent::saveRecordData()
{
NPY<short>* rx = getRecordData();
if(rx) rx->save(m_pfx, "rx", m_typ, m_tag, m_udet);
}
void OpticksEvent::saveDeluxeData()
{
NPY<double>* dx = getDeluxeData();
if(dx) dx->save(m_pfx, "dx", m_typ, m_tag, m_udet);
}
void OpticksEvent::saveSequenceData()
{
NPY<unsigned long long>* ph = getSequenceData();
if(ph) ph->save(m_pfx, "ph", m_typ, m_tag, m_udet);
}
void OpticksEvent::saveBoundaryData()
{
NPY<unsigned>* bn = getBoundaryData();
if(bn) bn->save(m_pfx, "bn", m_typ, m_tag, m_udet);
}
void OpticksEvent::saveDebugData()
{
NPY<float>* dg = getDebugData();
if(dg) dg->save(m_pfx, "dg", m_typ, m_tag, m_udet);
}
void OpticksEvent::saveWayData()
{
NPY<float>* wy = getWayData();
if(wy && wy->hasData()) wy->save(m_pfx, "wy", m_typ, m_tag, m_udet);
}
void OpticksEvent::saveSeedData()
{
// dont try, seed buffer is OPTIX_INPUT_ONLY , so attempts to download from GPU yields garbage
// also suspect such an attempt messes up the OptiX context is peculiar ways
//
// NPY<unsigned>* se = getSeedData();
// if(se) se->save(m_pfx, "se", m_typ, m_tag, m_udet);
}
void OpticksEvent::saveSourceData() const
{
// source data originates CPU side, and is INPUT_ONLY to GPU side
NPY<float>* so = getSourceData();
saveSourceData(so);
}
void OpticksEvent::saveSourceData(NPY<float>* so) const
{
if(so)
{
so->save(m_pfx, "so", m_typ, m_tag, m_udet);
//if(num_so == 0) LOG(info) << "saveSourceData zero source " ;
}
}
void OpticksEvent::makeReport(bool verbose)
{
LOG(LEVEL) << "tagdir " << getTagDir() ;
if(verbose)
m_parameters->dump();
m_report->add(m_versions->getLines());
m_report->add(m_parameters->getLines());
m_report->add(m_profile->getLines());
}
void OpticksEvent::saveReport()
{
std::string tagdir = getTagDir();
saveReport(tagdir.c_str());
std::string anno = getTimeStamp() ;
std::string tagdir_ts = getTagDir(anno.c_str());
saveReport(tagdir_ts.c_str());
}
void OpticksEvent::saveTimes()
{
std::string tagdir = getTagDir();
LOG(fatal) << " tagdir " << tagdir ;
saveTimes(tagdir.c_str());
std::string anno = getTimeStamp() ;
std::string tagdir_ts = getTagDir(anno.c_str());
saveTimes(tagdir_ts.c_str());
}
std::string OpticksEvent::TagDir(const char* pfx, const char* det, const char* typ, const char* tag, const char* anno)
{
std::string tagdir = BOpticksEvent::directory(pfx, det, typ, tag, anno ? anno : NULL );
return tagdir ;
}
std::string OpticksEvent::getTagDir(const char* anno)
{
const char* udet = getUDet();
std::string tagdir = TagDir(m_pfx, udet, m_typ, m_tag, anno ? anno : NULL );
if( anno == NULL )
{
const char* tagdir2 = getDir();
assert( strcmp( tagdir.c_str(), tagdir2) == 0 );
}
return tagdir ;
}
std::string OpticksEvent::getTagZeroDir(const char* anno)
{
const char* udet = getUDet();
const char* tagzero = "0" ;
std::string tagdir = TagDir(m_pfx, udet, m_typ, tagzero, anno ? anno : NULL );
return tagdir ;
}
void OpticksEvent::saveParameters()
{
std::string tagdir = getTagDir();
m_parameters->save(tagdir.c_str(), PARAMETERS_NAME);
std::string anno = getTimeStamp() ;
std::string tagdir_ts = getTagDir(anno.c_str());
m_parameters->save(tagdir_ts.c_str(), PARAMETERS_NAME);
}
void OpticksEvent::loadParameters()
{
std::string tagdir = getTagDir();
m_parameters->load(tagdir.c_str(), PARAMETERS_NAME );
}
void OpticksEvent::importParameters()
{
std::string mode_ = m_parameters->get<std::string>("mode");
OpticksMode* mode = new OpticksMode(mode_.c_str());
LOG(debug) << "OpticksEvent::importParameters "
<< " mode_ " << mode_
<< " --> " << mode->desc() ;
setMode(mode);
}
void OpticksEvent::saveReport(const char* dir)
{
assert(m_report);
LOG(LEVEL) << "[ " << dir ;
m_profile->save(dir);
m_report->save(dir);
LOG(LEVEL) << "] " << dir ;
}
void OpticksEvent::loadReport()
{
std::string tagdir_ = getTagDir();
const char* tagdir = tagdir_.c_str();
//LOG(error) << "tagdir " << tagdir ;
m_profile = OpticksProfile::Load( tagdir );
m_report = Report::load(tagdir );
}
void OpticksEvent::saveTimes(const char* dir)
{
LOG(LEVEL) << "[ " << dir ;
m_launch_times->save(dir);
m_prelaunch_times->save(dir);
LOG(LEVEL) << "] " << dir ;
}
void OpticksEvent::loadTimes()
{
std::string tagdir_ = getTagDir();
const char* tagdir = tagdir_.c_str();
m_launch_times = BTimes::Load(LAUNCH_LABEL, tagdir );
m_prelaunch_times = BTimes::Load(PRELAUNCH_LABEL, tagdir );
}
/**
OpticksEvent::setFakeNopstepPath
---------------------------------
Fake path used by OpticksEvent::load rather than standard one
used for visualization debugging. See: ana/debug/nopstep_viz_debug.py
**/
void OpticksEvent::setFakeNopstepPath(const char* path)
{
m_fake_nopstep_path = path ? strdup(path) : NULL ;
}
OpticksEvent* OpticksEvent::load( const char* pfx, const char* typ, const char* tag, const char* det, const char* cat, bool verbose)
{
LOG(info)
<< " pfx " << pfx
<< " typ " << typ
<< " tag " << tag
<< " det " << det
<< " cat " << ( cat ? cat : "NULL" )
;
OpticksEventSpec* spec = new OpticksEventSpec(pfx, typ, tag, det, cat);
OpticksEvent* evt = new OpticksEvent(spec);
evt->loadBuffers(verbose);
if(evt->isNoLoad())
{
LOG(warning) << "OpticksEvent::load FAILED " ;
delete evt ;
evt = NULL ;
}
return evt ;
}
void OpticksEvent::loadBuffersImportSpec(NPYBase* npy, NPYSpec* spec)
{
assert(npy->hasItemSpec(spec));
npy->setBufferSpec(spec);
}
/**
OpticksEvent::getPath
------------------------
See BOpticksEvent::path for notes on the composition of the path.
**/
const char* OpticksEvent::getPath(const char* xx)
{
std::string name = m_abbrev.count(xx) == 1 ? m_abbrev[xx] : xx ;
const char* udet = getUDet(); // cat overrides det if present
std::string path = BOpticksEvent::path(m_pfx, udet, m_typ, m_tag, name.c_str() );
return strdup(path.c_str()) ;
}
void OpticksEvent::importGenstepDataLoaded(NPY<float>* gs)
{
OpticksActionControl ctrl(gs->getActionControlPtr());
ctrl.add(OpticksActionControl::GS_LOADED_);
if(isTorchType()) ctrl.add(OpticksActionControl::GS_TORCH_);
}
/**
OpticksEvent::loadBuffers
---------------------------
TODO: move domain loading into separate method
**/
void OpticksEvent::loadBuffers(bool verbose)
{
OK_PROFILE("_OpticksEvent::loadBuffers");
const char* udet = getUDet(); // cat overrides det if present
bool qload = true ;
NPY<int>* idom = NPY<int>::load(m_pfx, idom_, m_typ, m_tag, udet, qload);
if(!idom)
{
std::string tagdir = getTagDir();
m_noload = true ;
LOG(warning) << "OpticksEvent::load NO SUCH EVENT : RUN WITHOUT --load OPTION TO CREATE IT "
<< " typ: " << m_typ
<< " tag: " << m_tag
<< " det: " << m_det
<< " cat: " << ( m_cat ? m_cat : "NULL" )
<< " udet: " << udet
<< " tagdir " << tagdir
;
return ;
}
m_loaded = true ;
NPY<float>* fdom = NPY<float>::load(m_pfx, fdom_, m_typ, m_tag, udet, qload );
setIDomain(idom);
setFDomain(fdom);
loadReport();
loadParameters();
importParameters();
loadIndex();
importDomainsBuffer();
createSpec(); // domains import sets maxrec allowing spec to be created
assert(idom->hasShapeSpec(m_idom_spec));
assert(fdom->hasShapeSpec(m_fdom_spec));
NPY<float>* no = NULL ;
if(m_fake_nopstep_path)
{
LOG(warning) << "OpticksEvent::loadBuffers using setFakeNopstepPath " << m_fake_nopstep_path ;
no = NPY<float>::debugload(m_fake_nopstep_path);
}
else
{
no = NPY<float>::load(m_pfx, "no", m_typ, m_tag, udet, qload);
}
if(no) loadBuffersImportSpec(no, m_nopstep_spec) ;
NPY<float>* gs = NPY<float>::load(m_pfx, "gs", m_typ, m_tag, udet, qload);
NPY<float>* ox = NPY<float>::load(m_pfx, "ox", m_typ, m_tag, udet, qload);
NPY<short>* rx = NPY<short>::load(m_pfx, "rx", m_typ, m_tag, udet, qload);
NPY<double>* dx = NPY<double>::load(m_pfx, "dx", m_typ, m_tag, udet, qload);
NPY<unsigned long long>* ph = NPY<unsigned long long>::load(m_pfx, "ph", m_typ, m_tag, udet, qload );
NPY<unsigned>* bn = NPY<unsigned>::load(m_pfx, "bn", m_typ, m_tag, udet, qload );
NPY<unsigned char>* ps = NPY<unsigned char>::load(m_pfx, "ps", m_typ, m_tag, udet, qload );
NPY<unsigned char>* rs = NPY<unsigned char>::load(m_pfx, "rs", m_typ, m_tag, udet, qload );
NPY<unsigned>* se = NPY<unsigned>::load( m_pfx, "se", m_typ, m_tag, udet, qload );
NPY<float>* ht = NPY<float>::load( m_pfx, "ht", m_typ, m_tag, udet, qload );
if(ph == NULL || ps == NULL || rs == NULL )
LOG(warning)
<< " " << getDir()
<< " MISSING INDEX BUFFER(S) "
<< " ph " << ph
<< " ps " << ps
<< " rs " << rs
;
if(gs) loadBuffersImportSpec(gs,m_genstep_spec) ;
if(ox) loadBuffersImportSpec(ox,m_photon_spec) ;
if(rx) loadBuffersImportSpec(rx,m_record_spec) ;
if(dx) loadBuffersImportSpec(dx,m_deluxe_spec) ;
if(ph) loadBuffersImportSpec(ph,m_sequence_spec) ;
if(bn) loadBuffersImportSpec(bn,m_boundary_spec) ;
if(ps) loadBuffersImportSpec(ps,m_phosel_spec) ;
if(rs) loadBuffersImportSpec(rs,m_recsel_spec) ;
if(se) loadBuffersImportSpec(se,m_seed_spec) ;
if(ht) loadBuffersImportSpec(ht,m_hit_spec) ;
if(gs) importGenstepDataLoaded(gs); // sets action control, so setGenstepData label checks can succeed
unsigned int num_genstep = gs ? gs->getShape(0) : 0 ;
unsigned int num_nopstep = no ? no->getShape(0) : 0 ;
unsigned int num_photons = ox ? ox->getShape(0) : 0 ;
unsigned int num_history = ph ? ph->getShape(0) : 0 ;
unsigned int num_phosel = ps ? ps->getShape(0) : 0 ;
unsigned int num_seed = se ? se->getShape(0) : 0 ;
unsigned int num_hit = ht ? ht->getShape(0) : 0 ;
// either zero or matching
assert(num_history == 0 || num_photons == num_history );
assert(num_phosel == 0 || num_photons == num_phosel );
assert(num_seed == 0 || num_photons == num_seed );
unsigned int num_records = rx ? rx->getShape(0) : 0 ;
unsigned int num_deluxe = dx ? dx->getShape(0) : 0 ;
unsigned int num_boundary = bn ? bn->getShape(0) : 0 ;
unsigned int num_recsel = rs ? rs->getShape(0) : 0 ;
assert(num_recsel == 0 || num_records == num_recsel );
assert(num_deluxe == 0 || num_records == num_deluxe );
assert(num_boundary == 0 || num_records == num_boundary );
LOG(LEVEL)
<< "before reshaping "
<< " num_genstep " << num_genstep
<< " num_nopstep " << num_nopstep
<< " [ "
<< " num_photons " << num_photons
<< " num_history " << num_history
<< " num_phosel " << num_phosel
<< " num_seed " << num_seed
<< " num_hit " << num_hit
<< " ] "
<< " [ "
<< " num_records " << num_records
<< " num_boundary " << num_boundary
<< " num_deluxe " << num_deluxe
<< " num_recsel " << num_recsel
<< " ] "
;
// treat "persisted for posterity" gensteps just like all other buffers
// progenitor input gensteps need different treatment
bool resize_ = false;
bool clone_ = false ;
setGenstepData(gs, resize_, clone_ );
setNopstepData(no, clone_ );
setPhotonData(ox);
setSequenceData(ph);
setBoundaryData(bn);
setRecordData(rx);
setDeluxeData(dx);
setPhoselData(ps);
setRecselData(rs);
setSeedData(se);
setHitData(ht);
OK_PROFILE("OpticksEvent::loadBuffers");
LOG(info) << getShapeString() ;
if(verbose)
{
fdom->Summary("fdom");
idom->Summary("idom");
if(no) no->Summary("no");
if(ox) ox->Summary("ox");
if(rx) rx->Summary("rx");
if(dx) dx->Summary("dx");
if(ph) ph->Summary("ph");
if(bn) bn->Summary("bn");
if(ps) ps->Summary("ps");
if(rs) rs->Summary("rs");
if(se) se->Summary("se");
if(ht) ht->Summary("ht");
}
if(!isIndexed())
{
LOG(warning) << "IS NOT INDEXED "
<< brief()
;
}
}
bool OpticksEvent::isIndexed() const
{
return m_phosel_data != NULL && m_recsel_data != NULL && m_seqhis != NULL && m_seqmat != NULL ;
}
NPY<float>* OpticksEvent::loadGenstepDerivativeFromFile(const char* stem)
{
std::string path = BOpticksEvent::path(m_det, m_typ, m_tag, stem, ".npy" ); // top/sub/tag/stem/ext
bool exists = BFile::ExistsFile(path.c_str()) ;
if(exists)
LOG(info) << "OpticksEvent::loadGenstepDerivativeFromFile "
<< " m_det " << m_det
<< " m_typ " << m_typ
<< " m_tag " << m_tag
<< " stem " << stem
<< " --> " << path
;
NPY<float>* npy = exists ? NPY<float>::load(path.c_str()) : NULL ;
return npy ;
}
void OpticksEvent::setNumG4Event(unsigned int n)
{
m_parameters->add<int>("NumG4Event", n);
}
void OpticksEvent::setNumPhotonsPerG4Event(unsigned int n)
{
m_parameters->add<int>("NumPhotonsPerG4Event", n);
}
unsigned int OpticksEvent::getNumG4Event()
{
return m_parameters->get<int>("NumG4Event","1");
}
unsigned int OpticksEvent::getNumPhotonsPerG4Event() const
{
return m_parameters->get<int>("NumPhotonsPerG4Event","0"); // "0" : fallback if not set (eg for G4GUN running )
}
/**
OpticksEvent::postPropagateGeant4
----------------------------------
Canonical invokations from::
CG4::postpropagate
For dynamically recorded g4evt the photon, sequence and record
buffers are grown during the instrumented Geant4 stepping, a
subsequent resize from setNumPhotons makes no difference to those buffers
but pulls up the counts for phosel and recsel (and seed) ready to
hold the CPU indices.
**/
void OpticksEvent::postPropagateGeant4()
{
unsigned int num_photons = m_photon_data->getShape(0);
LOG(info) << "OpticksEvent::postPropagateGeant4"
<< " shape " << getShapeString()
<< " num_photons " << num_photons
<< " dynamic " << getDynamic()
;
//if(!m_ok->isFabricatedGensteps())
int dynamic = getDynamic();
if(dynamic == 1)
{
LOG(fatal) << " setting num_photons " << num_photons
<< " as dynamic : to pull up recsel, phosel ready to hold the indices "
;
setNumPhotons(num_photons);
}
else
{
LOG(LEVEL) << " NOT setting num_photons, as STATIC running " << num_photons ;
}
indexPhotonsCPU();
collectPhotonHitsCPU();
}
/**
OpticksEvent::collectPhotonHitsCPU
-------------------------------------
Invoked by OpticksEvent::postPropagateGeant4
See notes/issues/geant4_opticks_integration/missing_cfg4_surface_detect.rst
**/
void OpticksEvent::collectPhotonHitsCPU()
{
OK_PROFILE("_OpticksEvent::collectPhotonHitsCPU");
NPY<float>* ox = getPhotonData();
NPY<float>* ht = getHitData();
unsigned hitmask = SURFACE_DETECT ; // TODO: this is an input, not a constant
unsigned numHits = ox->write_selection(ht, 3,3, hitmask );
LOG(info)
<< " hitmask " << hitmask
<< " numHits " << numHits
;
OK_PROFILE("OpticksEvent::collectPhotonHitsCPU");
}
/**
OpticksEvent::indexPhotonsCPU
------------------------------
* used only for g4evt ie CRecorder/CWriter collected
records, photons, sequence buffers.
* phosel and recsel are expected to have been sized, but
not to contain any data
* unsigned long long sequence is the input to the indexing
yielding phosel and recsel indices
**/
void OpticksEvent::indexPhotonsCPU()
{
// see tests/IndexerTest
OK_PROFILE("_OpticksEvent::indexPhotonsCPU");
NPY<unsigned long long>* sequence = getSequenceData();
NPY<unsigned char>* phosel = getPhoselData();
NPY<unsigned char>* recsel0 = getRecselData();
LOG(info) << "OpticksEvent::indexPhotonsCPU"
<< " sequence " << sequence->getShapeString()
<< " phosel " << phosel->getShapeString()
<< " phosel.hasData " << phosel->hasData()
<< " recsel0 " << recsel0->getShapeString()
<< " recsel0.hasData " << recsel0->hasData()
;
unsigned int maxrec = getMaxRec();
assert(sequence->hasItemShape(1,2));
assert(phosel->hasItemShape(1,4));
assert(recsel0->hasItemShape(maxrec,1,4));
// hmm this is expecting a resize to have been done ???
// in order to provide the slots in phosel and recsel
// for the index applyLookup to write to
if( sequence->getShape(0) != phosel->getShape(0))
{
LOG(fatal) << " length mismatch "
<< " sequence : " << sequence->getShape(0)
<< " phosel : " << phosel->getShape(0)
;
// << " ABORT indexing "
//return ;
}
assert(sequence->getShape(0) == phosel->getShape(0));
assert(sequence->getShape(0) == recsel0->getShape(0));
Indexer<unsigned long long>* idx = new Indexer<unsigned long long>(sequence) ;
LOG(info) << "indexSequence START " ;
idx->indexSequence(OpticksConst::SEQHIS_NAME_, OpticksConst::SEQMAT_NAME_);
LOG(info) << "indexSequence DONE " ;
assert(!phosel->hasData()) ;
phosel->zero();
unsigned char* phosel_values = phosel->getValues() ;
assert(phosel_values);
idx->applyLookup<unsigned char>(phosel_values);
NPY<unsigned char>* recsel1 = NPY<unsigned char>::make_repeat(phosel, maxrec ) ;
recsel1->reshape(-1, maxrec, 1, 4);
recsel1->setBufferSpec(m_recsel_spec);
if(recsel0 && recsel0->hasData()) LOG(warning) << " leaking recsel0 " ;
setRecselData(recsel1);
setHistoryIndex(idx->getHistoryIndex());
setMaterialIndex(idx->getMaterialIndex());
OK_PROFILE("OpticksEvent::indexPhotonsCPU");
}
void OpticksEvent::saveIndex()
{
bool is_indexed = isIndexed();
if(!is_indexed)
{
LOG(LEVEL) << "SKIP as not indexed " ;
return ;
}
NPY<unsigned char>* ps = getPhoselData();
NPY<unsigned char>* rs = getRecselData();
assert(ps);
assert(rs);
ps->save(m_pfx, "ps", m_typ, m_tag, m_udet);
rs->save(m_pfx, "rs", m_typ, m_tag, m_udet);
NPYBase::setGlobalVerbose(false);
std::string tagdir = getTagDir();
LOG(verbose)
<< " tagdir " << tagdir
<< " seqhis " << m_seqhis
<< " seqmat " << m_seqmat
<< " bndidx " << m_bndidx
;
if(m_seqhis)
m_seqhis->save(tagdir.c_str());
else
LOG(LEVEL) << "no seqhis to save " ;
if(m_seqmat)
m_seqmat->save(tagdir.c_str());
else
LOG(LEVEL) << "no seqmat to save " ;
if(m_bndidx)
m_bndidx->save(tagdir.c_str());
else
LOG(LEVEL) << "no bndidx to save " ;
}
void OpticksEvent::loadIndex()
{
std::string tagdir_ = getTagDir();
const char* tagdir = tagdir_.c_str();
const char* reldir = NULL ;
m_seqhis = Index::load(tagdir, OpticksConst::SEQHIS_NAME_, reldir );
m_seqmat = Index::load(tagdir, OpticksConst::SEQMAT_NAME_, reldir );
m_bndidx = Index::load(tagdir, OpticksConst::BNDIDX_NAME_, reldir );
LOG(debug)
<< " tagdir " << tagdir
<< " seqhis " << m_seqhis
<< " seqmat " << m_seqmat
<< " bndidx " << m_bndidx
;
}
Index* OpticksEvent::loadNamedIndex( const char* pfx, const char* typ, const char* tag, const char* udet, const char* name)
{
std::string tagdir = TagDir(pfx, udet, typ, tag);
const char* reldir = NULL ;
Index* index = Index::load(tagdir.c_str(), name, reldir);
if(!index)
{
LOG(warning) << "OpticksEvent::loadNamedIndex FAILED"
<< " name " << name
<< " typ " << typ
<< " tag " << tag
<< " udet " << udet
<< " tagdir " << tagdir
;
}
return index ;
}
Index* OpticksEvent::loadHistoryIndex( const char* pfx, const char* typ, const char* tag, const char* udet)
{
return loadNamedIndex(pfx, typ, tag, udet, OpticksConst::SEQHIS_NAME_);
}
Index* OpticksEvent::loadMaterialIndex( const char* pfx, const char* typ, const char* tag, const char* udet)
{
return loadNamedIndex(pfx, typ, tag, udet, OpticksConst::SEQMAT_NAME_);
}
Index* OpticksEvent::loadBoundaryIndex( const char* pfx, const char* typ, const char* tag, const char* udet)
{
return loadNamedIndex(pfx, typ, tag, udet, OpticksConst::BNDIDX_NAME_);
}
int OpticksEvent::seedDebugCheck(const char* msg)
{
// This can only be used with specific debug entry points
// that write seeds as uint into the photon buffer
//
// * entryCode T TRIVIAL
// * entryCode D DUMPSEED
assert(m_photon_data && m_photon_data->hasData());
assert(m_genstep_data && m_genstep_data->hasData());
TrivialCheckNPY chk(m_photon_data, m_genstep_data, m_ok->getEntryCode());
return chk.check(msg);
}
std::string OpticksEvent::getSeqHisString(unsigned photon_id) const
{
unsigned long long seqhis_ = getSeqHis(photon_id);
return OpticksFlags::FlagSequence(seqhis_);
}
unsigned long long OpticksEvent::getSeqHis(unsigned photon_id) const
{
unsigned num_seq = m_sequence_data ? m_sequence_data->getShape(0) : 0 ;
unsigned long long seqhis_ = photon_id < num_seq ? m_sequence_data->getValue(photon_id,0,0) : 0 ;
return seqhis_ ;
}
unsigned long long OpticksEvent::getSeqMat(unsigned photon_id ) const
{
unsigned long long sm = m_sequence_data ? m_sequence_data->getValue(photon_id,0,1) : 0 ;
return sm ;
}
| 28.153794 | 160 | 0.63447 | hanswenzel |
cc508af3a437ec839f10c521e777ae8d60c6ddc7 | 20,940 | cpp | C++ | Projects/mo_graphics/callbacks_binded.cpp | Neill3d/MoPlugs | 84efea03e045f820f3dc132c1a60a779fc5e34fc | [
"BSD-3-Clause"
] | 23 | 2017-10-20T07:01:18.000Z | 2022-02-25T08:46:07.000Z | Projects/mo_graphics/callbacks_binded.cpp | droidoid/MoPlugs | fce52e6469408e32e94af8ac8a303840bc956e53 | [
"BSD-3-Clause"
] | 1 | 2019-11-08T04:03:38.000Z | 2019-11-10T10:16:00.000Z | Projects/mo_graphics/callbacks_binded.cpp | droidoid/MoPlugs | fce52e6469408e32e94af8ac8a303840bc956e53 | [
"BSD-3-Clause"
] | 5 | 2017-12-03T20:43:27.000Z | 2020-01-22T16:54:13.000Z |
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// file: callbacks_binded.h
//
// Author Sergey Solokhin (Neill3d)
//
// GitHub page - https://github.com/Neill3d/MoPlugs
// Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "callbacks_binded.h"
#include "graphics\OGL_Utils_MOBU.h"
#include "ProjTex_shader.h"
///////////////////////////////////////////////////////////////////////////
// CShaderBindedCallback
const bool CUberShaderCallback::IsForShader(FBShader *pShader)
{
return true;
}
const bool CUberShaderCallback::IsForShaderAndPass(FBShader *pShader, const EShaderPass pass)
{
return true; // (pass == eShaderPassOpaque); // FBIS( pShader, ProjTexShader );
}
bool CUberShaderCallback::OnTypeBegin(const CRenderOptions &options, bool useMRT)
{
mShaderFX = mGPUFBScene->GetShaderFXPtr(mCurrentTech);
if (nullptr == mShaderFX)
return false;
ERenderGoal goal = options.GetGoal();
switch(goal)
{
case eRenderGoalSelectionId:
case eRenderGoalShadows:
mIsEarlyZ = true;
mRenderToNormalAndMaskOutput = false;
break;
default:
mIsEarlyZ = false;
mRenderToNormalAndMaskOutput = true;
}
// DONE: we should do this only when draw to buffer is used !!
// proj tex outputs to normal and mask attachments, not only color
/*
if ( useMRT && mRenderToNormalAndMaskOutput ) // pScene->IsRenderToBuffer()
{
GLenum buffers [] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
glDrawBuffers( 4, buffers );
}
else
{
GLenum buffers [] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers( 1, buffers );
}
*/
CHECK_GL_ERROR_MOBU();
mShaderFX->ModifyShaderFlags( Graphics::eShaderFlag_Bindless, mIsBindless );
//mUberShader->SetTechnique( mCurrentTech );
//mUberShader->SetBindless(mIsBindless);
//mUberShader->SetNumberOfProjectors( 0 );
//mUberShader->SetRimParameters( 0.0, 0.0, false, vec3(0.0f, 0.0f, 0.0f) );
//mUberShader->SetDepthDisplacement( 0.0f );
mShaderFX->SetTextureOffset( vec4( 0.0, 0.0, 0.0, 0.0) );
mShaderFX->SetTextureScaling( vec4( 1.0, 1.0, 1.0, 1.0) );
//
/*
if (options.IsCubeMapRender() && options.GetCubeMapData() )
{
const CubeMapRenderingData *cubemap = options.GetCubeMapData();
mUberShader->UploadCubeMapUniforms( cubemap->zmin,
cubemap->zmax,
cubemap->position,
cubemap->max,
cubemap->min,
cubemap->useParallax);
mUberShader->SetCubeMapRendering(true);
// TODO:
// mUberShader->UploadCameraUniforms(cameraMV, cameraPRJ, viewIT, vEyePos, width, height, farPlane, nullptr);
}
else
{
mUberShader->SetCubeMapRendering(false);
}
*/
mShaderFX->ModifyShaderFlags( Graphics::eShaderFlag_NoTextures, false == options.IsTextureMappingEnable() );
mShaderFX->ModifyShaderFlags( Graphics::eShaderFlag_EarlyZ, mIsEarlyZ );
//
OnTypeBeginPredefine( options, useMRT );
//
mGPUFBScene->PrepRender();
mGPUFBScene->BindUberShader( mNeedOverrideShading ); // || options.IsCubeMapRender() );
CGPUVertexData::renderPrep();
StoreCullMode(mCullFaceInfo);
return true;
}
void CUberShaderCallback::OnTypeEnd(const CRenderOptions &options)
{
if (nullptr == mShaderFX)
return;
/*
// proj tex outputs to normal and mask attachments, not only color
if ( mRenderToNormalAndMaskOutput ) // pScene->IsRenderToBuffer()
{
GLenum buffers [] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers( 1, buffers );
}
*/
mShaderFX->UnsetTextures();
mGPUFBScene->UnBindUberShader();
// unbind matCap and shadows
glActiveTexture(GL_TEXTURE6);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE7);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
CGPUVertexData::renderFinish();
FetchCullMode(mCullFaceInfo);
}
bool CUberShaderCallback::OnInstanceBegin(const CRenderOptions &options, FBRenderOptions *pFBRenderOptions, FBShader *pShader, CBaseShaderInfo *pInfo)
{
// TODO: bind projectors and instance lights list
mLastModel = nullptr;
mLastMaterial = nullptr;
mLastFXShader = nullptr;
//StoreCullMode(mCullFaceInfo);
return (options.GetPass() == eShaderPassOpaque);
}
void CUberShaderCallback::OnInstanceEnd(const CRenderOptions &options, FBShader *pShader, CBaseShaderInfo *pInfo)
{
//FetchCullMode(mCullFaceInfo);
}
// model sub-mesh has a material assigned
bool CUberShaderCallback::OnMaterialBegin(const CRenderOptions &options, FBRenderOptions *pRenderOptions, FBMaterial *pMaterial, bool forceInit)
{
// TODO: check for the last material, to not bind the same thing !
const ERenderGoal goal = options.GetGoal();
if (eRenderGoalSelectionId != goal && eRenderGoalShadows != goal && true == options.IsTextureMappingEnable() )
{
BindMaterialTextures(pMaterial, pRenderOptions, options.GetMutedTextureId(), forceInit );
}
CHECK_GL_ERROR_MOBU();
return true;
}
void CUberShaderCallback::OnMaterialEnd(const CRenderOptions &options, FBMaterial *pMaterial)
{
}
bool CUberShaderCallback::OnModelDraw(const CRenderOptions &options, FBRenderOptions *pFBRenderOptions, FBModel *pModel, CBaseShaderInfo *pInfo)
{
// support for cullmode
// TODO: check for the latest cullmode to not set the same thing !
FBModelCullingMode cullMode = pModel->GetCullingMode();
if (cullMode != options.GetLastCullingMode() )
{
switch(cullMode)
{
case kFBCullingOff:
glDisable(GL_CULL_FACE);
break;
case kFBCullingOnCW:
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
break;
case kFBCullingOnCCW:
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
break;
}
// mLastCullingMode = cullMode;
((CRenderOptions&)options).SetLastCullingMode(cullMode);
}
return true;
}
void CUberShaderCallback::BindMaterialTextures(FBMaterial *pMaterial, FBRenderOptions *pRenderOptions, const GLuint mutedTextureId, bool forceInit)
{
if (nullptr == pMaterial)
return;
// DONE: bind material textures
const int nId = GetTextureId( pMaterial->GetTexture(kFBMaterialTextureNormalMap), pRenderOptions, forceInit );
const int rId = GetTextureId( pMaterial->GetTexture(kFBMaterialTextureReflection), pRenderOptions, forceInit );
const int sId = GetTextureId( pMaterial->GetTexture(kFBMaterialTextureSpecular), pRenderOptions, forceInit );
const int tId = GetTextureId( pMaterial->GetTexture(kFBMaterialTextureTransparent), pRenderOptions, forceInit );
const int dId = GetTextureId( pMaterial->GetTexture(), pRenderOptions, forceInit );
if (nId > 0 && nId != mutedTextureId)
{
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, nId);
}
if (rId > 0 && rId != mutedTextureId)
{
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, rId);
// use specified cubemap uniforms for parallax correction when computing reflections in shader
//if (rId > 0)
//{
mGPUFBScene->UploadCubeMapUniforms(rId);
//}
}
if (sId > 0 && sId != mutedTextureId)
{
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, sId);
}
if (tId > 0 && tId != mutedTextureId)
{
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, tId);
}
if (dId > 0 && dId != mutedTextureId)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, dId);
}
}
/////////////////////////////////////////////////////////////////////////////
// Callback for ProjTex Shader
const bool CProjTexBindedCallback::IsForShader(FBShader *pShader)
{
return (FBIS( pShader, ProjTexShader )
|| FBIS(pShader, FXProjectionMapping) );
}
const bool CProjTexBindedCallback::IsForShaderAndPass(FBShader *pShader, const EShaderPass pass)
{
return (FBIS( pShader, ProjTexShader )
|| FBIS(pShader, FXProjectionMapping ) );
/*
if (FBIS( pShader, ProjTexShader ) )
{
ProjTexShader *pProjTex = (ProjTexShader*) pShader;
const bool isRenderOnBack = (true == pProjTex->RenderOnBack);
const bool isTransparent = (pProjTex->Transparency != kFBAlphaSourceNoAlpha && pProjTex->TransparencyFactor < 1.0);
switch (pass)
{
case eShaderPassBackground:
return (true == isRenderOnBack);
case eShaderPassTransparency:
return (true == isTransparent);
case eShaderPassOpaque:
return (false == isRenderOnBack && false == isTransparent);
}
}
return false;
*/
}
bool CProjTexBindedCallback::OnInstanceBegin(const CRenderOptions &options, FBRenderOptions *pFBRenderOptions, FBShader *pShader, CBaseShaderInfo *pInfo)
{
if (nullptr == mShaderFX)
return false;
//mShader = pInfo->GetFBShader();
mShader = pShader;
if (nullptr == mShader || !FBIS(mShader, ProjTexShader) )
return false;
ProjTexShader *pProjTex = (ProjTexShader*) mShader;
//const bool renderOnBack = pProjTex->RenderOnBack;
const FBAlphaSource alphaSource = pProjTex->Transparency;
const ERenderGoal goal = options.GetGoal();
const EShaderPass pass = options.GetPass();
bool skipShader = false;
switch(goal)
{
case eRenderGoalShading:
switch(pass)
{
case eShaderPassOpaque:
skipShader = (kFBAlphaSourceNoAlpha != alphaSource);
break;
case eShaderPassTransparency:
skipShader = (kFBAlphaSourceAccurateAlpha != alphaSource);
break;
case eShaderPassAdditive:
skipShader = (kFBAlphaSourceAdditiveAlpha != alphaSource);
break;
}
break;
/*
if (true == renderOnBack)
{
skipShader = true;
}
else
{
switch(pass)
{
case eShaderPassOpaque:
skipShader = (kFBAlphaSourceNoAlpha != alphaSource);
break;
case eShaderPassTransparency:
skipShader = (kFBAlphaSourceAccurateAlpha != alphaSource);
break;
case eShaderPassAdditive:
skipShader = (kFBAlphaSourceAdditiveAlpha != alphaSource);
break;
}
}
break;
case eRenderGoalBackground:
skipShader = (false == renderOnBack);
break;
*/
}
if (true == skipShader)
return false;
// TODO: bind projectors and instance lights list
if (eRenderGoalSelectionId != goal && eRenderGoalShadows != goal)
{
InternalInstanceBegin( options.IsTextureMappingEnable(), options.GetMutedTextureId() );
}
return true;
}
void CProjTexBindedCallback::InternalInstanceBegin(const bool textureMapping, const GLuint muteTextureId)
{
ProjTexShader *pProjTex = (ProjTexShader*) mShader;
mLastModel = nullptr;
mLastMaterial = nullptr;
mLastFXShader = nullptr;
hasExclusiveLights = false;
EShadingType shadingType = pProjTex->ShadingType;
// all about projections
//mUberShader->UpdateDepthDisplacement( pProjTex->DepthDisplacement );
/*
double useRim, rimPower;
FBColor rimColor;
pProjTex->UseRim.GetData( &useRim, sizeof(double) );
pProjTex->RimColor.GetData( rimColor, sizeof(FBColor) );
pProjTex->RimPower.GetData( &rimPower, sizeof(double) );
mUberShader->UpdateRimParameters( 0.01 * (float)useRim, 0.01 * (float)rimPower,
(pProjTex->RimTexture.GetCount()>0),
vec4( (float)rimColor[0], (float)rimColor[1], (float)rimColor[2], (float) pProjTex->RimBlend.AsInt() ) );
*/
if (eShadingTypeMatte == shadingType)
{
//mGPUFBScene->BindBackgroundTexture();
}
else
{
// rim lighting
if (pProjTex->RimTexture.GetCount() > 0)
{
GLuint rimId = 0;
FBTexture *pTexture = (FBTexture*) pProjTex->RimTexture.GetAt(0);
//pTexture->OGLInit();
rimId = pTexture->TextureOGLId;
if (0 == rimId)
{
glActiveTexture(GL_TEXTURE0);
pTexture->OGLInit();
rimId = pTexture->TextureOGLId;
}
mGPUFBScene->BindRimTexture(rimId);
}
// lighting or MatCap baked light
if ( (false == pProjTex->UseSceneLights && pProjTex->AffectingLights.GetCount() > 0)
&& (eShadingTypeDynamic == shadingType || eShadingTypeToon == shadingType) )
{
mGPUFBScene->BindLights( false, pProjTex->GetShaderLightsPtr() );
hasExclusiveLights = true;
}
else if (shadingType == eShadingTypeMatCap && pProjTex->MatCap.GetCount() > 0)
{
GLuint matCapId = 0;
FBTexture *pTexture = (FBTexture*) pProjTex->MatCap.GetAt(0);
matCapId = pTexture->TextureOGLId;
if (0 == matCapId)
{
glActiveTexture(GL_TEXTURE0);
pTexture->OGLInit();
matCapId = pTexture->TextureOGLId;
}
mGPUFBScene->BindMatCapTexture(matCapId);
FBVector3d rotation = pTexture->Rotation;
mShaderFX->SetMatCapRotation(rotation[2] / 180.0 * 3.1415);
}
}
// Bind Projective Data was here !
//
hasProjectors = (true == textureMapping && (shadingType != eShadingTypeMatte) );
mFXProjectionBinded = false;
if (hasProjectors)
hasProjectors = mGPUFBScene->BindProjectors( pProjTex->GetProjectorsPtr(), muteTextureId );
if (pProjTex->UsePolygonOffset)
{
double factor = pProjTex->PolygonOffsetFactor;
double units = pProjTex->PolygonOffsetUnits;
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset( (float) factor, (float) units );
}
// support for composite masks
/*
vec4 mask;
mask.x = (pProjTex->CompositeMaskA) ? 1.0f : 0.0f;
mask.y = (pProjTex->CompositeMaskB) ? 1.0f : 0.0f;
mask.z = (pProjTex->CompositeMaskC) ? 1.0f : 0.0f;
mask.w = (pProjTex->CompositeMaskD) ? 1.0f : 0.0f;
mUberShader->UpdateShaderMask( mask );
*/
}
void CProjTexBindedCallback::OnInstanceEnd(const CRenderOptions &options, FBShader *pShader, CBaseShaderInfo *pInfo)
{
const ERenderGoal goal = options.GetGoal();
if (eRenderGoalSelectionId != goal && eRenderGoalShadows != goal)
{
InternalInstanceEnd();
}
}
void CProjTexBindedCallback::InternalInstanceEnd()
{
if (nullptr == mShaderFX)
return;
if (FBIS(mShader, ProjTexShader))
{
ProjTexShader *projTex = (ProjTexShader*) mShader;
if (hasProjectors)
projTex->mProjectors.UnBind();
if (hasExclusiveLights)
mGPUFBScene->BindLights(false);
if (projTex->UsePolygonOffset)
{
glDisable(GL_POLYGON_OFFSET_FILL);
}
}
//FetchCullMode(mCullFaceInfo);
}
// model sub-mesh has a material assigned
bool CProjTexBindedCallback::OnMaterialBegin(const CRenderOptions &options, FBRenderOptions *pRenderOptions, FBMaterial *pMaterial, bool forceInit)
{
// TODO: check for the last material, to not bind the same thing !
const ERenderGoal goal = options.GetGoal();
if (eRenderGoalSelectionId != goal && eRenderGoalShadows != goal && true == options.IsTextureMappingEnable() )
{
BindMaterialTextures(pMaterial, pRenderOptions, options.GetMutedTextureId(), forceInit );
}
return true;
}
void CProjTexBindedCallback::OnMaterialEnd(const CRenderOptions &options, FBMaterial *pMaterial)
{
}
bool CProjTexBindedCallback::OnModelDraw(const CRenderOptions &options, FBRenderOptions *pFBRenderOptions, FBModel *pModel, CBaseShaderInfo *pInfo)
{
if (nullptr == mShaderFX)
return false;
// TODO: bind model sprite sheet property values !
// TODO: bind model cull mode
const ERenderGoal goal = options.GetGoal();
if (eRenderGoalSelectionId != goal && eRenderGoalShadows != goal)
{
InternalModelDraw(options, pModel, options.IsTextureMappingEnable(), options.GetMutedTextureId() );
// support for sprite sheets
FBPropertyAnimatable *pAnimProp = (FBPropertyAnimatable*) pModel->PropertyList.Find( "SpriteSheet Translation" );
if (pAnimProp)
{
FBVector3d v;
pAnimProp->GetData(v, sizeof(double)*3);
mShaderFX->UpdateTextureOffset( vec4( (float)v[0], (float)v[1], (float)v[2], 0.0) );
pAnimProp = (FBPropertyAnimatable*) pModel->PropertyList.Find( "SpriteSheet Scaling" );
if (pAnimProp)
{
pAnimProp->GetData(v, sizeof(double)*3);
mShaderFX->UpdateTextureScaling( vec4( (float)v[0], (float)v[1], (float)v[2], 0.0) );
}
}
else
{
mShaderFX->UpdateTextureOffset( vec4( 0.0, 0.0, 0.0, 0.0) );
mShaderFX->UpdateTextureScaling( vec4( 1.0, 1.0, 1.0, 1.0) );
}
}
return true;
}
void CProjTexBindedCallback::InternalModelDraw(const CRenderOptions &options, FBModel *pModel, const bool textureMapping, const GLuint muteTextureId)
{
EShadingType newShadingType = ( (ProjTexShader*) mShader)->ShadingType;
bool binded = false;
const CProjectors *newProjectors = nullptr;
const int numberOfShaders = pModel->Shaders.GetCount();
for (int i=1; i<numberOfShaders; ++i)
{
FBShader *pShader = pModel->Shaders[i];
if (false == pShader->Enable)
continue;
if ( FBIS(pShader, FXProjectionMapping) )
{
//( (ProjTexShader*) mShader)->mProjectors.UnBind();
//UnBindProjectionMapping();
mLastFXShader = (FXProjectionMapping*) pShader;
newProjectors = mLastFXShader->GetProjectorsPtr();
if (newProjectors->GetNumberOfProjectors() > 0)
{
binded = true;
mFXProjectionBinded = true;
}
else
{
mLastFXShader = nullptr;
newProjectors = nullptr;
mFXProjectionBinded = false;
}
//!!! Support only one projections override
//break;
}
else if ( FBIS(pShader, FXShadingShader) )
{
newShadingType = ( (FXShadingShader*) pShader)->ShadingType;
}
}
if (true == textureMapping)
{
// don't bind the same texture, check for changes
if (eShadingTypeMatte == newShadingType)
{
//mGPUFBScene->BindBackgroundTexture();
}
if (binded && nullptr != newProjectors)
{
mGPUFBScene->BindProjectors( newProjectors, muteTextureId );
}
else if (!binded && mFXProjectionBinded)
{
if (mLastFXShader)
{
//mLastFXShader->mProjectors.UnBind();
mLastFXShader = nullptr;
mFXProjectionBinded = false;
hasProjectors = mGPUFBScene->BindProjectors( ( (ProjTexShader*) mShader)->GetProjectorsPtr(), muteTextureId );
}
}
}
// support for cullmode
// TODO: check for the latest cullmode to not set the same thing !
const FBModelCullingMode cullMode = pModel->GetCullingMode();
if (cullMode != options.GetLastCullingMode())
{
switch(cullMode)
{
case kFBCullingOff:
glDisable(GL_CULL_FACE);
break;
case kFBCullingOnCW:
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
break;
case kFBCullingOnCCW:
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
break;
}
//mLastCullingMode = cullMode;
((CRenderOptions&)options).SetLastCullingMode(cullMode);
}
}
// executed one time per rendering frame (to setup gpu buffers, update data, etc.)
void CProjTexBindedCallback::PrepareInstance(const CRenderOptions &options, FBShader *pShader)
{
mShader = pShader;
if (nullptr == mShader || false == mShader->Enable )
return;
// const unsigned int uniqueFrameId = options.GetUniqueFrameId();
if (FBIS(mShader, ProjTexShader) )
{
ProjTexShader *pProjTex = (ProjTexShader*) mShader;
// TODO: update only on changes, NOT EACH FRAME !!!
// update only once, could be assigned to many models !
pProjTex->EventBeforeRenderNotify();
/*
if ( true == options.IsTextureMappingEnable()
&& true == pProjTex->DynamicUpdate
&& uniqueFrameId > pProjTex->mLastUniqueFrameId )
{
pProjTex->mProjectors.Prep( pProjTex );
pProjTex->mLastUniqueFrameId = uniqueFrameId;
//DoManualUpdate();
}
*/
}
else if (FBIS(pShader, FXProjectionMapping) )
{
mLastFXShader = (FXProjectionMapping*) pShader;
mLastFXShader->EventBeforeRenderNotify();
}
}
void CProjTexBindedCallback::PrepareModel(const CRenderOptions &options, FBModel *pModel, FBShader *pShader)
{
// const unsigned int uniqueFrameId = options.GetUniqueFrameId();
// check if we should update FX shader here as well
// TODO: update only once (could be assigned to many of models)
/*
const int numberOfShaders = pModel->Shaders.GetCount();
for (int i=0; i<numberOfShaders; ++i)
{
FBShader *pShader = pModel->Shaders[i];
if ( pShader->Enable && FBIS(pShader, FXProjectionMapping) )
{
mLastFXShader = (FXProjectionMapping*) pShader;
if (uniqueFrameId > mLastFXShader->mLastUniqueFrameId)
{
mLastFXShader->mProjectors.Prep(mLastFXShader);
mLastFXShader->mLastUniqueFrameId = uniqueFrameId;
}
}
}
*/
/*
FBModelVertexData *pData = pModel->ModelVertexData;
if (nullptr != pData)
{
if (false == pData->IsDrawable() )
{
pData->VertexArrayMappingRelease();
//pData->EnableOGLVertexData();
//pData->DisableOGLVertexData();
}
}
*/
}
/////////////////////////////////////////////////////////////////////////////////
// ProjTex binded info
void CProjTexBindedInfo::EventBeforeRenderNotify()
{
if (mNeedUpdateLightsList)
{
ProjTexShader *pProjTex = (ProjTexShader*) mShader;
mGPUFBScene->PrepShaderLights( pProjTex->UseSceneLights,
&pProjTex->AffectingLights, mLightsPtr, mShaderLights.get() );
mNeedUpdateLightsList = false;
}
}
void CProjTexBindedInfo::EventConnNotify(HISender pSender, HKEvent pEvent)
{
FBEventConnectionNotify lEvent(pEvent);
FBConnectionAction pAction = lEvent.Action;
FBPlug *pThis = lEvent.SrcPlug;
//FBPlug *pPlug = lEvent.DstPlug;
ProjTexShader *pProjTex = (ProjTexShader*) mShader;
if (pThis == &pProjTex->AffectingLights)
{
if (pAction == kFBConnectedSrc)
{
//pProjTex->ConnectSrc(pPlug);
UpdateLightsList();
}
else if (pAction == kFBDisconnectedSrc)
{
//pProjTex->DisconnectSrc(pPlug);
UpdateLightsList();
}
}
} | 26.641221 | 153 | 0.70745 | Neill3d |
cc50edbbb18ed86eca9e9afe840b6e7d08af8473 | 2,403 | cpp | C++ | 3]. Competitive Programming/05]. HackerEarth/1]. Practice/5]. Code Monk Series/06]. Check Point - 1/Little Monk and Balanced Parentheses.cpp | Utqrsh04/The-Complete-FAANG-Preparation | a0a4a6ef8768d047f4c2d7b8553732364a26e08e | [
"MIT"
] | 6,969 | 2021-05-29T11:38:30.000Z | 2022-03-31T19:31:49.000Z | 3]. Competitive Programming/05]. HackerEarth/1]. Practice/5]. Code Monk Series/06]. Check Point - 1/Little Monk and Balanced Parentheses.cpp | thisisbillall/The-Complete-FAANG-Preparation | b0c761e2ceb08c92c3b62d7c00b6e8835653cb6e | [
"MIT"
] | 75 | 2021-06-15T07:59:43.000Z | 2022-02-22T14:21:52.000Z | 3]. Competitive Programming/05]. HackerEarth/1]. Practice/5]. Code Monk Series/06]. Check Point - 1/Little Monk and Balanced Parentheses.cpp | thisisbillall/The-Complete-FAANG-Preparation | b0c761e2ceb08c92c3b62d7c00b6e8835653cb6e | [
"MIT"
] | 1,524 | 2021-05-29T16:03:36.000Z | 2022-03-31T17:46:13.000Z |
/*
Solution by Rahul Surana
***********************************************************
Given an array of positive and negative integers, denoting different types of parentheses.
The positive numbers xi denotes opening parentheses of type xi and negative number -xi denotes closing parentheses of type xi.
Open parentheses must be closed by the same type of parentheses. Open parentheses must be closed in the correct order, i.e.,
never close an open pair before its inner pair is closed (if it has an inner pair). Thus, [1,2,-2,-1] is balanced, while [1,2,-1,-2] is not balanced.
You have to find out the length of the longest subarray that is balanced.
Input Format:
First line contains an input N (1 <= N <= 2*10^5), denoting the number of parentheses.
Second line contains N space separated integers. xi (-10^5 <= xi <= 10^5, xi != 0) denoting the ith parentheses of the array.
Output Format:
Print the length of the longest subarray that is balanced.
***********************************************************
*/
#include <bits/stdc++.h>
#define ll long long
#define vl vector<ll>
#define vi vector<int>
#define pi pair<int,int>
#define pl pair<ll,ll>
#define all(a) a.begin(),a.end()
#define mem(a,x) memset(a,x,sizeof(a))
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define FOR(i,a) for(int i = 0; i < a; i++)
#define trace(x) cerr<<#x<<" : "<<x<<endl;
#define trace2(x,y) cerr<<#x<<" : "<<x<<" | "<<#y<<" : "<<y<<endl;
#define trace3(x,y,z) cerr<<#x<<" : "<<x<<" | "<<#y<<" : "<<y<<" | "<<#z<<" : "<<z<<endl;
#define fast_io std::ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
#define MOD 1000000007
using namespace std;
int ar[200000];
int main()
{
fast_io;
int n;
cin >> n;
mem(ar,0);
FOR(i,n) cin >> ar[i];
stack<int> st;
int c = 0,mx = 0;
int bc = 0;
FOR(i,n) {
if(ar[i] > 0) { st.push(i); }
else {
if(!st.empty() && ar[i] == -ar[st.top()]) {
st.pop();
int x;
if(st.empty()) x = -1;
else x = st.top();
c = i-x;
if(c > mx) mx = c;
}
else {
st.push(i);
}
}
}
cout << mx;
} | 30.417722 | 149 | 0.523096 | Utqrsh04 |
cc546e5155e60885bab5412fe212be512930dd84 | 428 | cpp | C++ | COS1511/Part2/Lesson11/a.cpp | GalliWare/UNISA-studies | 32bab94930b176c4dfe943439781ef102896fab5 | [
"Unlicense"
] | null | null | null | COS1511/Part2/Lesson11/a.cpp | GalliWare/UNISA-studies | 32bab94930b176c4dfe943439781ef102896fab5 | [
"Unlicense"
] | null | null | null | COS1511/Part2/Lesson11/a.cpp | GalliWare/UNISA-studies | 32bab94930b176c4dfe943439781ef102896fab5 | [
"Unlicense"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
// set constants
const int LOWEST_NUMBER = 10, LARGEST_NUMBER = 20;
// set variables
int number;
bool loop = true;
// as we set loop we can start the loop
while (loop)
{
cout << "Please provide number between 10 and 20: ";
cin >> number;
if (number > LOWEST_NUMBER && number < LARGEST_NUMBER)
{
loop = false;
}
}
return 0;
} | 17.12 | 58 | 0.614486 | GalliWare |
cc57d9e33d0a16a25da90bdd209d1bfb0b63bb8e | 1,843 | cpp | C++ | PAT-A/PATA1114_2.cpp | GRAYCN/Algorithm-notebook | 04fa7b759a797fb47e11bcdd1f8cc7bef297578c | [
"Apache-2.0"
] | 1 | 2019-07-06T10:40:28.000Z | 2019-07-06T10:40:28.000Z | PAT-A/PATA1114_2.cpp | GRAYCN/Algorithm-notebook | 04fa7b759a797fb47e11bcdd1f8cc7bef297578c | [
"Apache-2.0"
] | null | null | null | PAT-A/PATA1114_2.cpp | GRAYCN/Algorithm-notebook | 04fa7b759a797fb47e11bcdd1f8cc7bef297578c | [
"Apache-2.0"
] | null | null | null | //PATA1114_2
//UFS
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define maxn 1005
#define maxm 10005
struct People{
int id,fid,mid,num,area;
int cid[8];
}peo[maxn];
struct Answer{
int id;
double num,area;
int people;
bool flag;
}ans[maxm];
bool visit[maxm];
int father[maxm];
int find(int x){
int a=x;
while(x!=father[x]){
x=father[x];
}
while(a!=father[a]){
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
bool cmp(Answer a,Answer b){
if(a.area!=b.area) return a.area>b.area;
else return a.id<b.id;
}
void Union(int a,int b){
int fa=find(a);
int fb=find(b);
if(fa>fb){
//fb=father[fa];
father[fa]=fb;
}else if(fa<fb){
//fa=father[fb];
father[fb]=fa;
}
}
int main(){
int N,k;
for(int i=0;i<maxm;i++) father[i]=i;
cin>>N;
for(int i=0;i<N;i++){
cin>>peo[i].id>>peo[i].fid>>peo[i].mid>>k;
visit[peo[i].id]=true;
if(peo[i].fid!=-1){
visit[peo[i].fid]=true;
Union(peo[i].id,peo[i].fid);
}
if(peo[i].mid!=-1){
visit[peo[i].mid]=true;
Union(peo[i].id,peo[i].mid);
}
for(int j=0;j<k;j++){
cin>>peo[i].cid[j];
visit[peo[i].cid[j]]=true;
Union(peo[i].id,peo[i].cid[j]);
}
cin>>peo[i].num>>peo[i].area;
}
for(int i=0;i<N;i++){
if(visit[peo[i].id]){
int id=find(peo[i].id);
ans[id].id=id;
// ans[id].people++;
ans[id].num+=peo[i].num;
ans[id].area+=peo[i].area;
ans[id].flag=true;
}
}
for(int i=0;i<maxm;i++){
if(visit[i]){
int id=find(i);
ans[id].people++;
}
}
int cnt=0;
for(int i=0;i<maxm;i++){
if(ans[i].flag==true){
cnt++;
ans[i].num=(float)(ans[i].num/ans[i].people);
ans[i].area=(float)(ans[i].area/ans[i].people);
}
}
sort(ans,ans+maxm,cmp);
cout<<cnt<<endl;
for(int i=0;i<cnt;i++){
printf("%04d %d %.3f %.3f\n",ans[i].id,ans[i].people,ans[i].num,ans[i].area);
}
}
| 16.908257 | 79 | 0.568095 | GRAYCN |
cc594c7fe0ac6baec44374aaa2b6c78069fa0d01 | 1,402 | cc | C++ | source/common/rds/rds_route_config_provider_impl.cc | fishy/envoy | 2757eb9eb0faece7b2779f7c1e21953b31b836f4 | [
"Apache-2.0"
] | 1 | 2022-03-02T14:23:12.000Z | 2022-03-02T14:23:12.000Z | source/common/rds/rds_route_config_provider_impl.cc | fishy/envoy | 2757eb9eb0faece7b2779f7c1e21953b31b836f4 | [
"Apache-2.0"
] | 153 | 2021-10-04T04:32:48.000Z | 2022-03-31T04:22:40.000Z | source/common/rds/rds_route_config_provider_impl.cc | fishy/envoy | 2757eb9eb0faece7b2779f7c1e21953b31b836f4 | [
"Apache-2.0"
] | 1 | 2021-12-14T02:39:44.000Z | 2021-12-14T02:39:44.000Z | #include "source/common/rds/rds_route_config_provider_impl.h"
namespace Envoy {
namespace Rds {
RdsRouteConfigProviderImpl::RdsRouteConfigProviderImpl(
RdsRouteConfigSubscriptionSharedPtr&& subscription,
Server::Configuration::ServerFactoryContext& factory_context)
: subscription_(std::move(subscription)),
config_update_info_(subscription_->routeConfigUpdate()), tls_(factory_context.threadLocal()) {
auto initial_config = config_update_info_->parsedConfiguration();
ASSERT(initial_config);
tls_.set([initial_config](Event::Dispatcher&) {
return std::make_shared<ThreadLocalConfig>(initial_config);
});
// It should be 1:1 mapping due to shared rds config.
ASSERT(!subscription_->routeConfigProvider().has_value());
subscription_->routeConfigProvider().emplace(this);
}
RdsRouteConfigProviderImpl::~RdsRouteConfigProviderImpl() {
ASSERT(subscription_->routeConfigProvider().has_value());
subscription_->routeConfigProvider().reset();
}
const absl::optional<RouteConfigProvider::ConfigInfo>&
RdsRouteConfigProviderImpl::configInfo() const {
return config_update_info_->configInfo();
}
void RdsRouteConfigProviderImpl::onConfigUpdate() {
tls_.runOnAllThreads([new_config = config_update_info_->parsedConfiguration()](
OptRef<ThreadLocalConfig> tls) { tls->config_ = new_config; });
}
} // namespace Rds
} // namespace Envoy
| 35.948718 | 100 | 0.767475 | fishy |
cc59b3943685661b889fd0d4141b3aee2643586b | 2,424 | inl | C++ | src/vendor/mariadb-10.6.7/storage/innobase/include/fil0crypt.inl | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/innobase/include/fil0crypt.inl | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/innobase/include/fil0crypt.inl | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | 2 | 2022-02-27T14:00:01.000Z | 2022-03-31T06:24:22.000Z | /*****************************************************************************
Copyright (c) 2015, 2017, MariaDB Corporation.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
*****************************************************************************/
/**************************************************//**
@file include/fil0crypt.ic
The low-level file system encryption support functions
Created 04/01/2015 Jan Lindström
*******************************************************/
/*******************************************************************//**
Find out whether the page is page encrypted
@return true if page is page encrypted, false if not */
UNIV_INLINE
bool
fil_page_is_encrypted(
/*==================*/
const byte *buf) /*!< in: page */
{
return(mach_read_from_4(buf+FIL_PAGE_FILE_FLUSH_LSN_OR_KEY_VERSION) != 0);
}
/*******************************************************************//**
Get current encryption mode from crypt_data.
@return string representation */
UNIV_INLINE
const char *
fil_crypt_get_mode(
/*===============*/
const fil_space_crypt_t* crypt_data)
{
switch (crypt_data->encryption) {
case FIL_ENCRYPTION_DEFAULT:
return("Default tablespace encryption mode");
case FIL_ENCRYPTION_ON:
return("Tablespace encrypted");
case FIL_ENCRYPTION_OFF:
return("Tablespace not encrypted");
}
ut_error;
return ("NULL");
}
/*******************************************************************//**
Get current encryption type from crypt_data.
@return string representation */
UNIV_INLINE
const char *
fil_crypt_get_type(
const fil_space_crypt_t* crypt_data)
{
ut_ad(crypt_data != NULL);
switch (crypt_data->type) {
case CRYPT_SCHEME_UNENCRYPTED:
return("scheme unencrypted");
break;
case CRYPT_SCHEME_1:
return("scheme encrypted");
break;
default:
ut_error;
}
return ("NULL");
}
| 29.560976 | 78 | 0.606436 | zettadb |
cc5c176217bad9eea703faeea08e8da56812d72c | 13,573 | cpp | C++ | windows/c++/visualstudio/src/WorkerManager.cpp | afskylia/bachelor-starcraft-bot | e9d53345d77f6243f5a2db1781cdfcb7838ebcfd | [
"MIT"
] | null | null | null | windows/c++/visualstudio/src/WorkerManager.cpp | afskylia/bachelor-starcraft-bot | e9d53345d77f6243f5a2db1781cdfcb7838ebcfd | [
"MIT"
] | 2 | 2021-06-27T18:57:39.000Z | 2021-06-27T18:57:52.000Z | windows/c++/visualstudio/src/WorkerManager.cpp | afskylia/bachelor-starcraft-bot | e9d53345d77f6243f5a2db1781cdfcb7838ebcfd | [
"MIT"
] | null | null | null | #include "WorkerManager.h"
#include <BWAPI/Client/Client.h>
#include "Global.h"
#include "BWEM/src/bwem.h"
#include "Tools.h"
using namespace MiraBot;
WorkerManager::WorkerManager()
{
}
void WorkerManager::onFrame()
{
// Update workers, e.g. set job as 'Idle' when job completed
updateWorkerStatus();
// Send idle workers to gather resources
activateIdleWorkers();
// Send out a new scout if needed
if (BWAPI::Broodwar->getFrameCount() % 7919 == 0 && should_have_new_scout)
{
auto* new_scout = getAnyWorker();
m_workerData.setWorkerJob(new_scout, WorkerData::Scout, scout_last_known_position);
should_have_new_scout = false;
}
if (lateScout)
{
// Hotfix
while (Global::combat().m_attack_units.size() > 30 && m_workerData.getWorkers(WorkerData::Repair).size() < 6)
{
if (m_workerData.getWorkers(WorkerData::Minerals).size() <= 40) break;
std::cout << "Making late game scout\n";
m_workerData.setLateGameScout(getAnyWorker());
}
}
}
void WorkerManager::updateWorkerStatus()
{
for (const auto& worker : m_workerData.getWorkers())
{
const auto job = m_workerData.getWorkerJob(worker);
if (!worker->isCompleted()) continue;
// Workers can be idle for various reasons, e.g. a builder waiting to build
if (worker->isIdle() || job == WorkerData::Scout && worker->isStuck()
)
{
switch (job)
{
case WorkerData::Build:
{
/* Builder is idle when it has reached the build location and is waiting to build,
* or it has gotten stuck along the way*/
handleIdleBuildWorker(worker);
break;
}
case WorkerData::Scout:
{
// Scout is idle when it has reached its current scouting target
handleIdleScout(worker);
break;
}
case WorkerData::Repair:
{
auto random_pos = Global::map().map.RandomPosition();
auto pos = BWAPI::Position(Global::production().m_building_placer_.getBuildLocationNear(
BWAPI::TilePosition(random_pos), BWAPI::UnitTypes::Protoss_Nexus));
worker->move(pos);
break;
}
case WorkerData::Move:
{
// Mover is idle when it has reached its destination
break;
}
default:
{
if (!getWorkerScout() && getScoutPosition(worker)) setScout(worker);
else m_workerData.setWorkerJob(worker, WorkerData::Idle, nullptr);
}
}
}
}
}
void WorkerManager::setScout(BWAPI::Unit unit)
{
m_workerData.setWorkerJob(unit, WorkerData::Scout, getScoutPosition(unit));
}
// Assign jobs to idle workers
// TODO: 2 workers per mineral patch is optimal
// TODO: Look at total minerals and gas - e.g. maybe we have plenty of gas but no minerals
void WorkerManager::activateIdleWorkers()
{
const auto mineral_worker_count = m_workerData.getWorkers(WorkerData::Minerals).size();
const auto gas_worker_count = m_workerData.getWorkers(WorkerData::Gas).size();
for (auto& worker : m_workerData.getWorkers())
{
if (m_workerData.getWorkerJob(worker) == WorkerData::Idle)
{
const auto refinery_type = BWAPI::Broodwar->self()->getRace().getRefinery();
const auto refinery_count = Tools::countUnitsOfType(refinery_type);
// We don't want more than 3 gas workers per refinery
if (refinery_count > 0 && gas_worker_count < mineral_worker_count / 4
&& gas_worker_count < Tools::countUnitsOfType(refinery_type) * 4)
setGasWorker(worker);
else setMineralWorker(worker);
}
}
}
void WorkerManager::setMineralWorker(BWAPI::Unit unit)
{
BWAPI::Unit closestDepot = getClosestDepot(unit);
if (closestDepot)
{
m_workerData.setWorkerJob(unit, WorkerData::Minerals, closestDepot);
}
}
void WorkerManager::setGasWorker(BWAPI::Unit unit)
{
BWAPI::Unit closestDepot = getClosestDepot(unit);
if (closestDepot)
{
m_workerData.setWorkerJob(unit, WorkerData::Gas, closestDepot);
}
}
void WorkerManager::setBuildingWorker(BWAPI::Unit unit, WorkerData::BuildJob buildJob)
{
m_workerData.setWorkerJob(unit, WorkerData::Build, buildJob);
}
void WorkerManager::onUnitComplete(BWAPI::Unit unit)
{
if (!unit->getType().isWorker()) return;
updateWorkerCounts();
m_workerData.addWorker(unit, WorkerData::Idle, nullptr);
}
void WorkerManager::onUnitDestroy(BWAPI::Unit unit)
{
m_workerData.workerDestroyed(unit);
}
void WorkerManager::updateWorkerCounts()
{
auto num_patches = 0;
auto num_geysers = 0;
for (const auto* base : Global::map().expos)
{
num_patches += base->Minerals().size();
num_geysers += base->Geysers().size();
}
//max_workers = num_patches * 3 + m_workerData.getWorkers(WorkerData::Scout).size() + 5;
max_workers = 65;
}
void WorkerManager::sendScouts(int num)
{
}
BWAPI::Unit WorkerManager::getClosestDepot(BWAPI::Unit worker)
{
BWAPI::Unit closestDepot = nullptr;
double closestDistance = 0;
for (auto& unit : BWAPI::Broodwar->self()->getUnits())
{
if (unit->getType().isResourceDepot() && unit->isCompleted())
{
const double distance = unit->getDistance(worker);
if (!closestDepot || distance < closestDistance)
{
closestDepot = unit;
closestDistance = distance;
}
}
}
return closestDepot;
}
// Returns next scouting location for scout, favoring closest locations
BWAPI::Position WorkerManager::getScoutPosition(BWAPI::Unit scout)
{
// if we found enemy, we don't have more positions
//if (Global::information().enemy_start_location) return BWAPI::Positions::None;
auto& startLocations = BWAPI::Broodwar->getStartLocations();
BWAPI::Position closestPosition = BWAPI::Positions::None;
double closestDistance = 0;
for (BWAPI::TilePosition position : startLocations)
{
auto pos = BWAPI::Position(position);
if (!BWAPI::Broodwar->isExplored(position) || (Global::map().lastSeen(position) > 5000 && !BWAPI::Broodwar->
isVisible(position)))
{
const BWAPI::Position pos(position);
const double distance = scout->getDistance(pos);
if (!closestPosition || distance < closestDistance)
{
closestPosition = pos;
closestDistance = distance;
}
}
}
return closestPosition;
}
// Returns the scout
BWAPI::Unit WorkerManager::getWorkerScout()
{
for (auto& worker : m_workerData.getWorkers())
{
if (!worker) continue;
if (m_workerData.getWorkerJob(worker) == WorkerData::Scout)
{
return worker;
}
}
return nullptr;
}
// Looks through mineral workers and returns the closest candidate to given position
BWAPI::Unit WorkerManager::getBuilder(BWAPI::UnitType type, BWAPI::Position pos)
{
BWAPI::Unit closestUnit = nullptr;
auto unitSet = m_workerData.getWorkers(WorkerData::Minerals);
for (auto& unit : unitSet)
{
// If worker isn't of required type or hasn't been trained yet, continue
if (!(unit->getType() == type && unit->isCompleted())) continue;
// Set initially closest worker
if (!closestUnit)
{
closestUnit = unit;
continue;
}
// If position doesn't matter, use the first found candidate
if (pos == BWAPI::Positions::None) break;
// Check if this unit is closer to the position than closestUnit
if (closestUnit->getDistance(pos) > unit->getDistance(pos))
{
closestUnit = unit;
}
}
// Return the closest worker, or nullptr if none was found
return closestUnit;
}
// Returns a worker: used when you just need a worker asap
BWAPI::Unit WorkerManager::getAnyWorker(BWAPI::Position pos)
{
// Prioritized job order: Prefers Idle, Default, Minerals, ..., Combat, Repair
for (auto& job : m_workerData.prioritized_jobs)
{
const auto workers = m_workerData.getWorkers(job);
if (workers.empty()) continue;
// If position doesn't matter, use first found candidate
if (pos == BWAPI::Positions::None)
{
for (auto& unit : workers) return unit;
}
// Return closest candidate
auto sorted_workers = Tools::sortUnitsByClosest(pos, workers);
return sorted_workers[0];
}
return nullptr;
}
// Handles a build-worker who is idling
void WorkerManager::handleIdleBuildWorker(BWAPI::Unit worker)
{
// Get build job assigned to worker
const auto building_type = m_workerData.m_workerBuildingTypeMap[worker];
auto building_pos = m_workerData.m_buildPosMap[worker];
auto initiatedBuilding = m_workerData.m_initiatedBuildingMap[worker];
if (building_type == BWAPI::UnitTypes::Protoss_Nexus)
{
int i = 0;
}
// If worker idling because build job is completed, set job to idle
if (initiatedBuilding && !worker->isConstructing())
{
if (Tools::getUnitsOfType(building_type, false, false).empty())
{
}
else
{
m_workerData.setWorkerJob(worker, WorkerData::Idle, nullptr);
return;
}
}
if (building_type == BWAPI::UnitTypes::None || worker->isConstructing())
{
}
// Otherwise, worker is idling because it is waiting for the required resources
if (building_type.mineralPrice() > 0 && building_type.mineralPrice() + 10 > BWAPI::Broodwar->self()->minerals())
return;
if (building_type.gasPrice() > 0 && building_type.gasPrice() + 10 > BWAPI::Broodwar->self()->gas()) return;
// Check build position validity
auto canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker);
if (!canbuild)
{
if (building_pos != BWAPI::TilePositions::None)
{
building_pos = Global::production().m_building_placer_.getBuildLocationNear(building_pos, building_type);
canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker);
if (canbuild)
{
goto sup;
}
}
// First attempt: Build position based on builder position
building_pos = Global::production().m_building_placer_.getBuildLocationNear(
worker->getTilePosition(), building_type);
canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker);
if (canbuild)
{
goto sup;
}
// Second attempt: Build position using built-in StarCraft building placer
building_pos = BWAPI::Broodwar->getBuildLocation(building_type, worker->getTilePosition(), 400);
canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker);
if (canbuild)
{
goto sup;
}
// Final attempt: Get any damn build position
building_pos = Global::production().m_building_placer_.getBuildLocation(building_type);
canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker);
if (canbuild)
{
goto sup;
}
m_workerData.setWorkerJob(worker, WorkerData::Idle, nullptr);
return;
}
sup:
// Try to place the building and generate new position if the first one fails
bool built = worker->build(building_type, building_pos);
if (!built)
{
std::cout << "Failed to build " << building_type.getName() << "\n";
m_workerData.setWorkerJob(worker, WorkerData::Idle, nullptr);
return;
}
// Used in the beginning of the function next frame
//m_workerData.m_workerBuildingTypeMap[worker] = BWAPI::UnitTypes::None;
m_workerData.m_initiatedBuildingMap[worker] = true;
//BWAPI::Broodwar->printf("Building %s", building_type.getName().c_str());
}
// Send worker to unexplored scout position
void WorkerManager::handleIdleScout(BWAPI::Unit worker)
{
const auto scout_position = getScoutPosition(worker);
if (!scout_position)
{
auto enemy_area = Global::map().map.GetNearestArea(Global::information().enemy_start_location);
auto top_right = BWAPI::Position(BWAPI::TilePosition(enemy_area->BottomRight().x, enemy_area->TopLeft().y));
auto bottom_left = BWAPI::Position(BWAPI::TilePosition(enemy_area->TopLeft().x, enemy_area->BottomRight().y));
auto top_left = BWAPI::Position(enemy_area->TopLeft());
auto bottom_right = BWAPI::Position(enemy_area->BottomRight());
auto go_to_pos = top_left;
// All starting positions have been explored
// If worker is away from enemy base keep going in and out
if (top_left.getApproxDistance(worker->getPosition()) <= 400)
{
go_to_pos = top_right;
}
else if (top_right.getApproxDistance(worker->getPosition()) <= 400)
{
go_to_pos = bottom_right;
}
else if (bottom_right.getApproxDistance(worker->getPosition()) <= 400)
{
go_to_pos = bottom_left;
}
else if (bottom_left.getApproxDistance(worker->getPosition()) <= 400)
{
go_to_pos = top_left;
}
m_workerData.setWorkerJob(worker, WorkerData::Scout,
BWAPI::Position(BWAPI::WalkPosition(go_to_pos)));
}
else
{
// Set scout's new target position
m_workerData.setWorkerJob(worker, WorkerData::Scout, scout_position);
}
}
// Returns a vector of all active (=unfinished) build jobs
std::vector<WorkerData::BuildJob> WorkerManager::getActiveBuildJobs()
{
std::vector<WorkerData::BuildJob> build_jobs;
auto builders = m_workerData.getWorkers(WorkerData::Build);
for (const auto& unit : builders)
{
auto unit_building_type = m_workerData.m_workerBuildingTypeMap[unit];
if (unit_building_type == BWAPI::UnitTypes::None) continue;
// TODO: safer way to check map, this can cause exceptions - use find instead
auto build_job = WorkerData::BuildJob{m_workerData.m_buildPosMap[unit], unit_building_type};
build_jobs.push_back(build_job);
}
return build_jobs;
}
// Returns a vector of active (=unfinished) build jobs of given unit type
std::vector<WorkerData::BuildJob> WorkerManager::getActiveBuildJobs(BWAPI::UnitType unit_type)
{
std::vector<WorkerData::BuildJob> build_jobs;
auto builders = m_workerData.getWorkers(WorkerData::Build);
for (const auto& unit : builders)
{
// If unit has build job for this unit type, add to vector
const auto it = m_workerData.m_workerBuildingTypeMap.find(unit);
if (it != m_workerData.m_workerBuildingTypeMap.end() && it->second == unit_type)
{
auto build_job = WorkerData::BuildJob{m_workerData.m_buildPosMap[unit], unit_type};
build_jobs.push_back(build_job);
}
}
return build_jobs;
}
| 29.002137 | 113 | 0.719959 | afskylia |
cc5cc401a2e71fc0ab458087c6a939940671fadf | 812 | cc | C++ | src/Vec3.cc | alexander-koch/airfoil | 4c7afa81d6166b463de6afde5c2d491226fffa52 | [
"MIT"
] | null | null | null | src/Vec3.cc | alexander-koch/airfoil | 4c7afa81d6166b463de6afde5c2d491226fffa52 | [
"MIT"
] | null | null | null | src/Vec3.cc | alexander-koch/airfoil | 4c7afa81d6166b463de6afde5c2d491226fffa52 | [
"MIT"
] | null | null | null | #include "Vec3.hpp"
Vec3 Vec3::operator+(Vec3 v2) {
return Vec3(x + v2.x, y + v2.y, z + v2.z);
}
void Vec3::operator+=(Vec3 v2) {
x += v2.x;
y += v2.y;
z += v2.z;
}
Vec3 Vec3::operator*(double f) {
return Vec3(x * f, y * f, z * f);
}
Vec3 Vec3::operator-(Vec3 v2) {
return Vec3(x - v2.x, y - v2.y, z - v2.z);
}
Vec3 Vec3::cross(Vec3 v2) {
return Vec3(
y * v2.z - v2.y * z,
z * v2.x - v2.z * x,
x * v2.y - v2.x * y);
}
double Vec3::dot(Vec3 v2) {
return x * v2.x + y * v2.y + z * v2.z;
}
double Vec3::length() {
return sqrt(dot(*this));
}
Vec3 Vec3::normalize() {
double len = length();
return Vec3(x / len, y / len, z / len);
}
Vec3 Vec3::zero() {
return Vec3(0.0, 0.0, 0.0);
}
Vec3 Vec3::up() {
return Vec3(0.0, 0.0, 1.0);
}
| 16.916667 | 46 | 0.5 | alexander-koch |
7fe7ce4dda7d7f0e2b562fe539c2e264ad229ee8 | 905 | cpp | C++ | main.cpp | birdiFVZ/neuralNetwork | 4e1eeb5a2641feff9a6b71c83cb7c09de499c50d | [
"MIT"
] | null | null | null | main.cpp | birdiFVZ/neuralNetwork | 4e1eeb5a2641feff9a6b71c83cb7c09de499c50d | [
"MIT"
] | null | null | null | main.cpp | birdiFVZ/neuralNetwork | 4e1eeb5a2641feff9a6b71c83cb7c09de499c50d | [
"MIT"
] | null | null | null | #include <iostream>
#include "src/MyMatrix.h"
#include "src/MyNetwork.h"
#include "src/functions.h"
#include "src/MyFile.h"
#include "src/MyBodyData.h"
using namespace std;
int main() {
string trainingPath = "/home/birdi/Schreibtisch/neuralNetwork07022018/data/training.csv";
MyFile trainingFile(trainingPath);
//MyBodyData trainingData(training);
/*
MyMatrix weight(4,4);
MyMatrix biasTraining(10,1);
MyMatrix biasValidation(10,1);
MyMatrix biasTest(10,1);
biasTraining.fill(1);
biasValidation.fill(1);
biasTest.fill(1);
weight.fillRandomize(0,0.5);
MyNetwork network;
network.set("weight", weight);
network.set("biasTrainig", biasTraining);
network.set("biasValidation", biasValidation);
network.set("biasTest", biasTest);
int whileCount = 0;
while(whileCount < 500) {
whileCount++;
}
*/
return 0;
} | 20.568182 | 93 | 0.672928 | birdiFVZ |
7fe89aa59cb2b88b5b6003541db2e75b4dc9a7d5 | 729 | cpp | C++ | libKBEClient/KBEGameSocket.cpp | ypfsoul/kbengine-client-cocos2dx-3.11-MyGame | 3729c4457feaf9540ad5f274b6fe42542b0d9608 | [
"MIT"
] | 3 | 2017-07-23T23:37:34.000Z | 2017-09-22T06:28:34.000Z | libKBEClient/KBEGameSocket.cpp | ypfsoul/kbengine-client-cocos2dx-3.11-MyGame | 3729c4457feaf9540ad5f274b6fe42542b0d9608 | [
"MIT"
] | null | null | null | libKBEClient/KBEGameSocket.cpp | ypfsoul/kbengine-client-cocos2dx-3.11-MyGame | 3729c4457feaf9540ad5f274b6fe42542b0d9608 | [
"MIT"
] | null | null | null | #include "KBEGameSocket.h"
KBEGameSocket::KBEGameSocket()
{
gameSocket = NULL;
}
KBEGameSocket::~KBEGameSocket()
{
releaseSocket();
}
bool KBEGameSocket::connectionServer(const char* ipStr, uint32 port)
{
ip = ipStr;
port = port;
releaseSocket();
createSocket();
if(gameSocket->connect(ip.c_str(), port))
{
return true;
}
return false;
}
void KBEGameSocket::releaseSocket()
{
if (gameSocket)
{
gameSocket->close();
gameSocket->release();
gameSocket = NULL;
}
}
void KBEGameSocket::createSocket()
{
gameSocket = new GameNetClient();
gameSocket->autorelease();
gameSocket->retain();
}
void KBEGameSocket::sendData( char* data ,int size)
{
if (gameSocket)
{
gameSocket->sendData(data,size);
}
}
| 14.877551 | 68 | 0.694102 | ypfsoul |
7fe8f9fdc08a669da9dde582a977bd081cc12df0 | 311 | cpp | C++ | LISTAS/lista_1/q9/q9.cpp | EduFreit4s/Tecnicas-de-Program | 360a2addabe8226b4abc78b26fd6ece0297892f4 | [
"MIT"
] | 5 | 2019-10-03T22:14:13.000Z | 2020-02-18T00:23:55.000Z | LISTAS/lista_1/q9/q9.cpp | EduFreit4s/Tecnicas-de-Program | 360a2addabe8226b4abc78b26fd6ece0297892f4 | [
"MIT"
] | null | null | null | LISTAS/lista_1/q9/q9.cpp | EduFreit4s/Tecnicas-de-Program | 360a2addabe8226b4abc78b26fd6ece0297892f4 | [
"MIT"
] | 2 | 2019-10-24T21:32:53.000Z | 2019-12-05T18:36:56.000Z | #include <iostream>
using namespace std;
string hello(string a){
string b = "olá ";
return b += a;
}
int main() {
string a; // salva nome
cout << "digite seu nome: "; //pede para digitar nome
cin >> a; //coleta nome
cout << hello(a) << endl; // chama a funcao que devolve a resposta
return 0;
} | 17.277778 | 68 | 0.620579 | EduFreit4s |
7fee15b624e398e4620c86ea0754e1f806ab1020 | 26,361 | cpp | C++ | Source/Tests/Replica/SceneSynchronization.cpp | jayrulez/rbfx | 8641813787d558b6e8318c1b8e9da86c0e52f9dc | [
"MIT"
] | 48 | 2016-11-14T00:39:35.000Z | 2018-12-18T16:37:43.000Z | Source/Tests/Replica/SceneSynchronization.cpp | jayrulez/rbfx | 8641813787d558b6e8318c1b8e9da86c0e52f9dc | [
"MIT"
] | 54 | 2017-10-18T07:18:12.000Z | 2018-12-23T14:09:30.000Z | Source/Tests/Replica/SceneSynchronization.cpp | jayrulez/rbfx | 8641813787d558b6e8318c1b8e9da86c0e52f9dc | [
"MIT"
] | 10 | 2017-11-10T11:46:15.000Z | 2018-12-18T11:58:44.000Z | //
// Copyright (c) 2017-2021 the rbfx project.
//
// 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 rhs
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR rhsWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR rhs DEALINGS IN
// THE SOFTWARE.
//
#include "../CommonUtils.h"
#include "../NetworkUtils.h"
#include "../SceneUtils.h"
#include <Urho3D/Graphics/Light.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Network/Network.h>
#include <Urho3D/Network/NetworkEvents.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Physics/PhysicsWorld.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Replica/BehaviorNetworkObject.h>
#include <Urho3D/Replica/ReplicationManager.h>
#include <Urho3D/Replica/NetworkObject.h>
#include <Urho3D/Replica/NetworkValue.h>
#include <Urho3D/Replica/ReplicatedTransform.h>
#include <Urho3D/Resource/XMLFile.h>
namespace
{
SharedPtr<XMLFile> CreateComplexTestPrefab(Context* context)
{
auto node = MakeShared<Node>(context);
node->CreateComponent<ReplicatedTransform>();
auto staticModel = node->CreateComponent<StaticModel>();
staticModel->SetCastShadows(true);
auto childNode = node->CreateChild("Child");
childNode->SetPosition({0.0f, 1.0f, 0.0f});
auto light = childNode->CreateComponent<Light>();
light->SetCastShadows(true);
light->SetColor(Color::RED);
return Tests::ConvertNodeToPrefab(node);
}
SharedPtr<XMLFile> CreateSimpleTestPrefab(Context* context)
{
auto node = MakeShared<Node>(context);
node->CreateComponent<ReplicatedTransform>();
return Tests::ConvertNodeToPrefab(node);
}
}
TEST_CASE("Scene is synchronized between client and server")
{
auto context = Tests::GetOrCreateContext(Tests::CreateCompleteContext);
context->GetSubsystem<Network>()->SetUpdateFps(Tests::NetworkSimulator::FramesInSecond);
const float syncDelay = 0.25f;
auto prefab = Tests::GetOrCreateResource<XMLFile>(context, "@/SceneSynchronization/SimpleTestPrefab.xml", CreateSimpleTestPrefab);
// Setup scenes
const auto quality = Tests::ConnectionQuality{ 0.08f, 0.12f, 0.20f, 0.02f, 0.02f };
auto serverScene = MakeShared<Scene>(context);
SharedPtr<Scene> clientScenes[] = {
MakeShared<Scene>(context),
MakeShared<Scene>(context),
MakeShared<Scene>(context)
};
// Reference transforms, should stay the same
Matrix3x4 transformReplicatedNodeA;
Matrix3x4 transformReplicatedNodeB;
Matrix3x4 transformReplicatedNodeChild1;
Matrix3x4 transformReplicatedNodeChild2;
Matrix3x4 transformReplicatedNodeChild4;
{
for (Scene* clientScene : clientScenes)
clientScene->CreateChild("Client Only Node", LOCAL);
auto serverOnlyNode = serverScene->CreateChild("Server Only Node", LOCAL);
auto replicatedNodeA = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Replicated Node A");
replicatedNodeA->SetScale(2.0f);
transformReplicatedNodeA = replicatedNodeA->GetWorldTransform();
auto replicatedNodeB = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Replicated Node B");
replicatedNodeB->SetPosition({ -1.0f, 2.0f, 0.5f });
transformReplicatedNodeB = replicatedNodeB->GetWorldTransform();
auto replicatedNodeChild1 = Tests::SpawnOnServer<BehaviorNetworkObject>(replicatedNodeA, prefab, "Replicated Node Child 1");
replicatedNodeChild1->SetPosition({ -2.0f, 3.0f, 1.5f });
transformReplicatedNodeChild1 = replicatedNodeChild1->GetWorldTransform();
auto replicatedNodeChild2 = Tests::SpawnOnServer<BehaviorNetworkObject>(replicatedNodeChild1, prefab, "Replicated Node Child 2");
replicatedNodeChild2->SetRotation({ 90.0f, Vector3::UP });
transformReplicatedNodeChild2 = replicatedNodeChild2->GetWorldTransform();
auto serverOnlyChild3 = replicatedNodeB->CreateChild("Server Only Child 3", LOCAL);
serverOnlyChild3->SetPosition({ -1.0f, 0.0f, 0.0f });
auto replicatedNodeChild4 = Tests::SpawnOnServer<BehaviorNetworkObject>(serverOnlyChild3, prefab, "Replicated Node Child 4");
transformReplicatedNodeChild4 = replicatedNodeChild4->GetWorldTransform();
}
// Spend some time alone
Tests::NetworkSimulator sim(serverScene);
sim.SimulateTime(10.0f);
// Add clients and wait for synchronization
for (Scene* clientScene : clientScenes)
sim.AddClient(clientScene, quality);
sim.SimulateTime(10.0f);
for (Scene* clientScene : clientScenes)
{
auto clientOnlyNode = clientScene->GetChild("Client Only Node", true);
auto replicatedNodeA = clientScene->GetChild("Replicated Node A", true);
auto replicatedNodeB = clientScene->GetChild("Replicated Node B", true);
auto replicatedNodeChild1 = clientScene->GetChild("Replicated Node Child 1", true);
auto replicatedNodeChild2 = clientScene->GetChild("Replicated Node Child 2", true);
auto replicatedNodeChild4 = clientScene->GetChild("Replicated Node Child 4", true);
REQUIRE(clientScene->GetNumChildren() == 3);
REQUIRE(clientScene == clientOnlyNode->GetParent());
REQUIRE(clientScene == replicatedNodeA->GetParent());
REQUIRE(clientScene == replicatedNodeB->GetParent());
REQUIRE(clientOnlyNode->GetNumChildren() == 0);
REQUIRE(replicatedNodeA->GetNumChildren() == 1);
REQUIRE(replicatedNodeA == replicatedNodeChild1->GetParent());
REQUIRE(replicatedNodeChild1->GetNumChildren() == 1);
REQUIRE(replicatedNodeChild1 == replicatedNodeChild2->GetParent());
REQUIRE(replicatedNodeChild2->GetNumChildren() == 0);
REQUIRE(replicatedNodeB->GetNumChildren() == 1);
REQUIRE(replicatedNodeB == replicatedNodeChild4->GetParent());
REQUIRE(replicatedNodeChild4->GetNumChildren() == 0);
REQUIRE(replicatedNodeA->GetWorldTransform().Equals(transformReplicatedNodeA));
REQUIRE(replicatedNodeB->GetWorldTransform().Equals(transformReplicatedNodeB));
REQUIRE(replicatedNodeChild1->GetWorldTransform().Equals(transformReplicatedNodeChild1));
REQUIRE(replicatedNodeChild2->GetWorldTransform().Equals(transformReplicatedNodeChild2));
REQUIRE(replicatedNodeChild4->GetWorldTransform().Equals(transformReplicatedNodeChild4));
}
// Re-parent "Server Only Child 3" to "Replicated Node A"
// Re-parent "Replicated Node Child 1" to Scene
// Wait for synchronization
{
auto serverOnlyChild3 = serverScene->GetChild("Server Only Child 3", true);
auto replicatedNodeA = serverScene->GetChild("Replicated Node A", true);
auto replicatedNodeChild1 = serverScene->GetChild("Replicated Node Child 1", true);
serverOnlyChild3->SetParent(replicatedNodeA);
replicatedNodeChild1->SetParent(serverScene);
}
sim.SimulateTime(syncDelay);
for (Scene* clientScene : clientScenes)
{
auto clientOnlyNode = clientScene->GetChild("Client Only Node", true);
auto replicatedNodeA = clientScene->GetChild("Replicated Node A", true);
auto replicatedNodeB = clientScene->GetChild("Replicated Node B", true);
auto replicatedNodeChild1 = clientScene->GetChild("Replicated Node Child 1", true);
auto replicatedNodeChild2 = clientScene->GetChild("Replicated Node Child 2", true);
auto replicatedNodeChild4 = clientScene->GetChild("Replicated Node Child 4", true);
REQUIRE(clientScene->GetNumChildren() == 4);
REQUIRE(clientScene == clientOnlyNode->GetParent());
REQUIRE(clientScene == replicatedNodeA->GetParent());
REQUIRE(clientScene == replicatedNodeB->GetParent());
REQUIRE(clientScene == replicatedNodeChild1->GetParent());
REQUIRE(clientOnlyNode->GetNumChildren() == 0);
REQUIRE(replicatedNodeA->GetNumChildren() == 1);
REQUIRE(replicatedNodeA == replicatedNodeChild4->GetParent());
REQUIRE(replicatedNodeChild4->GetNumChildren() == 0);
REQUIRE(replicatedNodeB->GetNumChildren() == 0);
REQUIRE(replicatedNodeChild1->GetNumChildren() == 1);
REQUIRE(replicatedNodeChild1 == replicatedNodeChild2->GetParent());
REQUIRE(replicatedNodeChild2->GetNumChildren() == 0);
REQUIRE(replicatedNodeA->GetWorldTransform().Equals(transformReplicatedNodeA, M_LARGE_EPSILON));
REQUIRE(replicatedNodeB->GetWorldTransform().Equals(transformReplicatedNodeB, M_LARGE_EPSILON));
REQUIRE(replicatedNodeChild1->GetWorldTransform().Equals(transformReplicatedNodeChild1, M_LARGE_EPSILON));
REQUIRE(replicatedNodeChild2->GetWorldTransform().Equals(transformReplicatedNodeChild2, M_LARGE_EPSILON));
REQUIRE(replicatedNodeChild4->GetWorldTransform().Equals(transformReplicatedNodeChild4, M_LARGE_EPSILON));
}
// Remove "Replicated Node A"
// Add "Replicated Node C"
{
auto replicatedNodeA = serverScene->GetChild("Replicated Node A", true);
replicatedNodeA->Remove();
auto replicatedNodeC = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Replicated Node C");
}
sim.SimulateTime(syncDelay);
for (Scene* clientScene : clientScenes)
{
auto clientOnlyNode = clientScene->GetChild("Client Only Node", true);
auto replicatedNodeB = clientScene->GetChild("Replicated Node B", true);
auto replicatedNodeC = clientScene->GetChild("Replicated Node C", true);
auto replicatedNodeChild1 = clientScene->GetChild("Replicated Node Child 1", true);
auto replicatedNodeChild2 = clientScene->GetChild("Replicated Node Child 2", true);
REQUIRE(clientScene->GetNumChildren() == 4);
REQUIRE(clientScene == clientOnlyNode->GetParent());
REQUIRE(clientScene == replicatedNodeB->GetParent());
REQUIRE(clientScene == replicatedNodeC->GetParent());
REQUIRE(clientScene == replicatedNodeChild1->GetParent());
REQUIRE(clientOnlyNode->GetNumChildren() == 0);
REQUIRE(replicatedNodeB->GetNumChildren() == 0);
REQUIRE(replicatedNodeChild1->GetNumChildren() == 1);
REQUIRE(replicatedNodeChild1 == replicatedNodeChild2->GetParent());
REQUIRE(replicatedNodeChild2->GetNumChildren() == 0);
REQUIRE(replicatedNodeB->GetWorldTransform().Equals(transformReplicatedNodeB, M_LARGE_EPSILON));
REQUIRE(replicatedNodeC->GetWorldTransform().Equals(Matrix3x4::IDENTITY, M_LARGE_EPSILON));
REQUIRE(replicatedNodeChild1->GetWorldTransform().Equals(transformReplicatedNodeChild1, M_LARGE_EPSILON));
REQUIRE(replicatedNodeChild2->GetWorldTransform().Equals(transformReplicatedNodeChild2, M_LARGE_EPSILON));
}
// Re-parent "Replicated Node Child 2" to Scene
// Remove "Replicated Node Child 1", "Replicated Node B", "Replicated Node C"
{
auto replicatedNodeChild1 = serverScene->GetChild("Replicated Node Child 1", true);
auto replicatedNodeChild2 = serverScene->GetChild("Replicated Node Child 2", true);
auto replicatedNodeB = serverScene->GetChild("Replicated Node B", true);
auto replicatedNodeC = serverScene->GetChild("Replicated Node C", true);
replicatedNodeChild2->SetParent(serverScene);
replicatedNodeChild1->Remove();
replicatedNodeB->Remove();
replicatedNodeC->Remove();
}
sim.SimulateTime(syncDelay);
for (Scene* clientScene : clientScenes)
{
auto clientOnlyNode = clientScene->GetChild("Client Only Node", true);
auto replicatedNodeChild2 = clientScene->GetChild("Replicated Node Child 2", true);
REQUIRE(clientScene->GetNumChildren() == 2);
REQUIRE(clientScene == clientOnlyNode->GetParent());
REQUIRE(clientScene == replicatedNodeChild2->GetParent());
REQUIRE(replicatedNodeChild2->GetWorldTransform().Equals(transformReplicatedNodeChild2, M_LARGE_EPSILON));
}
}
TEST_CASE("Position and rotation are synchronized between client and server")
{
auto context = Tests::GetOrCreateContext(Tests::CreateCompleteContext);
context->GetSubsystem<Network>()->SetUpdateFps(Tests::NetworkSimulator::FramesInSecond);
auto prefab = Tests::GetOrCreateResource<XMLFile>(context, "@/SceneSynchronization/SimpleTestPrefab.xml", CreateSimpleTestPrefab);
// Setup scenes
const auto interpolationQuality = Tests::ConnectionQuality{0.08f, 0.12f, 0.20f, 0, 0};
const auto extrapolationQuality = Tests::ConnectionQuality{0.25f, 0.35f, 0.40f, 0, 0};
const float positionError = ReplicatedTransform::DefaultMovementThreshold;
const float moveSpeedNodeA = 1.0f;
const float rotationSpeedNodeA = 10.0f;
const float moveSpeedNodeB = 0.1f;
auto serverScene = MakeShared<Scene>(context);
SharedPtr<Scene> interpolatingClientScene = MakeShared<Scene>(context);
interpolatingClientScene->SetName("Interpolating Scene");
SharedPtr<Scene> extrapolatingClientScene = MakeShared<Scene>(context);
extrapolatingClientScene->SetName("Extrapolation Scene");
Node* serverNodeA = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Node");
auto serverTransformA = serverNodeA->GetComponent<ReplicatedTransform>();
serverTransformA->SetExtrapolateRotation(true);
Node* serverNodeB = Tests::SpawnOnServer<BehaviorNetworkObject>(serverNodeA, prefab, "Node Child", { 0.0f, 0.0f, 1.0f });
auto serverTransformB = serverNodeB->GetComponent<ReplicatedTransform>();
serverTransformB->SetExtrapolateRotation(true);
// Animate objects forever
serverScene->SubscribeToEvent(serverScene, E_SCENEUPDATE,
[&](StringHash, VariantMap& eventData)
{
const float timeStep = eventData[SceneUpdate::P_TIMESTEP].GetFloat();
serverNodeA->Translate(timeStep * moveSpeedNodeA * Vector3::LEFT, TS_PARENT);
serverNodeA->Rotate({ timeStep * rotationSpeedNodeA, Vector3::UP }, TS_PARENT);
serverNodeB->Translate(timeStep * moveSpeedNodeB * Vector3::FORWARD, TS_PARENT);
});
// Spend some time alone
Tests::NetworkSimulator sim(serverScene);
const auto& serverReplicator = *serverScene->GetComponent<ReplicationManager>()->GetServerReplicator();
sim.SimulateTime(9.0f);
// Add clients and wait for synchronization
sim.AddClient(interpolatingClientScene, interpolationQuality);
sim.AddClient(extrapolatingClientScene, extrapolationQuality);
sim.SimulateTime(9.0f);
// Expect positions and rotations to be precisely synchronized on interpolating client
{
const auto& clientReplica = *interpolatingClientScene->GetComponent<ReplicationManager>()->GetClientReplica();
const NetworkTime replicaTime = clientReplica.GetReplicaTime();
const double delay = serverReplicator.GetServerTime() - replicaTime;
auto clientNodeA = interpolatingClientScene->GetChild("Node", true);
auto clientNodeB = interpolatingClientScene->GetChild("Node Child", true);
REQUIRE(delay / Tests::NetworkSimulator::FramesInSecond == Catch::Approx(0.2).margin(0.03));
REQUIRE(serverTransformA->SampleTemporalPosition(replicaTime).value_.Equals(clientNodeA->GetWorldPosition(), positionError));
REQUIRE(serverTransformA->SampleTemporalRotation(replicaTime).value_.Equivalent(clientNodeA->GetWorldRotation(), M_EPSILON));
REQUIRE(serverTransformB->SampleTemporalPosition(replicaTime).value_.Equals(clientNodeB->GetWorldPosition(), positionError));
REQUIRE(serverTransformB->SampleTemporalRotation(replicaTime).value_.Equivalent(clientNodeB->GetWorldRotation(), M_EPSILON));
}
// Expect positions and rotations to be roughly synchronized on extrapolating client
{
const auto& clientReplica = *extrapolatingClientScene->GetComponent<ReplicationManager>()->GetClientReplica();
const NetworkTime replicaTime = clientReplica.GetReplicaTime();
const double delay = serverReplicator.GetServerTime() - replicaTime;
auto clientNodeA = extrapolatingClientScene->GetChild("Node", true);
auto clientNodeB = extrapolatingClientScene->GetChild("Node Child", true);
REQUIRE(delay / Tests::NetworkSimulator::FramesInSecond == Catch::Approx(0.25).margin(0.03));
REQUIRE(serverTransformA->SampleTemporalPosition(replicaTime).value_.Equals(clientNodeA->GetWorldPosition(), positionError));
REQUIRE(serverTransformA->SampleTemporalRotation(replicaTime).value_.Equivalent(clientNodeA->GetWorldRotation(), M_EPSILON));
REQUIRE(serverTransformB->SampleTemporalPosition(replicaTime).value_.Equals(clientNodeB->GetWorldPosition(), 0.002f));
REQUIRE(serverTransformB->SampleTemporalRotation(replicaTime).value_.Equivalent(clientNodeB->GetWorldRotation(), M_EPSILON));
}
}
TEST_CASE("Prefabs are replicated on clients")
{
auto context = Tests::GetOrCreateContext(Tests::CreateCompleteContext);
context->GetSubsystem<Network>()->SetUpdateFps(Tests::NetworkSimulator::FramesInSecond);
auto prefab = Tests::GetOrCreateResource<XMLFile>(context, "@/SceneSynchronization/ComplexTestPrefab.xml", CreateComplexTestPrefab);
// Setup scenes
const auto quality = Tests::ConnectionQuality{ 0.08f, 0.12f, 0.20f, 0.02f, 0.02f };
auto serverScene = MakeShared<Scene>(context);
SharedPtr<Scene> clientScenes[] = {
MakeShared<Scene>(context),
MakeShared<Scene>(context),
MakeShared<Scene>(context)
};
// Start simulation
Tests::NetworkSimulator sim(serverScene);
for (Scene* clientScene : clientScenes)
sim.AddClient(clientScene, quality);
// Create nodes
{
Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Node 1", {1.0f, 0.0f, 0.0f});
Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Node 2", {2.0f, 0.0f, 0.0f});
}
sim.SimulateTime(10.0f);
// Expect prefabs replicated
for (Scene* clientScene : clientScenes)
{
auto node1 = clientScene->GetChild("Node 1", true);
REQUIRE(node1);
auto node2 = clientScene->GetChild("Node 2", true);
REQUIRE(node2);
auto node1Child = node1->GetChild("Child");
REQUIRE(node1Child);
auto node2Child = node2->GetChild("Child");
REQUIRE(node2Child);
CHECK(node1->GetWorldPosition().Equals({1.0f, 0.0f, 0.0f}));
CHECK(node1Child->GetWorldPosition().Equals({1.0f, 1.0f, 0.0f}));
CHECK(node2->GetWorldPosition().Equals({2.0f, 0.0f, 0.0f}));
CHECK(node2Child->GetWorldPosition().Equals({2.0f, 1.0f, 0.0f}));
auto staticModel1 = node1->GetComponent<StaticModel>();
REQUIRE(staticModel1);
auto staticModel2 = node2->GetComponent<StaticModel>();
REQUIRE(staticModel2);
auto light1 = node1Child->GetComponent<Light>();
REQUIRE(light1);
auto light2 = node2Child->GetComponent<Light>();
REQUIRE(light2);
CHECK(staticModel1->GetCastShadows() == true);
CHECK(staticModel2->GetCastShadows() == true);
CHECK(light1->GetCastShadows() == true);
CHECK(light2->GetCastShadows() == true);
CHECK(light1->GetColor() == Color::RED);
CHECK(light2->GetColor() == Color::RED);
}
}
TEST_CASE("Ownership is consistent on server and on clients")
{
auto context = Tests::GetOrCreateContext(Tests::CreateCompleteContext);
context->GetSubsystem<Network>()->SetUpdateFps(Tests::NetworkSimulator::FramesInSecond);
auto prefab = Tests::GetOrCreateResource<XMLFile>(context, "@/SceneSynchronization/SimpleTestPrefab.xml", CreateSimpleTestPrefab);
// Setup scenes
const auto quality = Tests::ConnectionQuality{ 0.08f, 0.12f, 0.20f, 0.02f, 0.02f };
auto serverScene = MakeShared<Scene>(context);
SharedPtr<Scene> clientScenes[] = {
MakeShared<Scene>(context),
MakeShared<Scene>(context),
MakeShared<Scene>(context)
};
// Start simulation
Tests::NetworkSimulator sim(serverScene);
for (Scene* clientScene : clientScenes)
sim.AddClient(clientScene, quality);
// Create nodes
{
Node* node = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Unowned Node");
auto object = node->GetDerivedComponent<NetworkObject>();
REQUIRE(object->GetNetworkMode() == NetworkObjectMode::Standalone);
}
{
Node* node = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Owned Node 0");
auto object = node->GetDerivedComponent<NetworkObject>();
object->SetOwner(sim.GetServerToClientConnection(clientScenes[0]));
REQUIRE(object->GetNetworkMode() == NetworkObjectMode::Standalone);
}
{
Node* node = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Owned Node 1");
auto object = node->GetDerivedComponent<NetworkObject>();
object->SetOwner(sim.GetServerToClientConnection(clientScenes[1]));
REQUIRE(object->GetNetworkMode() == NetworkObjectMode::Standalone);
}
{
Node* node = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Owned Node 2");
auto object = node->GetDerivedComponent<NetworkObject>();
object->SetOwner(sim.GetServerToClientConnection(clientScenes[2]));
REQUIRE(object->GetNetworkMode() == NetworkObjectMode::Standalone);
}
sim.SimulateTime(10.0f);
// Check ownership of objects
const auto getObject = [](Scene* scene, const ea::string& name)
{
return scene->GetChild(name, true)->GetDerivedComponent<NetworkObject>();
};
REQUIRE(getObject(serverScene, "Unowned Node")->GetNetworkMode() == NetworkObjectMode::Server);
REQUIRE(getObject(serverScene, "Owned Node 0")->GetNetworkMode() == NetworkObjectMode::Server);
REQUIRE(getObject(serverScene, "Owned Node 1")->GetNetworkMode() == NetworkObjectMode::Server);
REQUIRE(getObject(serverScene, "Owned Node 2")->GetNetworkMode() == NetworkObjectMode::Server);
REQUIRE(getObject(clientScenes[0], "Unowned Node")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[0], "Owned Node 0")->GetNetworkMode() == NetworkObjectMode::ClientOwned);
REQUIRE(getObject(clientScenes[0], "Owned Node 1")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[0], "Owned Node 2")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[1], "Unowned Node")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[1], "Owned Node 0")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[1], "Owned Node 1")->GetNetworkMode() == NetworkObjectMode::ClientOwned);
REQUIRE(getObject(clientScenes[1], "Owned Node 2")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[2], "Unowned Node")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[2], "Owned Node 0")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[2], "Owned Node 1")->GetNetworkMode() == NetworkObjectMode::ClientReplicated);
REQUIRE(getObject(clientScenes[2], "Owned Node 2")->GetNetworkMode() == NetworkObjectMode::ClientOwned);
// Check client-side arrays
const auto getClientReplica = [](Scene* scene)
{
return scene->GetComponent<ReplicationManager>()->GetClientReplica();
};
REQUIRE(getClientReplica(clientScenes[0])->GetOwnedNetworkObject() == getObject(clientScenes[0], "Owned Node 0"));
REQUIRE(getClientReplica(clientScenes[1])->GetOwnedNetworkObject() == getObject(clientScenes[1], "Owned Node 1"));
REQUIRE(getClientReplica(clientScenes[2])->GetOwnedNetworkObject() == getObject(clientScenes[2], "Owned Node 2"));
// Check server-side arrays
auto serverReplicator = serverScene->GetComponent<ReplicationManager>()->GetServerReplicator();
REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[0])) == getObject(serverScene, "Owned Node 0"));
REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[1])) == getObject(serverScene, "Owned Node 1"));
REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[2])) == getObject(serverScene, "Owned Node 2"));
// Remove all owned nodes
serverScene->GetChild("Owned Node 0", true)->Remove();
serverScene->GetChild("Owned Node 1", true)->Remove();
serverScene->GetChild("Owned Node 2", true)->Remove();
sim.SimulateTime(10.0f);
REQUIRE(getClientReplica(clientScenes[0])->GetOwnedNetworkObject() == nullptr);
REQUIRE(getClientReplica(clientScenes[1])->GetOwnedNetworkObject() == nullptr);
REQUIRE(getClientReplica(clientScenes[2])->GetOwnedNetworkObject() == nullptr);
REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[0])) == nullptr);
REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[1])) == nullptr);
REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[2])) == nullptr);
}
| 47.669078 | 157 | 0.721672 | jayrulez |
7ff2642d55b39b8c6c655072137a1d1a3f17cdc4 | 739 | cpp | C++ | STL_C++/Iterators.cpp | prabhash-varma/DSA-CP | 685b13d960d2045d003e30f235d678b9f05548b3 | [
"MIT"
] | null | null | null | STL_C++/Iterators.cpp | prabhash-varma/DSA-CP | 685b13d960d2045d003e30f235d678b9f05548b3 | [
"MIT"
] | null | null | null | STL_C++/Iterators.cpp | prabhash-varma/DSA-CP | 685b13d960d2045d003e30f235d678b9f05548b3 | [
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> v ={2,3,5,6,7};
// for(int i=0;i<v.size();i++){
// cout<<v[i]<< " ";
// }
// cout<<endl;
//Iterator declaration
vector<int> :: iterator it = v.begin();
//cout<<(*(it+1))<<endl;
for(it=v.begin();it !=v.end();it++){
cout<<(*it)<<endl;
}
//vector of pair
vector<pair<int,int>> v_p ={{1,2},{2,3},{3,4}};
vector<pair<int,int>> :: iterator ite;
for(ite=v_p.begin();ite!=v_p.end();ite++){
cout<< (*ite).first<<" "<<(*ite).second<<endl;
}
// (*it).first == (it->first)
for(ite=v_p.begin();ite!=v_p.end();ite++){
cout<< (ite->first)<<" "<<(ite->second)<<endl;
}
}
| 18.02439 | 54 | 0.470907 | prabhash-varma |
7ff59dcffba8ef64c7f8d3e79b5160afe82ecb15 | 2,727 | cpp | C++ | C++/rectangle-area-ii.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/rectangle-area-ii.cpp | pnandini/LeetCode | e746c3298be96dec8e160da9378940568ef631b1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/rectangle-area-ii.cpp | pnandini/LeetCode | e746c3298be96dec8e160da9378940568ef631b1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(nlogn)
// Space: O(n)
class Solution {
public:
enum { OPEN = 1, CLOSE = -1};
int rectangleArea(vector<vector<int>>& rectangles) {
vector<vector<int>> events;
set<int> Xvals;
for (const auto& rec: rectangles) {
events.emplace_back(vector<int>{rec[1], OPEN, rec[0], rec[2]});
events.emplace_back(vector<int>{rec[3], CLOSE, rec[0], rec[2]});
Xvals.emplace(rec[0]);
Xvals.emplace(rec[2]);
}
sort(events.begin(), events.end());
vector<int> X(Xvals.cbegin(), Xvals.cend());
unordered_map<int, int> Xi;
for (int i = 0; i < X.size(); ++i) {
Xi[X[i]] = i;
}
auto st = new SegmentTreeNode(0, X.size() - 1, X);
int64_t result = 0;
int64_t cur_x_sum = 0;
int cur_y = events[0][0];
for (const auto& event: events) {
int y = event[0], type = event[1], x1 = event[2], x2 = event[3];
result += cur_x_sum * (y - cur_y);
cur_x_sum = st->update(Xi[x1], Xi[x2], type);
cur_y = y;
}
return result % static_cast<int64_t>(1e9 + 7);
}
class SegmentTreeNode {
public:
SegmentTreeNode(int start, int end, const vector<int>& X) :
start_(start),
end_(end),
X_(X),
left_(nullptr),
right_(nullptr),
count_(0),
total_(0) {
}
int mid() const {
return start_ + (end_ - start_) / 2;
}
SegmentTreeNode *left() {
if (left_ == nullptr) {
left_ = new SegmentTreeNode(start_, mid(), X_);
}
return left_;
}
SegmentTreeNode *right() {
if (right_ == nullptr) {
right_ = new SegmentTreeNode(mid(), end_, X_);
}
return right_;
}
int64_t total() const {
return total_;
}
int64_t update(int i, int j, int val) {
if (i >= j) {
return 0;
}
if (start_ == i && end_ == j) {
count_ += val;
} else {
left()->update(i, min(mid(), j), val);
right()->update(max(mid(), i), j, val);
}
if (count_ > 0) {
total_ = X_[end_] - X_[start_];
} else {
total_ = left()->total() + right()->total();
}
return total_;
}
private:
int start_, end_;
const vector<int>& X_;
SegmentTreeNode *left_, *right_;
int count_;
int64_t total_;
};
};
| 28.113402 | 76 | 0.441511 | jaiskid |
7ff873a32d8231c89f28f48b8804cbd12e64d12a | 968 | cpp | C++ | Angel/Libraries/FTGL/src/FTLibrary.cpp | Tifox/Grog-Knight | 377a661286cda7ee3b2b2d0099641897938c2f8f | [
"Apache-2.0"
] | 171 | 2015-01-08T10:35:56.000Z | 2021-07-03T12:35:10.000Z | Angel/Libraries/FTGL/src/FTLibrary.cpp | Tifox/Grog-Knight | 377a661286cda7ee3b2b2d0099641897938c2f8f | [
"Apache-2.0"
] | 11 | 2015-01-30T05:30:54.000Z | 2017-04-08T23:34:33.000Z | Angel/Libraries/FTGL/src/FTLibrary.cpp | Tifox/Grog-Knight | 377a661286cda7ee3b2b2d0099641897938c2f8f | [
"Apache-2.0"
] | 59 | 2015-02-01T03:43:00.000Z | 2020-12-01T02:08:57.000Z | #include "FTLibrary.h"
const FTLibrary& FTLibrary::Instance()
{
static FTLibrary ftlib;
return ftlib;
}
FTLibrary::~FTLibrary()
{
if( library != 0)
{
FT_Done_FreeType( *library);
delete library;
library= 0;
}
// if( manager != 0)
// {
// FTC_Manager_Done( manager );
//
// delete manager;
// manager= 0;
// }
}
FTLibrary::FTLibrary()
: library(0),
err(0)
{
Initialise();
}
bool FTLibrary::Initialise()
{
if( library != 0)
return true;
library = new FT_Library;
err = FT_Init_FreeType( library);
if( err)
{
delete library;
library = 0;
return false;
}
// FTC_Manager* manager;
//
// if( FTC_Manager_New( lib, 0, 0, 0, my_face_requester, 0, manager )
// {
// delete manager;
// manager= 0;
// return false;
// }
return true;
}
| 14.892308 | 71 | 0.494835 | Tifox |
7ffed48a819bd9a7b61789e434ca57e9e39d0e72 | 5,631 | cc | C++ | project/c++/mri/src/iwf/test/iwf_pipeline_test.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | project/c++/mri/src/iwf/test/iwf_pipeline_test.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | project/c++/mri/src/iwf/test/iwf_pipeline_test.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | #include "boost/foreach.hpp"
#include "boost/scoped_ptr.hpp"
#include "boost/shared_ptr.hpp"
#include "tbb/pipeline.h"
#include "gtest/gtest.h"
#include "xtreme/iwf/internal/iwf_pipeline.h"
#include "xtreme/iwf/stats_publisher.h"
#include "xtreme/iwf/config_manager.h"
#include "xtreme/iwf/internal/iwf_pipeline_ingress_worker.h"
#include "xtreme/iwf/iwf.h"
#include "xtreme/iwf/internal/iwf_mock_event_counting_subscriber.h"
#include "xtreme/cs/cs.h"
#include "xtreme/common/event_timesync.h"
#include "xtreme/common/event_types.h"
#include "xtreme/common/pub_subs.h"
TEST(IWF_PIPELINE_TESTS, IwfStartStopComponents)
{
using xtreme::iwf::iwf;
using xtreme::cs::CS;
using xtreme::iwf::pipeline::Pipeline;
using xtreme::IPublisherList;
CS cs;
boost::scoped_ptr<iwf> iwf_tmp(new iwf(cs));
iwf_tmp->InitComponent();
iwf_tmp->StartComponent();
usleep(500000);
iwf_tmp->StopComponent();
}
TEST(IWF_PIPELINE_TESTS, PipelinePublisherReturned)
{
using xtreme::iwf::iwf;
using xtreme::cs::CS;
using xtreme::iwf::pipeline::Pipeline;
using xtreme::IPublisherList;
CS cs;
boost::scoped_ptr<iwf> iwf_tmp(new iwf(cs));
iwf_tmp->InitComponent();
IPublisherList lst = iwf_tmp->GetPublisherForType( xtreme::kEVENT_CP_FRAME );
ASSERT_EQ( lst.size(), (size_t) 1 );
lst.clear();
lst = iwf_tmp->GetPublisherForType( xtreme::kEVENT_UP_FRAME );
ASSERT_EQ( lst.size(), (size_t) 3 );
}
TEST(IWF_PIPELINE_TESTS, StartStopPipeline)
{
using xtreme::iwf::iwf;
using xtreme::cs::CS;
using xtreme::iwf::pipeline::Pipeline;
using xtreme::iwf::pipeline::CPPipeline;
CS cs;
boost::scoped_ptr<iwf> iwf_tmp(new iwf(cs));
boost::scoped_ptr<Pipeline> cpp_pipe( CPPipeline::CreateCppPipeline( iwf_tmp.get(), nullptr ) );
cpp_pipe->Start();
cpp_pipe->Stop();
}
TEST(PIPELINE_TESTS, SimpleTbbPipeCreation) {
tbb::pipeline *pline = new tbb::pipeline;
ASSERT_TRUE( NULL != pline );
}
TEST(IWF_STATS_PUB_TEST, CreateDelete)
{
using xtreme::iwf::StatsPublisher;
using xtreme::iwf::ConfigManager;
ConfigManager *cm( new ConfigManager );
boost::scoped_ptr<StatsPublisher> sp( new StatsPublisher(cm,nullptr) );
delete cm;
}
TEST(IWF_PIPELINE_TESTS, CreateDeletePipelines)
{
using xtreme::iwf::iwf;
using xtreme::cs::CS;
using xtreme::iwf::pipeline::Pipeline;
using xtreme::iwf::pipeline::CPPipeline;
CS cs;
boost::scoped_ptr<iwf> iwf_tmp(new iwf(cs));
boost::scoped_ptr<Pipeline> cpp_pipe( CPPipeline::CreateCppPipeline( iwf_tmp.get(), nullptr ) );
std::list< boost::shared_ptr<Pipeline> > upp_pipes;
for (int i=0; i < 3; ++i)
{
upp_pipes.push_back(boost::shared_ptr<Pipeline>(Pipeline::CreateUppPipeline(iwf_tmp.get(), nullptr, i)));
}
cpp_pipe->Start();
BOOST_FOREACH( boost::shared_ptr<Pipeline> pipe, upp_pipes ) {
pipe->Start();
}
}
TEST(IWF_PIPELINE_TESTS, PumpPipeline)
{
using xtreme::iwf::iwf;
using xtreme::EventPtr;
using xtreme::TimeSyncEvent;
using xtreme::cs::CS;
using xtreme::iwf::pipeline::Pipeline;
using xtreme::iwf::pipeline::CPPipeline;
CS cs;
boost::scoped_ptr<iwf> iwf_tmp(new iwf(cs));
boost::scoped_ptr<Pipeline> cpp_pipe( CPPipeline::CreateCppPipeline( iwf_tmp.get(), nullptr ) );
cpp_pipe->Start();
for (int i=0; i < 1000000; ++i)
{
EventPtr ts( new TimeSyncEvent );
cpp_pipe->PushEvent( ts );
}
cpp_pipe->Stop(true);
}
TEST(IWF_PIPELINE_TESTS, PumpPipelineSubscriber)
{
using xtreme::iwf::iwf;
using xtreme::EventPtr;
using xtreme::TimeSyncEvent;
using xtreme::cs::CS;
using xtreme::iwf::pipeline::Pipeline;
using xtreme::iwf::pipeline::CPPipeline;
using xtreme::iwf::MockCountingSubscriber;
using xtreme::Subscription;
CS cs;
boost::scoped_ptr<iwf> iwf_tmp(new iwf(cs));
boost::scoped_ptr<Pipeline> cpp_pipe( CPPipeline::CreateCppPipeline( iwf_tmp.get(), nullptr ) );
cpp_pipe->Start();
MockCountingSubscriber *sub = new MockCountingSubscriber( );
Subscription *subscription = new Subscription( xtreme::kEVENT_FRAME, NULL );;
cpp_pipe->GetPublisher()->AddSubscription( sub, subscription );
const int k_event_count = 1000000;
for (int i=0; i < k_event_count; ++i)
{
EventPtr ts( new TimeSyncEvent );
cpp_pipe->PushEvent( ts );
}
cpp_pipe->Stop(true);
// To look at further. Need to understand why there are outstanding events that require a sleep to complete.
// (Because Stop shouldn't return until the pipeline thread finishes, which is when the pipeline has dealt with
// all events), and the publisher and subscriber are all invoked from the EgressWorker.
usleep(50000);
ASSERT_EQ( k_event_count+1, sub->count_ );
}
TEST(IWF_PIPELINE_TESTS, CppPipelineHasAPublisher)
{
using xtreme::iwf::iwf;
using xtreme::cs::CS;
using xtreme::iwf::pipeline::Pipeline;
using xtreme::iwf::pipeline::CPPipeline;
CS cs;
boost::scoped_ptr<iwf> iwf_tmp(new iwf(cs));
boost::scoped_ptr<Pipeline> cpp_pipe( CPPipeline::CreateCppPipeline( iwf_tmp.get(), nullptr ) );
ASSERT_TRUE( NULL != cpp_pipe->GetPublisher() );
}
TEST(IWF_PIPELINE_TESTS, UppPipelineHasAPublisher)
{
using xtreme::iwf::iwf;
using xtreme::cs::CS;
using xtreme::iwf::pipeline::Pipeline;
CS cs;
boost::scoped_ptr<iwf> iwf_tmp(new iwf(cs));
boost::scoped_ptr<Pipeline> upp_pipe( Pipeline::CreateUppPipeline( iwf_tmp.get(), nullptr, 0 ) );
ASSERT_TRUE( NULL != upp_pipe->GetPublisher() );
}
| 32.362069 | 115 | 0.690641 | jia57196 |
3d00d94ec5c106e63b74c91e2e0d40c6ff05aa35 | 6,403 | cpp | C++ | src/QtManagers/Images/nSubgroupPictures.cpp | Vladimir-Lin/QtManagers | 2f906b165f773bff054a8349c577b7d07c2345d9 | [
"MIT"
] | null | null | null | src/QtManagers/Images/nSubgroupPictures.cpp | Vladimir-Lin/QtManagers | 2f906b165f773bff054a8349c577b7d07c2345d9 | [
"MIT"
] | null | null | null | src/QtManagers/Images/nSubgroupPictures.cpp | Vladimir-Lin/QtManagers | 2f906b165f773bff054a8349c577b7d07c2345d9 | [
"MIT"
] | null | null | null | #include <qtmanagers.h>
N::SubgroupPictures:: SubgroupPictures (QWidget * parent,Plan * p)
: SubgroupLists ( parent, p)
{
WidgetClass ;
Configure ( ) ;
}
N::SubgroupPictures::~SubgroupPictures(void)
{
}
void N::SubgroupPictures::Configure(void)
{
}
void N::SubgroupPictures::DeletePictures(QListWidgetItem * it)
{
SUID u = nListUuid(it) ;
QString M ;
M = tr("Delete [%1] pictures").arg(it->text()) ;
plan->showMessage(M) ;
setEnabled ( false ) ;
EnterSQL ( SC , plan->sql ) ;
QString Q ;
Q = SC.sql.DeleteFrom (
PlanTable(Groups) ,
FirstItem (
u ,
EachType() ,
Types::Picture ,
Groups::Subordination )
) ;
SC.Query(Q) ;
LeaveSQL ( SC , plan->sql ) ;
setEnabled ( true ) ;
Alert ( Done ) ;
}
bool N::SubgroupPictures::Menu(QPoint pos)
{
nScopedMenu ( mm , this ) ;
QMenu * me ;
QMenu * mc ;
QAction * aa ;
QListWidgetItem * it ;
SUID u = 0 ;
///////////////////////////////////////////////////
it = itemAt(pos) ;
if (NotNull(it) && !it->isSelected()) it = NULL ;
if (NotNull(it)) u = nListUuid(it) ;
///////////////////////////////////////////////////
mm.add(101,tr("New subgroup")) ;
mm.add(201,tr("Reflush" )) ;
if (NotNull(it)) mm.add(202,tr("Reflush item")) ;
mm.addSeparator() ;
me = mm.addMenu(tr("Edit" )) ;
if (NotNull(it)) {
mc = mm.addMenu(tr("Categorize")) ;
} ;
mm.addSeparator() ;
mm.add(301,tr("Copy to clipboard")) ;
mm.add(302,tr("Clear selection" )) ;
mm.add(303,tr("Select all" )) ;
///////////////////////////////////////////////////
if (NotNull(it)) {
mm.add(me,102,tr("Rename")) ;
mm.add(me,103,tr("Delete this subgroup")) ;
mm.addSeparator() ;
mm.add(me,104,tr("Delete all pictures")) ;
mm.addSeparator() ;
if (u>0) mm.add(me,401,tr("Pictures")) ;
} ;
mm.add(me,211,tr("Multilingual translations")) ;
AdjustMenu(mm,me) ;
///////////////////////////////////////////////////
if (NotNull(it)) {
mm.add(mc,501,tr("Constraints")) ;
mm.add(mc,502,tr("Rule tables")) ;
} ;
///////////////////////////////////////////////////
mm . setFont ( plan ) ;
aa = mm.exec ( ) ;
nKickOut ( IsNull(aa) , true ) ;
///////////////////////////////////////////////////
UUIDs Tuids ;
switch (mm[aa]) {
case 101 :
New ( ) ;
break ;
case 102 :
Rename ( ) ;
break ;
case 103 :
Delete ( ) ;
break ;
case 104 :
DeletePictures ( it ) ;
break ;
case 201 :
startup ( ) ;
break ;
case 202 :
Refresh ( it ) ;
break ;
case 211 :
Tuids = ItemUuids() ;
emit Translations(windowTitle(),Tuids) ;
break ;
case 301 :
CopyToClipboard ( ) ;
break ;
case 302 :
SelectNone ( ) ;
break ;
case 303 :
SelectAll ( ) ;
break ;
case 401 :
if (u>0) {
emit SeePictures(ObjectUuid(),u,it->text()) ;
} ;
break ;
case 501 :
emit Constraints ( windowTitle() , u ) ;
break ;
case 502 :
emit RuleTables ( windowTitle() , u ) ;
break ;
default :
RunAdjustment ( mm , aa ) ;
break ;
} ;
return true ;
}
| 46.737226 | 66 | 0.243948 | Vladimir-Lin |
3d02954a743a61220b443910cdc98dc49c0a4793 | 5,379 | cxx | C++ | main/dbaccess/source/ui/querydesign/QueryTabConnUndoAction.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/dbaccess/source/ui/querydesign/QueryTabConnUndoAction.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/dbaccess/source/ui/querydesign/QueryTabConnUndoAction.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbui.hxx"
#ifndef DBAUI_QUERYTABCONNUNDOACTION_HXX
#include "QueryTabConnUndoAction.hxx"
#endif
#ifndef DBAUI_QUERYTABLECONNECTION_HXX
#include "QTableConnection.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBAUI_QUERYTABLEVIEW_HXX
#include "QueryTableView.hxx"
#endif
#ifndef DBAUI_QUERYADDTABCONNUNDOACTION_HXX
#include "QueryAddTabConnUndoAction.hxx"
#endif
#ifndef DBAUI_QUERYTABWINSHOWUNDOACT_HXX
#include "QueryTabWinShowUndoAct.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
using namespace dbaui;
DBG_NAME(OQueryTabConnUndoAction)
// ------------------------------------------------------------------------------------------------
OQueryTabConnUndoAction::~OQueryTabConnUndoAction()
{
DBG_DTOR(OQueryTabConnUndoAction,NULL);
if (m_bOwnerOfConn)
{ // ich besitze die Connection -> loeschen
m_pOwner->DeselectConn(m_pConnection);
delete m_pConnection;
}
}
// ------------------------------------------------------------------------------------------------
OQueryTabConnUndoAction::OQueryTabConnUndoAction(OQueryTableView* pOwner, sal_uInt16 nCommentID)
:OQueryDesignUndoAction(pOwner, nCommentID)
,m_pConnection(NULL)
,m_bOwnerOfConn(sal_False)
{
DBG_CTOR(OQueryTabConnUndoAction,NULL);
}
// -----------------------------------------------------------------------------
OQueryAddTabConnUndoAction::OQueryAddTabConnUndoAction(OQueryTableView* pOwner)
: OQueryTabConnUndoAction(pOwner, STR_QUERY_UNDO_INSERTCONNECTION)
{
}
// -----------------------------------------------------------------------------
void OQueryAddTabConnUndoAction::Undo()
{
static_cast<OQueryTableView*>(m_pOwner)->DropConnection(m_pConnection);
SetOwnership(sal_True);
}
// -----------------------------------------------------------------------------
void OQueryAddTabConnUndoAction::Redo()
{
static_cast<OQueryTableView*>(m_pOwner)->GetConnection(m_pConnection);
SetOwnership(sal_False);
}
// -----------------------------------------------------------------------------
OQueryDelTabConnUndoAction::OQueryDelTabConnUndoAction(OQueryTableView* pOwner)
: OQueryTabConnUndoAction(pOwner, STR_QUERY_UNDO_REMOVECONNECTION)
{
}
// -----------------------------------------------------------------------------
void OQueryDelTabConnUndoAction::Undo()
{
static_cast<OQueryTableView*>(m_pOwner)->GetConnection(m_pConnection);
SetOwnership(sal_False);
}
// -----------------------------------------------------------------------------
void OQueryDelTabConnUndoAction::Redo()
{
static_cast<OQueryTableView*>(m_pOwner)->DropConnection(m_pConnection);
SetOwnership(sal_True);
}
// -----------------------------------------------------------------------------
OQueryTabWinShowUndoAct::OQueryTabWinShowUndoAct(OQueryTableView* pOwner)
: OQueryTabWinUndoAct(pOwner, STR_QUERY_UNDO_TABWINSHOW)
{
}
// -----------------------------------------------------------------------------
OQueryTabWinShowUndoAct::~OQueryTabWinShowUndoAct()
{
}
// -----------------------------------------------------------------------------
void OQueryTabWinShowUndoAct::Undo()
{
static_cast<OQueryTableView*>(m_pOwner)->HideTabWin(m_pTabWin, this);
SetOwnership(sal_True);
}
// -----------------------------------------------------------------------------
void OQueryTabWinShowUndoAct::Redo()
{
static_cast<OQueryTableView*>(m_pOwner)->ShowTabWin(m_pTabWin, this,sal_True);
SetOwnership(sal_False);
}
// -----------------------------------------------------------------------------
OQueryTabWinDelUndoAct::OQueryTabWinDelUndoAct(OQueryTableView* pOwner)
: OQueryTabWinUndoAct(pOwner, STR_QUERY_UNDO_TABWINDELETE)
{
}
// -----------------------------------------------------------------------------
OQueryTabWinDelUndoAct::~OQueryTabWinDelUndoAct()
{
}
// -----------------------------------------------------------------------------
void OQueryTabWinDelUndoAct::Undo()
{
static_cast<OQueryTableView*>(m_pOwner)->ShowTabWin( m_pTabWin, this,sal_True );
SetOwnership(sal_False);
}
// -----------------------------------------------------------------------------
void OQueryTabWinDelUndoAct::Redo()
{
static_cast<OQueryTableView*>(m_pOwner)->HideTabWin( m_pTabWin, this );
SetOwnership(sal_True);
}
// -----------------------------------------------------------------------------
| 36.591837 | 99 | 0.569251 | Grosskopf |
3d044280e5761f56c99117d4fd339b4afb3c8305 | 2,341 | cpp | C++ | tests/test/util/test_queue.cpp | n-krueger/faabric | c95c3baf9406613629e5f382efc0fc8366b22752 | [
"Apache-2.0"
] | null | null | null | tests/test/util/test_queue.cpp | n-krueger/faabric | c95c3baf9406613629e5f382efc0fc8366b22752 | [
"Apache-2.0"
] | null | null | null | tests/test/util/test_queue.cpp | n-krueger/faabric | c95c3baf9406613629e5f382efc0fc8366b22752 | [
"Apache-2.0"
] | null | null | null | #include <catch.hpp>
#include <faabric/util/bytes.h>
#include <faabric/util/queue.h>
#include <future>
#include <thread>
#include <unistd.h>
using namespace faabric::util;
typedef faabric::util::Queue<int> IntQueue;
namespace tests {
TEST_CASE("Test queue operations", "[util]")
{
IntQueue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(5);
REQUIRE(q.dequeue() == 1);
REQUIRE(q.dequeue() == 2);
REQUIRE(*(q.peek()) == 3);
REQUIRE(*(q.peek()) == 3);
REQUIRE(*(q.peek()) == 3);
REQUIRE(q.dequeue() == 3);
REQUIRE(q.dequeue() == 4);
REQUIRE(q.dequeue() == 5);
REQUIRE_THROWS(q.dequeue(1));
}
TEST_CASE("Test drain queue", "[util]")
{
IntQueue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
REQUIRE(q.size() == 3);
q.drain();
REQUIRE(q.size() == 0);
}
TEST_CASE("Test wait for draining empty queue", "[util]")
{
// Just need to check this doesn't fail
IntQueue q;
q.waitToDrain(100);
}
TEST_CASE("Test wait for draining queue with elements", "[util]")
{
IntQueue q;
int nElems = 5;
std::vector<int> dequeued;
std::vector<int> expected;
for (int i = 0; i < nElems; i++) {
q.enqueue(i);
expected.emplace_back(i);
}
// Background thread to consume elements
std::thread t([&q, &dequeued, nElems] {
for (int i = 0; i < nElems; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
int j = q.dequeue();
dequeued.emplace_back(j);
}
});
q.waitToDrain(2000);
if (t.joinable()) {
t.join();
}
REQUIRE(dequeued == expected);
}
TEST_CASE("Test queue on non-copy-constructible object", "[util]")
{
faabric::util::Queue<std::promise<int32_t>> q;
std::promise<int32_t> a;
std::promise<int32_t> b;
std::future<int32_t> fa = a.get_future();
std::future<int32_t> fb = b.get_future();
q.enqueue(std::move(a));
q.enqueue(std::move(b));
std::thread ta([&q] { q.dequeue().set_value(1); });
std::thread tb([&q] {
usleep(500 * 1000);
q.dequeue().set_value(2);
});
if (ta.joinable()) {
ta.join();
}
if (tb.joinable()) {
tb.join();
}
REQUIRE(fa.get() == 1);
REQUIRE(fb.get() == 2);
}
}
| 19.508333 | 72 | 0.556173 | n-krueger |
3d049e20010fb075d1aae3832f07acdf5d61e1b7 | 1,291 | cpp | C++ | libraries/RTClib/src/RTC_Micros.cpp | FelipeJojoa28/MQTT_Iot | f35f74775ae9edacb4a456d74a6aa55c12734b17 | [
"Apache-2.0"
] | 1 | 2022-03-10T11:19:46.000Z | 2022-03-10T11:19:46.000Z | libraries/RTClib/src/RTC_Micros.cpp | FelipeJojoa28/MQTT_Iot | f35f74775ae9edacb4a456d74a6aa55c12734b17 | [
"Apache-2.0"
] | null | null | null | libraries/RTClib/src/RTC_Micros.cpp | FelipeJojoa28/MQTT_Iot | f35f74775ae9edacb4a456d74a6aa55c12734b17 | [
"Apache-2.0"
] | 1 | 2018-09-28T11:43:20.000Z | 2018-09-28T11:43:20.000Z | #include "RTClib.h"
/**************************************************************************/
/*!
@brief Set the current date/time of the RTC_Micros clock.
@param dt DateTime object with the desired date and time
*/
/**************************************************************************/
void RTC_Micros::adjust(const DateTime &dt) {
lastMicros = micros();
lastUnix = dt.unixtime();
}
/**************************************************************************/
/*!
@brief Adjust the RTC_Micros clock to compensate for system clock drift
@param ppm Adjustment to make. A positive adjustment makes the clock faster.
*/
/**************************************************************************/
void RTC_Micros::adjustDrift(int ppm) { microsPerSecond = 1000000 - ppm; }
/**************************************************************************/
/*!
@brief Get the current date/time from the RTC_Micros clock.
@return DateTime object containing the current date/time
*/
/**************************************************************************/
DateTime RTC_Micros::now() {
uint32_t elapsedSeconds = (micros() - lastMicros) / microsPerSecond;
lastMicros += elapsedSeconds * microsPerSecond;
lastUnix += elapsedSeconds;
return lastUnix;
}
| 37.970588 | 80 | 0.463207 | FelipeJojoa28 |
3d04c7c1aa478d4067a24bbaa522f7df232b5972 | 239 | cpp | C++ | Source/Borderlands/weapon/WeaponStateInactive.cpp | yongaro/Borderlands | 39fbcf095400b53f4394cc115e59f40e59520484 | [
"Apache-2.0"
] | 1 | 2020-04-03T13:29:51.000Z | 2020-04-03T13:29:51.000Z | Source/Borderlands/weapon/WeaponStateInactive.cpp | yongaro/Borderlands | 39fbcf095400b53f4394cc115e59f40e59520484 | [
"Apache-2.0"
] | null | null | null | Source/Borderlands/weapon/WeaponStateInactive.cpp | yongaro/Borderlands | 39fbcf095400b53f4394cc115e59f40e59520484 | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "WeaponStateInactive.h"
#include "Borderlands.h"
UWeaponStateInactive::UWeaponStateInactive()
{
}
UWeaponStateInactive::~UWeaponStateInactive()
{
}
| 18.384615 | 78 | 0.790795 | yongaro |
3d05e3dde5a40e2d905e87d8dc61665ba96ef62c | 1,218 | hpp | C++ | src/Program.hpp | Fabio3rs/dbdhelp | 1afeef265b826220e2a769353b932fc6b8436905 | [
"MIT"
] | null | null | null | src/Program.hpp | Fabio3rs/dbdhelp | 1afeef265b826220e2a769353b932fc6b8436905 | [
"MIT"
] | null | null | null | src/Program.hpp | Fabio3rs/dbdhelp | 1afeef265b826220e2a769353b932fc6b8436905 | [
"MIT"
] | null | null | null | #pragma once
#ifndef MIGRATIONMGR_PROGRAM_HPP
#define MIGRATIONMGR_PROGRAM_HPP
#include <deque>
#include <cstdint>
#include <string>
#include "Database.hpp"
#include "CLuaH.hpp"
#include "CLuaFunctions.hpp"
#include "CViewsManager.hpp"
namespace migmgr
{
class Program
{
std::string config_script;
std::string migrations_directory;
std::deque<Database> dbs;
CLuaH::scriptStorage scripts;
bool loaded;
static int registerFunctions(lua_State* L);
static int registerGlobals(lua_State* L);
// Lua functions
static int select_database(lua_State* L);
static int create_table(lua_State* L);
static int alter_table(lua_State* L);
static int set_table_nicename(lua_State *L);
static int field_id(lua_State* L);
static int field_timestamps(lua_State* L);
static int create_field(lua_State *L);
static int dumptbl(lua_State *L);
public:
bool load();
void run();
void output_models();
void output_migrations();
static Program &prog();
private:
Program() noexcept;
};
}
#endif
| 22.981132 | 57 | 0.62069 | Fabio3rs |
3d0794c35948a79e6a18ccf73b93aa165aa37257 | 1,551 | cpp | C++ | Solutions/Candy/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | 1 | 2015-04-13T10:58:30.000Z | 2015-04-13T10:58:30.000Z | Solutions/Candy/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | Solutions/Candy/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <numeric>
using namespace std;
class Solution {
public:
//time limit exceeded
int candy(vector<int> &ratings) {
vector<int> res_v(ratings.size(), 1);
vector<int>::size_type size = ratings.size();
for(vector<int>::size_type i = 1; i < size; i++) {
if(ratings[i] > ratings[i-1]) {
res_v[i] = res_v[i-1] + 1;
}
else {
res_v[i] = 1;
for(auto j = i; j>0 && ratings[j-1] > ratings[j] && res_v[j-1] <= res_v[j]; j--) {
res_v[j-1] += 1;
}
}
}
int res = 0;
return accumulate(res_v.begin(),res_v.end(),res);
}
int candy2(vector<int > &ratings) {
vector<int>::size_type size = ratings.size();
vector<int> left(size,1), right(size,1);
int res = 0;
left[0] = 1;
right[size-1] = 1;
for(vector<int>::size_type i = 1; i< size; i++) {
if (ratings[i] > ratings[i-1]) {
left[i] = left[i-1] + 1;
}
if (ratings[size-i-1] > ratings[size-i]) {
right[size-1-i] = right[size-i] + 1;
}
}
for(vector<int>::size_type i = 0; i < size; i++) {
res += max(left[i], right[i]);
}
return res;
}
};
int main()
{
Solution s;
vector<int > ratings = {1,2,2};
cout<<s.candy(ratings)<<endl;
cout<<endl;
cout<<s.candy2(ratings)<<endl;
return 0;
}
| 27.210526 | 98 | 0.459059 | Crayzero |
3d0bf051397043a1671cf2fa0f9fe0964a689f4b | 2,997 | cpp | C++ | lib/util/Configurations.cpp | GloomyGrave/Sinsy-NG | 30c464b24eeb0d88caa9412286741889d1c84714 | [
"Unlicense"
] | 2 | 2021-03-20T10:29:29.000Z | 2022-02-09T03:48:36.000Z | lib/util/Configurations.cpp | GloomyGrave/Sinsy-NG | 30c464b24eeb0d88caa9412286741889d1c84714 | [
"Unlicense"
] | null | null | null | lib/util/Configurations.cpp | GloomyGrave/Sinsy-NG | 30c464b24eeb0d88caa9412286741889d1c84714 | [
"Unlicense"
] | 2 | 2020-10-24T02:51:41.000Z | 2022-03-26T20:32:39.000Z | /* Created by Ghost Gloomy on 2018/11/8. */
#include <fstream>
#include "Configurations.h"
#include "util_log.h"
#include "util_string.h"
#include "StringTokenizer.h"
namespace sinsy
{
namespace
{
const std::string SEPARATOR = "=";
};
/*!
constructor
*/
Configurations::Configurations()
{
}
/*!
destructor
*/
Configurations::~Configurations()
{
clear();
}
/*!
clear
*/
void Configurations::clear()
{
configs.clear();
}
/*!
read configurations from file
*/
bool Configurations::read(const std::string& fpath)
{
std::ifstream ifs(fpath.c_str());
if (!ifs) {
ERR_MSG("Cannot open config file : " << fpath);
return false;
}
clear();
std::string buffer;
while (!ifs.eof()) {
std::getline(ifs, buffer);
// remove comments
size_t idx = buffer.find("#");
if (idx != std::string::npos) {
buffer.resize(idx);
}
StringTokenizer st(buffer, SEPARATOR);
size_t sz(st.size());
if (0 == sz) {
continue;
} else if (2 != st.size()) {
ERR_MSG("Syntax error : " << fpath);
return false;
}
std::string key(st.at(0));
cutBlanks(key);
std::string value(st.at(1));
cutBlanks(value);
if (key.empty() || value.empty()) {
ERR_MSG("Syntax error : " << fpath);
return false;
}
// cut " and '
if (1 < value.size()) {
if ((('\"' == value[0]) && ('\"' == value[value.size() - 1])) || (('\'' == value[0]) && ('\'' == value[value.size() - 1]))) {
value = value.substr(1, value.size() - 2);
cutBlanks(value);
if (value.empty()) {
ERR_MSG("Syntax error : " << fpath);
return false;
}
}
}
configs.insert(std::make_pair/*<std::string, std::string>*/(key, value));
}
return true;
}
/*!
for std::string (need default)
*/
template<>
std::string Configurations::get<std::string>(const std::string& key, const std::string& def) const
{
Configs::const_iterator itr(configs.find(key));
if (configs.end() != itr) {
return itr->second;
}
return def;
}
/*!
for std::string (not need default)
*/
std::string Configurations::get(const std::string& key) const
{
Configs::const_iterator itr(configs.find(key));
if (configs.end() != itr) {
return itr->second;
}
return std::string();
}
/*!
for bool
*/
template<>
bool Configurations::get<bool>(const std::string& key, const bool& def) const
{
Configs::const_iterator itr(configs.find(key));
if (configs.end() != itr) {
std::string value(itr->second);
toLower(value);
if (value == "true") {
return true;
} else if (value == "false") {
return false;
}
int i(-1);
std::istringstream iss(value);
iss >> i;
if (0 == i) {
return false;
} else if (0 < i) {
return true;
}
}
return def;
}
}; // namespace sinsy
| 19.588235 | 134 | 0.539206 | GloomyGrave |
3d0e0842735b49023f5255f453912b41eceda925 | 999 | hpp | C++ | range.hpp | snir1551/Ex10_C- | 70c0701aa7d130be19ace214c83f66ac17b96d8d | [
"MIT"
] | 1 | 2021-05-31T13:09:48.000Z | 2021-05-31T13:09:48.000Z | range.hpp | snir1551/Ex10_C- | 70c0701aa7d130be19ace214c83f66ac17b96d8d | [
"MIT"
] | null | null | null | range.hpp | snir1551/Ex10_C- | 70c0701aa7d130be19ace214c83f66ac17b96d8d | [
"MIT"
] | null | null | null | #ifndef _RANGE_HPP
#define _RANGE_HPP
#include <iostream>
namespace itertools
{
//iterator class
class iterator
{
private:
int _num; //parameter
public:
iterator(int num): _num(num)
{
}
void operator++()
{
++(this->_num);
}
bool operator!=(const iterator& it) const
{
return (it._num != _num);
}
int operator*() const
{
return this->_num;
}
};
class range
{
private:
int _begin, _end;
public:
typedef int value_type;
range(int begin,int end): _begin(begin), _end(end)
{
}
iterator begin() const
{
return iterator(_begin);
}
iterator end() const
{
return iterator(_end);
}
};
}
#endif | 16.932203 | 62 | 0.409409 | snir1551 |
3d13ca4c6ef02ed64ada5a6e3f3b47f5da8f3f96 | 1,186 | cpp | C++ | LeetCode/Problems/Algorithms/#1337_TheKWeakestRowsInAMatrix_sol3_binary_search_and_heap_O(RlogC+RlogK)_time_O(R+K)_extra_space_12ms_10.5MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#1337_TheKWeakestRowsInAMatrix_sol3_binary_search_and_heap_O(RlogC+RlogK)_time_O(R+K)_extra_space_12ms_10.5MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#1337_TheKWeakestRowsInAMatrix_sol3_binary_search_and_heap_O(RlogC+RlogK)_time_O(R+K)_extra_space_12ms_10.5MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
private:
int soldiersCount(const vector<int>& V){
int l = 0;
int r = (int)V.size() - 1;
while(l != r){
int mid = (l + r + 1) / 2;
if(V[mid] == 1){
l = mid;
}else{
r = mid - 1;
}
}
int soldiers = 0;
if(V[r] == 1){
soldiers = r + 1;
}
return soldiers;
}
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
const int N = mat.size();
vector<int> soldiers(N, 0);
for(int row = 0; row < N; ++row){
soldiers[row] = soldiersCount(mat[row]);
}
priority_queue<pair<int, int>> maxHeap;
for(int row = 0; row < N; ++row){
maxHeap.push({soldiers[row], row});
if(maxHeap.size() == k + 1){
maxHeap.pop();
}
}
vector<int> answer(k);
for(int i = k - 1; i >= 0; --i){
answer[i] = maxHeap.top().second;
maxHeap.pop();
}
return answer;
}
}; | 25.782609 | 64 | 0.378583 | Tudor67 |
3d1b9ec61abe0fea9930aa8f553b718ef1f3d5fe | 1,282 | hpp | C++ | src/rynx/editor/tools/collisions_tool.hpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | 11 | 2019-08-19T08:44:14.000Z | 2020-09-22T20:04:46.000Z | src/rynx/editor/tools/collisions_tool.hpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | null | null | null | src/rynx/editor/tools/collisions_tool.hpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | null | null | null |
#pragma once
#include <rynx/editor/tools/tool.hpp>
namespace rynx {
class ecs;
namespace editor {
namespace tools {
class collisions_tool : public itool {
public:
collisions_tool(rynx::scheduler::context& ctx);
virtual void update(rynx::scheduler::context& ctx) override;
virtual void on_tool_selected() override {}
virtual void on_tool_unselected() override {}
virtual void verify(rynx::scheduler::context& ctx, error_emitter& emitter) override;
virtual bool operates_on(const std::string& type_name) override {
return type_name.find("rynx::components::collision") != std::string::npos;
}
virtual void on_entity_component_removed(
rynx::scheduler::context* ctx,
std::string componentTypeName,
rynx::ecs& ecs,
rynx::id id) override;
// default removing collision type component is not ok,
// need to know how to inform collision detection of the change.
virtual bool allow_component_remove(const std::string& type_name) override { return !operates_on(type_name); }
virtual std::string get_tool_name() override {
return "collisions";
}
virtual std::string get_button_texture() override {
return "collisions_tool";
}
private:
rynx::ecs& m_ecs;
};
}
}
}
| 25.64 | 114 | 0.695788 | Apodus |
3d1d26ca1d048cbee612aa44befec9696ae6d13c | 12,712 | cpp | C++ | emulator/src/mame/drivers/amspdwy.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/drivers/amspdwy.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/drivers/amspdwy.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Luca Elia
/***************************************************************************
-= American Speedway =-
driver by Luca Elia (l.elia@tin.it)
CPU : Z80A x 2
Sound: YM2151
(c)1987 Enerdyne Technologies, Inc. / PGD
***************************************************************************/
#include "emu.h"
#include "includes/amspdwy.h"
#include "cpu/z80/z80.h"
#include "speaker.h"
/***************************************************************************
Main CPU
***************************************************************************/
/*
765----- Buttons
---4---- Sgn(Wheel Delta)
----3210 Abs(Wheel Delta)
Or last value when wheel delta = 0
*/
uint8_t amspdwy_state::amspdwy_wheel_r( int index )
{
static const char *const portnames[] = { "WHEEL1", "WHEEL2", "AN1", "AN2" };
uint8_t wheel = ioport(portnames[2 + index])->read();
if (wheel != m_wheel_old[index])
{
wheel = (wheel & 0x7fff) - (wheel & 0x8000);
if (wheel > m_wheel_old[index])
m_wheel_return[index] = ((+wheel) & 0xf) | 0x00;
else
m_wheel_return[index] = ((-wheel) & 0xf) | 0x10;
m_wheel_old[index] = wheel;
}
return m_wheel_return[index] | ioport(portnames[index])->read();
}
READ8_MEMBER(amspdwy_state::amspdwy_wheel_0_r)
{
// player 1
return amspdwy_wheel_r(0);
}
READ8_MEMBER(amspdwy_state::amspdwy_wheel_1_r)
{
// player 2
return amspdwy_wheel_r(1);
}
READ8_MEMBER(amspdwy_state::amspdwy_sound_r)
{
return (m_ym2151->status_r(space, 0) & ~0x30) | ioport("IN0")->read();
}
void amspdwy_state::amspdwy_map(address_map &map)
{
map(0x0000, 0x7fff).rom();
map(0x8000, 0x801f).w(m_palette, FUNC(palette_device::write8)).share("palette");
map(0x9000, 0x93ff).mirror(0x0400).ram().w(this, FUNC(amspdwy_state::amspdwy_videoram_w)).share("videoram");
map(0x9800, 0x9bff).ram().w(this, FUNC(amspdwy_state::amspdwy_colorram_w)).share("colorram");
map(0x9c00, 0x9fff).ram(); // unused?
// AM_RANGE(0xa000, 0xa000) AM_WRITENOP // ?
map(0xa000, 0xa000).portr("DSW1");
map(0xa400, 0xa400).portr("DSW2").w(this, FUNC(amspdwy_state::amspdwy_flipscreen_w));
map(0xa800, 0xa800).r(this, FUNC(amspdwy_state::amspdwy_wheel_0_r));
map(0xac00, 0xac00).r(this, FUNC(amspdwy_state::amspdwy_wheel_1_r));
map(0xb000, 0xb000).nopw(); // irq ack?
map(0xb400, 0xb400).r(this, FUNC(amspdwy_state::amspdwy_sound_r)).w(m_soundlatch, FUNC(generic_latch_8_device::write));
map(0xc000, 0xc0ff).ram().share("spriteram");
map(0xe000, 0xe7ff).ram();
}
void amspdwy_state::amspdwy_portmap(address_map &map)
{
map(0x0000, 0x7fff).rom().region("tracks", 0);
}
/***************************************************************************
Sound CPU
***************************************************************************/
void amspdwy_state::amspdwy_sound_map(address_map &map)
{
map(0x0000, 0x7fff).rom();
// AM_RANGE(0x8000, 0x8000) AM_WRITENOP // ? writes 0 at start
map(0x9000, 0x9000).r(m_soundlatch, FUNC(generic_latch_8_device::read));
map(0xa000, 0xa001).rw(m_ym2151, FUNC(ym2151_device::read), FUNC(ym2151_device::write));
map(0xc000, 0xdfff).ram();
map(0xffff, 0xffff).nopr(); // ??? IY = FFFF at the start ?
}
/***************************************************************************
Input Ports
***************************************************************************/
static INPUT_PORTS_START( amspdwy )
PORT_START("DSW1")
PORT_DIPNAME( 0x01, 0x00, "Character Test" ) PORT_DIPLOCATION("SW1:8")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x01, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, "Show Arrows" ) PORT_DIPLOCATION("SW1:7")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x02, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW1:6")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x04, DEF_STR( On ) )
PORT_SERVICE_DIPLOC( 0x08, IP_ACTIVE_HIGH, "SW1:5" )
PORT_DIPNAME( 0x10, 0x00, "Steering Test" ) PORT_DIPLOCATION("SW1:4")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x10, DEF_STR( On ) )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x00, "SW1:3" ) /* Listed as "Unused" */
PORT_DIPUNUSED_DIPLOC( 0x40, 0x00, "SW1:2" ) /* Listed as "Unused" */
PORT_DIPUNUSED_DIPLOC( 0x80, 0x00, "SW1:1" ) /* Listed as "Unused" */
PORT_START("DSW2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW2:7,8")
PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C ) )
// PORT_DIPSETTING( 0x02, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) )
PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SW2:5,6")
PORT_DIPSETTING( 0x00, DEF_STR( Easy ) )
PORT_DIPSETTING( 0x04, DEF_STR( Normal ) )
PORT_DIPSETTING( 0x08, DEF_STR( Hard ) )
PORT_DIPSETTING( 0x0c, DEF_STR( Hardest ) )
PORT_DIPNAME( 0x30, 0x00, "Time To Qualify" ) PORT_DIPLOCATION("SW2:3,4") /* code at 0x1770 */
PORT_DIPSETTING( 0x30, "20 sec" )
PORT_DIPSETTING( 0x20, "30 sec" )
PORT_DIPSETTING( 0x10, "45 sec" )
PORT_DIPSETTING( 0x00, "60 sec" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x00, "SW2:2" ) /* Listed as "Unused" */
PORT_DIPUNUSED_DIPLOC( 0x80, 0x00, "SW2:1" ) /* Listed as "Unused" */
PORT_START("WHEEL1") // Player 1 Wheel + Coins
PORT_BIT( 0x1f, IP_ACTIVE_HIGH, IPT_SPECIAL ) // wheel
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_IMPULSE(2) // 2-3f
PORT_START("WHEEL2") // Player 2 Wheel + Coins
PORT_BIT( 0x1f, IP_ACTIVE_HIGH, IPT_SPECIAL )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_IMPULSE(2)
PORT_START("IN0") // Player 1&2 Pedals + YM2151 Sound Status
PORT_BIT( 0x0f, IP_ACTIVE_HIGH, IPT_SPECIAL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0xc0, IP_ACTIVE_HIGH, IPT_SPECIAL )
PORT_START("AN1") // Player 1 Analog Fake Port
PORT_BIT( 0xffff, 0x0000, IPT_DIAL ) PORT_SENSITIVITY(15) PORT_KEYDELTA(20) PORT_CODE_DEC(KEYCODE_LEFT) PORT_CODE_INC(KEYCODE_RIGHT) PORT_PLAYER(1)
PORT_START("AN2") // Player 2 Analog Fake Port
PORT_BIT( 0xffff, 0x0000, IPT_DIAL ) PORT_SENSITIVITY(15) PORT_KEYDELTA(20) PORT_CODE_DEC(KEYCODE_D) PORT_CODE_INC(KEYCODE_G) PORT_PLAYER(2)
INPUT_PORTS_END
static INPUT_PORTS_START( amspdwya )
PORT_INCLUDE(amspdwy)
PORT_MODIFY("DSW2")
PORT_DIPNAME( 0x10, 0x00, "Time To Qualify" ) PORT_DIPLOCATION("SW2:4") /* code at 0x2696 */
PORT_DIPSETTING( 0x10, "45 sec" )
PORT_DIPSETTING( 0x00, "60 sec" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x00, "SW2:3" ) /* Listed as "Unused" */
INPUT_PORTS_END
/***************************************************************************
Graphics Layouts
***************************************************************************/
static const gfx_layout layout_8x8x2 =
{
8,8,
RGN_FRAC(1,2),
2,
{ RGN_FRAC(0,2), RGN_FRAC(1,2) },
{ STEP8(0,1) },
{ STEP8(0,8) },
8*8
};
static GFXDECODE_START( amspdwy )
GFXDECODE_ENTRY( "gfx1", 0, layout_8x8x2, 0, 8 )
GFXDECODE_END
/***************************************************************************
Machine Drivers
***************************************************************************/
void amspdwy_state::machine_start()
{
save_item(NAME(m_flipscreen));
save_item(NAME(m_wheel_old));
save_item(NAME(m_wheel_return));
}
void amspdwy_state::machine_reset()
{
m_flipscreen = 0;
m_wheel_old[0] = 0;
m_wheel_old[1] = 0;
m_wheel_return[0] = 0;
m_wheel_return[1] = 0;
}
MACHINE_CONFIG_START(amspdwy_state::amspdwy)
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", Z80, 3000000)
MCFG_CPU_PROGRAM_MAP(amspdwy_map)
MCFG_CPU_IO_MAP(amspdwy_portmap)
MCFG_CPU_VBLANK_INT_DRIVER("screen", amspdwy_state, irq0_line_hold) /* IRQ: 60Hz, NMI: retn */
MCFG_CPU_ADD("audiocpu", Z80, 3000000)
MCFG_CPU_PROGRAM_MAP(amspdwy_sound_map)
MCFG_QUANTUM_PERFECT_CPU("maincpu")
/* video hardware */
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_REFRESH_RATE(60)
MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0))
MCFG_SCREEN_SIZE(256, 256)
MCFG_SCREEN_VISIBLE_AREA(0, 256-1, 0+16, 256-16-1)
MCFG_SCREEN_UPDATE_DRIVER(amspdwy_state, screen_update_amspdwy)
MCFG_SCREEN_PALETTE("palette")
MCFG_GFXDECODE_ADD("gfxdecode", "palette", amspdwy)
MCFG_PALETTE_ADD("palette", 32)
MCFG_PALETTE_FORMAT(BBGGGRRR_inverted)
/* sound hardware */
MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
MCFG_GENERIC_LATCH_8_ADD("soundlatch")
MCFG_GENERIC_LATCH_DATA_PENDING_CB(INPUTLINE("audiocpu", INPUT_LINE_NMI))
MCFG_YM2151_ADD("ymsnd", 3000000)
MCFG_YM2151_IRQ_HANDLER(INPUTLINE("audiocpu", 0))
MCFG_SOUND_ROUTE(0, "lspeaker", 1.0)
MCFG_SOUND_ROUTE(1, "rspeaker", 1.0)
MACHINE_CONFIG_END
/***************************************************************************
ROMs Loading
***************************************************************************/
/***************************************************************************
American Speedway
USES TWO Z80 CPU'S W/YM2151 SOUND
THE NUMBERS WITH THE NAMES ARE PROBABLY CHECKSUMS
NAME LOCATION TYPE
------------------------
AUDI9363 U2 27256 CONN BD
GAME5807 U33 " "
TRKS6092 U34 " "
HIHIE12A 4A 2732 REAR BD
HILO9B3C 5A " "
LOHI4644 2A " "
LOLO1D51 1A " "
American Speedway (Set 2)
1987 Enerdyne Technologies, Inc. Has Rev 4 PGD written on the top board.
Processors
------------------
Dual Z80As
YM2151 (sound)
RAM
------------------
12 2114
5 82S16N
Eproms
==================
Name Loc TYpe Checksum
---------- ---- ----- --------
Game.u22 U33 27256 A222
Tracks.u34 U34 27256 6092
Audio.U02 U2 27256 9363
LOLO1.1A 1A 2732 1D51
LOHI.2A 2A 2732 4644
HIHI.4A 3/4A 2732 E12A
HILO.5A 5A 2732 9B3C
***************************************************************************/
ROM_START( amspdwy )
ROM_REGION( 0x10000, "maincpu", 0 ) /* Main Z80 Code */
ROM_LOAD( "game5807.u33", 0x0000, 0x8000, CRC(88233b59) SHA1(bfdf10dde1731cde5c579a9a5173cafe9295a80c) )
ROM_REGION( 0x10000, "audiocpu", 0 ) /* Sound Z80 Code */
ROM_LOAD( "audi9463.u2", 0x0000, 0x8000, CRC(61b0467e) SHA1(74509e7712838dd760919893aeda9241d308d0c3) )
ROM_REGION( 0x8000, "tracks", 0 )
ROM_LOAD( "trks6092.u34", 0x0000, 0x8000, CRC(74a4e7b7) SHA1(b4f6e3faaf048351c6671205f52378a64b81bcb1) )
ROM_REGION( 0x4000, "gfx1", 0 ) /* Layer + Sprites */
ROM_LOAD( "hilo9b3c.5a", 0x0000, 0x1000, CRC(f50f864c) SHA1(5b2412c1558b30a04523fcdf1d5cf6fdae1ba88d) )
ROM_LOAD( "hihie12a.4a", 0x1000, 0x1000, CRC(3d7497f3) SHA1(34820ba42d9c9dab1d6fdda15795450ce08392c1) )
ROM_LOAD( "lolo1d51.1a", 0x2000, 0x1000, CRC(58701c1c) SHA1(67b476e697652a6b684bd76ae6c0078ed4b3e3a2) )
ROM_LOAD( "lohi4644.2a", 0x3000, 0x1000, CRC(a1d802b1) SHA1(1249ce406b1aa518885a02ab063fa14906ccec2e) )
ROM_END
ROM_START( amspdwya )
ROM_REGION( 0x10000, "maincpu", 0 ) /* Main Z80 Code */
ROM_LOAD( "game.u33", 0x0000, 0x8000, CRC(facab102) SHA1(e232969eaaad8b89ac8e28ee0a7996107a7de9a2) )
ROM_REGION( 0x10000, "audiocpu", 0 ) /* Sound Z80 Code */
ROM_LOAD( "audi9463.u2", 0x0000, 0x8000, CRC(61b0467e) SHA1(74509e7712838dd760919893aeda9241d308d0c3) )
ROM_REGION( 0x8000, "tracks", 0 )
ROM_LOAD( "trks6092.u34", 0x0000, 0x8000, CRC(74a4e7b7) SHA1(b4f6e3faaf048351c6671205f52378a64b81bcb1) )
ROM_REGION( 0x4000, "gfx1", 0 ) /* Layer + Sprites */
ROM_LOAD( "hilo9b3c.5a", 0x0000, 0x1000, CRC(f50f864c) SHA1(5b2412c1558b30a04523fcdf1d5cf6fdae1ba88d) )
ROM_LOAD( "hihie12a.4a", 0x1000, 0x1000, CRC(3d7497f3) SHA1(34820ba42d9c9dab1d6fdda15795450ce08392c1) )
ROM_LOAD( "lolo1d51.1a", 0x2000, 0x1000, CRC(58701c1c) SHA1(67b476e697652a6b684bd76ae6c0078ed4b3e3a2) )
ROM_LOAD( "lohi4644.2a", 0x3000, 0x1000, CRC(a1d802b1) SHA1(1249ce406b1aa518885a02ab063fa14906ccec2e) )
ROM_END
/* (C) 1987 ETI 8402 MAGNOLIA ST. #C SANTEE, CA 92071 */
GAME( 1987, amspdwy, 0, amspdwy, amspdwy, amspdwy_state, 0, ROT0, "Enerdyne Technologies Inc.", "American Speedway (set 1)", MACHINE_SUPPORTS_SAVE )
GAME( 1987, amspdwya, amspdwy, amspdwy, amspdwya, amspdwy_state, 0, ROT0, "Enerdyne Technologies Inc.", "American Speedway (set 2)", MACHINE_SUPPORTS_SAVE )
| 32.932642 | 156 | 0.617527 | rjw57 |
3d20528cbf586c5c85e76140b4bb84b731a09e46 | 1,283 | hpp | C++ | PSME/agent/compute/include/status/state_machine_action.hpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 5 | 2021-10-07T15:36:37.000Z | 2022-03-01T07:21:49.000Z | PSME/agent/compute/include/status/state_machine_action.hpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | null | null | null | PSME/agent/compute/include/status/state_machine_action.hpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 1 | 2022-03-01T07:21:51.000Z | 2022-03-01T07:21:51.000Z | /*!
* @copyright
* Copyright (c) 2015-2017 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* @file state_machine_thread.hpp
* @brief StateMachine thread.
* */
#pragma once
#include "agent-framework/state_machine/state_machine_thread_action.hpp"
#include "agent-framework/state_machine/state_thread_entry.hpp"
namespace agent_framework {
namespace discovery {
class Discovery;
}
}
/*! Psme namespace */
namespace agent {
namespace compute {
class StateMachineAction final : public agent_framework::state_machine::StateMachineThreadAction {
public:
/*! @brief Default destructor. */
~StateMachineAction() = default;
void execute(StateThreadEntrySharedPtr entry) override;
};
}
}
| 22.508772 | 98 | 0.742011 | opencomputeproject |
3d20c199e6f8d433ba64037dc25b0f7ccdda1efd | 3,768 | cpp | C++ | qws/src/gui/QTreeWidgetItem_DhClass.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 42 | 2015-02-16T19:29:16.000Z | 2021-07-25T11:09:03.000Z | qws/src/gui/QTreeWidgetItem_DhClass.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 1 | 2017-11-23T12:49:25.000Z | 2017-11-23T12:49:25.000Z | qws/src/gui/QTreeWidgetItem_DhClass.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 5 | 2015-10-15T21:25:30.000Z | 2017-11-22T13:18:24.000Z | /////////////////////////////////////////////////////////////////////////////
//
// File : QTreeWidgetItem_DhClass.cpp
// Copyright : (c) David Harley 2010
// Project : qtHaskell
// Version : 1.1.4
// Modified : 2010-09-02 17:02:05
//
// Warning : this file is machine generated - do not modify.
//
/////////////////////////////////////////////////////////////////////////////
#include <gui/QTreeWidgetItem_DhClass.h>
void DhQTreeWidgetItem::userDefined(int x1) const {
void* ro_ptr;
void* rf_ptr;
if(handlerSetud(x1,(void*&)ro_ptr,(void*&)rf_ptr,0)) (*(void(*)(void*))rf_ptr)(ro_ptr);
}
QVariant* DhQTreeWidgetItem::userDefinedVariant(int x1, QVariant* x2) const {
void* ro_ptr;
void* rf_ptr;
if(handlerSetud(x1,(void*&)ro_ptr,(void*&)rf_ptr,1)) return (QVariant*)(*(void*(*)(void*,void*))rf_ptr)(ro_ptr, (void*)x2);
return NULL
;}
QTreeWidgetItem* DhQTreeWidgetItem::clone() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(0,(void*&)ro_ptr,(void*&)rf_ptr)) return (QTreeWidgetItem*)(*(void*(*)(void*))rf_ptr)(ro_ptr);
return QTreeWidgetItem::clone();
}
QTreeWidgetItem* DhQTreeWidgetItem::Dhclone() const {
return QTreeWidgetItem::clone();
}
QTreeWidgetItem* DhQTreeWidgetItem::Dvhclone() const {
return clone();
}
QVariant DhQTreeWidgetItem::data(int x1, int x2) const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(1,(void*&)ro_ptr,(void*&)rf_ptr)) return *(QVariant*)(*(void*(*)(void*,int,int))rf_ptr)(ro_ptr, x1, x2);
return QTreeWidgetItem::data(x1, x2);
}
QVariant DhQTreeWidgetItem::Dhdata(int x1, int x2) const {
return QTreeWidgetItem::data(x1, x2);
}
QVariant DhQTreeWidgetItem::Dvhdata(int x1, int x2) const {
return data(x1, x2);
}
void DhQTreeWidgetItem::setData(int x1, int x2, const QVariant& x3) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(2,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,int,int,void*))rf_ptr)(ro_ptr, x1, x2, (void*)&x3);
return QTreeWidgetItem::setData(x1, x2, x3);
}
void DhQTreeWidgetItem::DhsetData(int x1, int x2, const QVariant& x3) {
return QTreeWidgetItem::setData(x1, x2, x3);
}
void DhQTreeWidgetItem::DvhsetData(int x1, int x2, const QVariant& x3) {
return setData(x1, x2, x3);
}
QHash <QByteArray, int> DhQTreeWidgetItem::initXhHash() {
QHash <QByteArray, int> txh;
txh[QMetaObject::normalizedSignature("(QTreeWidgetItem*)clone()")] = 0;
txh[QMetaObject::normalizedSignature("(QVariant)data(int,int)")] = 1;
txh[QMetaObject::normalizedSignature("setData(int,int,const QVariant&)")] = 2;
return txh;
}
QHash <QByteArray, int> DhQTreeWidgetItem::xhHash = DhQTreeWidgetItem::initXhHash();
bool DhQTreeWidgetItem::setDynamicQHandler(void * ro_ptr, char * eventId, void * rf_ptr, void * st_ptr, void * df_ptr) {
QByteArray theHandler = QMetaObject::normalizedSignature(eventId);
if (xhHash.contains(theHandler)) {
int thir = xhHash.value(theHandler);
return isetDynamicQHandler(ro_ptr, thir, rf_ptr, st_ptr, df_ptr);
}
return false;
}
bool DhQTreeWidgetItem::setDynamicQHandlerud(int udtyp, void * ro_ptr, int eventId, void * rf_ptr, void * st_ptr, void * df_ptr) {
if ((udtyp < 0) || (udtyp > 2)) {
return false;
}
return isetDynamicQHandlerud(ro_ptr, eventId, rf_ptr, st_ptr, df_ptr, udtyp);
}
bool DhQTreeWidgetItem::unSetDynamicQHandler(char * eventId) {
QByteArray theHandler = QMetaObject::normalizedSignature(eventId);
if (xhHash.contains(theHandler)) {
int thir = xhHash.value(theHandler);
return iunSetDynamicQHandler(thir);
}
return false;
}
bool DhQTreeWidgetItem::unSetDynamicQHandlerud(int udtyp, int eventId) {
if ((udtyp < 0) || (udtyp > 2)) {
return false;
}
return iunSetDynamicQHandlerud(eventId, udtyp);
}
| 32.765217 | 130 | 0.666401 | keera-studios |
3d231a259d8b4b593c281eb60bdb2ef46b457ea1 | 49,307 | cpp | C++ | src/services/pcn-simplebridge/src/api/SimplebridgeApi.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-07-16T04:49:29.000Z | 2020-07-16T04:49:29.000Z | src/services/pcn-simplebridge/src/api/SimplebridgeApi.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/services/pcn-simplebridge/src/api/SimplebridgeApi.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /**
* simplebridge API
* Simple L2 Bridge Service
*
* OpenAPI spec version: 1.0.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/polycube-network/swagger-codegen.git
* branch polycube
*/
/* Do not edit this file manually */
#include "SimplebridgeApi.h"
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
SimplebridgeApi::SimplebridgeApi() {
setup_routes();
};
void SimplebridgeApi::control_handler(const HttpHandleRequest &request, HttpHandleResponse &response) {
try {
auto s = router.route(request, response);
if (s == Rest::Router::Status::NotFound) {
response.send(Http::Code::Not_Found);
}
} catch (const std::exception &e) {
response.send(polycube::service::Http::Code::Bad_Request, e.what());
}
}
void SimplebridgeApi::setup_routes() {
using namespace polycube::service::Rest;
Routes::Post(router, base + ":name/", Routes::bind(&SimplebridgeApi::create_simplebridge_by_id_handler, this));
Routes::Post(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_by_id_handler, this));
Routes::Post(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_entry_by_id_handler, this));
Routes::Post(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_entry_list_by_id_handler, this));
Routes::Post(router, base + ":name/fdb/flush/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_flush_by_id_handler, this));
Routes::Post(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::create_simplebridge_ports_by_id_handler, this));
Routes::Post(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::create_simplebridge_ports_list_by_id_handler, this));
Routes::Delete(router, base + ":name/", Routes::bind(&SimplebridgeApi::delete_simplebridge_by_id_handler, this));
Routes::Delete(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::delete_simplebridge_fdb_by_id_handler, this));
Routes::Delete(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::delete_simplebridge_fdb_entry_by_id_handler, this));
Routes::Delete(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::delete_simplebridge_fdb_entry_list_by_id_handler, this));
Routes::Delete(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::delete_simplebridge_ports_by_id_handler, this));
Routes::Delete(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::delete_simplebridge_ports_list_by_id_handler, this));
Routes::Get(router, base + ":name/", Routes::bind(&SimplebridgeApi::read_simplebridge_by_id_handler, this));
Routes::Get(router, base + ":name/fdb/aging-time/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_aging_time_by_id_handler, this));
Routes::Get(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_by_id_handler, this));
Routes::Get(router, base + ":name/fdb/entry/:address/age/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_age_by_id_handler, this));
Routes::Get(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_by_id_handler, this));
Routes::Get(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_list_by_id_handler, this));
Routes::Get(router, base + ":name/fdb/entry/:address/port/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_port_by_id_handler, this));
Routes::Get(router, base + "", Routes::bind(&SimplebridgeApi::read_simplebridge_list_by_id_handler, this));
Routes::Get(router, base + ":name/loglevel/", Routes::bind(&SimplebridgeApi::read_simplebridge_loglevel_by_id_handler, this));
Routes::Get(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_by_id_handler, this));
Routes::Get(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_list_by_id_handler, this));
Routes::Get(router, base + ":name/ports/:ports_name/mac/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_mac_by_id_handler, this));
Routes::Get(router, base + ":name/ports/:ports_name/peer/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_peer_by_id_handler, this));
Routes::Get(router, base + ":name/ports/:ports_name/status/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_status_by_id_handler, this));
Routes::Get(router, base + ":name/ports/:ports_name/uuid/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_uuid_by_id_handler, this));
Routes::Get(router, base + ":name/type/", Routes::bind(&SimplebridgeApi::read_simplebridge_type_by_id_handler, this));
Routes::Get(router, base + ":name/uuid/", Routes::bind(&SimplebridgeApi::read_simplebridge_uuid_by_id_handler, this));
Routes::Put(router, base + ":name/", Routes::bind(&SimplebridgeApi::replace_simplebridge_by_id_handler, this));
Routes::Put(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::replace_simplebridge_fdb_by_id_handler, this));
Routes::Put(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::replace_simplebridge_fdb_entry_by_id_handler, this));
Routes::Put(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::replace_simplebridge_fdb_entry_list_by_id_handler, this));
Routes::Put(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::replace_simplebridge_ports_by_id_handler, this));
Routes::Put(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::replace_simplebridge_ports_list_by_id_handler, this));
Routes::Patch(router, base + ":name/", Routes::bind(&SimplebridgeApi::update_simplebridge_by_id_handler, this));
Routes::Patch(router, base + ":name/fdb/aging-time/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_aging_time_by_id_handler, this));
Routes::Patch(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_by_id_handler, this));
Routes::Patch(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_entry_by_id_handler, this));
Routes::Patch(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_entry_list_by_id_handler, this));
Routes::Patch(router, base + ":name/fdb/entry/:address/port/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_entry_port_by_id_handler, this));
Routes::Patch(router, base + "", Routes::bind(&SimplebridgeApi::update_simplebridge_list_by_id_handler, this));
Routes::Patch(router, base + ":name/loglevel/", Routes::bind(&SimplebridgeApi::update_simplebridge_loglevel_by_id_handler, this));
Routes::Patch(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::update_simplebridge_ports_by_id_handler, this));
Routes::Patch(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::update_simplebridge_ports_list_by_id_handler, this));
Routes::Patch(router, base + ":name/ports/:ports_name/peer/", Routes::bind(&SimplebridgeApi::update_simplebridge_ports_peer_by_id_handler, this));
Routes::Options(router, base + ":name/", Routes::bind(&SimplebridgeApi::read_simplebridge_by_id_help, this));
Routes::Options(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_by_id_help, this));
Routes::Options(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_by_id_help, this));
Routes::Options(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_list_by_id_help, this));
Routes::Options(router, base + "", Routes::bind(&SimplebridgeApi::read_simplebridge_list_by_id_help, this));
Routes::Options(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_by_id_help, this));
Routes::Options(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_list_by_id_help, this));
Routes::Options(router, base + ":name/fdb/flush/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_flush_by_id_help, this));
}
void SimplebridgeApi::create_simplebridge_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
// Getting the body param
SimplebridgeJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setName(name);
value.validateMandatoryFields();
value.validateParams();
create_simplebridge_by_id(name, value);
response.send(polycube::service::Http::Code::Created);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::create_simplebridge_fdb_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
// Getting the body param
FdbJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.validateMandatoryFields();
value.validateParams();
create_simplebridge_fdb_by_id(name, value);
response.send(polycube::service::Http::Code::Created);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::create_simplebridge_fdb_entry_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
try {
// Getting the body param
FdbEntryJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setAddress(address);
value.validateMandatoryFields();
value.validateParams();
create_simplebridge_fdb_entry_by_id(name, address, value);
response.send(polycube::service::Http::Code::Created);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::create_simplebridge_fdb_entry_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
// Getting the body param
std::vector<FdbEntryJsonObject> value;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
for (auto &j : request_body) {
FdbEntryJsonObject a;
a.fromJson(j);
a.validateKeys();
a.validateMandatoryFields();
a.validateParams();
value.push_back(a);
}
create_simplebridge_fdb_entry_list_by_id(name, value);
response.send(polycube::service::Http::Code::Created);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::create_simplebridge_fdb_flush_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = create_simplebridge_fdb_flush_by_id(name);
nlohmann::json response_body;
response_body = x.toJson();
response.send(polycube::service::Http::Code::Created, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::create_simplebridge_ports_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
// Getting the body param
PortsJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setName(portsName);
value.validateMandatoryFields();
value.validateParams();
create_simplebridge_ports_by_id(name, portsName, value);
response.send(polycube::service::Http::Code::Created);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::create_simplebridge_ports_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
// Getting the body param
std::vector<PortsJsonObject> value;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
for (auto &j : request_body) {
PortsJsonObject a;
a.fromJson(j);
a.validateKeys();
a.validateMandatoryFields();
a.validateParams();
value.push_back(a);
}
create_simplebridge_ports_list_by_id(name, value);
response.send(polycube::service::Http::Code::Created);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::delete_simplebridge_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
delete_simplebridge_by_id(name);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::delete_simplebridge_fdb_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
delete_simplebridge_fdb_by_id(name);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::delete_simplebridge_fdb_entry_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
try {
delete_simplebridge_fdb_entry_by_id(name, address);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::delete_simplebridge_fdb_entry_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
delete_simplebridge_fdb_entry_list_by_id(name);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::delete_simplebridge_ports_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
delete_simplebridge_ports_by_id(name, portsName);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::delete_simplebridge_ports_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
delete_simplebridge_ports_list_by_id(name);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = read_simplebridge_by_id(name);
nlohmann::json response_body;
response_body = x.toJson();
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_fdb_aging_time_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = read_simplebridge_fdb_aging_time_by_id(name);
nlohmann::json response_body;
response_body = x;
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_fdb_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = read_simplebridge_fdb_by_id(name);
nlohmann::json response_body;
response_body = x.toJson();
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_fdb_entry_age_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
try {
auto x = read_simplebridge_fdb_entry_age_by_id(name, address);
nlohmann::json response_body;
response_body = x;
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_fdb_entry_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
try {
auto x = read_simplebridge_fdb_entry_by_id(name, address);
nlohmann::json response_body;
response_body = x.toJson();
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_fdb_entry_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = read_simplebridge_fdb_entry_list_by_id(name);
nlohmann::json response_body;
for (auto &i : x) {
response_body += i.toJson();
}
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_fdb_entry_port_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
try {
auto x = read_simplebridge_fdb_entry_port_by_id(name, address);
nlohmann::json response_body;
response_body = x;
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
try {
auto x = read_simplebridge_list_by_id();
nlohmann::json response_body;
for (auto &i : x) {
response_body += i.toJson();
}
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_loglevel_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = read_simplebridge_loglevel_by_id(name);
nlohmann::json response_body;
response_body = SimplebridgeJsonObject::SimplebridgeLoglevelEnum_to_string(x);
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_ports_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
auto x = read_simplebridge_ports_by_id(name, portsName);
nlohmann::json response_body;
response_body = x.toJson();
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_ports_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = read_simplebridge_ports_list_by_id(name);
nlohmann::json response_body;
for (auto &i : x) {
response_body += i.toJson();
}
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_ports_mac_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
auto x = read_simplebridge_ports_mac_by_id(name, portsName);
nlohmann::json response_body;
response_body = x;
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_ports_peer_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
auto x = read_simplebridge_ports_peer_by_id(name, portsName);
nlohmann::json response_body;
response_body = x;
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_ports_status_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
auto x = read_simplebridge_ports_status_by_id(name, portsName);
nlohmann::json response_body;
response_body = PortsJsonObject::PortsStatusEnum_to_string(x);
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_ports_uuid_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
auto x = read_simplebridge_ports_uuid_by_id(name, portsName);
nlohmann::json response_body;
response_body = x;
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_type_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = read_simplebridge_type_by_id(name);
nlohmann::json response_body;
response_body = SimplebridgeJsonObject::CubeType_to_string(x);
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_uuid_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
auto x = read_simplebridge_uuid_by_id(name);
nlohmann::json response_body;
response_body = x;
response.send(polycube::service::Http::Code::Ok, response_body.dump(4));
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::replace_simplebridge_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
// Getting the body param
SimplebridgeJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setName(name);
value.validateMandatoryFields();
value.validateParams();
replace_simplebridge_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::replace_simplebridge_fdb_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
// Getting the body param
FdbJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.validateMandatoryFields();
value.validateParams();
replace_simplebridge_fdb_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::replace_simplebridge_fdb_entry_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
try {
// Getting the body param
FdbEntryJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setAddress(address);
value.validateMandatoryFields();
value.validateParams();
replace_simplebridge_fdb_entry_by_id(name, address, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::replace_simplebridge_fdb_entry_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
// Getting the body param
std::vector<FdbEntryJsonObject> value;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
for (auto &j : request_body) {
FdbEntryJsonObject a;
a.fromJson(j);
a.validateKeys();
a.validateMandatoryFields();
a.validateParams();
value.push_back(a);
}
replace_simplebridge_fdb_entry_list_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::replace_simplebridge_ports_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
// Getting the body param
PortsJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setName(portsName);
value.validateMandatoryFields();
value.validateParams();
replace_simplebridge_ports_by_id(name, portsName, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::replace_simplebridge_ports_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
// Getting the body param
std::vector<PortsJsonObject> value;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
for (auto &j : request_body) {
PortsJsonObject a;
a.fromJson(j);
a.validateKeys();
a.validateMandatoryFields();
a.validateParams();
value.push_back(a);
}
replace_simplebridge_ports_list_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
// Getting the body param
SimplebridgeJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setName(name);
value.validateParams();
update_simplebridge_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_fdb_aging_time_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
// Getting the body param
uint32_t value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
// The conversion is done automatically by the json library
value = request_body;
update_simplebridge_fdb_aging_time_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_fdb_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
// Getting the body param
FdbJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.validateParams();
update_simplebridge_fdb_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_fdb_entry_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
try {
// Getting the body param
FdbEntryJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setAddress(address);
value.validateParams();
update_simplebridge_fdb_entry_by_id(name, address, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_fdb_entry_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
// Getting the body param
std::vector<FdbEntryJsonObject> value;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
for (auto &j : request_body) {
FdbEntryJsonObject a;
a.fromJson(j);
a.validateKeys();
a.validateParams();
value.push_back(a);
}
update_simplebridge_fdb_entry_list_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_fdb_entry_port_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
try {
// Getting the body param
std::string value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
// The conversion is done automatically by the json library
value = request_body;
update_simplebridge_fdb_entry_port_by_id(name, address, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the body param
std::vector<SimplebridgeJsonObject> value;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
for (auto &j : request_body) {
SimplebridgeJsonObject a;
a.fromJson(j);
a.validateKeys();
a.validateParams();
value.push_back(a);
}
update_simplebridge_list_by_id(value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_loglevel_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
try {
// Getting the body param
SimplebridgeLoglevelEnum value_;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value_ = SimplebridgeJsonObject::string_to_SimplebridgeLoglevelEnum(request_body);
update_simplebridge_loglevel_by_id(name, value_);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_ports_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
// Getting the body param
PortsJsonObject value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
value.fromJson(request_body);
value.setName(portsName);
value.validateParams();
update_simplebridge_ports_by_id(name, portsName, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_ports_list_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
// Getting the body param
std::vector<PortsJsonObject> value;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
for (auto &j : request_body) {
PortsJsonObject a;
a.fromJson(j);
a.validateKeys();
a.validateParams();
value.push_back(a);
}
update_simplebridge_ports_list_by_id(name, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::update_simplebridge_ports_peer_by_id_handler(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
try {
// Getting the body param
std::string value;
nlohmann::json request_body = nlohmann::json::parse(request.body());
// The conversion is done automatically by the json library
value = request_body;
update_simplebridge_ports_peer_by_id(name, portsName, value);
response.send(polycube::service::Http::Code::Ok);
} catch(const std::exception &e) {
response.send(polycube::service::Http::Code::Internal_Server_Error, e.what());
}
}
void SimplebridgeApi::read_simplebridge_by_id_help(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
using polycube::service::HelpType;
nlohmann::json val = nlohmann::json::object();
switch (request.help_type()) {
case HelpType::SHOW:
val["params"] = SimplebridgeJsonObject::helpElements();
break;
case HelpType::ADD:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::SET:
val["params"] = SimplebridgeJsonObject::helpWritableLeafs();
break;
case HelpType::DEL:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::NONE:
val["commands"] = {"set", "show"};
val["params"] = SimplebridgeJsonObject::helpComplexElements();
val["actions"] = SimplebridgeJsonObject::helpActions();
break;
case HelpType::NO_HELP:
response.send(polycube::service::Http::Code::Bad_Request);
return;
}
response.send(polycube::service::Http::Code::Ok, val.dump(4));
}
void SimplebridgeApi::read_simplebridge_fdb_by_id_help(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
using polycube::service::HelpType;
nlohmann::json val = nlohmann::json::object();
switch (request.help_type()) {
case HelpType::SHOW:
val["params"] = FdbJsonObject::helpElements();
break;
case HelpType::ADD:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::SET:
val["params"] = FdbJsonObject::helpWritableLeafs();
break;
case HelpType::DEL:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::NONE:
val["commands"] = {"set", "show"};
val["params"] = FdbJsonObject::helpComplexElements();
val["actions"] = FdbJsonObject::helpActions();
break;
case HelpType::NO_HELP:
response.send(polycube::service::Http::Code::Bad_Request);
return;
}
response.send(polycube::service::Http::Code::Ok, val.dump(4));
}
void SimplebridgeApi::read_simplebridge_fdb_entry_by_id_help(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto address = request.param(":address").as<std::string>();
using polycube::service::HelpType;
nlohmann::json val = nlohmann::json::object();
switch (request.help_type()) {
case HelpType::SHOW:
val["params"] = FdbEntryJsonObject::helpElements();
break;
case HelpType::ADD:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::SET:
val["params"] = FdbEntryJsonObject::helpWritableLeafs();
break;
case HelpType::DEL:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::NONE:
val["commands"] = {"set", "show"};
val["params"] = FdbEntryJsonObject::helpComplexElements();
val["actions"] = FdbEntryJsonObject::helpActions();
break;
case HelpType::NO_HELP:
response.send(polycube::service::Http::Code::Bad_Request);
return;
}
response.send(polycube::service::Http::Code::Ok, val.dump(4));
}
void SimplebridgeApi::read_simplebridge_fdb_entry_list_by_id_help(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
using polycube::service::HelpType;
nlohmann::json val = nlohmann::json::object();
switch (request.help_type()) {
case HelpType::SHOW:
val["params"] = FdbEntryJsonObject::helpKeys();
val["elements"] = read_simplebridge_fdb_entry_list_by_id_get_list(name);
break;
case HelpType::ADD:
val["params"] = FdbEntryJsonObject::helpKeys();
val["optional-params"] = FdbEntryJsonObject::helpWritableLeafs();
break;
case HelpType::SET:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::DEL:
val["params"] = FdbEntryJsonObject::helpKeys();
val["elements"] = read_simplebridge_fdb_entry_list_by_id_get_list(name);
break;
case HelpType::NONE:
val["commands"] = {"add", "del", "show"};
val["params"] = FdbEntryJsonObject::helpKeys();
val["elements"] = read_simplebridge_fdb_entry_list_by_id_get_list(name);
break;
case HelpType::NO_HELP:
response.send(polycube::service::Http::Code::Bad_Request);
return;
}
response.send(polycube::service::Http::Code::Ok, val.dump(4));
}
void SimplebridgeApi::read_simplebridge_list_by_id_help(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
using polycube::service::HelpType;
nlohmann::json val = nlohmann::json::object();
switch (request.help_type()) {
case HelpType::SHOW:
val["params"] = SimplebridgeJsonObject::helpKeys();
val["elements"] = read_simplebridge_list_by_id_get_list();
break;
case HelpType::ADD:
val["params"] = SimplebridgeJsonObject::helpKeys();
val["optional-params"] = SimplebridgeJsonObject::helpWritableLeafs();
break;
case HelpType::SET:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::DEL:
val["params"] = SimplebridgeJsonObject::helpKeys();
val["elements"] = read_simplebridge_list_by_id_get_list();
break;
case HelpType::NONE:
val["commands"] = {"add", "del", "show"};
val["params"] = SimplebridgeJsonObject::helpKeys();
val["elements"] = read_simplebridge_list_by_id_get_list();
break;
case HelpType::NO_HELP:
response.send(polycube::service::Http::Code::Bad_Request);
return;
}
response.send(polycube::service::Http::Code::Ok, val.dump(4));
}
void SimplebridgeApi::read_simplebridge_ports_by_id_help(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
auto portsName = request.param(":ports_name").as<std::string>();
using polycube::service::HelpType;
nlohmann::json val = nlohmann::json::object();
switch (request.help_type()) {
case HelpType::SHOW:
val["params"] = PortsJsonObject::helpElements();
break;
case HelpType::ADD:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::SET:
val["params"] = PortsJsonObject::helpWritableLeafs();
break;
case HelpType::DEL:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::NONE:
val["commands"] = {"set", "show"};
val["params"] = PortsJsonObject::helpComplexElements();
val["actions"] = PortsJsonObject::helpActions();
break;
case HelpType::NO_HELP:
response.send(polycube::service::Http::Code::Bad_Request);
return;
}
response.send(polycube::service::Http::Code::Ok, val.dump(4));
}
void SimplebridgeApi::read_simplebridge_ports_list_by_id_help(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
// Getting the path params
auto name = request.param(":name").as<std::string>();
using polycube::service::HelpType;
nlohmann::json val = nlohmann::json::object();
switch (request.help_type()) {
case HelpType::SHOW:
val["params"] = PortsJsonObject::helpKeys();
val["elements"] = read_simplebridge_ports_list_by_id_get_list(name);
break;
case HelpType::ADD:
val["params"] = PortsJsonObject::helpKeys();
val["optional-params"] = PortsJsonObject::helpWritableLeafs();
break;
case HelpType::SET:
response.send(polycube::service::Http::Code::Bad_Request);
return;
case HelpType::DEL:
val["params"] = PortsJsonObject::helpKeys();
val["elements"] = read_simplebridge_ports_list_by_id_get_list(name);
break;
case HelpType::NONE:
val["commands"] = {"add", "del", "show"};
val["params"] = PortsJsonObject::helpKeys();
val["elements"] = read_simplebridge_ports_list_by_id_get_list(name);
break;
case HelpType::NO_HELP:
response.send(polycube::service::Http::Code::Bad_Request);
return;
}
response.send(polycube::service::Http::Code::Ok, val.dump(4));
}
void SimplebridgeApi::create_simplebridge_fdb_flush_by_id_help(
const polycube::service::Rest::Request &request,
polycube::service::HttpHandleResponse &response) {
nlohmann::json val = nlohmann::json::object();
response.send(polycube::service::Http::Code::Ok, val.dump(4));
}
}
}
}
}
| 36.0959 | 153 | 0.719614 | mbertrone |
3d23e625060917c46c7b12dd9ed6a76c4cc94211 | 647 | cpp | C++ | test_mdsplus.cpp | golfit/C-Mod | 8132d1b1f21611d13f332a3770f5a94dfdecbb0a | [
"MIT"
] | null | null | null | test_mdsplus.cpp | golfit/C-Mod | 8132d1b1f21611d13f332a3770f5a94dfdecbb0a | [
"MIT"
] | null | null | null | test_mdsplus.cpp | golfit/C-Mod | 8132d1b1f21611d13f332a3770f5a94dfdecbb0a | [
"MIT"
] | null | null | null | //============================================================================
// Name : mode_survey.cpp
// Author : Theodore Golfinopoulos
// Version :
// Copyright : 2018, All rights reserved, MIT License
// Description :
//============================================================================
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <mdslib.h>
using namespace std;
int main(int argc, char *argv[]) {
//Local variables
int socket;
/* Connect to MDSplus */
socket=MdsConnect("alcdata.psfc.mit.edu");
//cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
| 24.884615 | 78 | 0.48068 | golfit |
3d28a3b8e82ba15527a55961f00cf00fd63a9022 | 458 | cpp | C++ | src/output_writer/output_writer.cpp | kimkroener/NumSim | eb56fa90cb5717123d80a4b5711d2a5bcaf67a27 | [
"MIT"
] | 2 | 2021-12-09T23:20:23.000Z | 2022-01-12T18:03:18.000Z | src/output_writer/output_writer.cpp | kimkroener/NumSim | eb56fa90cb5717123d80a4b5711d2a5bcaf67a27 | [
"MIT"
] | 31 | 2021-11-03T13:25:01.000Z | 2021-12-09T12:27:08.000Z | src/output_writer/output_writer.cpp | kimkroener/NumSim | eb56fa90cb5717123d80a4b5711d2a5bcaf67a27 | [
"MIT"
] | 3 | 2021-11-09T13:41:08.000Z | 2021-11-26T16:33:42.000Z | #include "output_writer/output_writer.h"
#include <iostream>
OutputWriter::OutputWriter(std::shared_ptr<Discretization> discretization, std::shared_ptr<Partitioning> partitioning)
: discretization_(discretization), partitioning_(partitioning), fileNo_(0)
{
// create "out" subdirectory if it does not yet exist
int returnValue = system("mkdir -p out");
if (returnValue != 0)
std::cout << "Could not create subdirectory \"out\"." << std::endl;
}
| 35.230769 | 118 | 0.740175 | kimkroener |
3d29352cacf853e6cc7ca59d6fb231c033b2b19b | 138 | cpp | C++ | src/ComandList.cpp | Wason-Fok/Motor-command-generation | d85ef1e22b9ee8ba6b8025460563cd1a2c3f5c64 | [
"Apache-2.0"
] | null | null | null | src/ComandList.cpp | Wason-Fok/Motor-command-generation | d85ef1e22b9ee8ba6b8025460563cd1a2c3f5c64 | [
"Apache-2.0"
] | null | null | null | src/ComandList.cpp | Wason-Fok/Motor-command-generation | d85ef1e22b9ee8ba6b8025460563cd1a2c3f5c64 | [
"Apache-2.0"
] | null | null | null | #include "ComandList.h"
ComandList::ComandList(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
}
ComandList::~ComandList()
{
}
| 11.5 | 39 | 0.702899 | Wason-Fok |
3d294aa09d23bf767e526fd94bd4c3ea7f7a88b7 | 4,489 | cpp | C++ | unit_tests/chustd_ut/File_Test.cpp | hadrien-psydk/pngoptimizer | d92946e63a57a4562af0feaa9e4cfd8628373777 | [
"Zlib"
] | 90 | 2016-08-23T00:13:04.000Z | 2022-02-22T09:40:46.000Z | unit_tests/chustd_ut/File_Test.cpp | hadrien-psydk/pngoptimizer | d92946e63a57a4562af0feaa9e4cfd8628373777 | [
"Zlib"
] | 25 | 2016-09-01T07:09:03.000Z | 2022-01-31T16:18:57.000Z | unit_tests/chustd_ut/File_Test.cpp | hadrien-psydk/pngoptimizer | d92946e63a57a4562af0feaa9e4cfd8628373777 | [
"Zlib"
] | 17 | 2017-05-03T17:49:25.000Z | 2021-12-28T06:47:56.000Z | #include "stdafx.h"
TEST(File, GetDrive)
{
String str0 = File::GetDrive("abc");
ASSERT_TRUE(str0.IsEmpty());
String str1 = File::GetDrive("/abc");
ASSERT_TRUE(str1.IsEmpty());
String str2 = File::GetDrive("\\abc");
ASSERT_TRUE(str2.IsEmpty());
String str3 = File::GetDrive("System:abc");
ASSERT_TRUE(str3 == "System");
String str4 = File::GetDrive("System:/abc");
ASSERT_TRUE(str4 == "System");
}
TEST(File, Open)
{
String filePath = Process::GetCurrentDirectory();
filePath = FilePath::Combine(filePath, "testfile.bin");
File::Delete(filePath); // Ensure clean state
// Write a new file
{
File file;
ASSERT_TRUE( file.Open(filePath, File::modeWrite) );
ASSERT_TRUE( file.WriteStringUtf8("plop") );
file.Close();
}
// Check content
{
File file;
ASSERT_TRUE( file.Open(filePath, File::modeRead) );
char buf[100];
ASSERT_EQ( 4, file.Read(buf, sizeof(buf)) );
ASSERT_TRUE( memcmp(buf, "plop", 4) == 0 );
file.Close();
}
// Reopen in write mode, the size should shrink to 0 upon Open
{
File file;
ASSERT_TRUE( file.Open(filePath, File::modeWrite) );
ASSERT_TRUE( file.WriteStringUtf8("xy") );
file.Close();
}
// Check content again
{
File file;
ASSERT_TRUE( file.Open(filePath, File::modeRead) );
char buf[100];
ASSERT_EQ( 2, file.Read(buf, sizeof(buf)) );
ASSERT_TRUE( memcmp(buf, "xy", 2) == 0 );
file.Close();
}
ASSERT_TRUE( File::Delete(filePath));
}
TEST(File, Append)
{
String filePath = Process::GetCurrentDirectory();
filePath = FilePath::Combine(filePath, "testfile.txt");
if( File::Exists(filePath) )
{
ASSERT_TRUE( File::Delete(filePath));
}
File file0;
for(int i = 0; i < 4; ++i)
{
ASSERT_TRUE( file0.Open(filePath, File::modeAppend) );
ASSERT_TRUE( file0.WriteString("A", TextEncoding::Windows1252()) == 1 );
file0.Close();
}
uint32 nContent;
ASSERT_TRUE( file0.Open(filePath) );
ASSERT_TRUE( file0.GetSize() == 4 );
ASSERT_TRUE( file0.Read32(nContent) );
// No more data
uint8 buf[10];
ASSERT_EQ( 0, file0.Read(buf, 0) );
ASSERT_EQ( 0, file0.Read(buf, 10) );
file0.Close();
ASSERT_TRUE( nContent == MAKE32('A','A','A','A') );
ASSERT_TRUE( File::Delete(filePath) );
}
TEST(File, LastWriteTime)
{
{
File file;
DateTime now = DateTime::GetNow();
ASSERT_TRUE( file.Open("test-file.txt", File::modeWrite) );
DateTime dt = file.GetLastWriteTime();
Duration dur = dt - now;
ASSERT_TRUE( dur.GetTotalSeconds() < 10 );
file.Close();
}
{
File file;
ASSERT_TRUE( file.Open("test-file2.txt", File::modeWrite) );
DateTime dt(1999, 9, 9, 0, 0, 42);
ASSERT_TRUE( file.SetLastWriteTime(dt) );
file.Close();
ASSERT_TRUE( file.Open("test-file2.txt", File::modeRead) );
ASSERT_TRUE( dt == file.GetLastWriteTime() );
file.Close();
}
ASSERT_TRUE( File::Delete("test-file.txt") );
ASSERT_TRUE( File::Delete("test-file2.txt") );
}
TEST(File, Rename)
{
ASSERT_TRUE( File::WriteTextUtf8("test-file.txt", "rename") );
ASSERT_TRUE( File::Rename("test-file.txt", "test-file-renamed.txt") );
ASSERT_TRUE( File::Delete("test-file-renamed.txt") );
}
TEST(File, SetByteOrder)
{
String filePath = "test-file.txt";
ByteArray bytes;
bytes.Add(0x01);
bytes.Add(0x02);
bytes.Add(0x03);
bytes.Add(0x04);
ASSERT_TRUE( File::SetContent(filePath, bytes) );
File file;
ASSERT_TRUE( file.Open(filePath, File::modeRead) );
uint32 val = 0;
// By default, a file reads in big endian
val = 0;
ASSERT_TRUE( file.Read32(val) );
ASSERT_EQ( 0x01020304u, val );
ASSERT_TRUE( file.SetPosition(0) );
file.SetByteOrder(boLittleEndian);
val = 0;
ASSERT_TRUE( file.Read32(val) );
ASSERT_EQ( 0x04030201u, val );
// Back to big endian
ASSERT_TRUE( file.SetPosition(0) );
file.SetByteOrder(boBigEndian);
val = 0;
ASSERT_TRUE( file.Read32(val) );
ASSERT_EQ( 0x01020304u, val );
file.Close();
File::Delete(filePath);
}
TEST(File, Attributes)
{
String filePath = "a.txt";
File::Delete(filePath);
ASSERT_TRUE( File::WriteTextUtf8(filePath, "blah") );
bool isDir = false;
bool readOnly = false;
ASSERT_TRUE( File::GetFileAttributes(filePath, isDir, readOnly) );
ASSERT_FALSE( isDir );
ASSERT_FALSE( readOnly );
ASSERT_TRUE( File::SetReadOnly(filePath) );
ASSERT_TRUE( File::GetFileAttributes(filePath, isDir, readOnly) );
ASSERT_FALSE( isDir );
ASSERT_TRUE( readOnly );
ASSERT_TRUE( File::SetReadOnly(filePath, false) );
ASSERT_TRUE( File::GetFileAttributes(filePath, isDir, readOnly) );
ASSERT_FALSE( isDir );
ASSERT_FALSE( readOnly );
File::Delete(filePath);
}
| 22.445 | 74 | 0.681889 | hadrien-psydk |
3d297601f2a9c6b177465239041f2c8df4023e0d | 7,303 | cpp | C++ | src/opengl_class/VertexArray.cpp | hkzhugc/MyBreakOut | cbeb086195a5aa25113d6bd8d7ad30b96c385f2d | [
"MIT"
] | null | null | null | src/opengl_class/VertexArray.cpp | hkzhugc/MyBreakOut | cbeb086195a5aa25113d6bd8d7ad30b96c385f2d | [
"MIT"
] | null | null | null | src/opengl_class/VertexArray.cpp | hkzhugc/MyBreakOut | cbeb086195a5aa25113d6bd8d7ad30b96c385f2d | [
"MIT"
] | null | null | null | #include "VertexArray.h"
using namespace std;
static float quadVertices[] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
// positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
static float cubeVertices[] = {
// back face
-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left
1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right
1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, // bottom-right
1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right
-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left
-1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, // top-left
// front face
-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left
1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, // bottom-right
1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right
1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right
-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, // top-left
-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left
// left face
-1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right
-1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-left
-1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left
-1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left
-1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-right
-1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right
// right face
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left
1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right
1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-right
1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left
1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-left
// bottom face
-1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right
1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // top-left
1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left
1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left
-1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-right
-1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right
// top face
-1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left
1.0f, 1.0f , 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right
1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right
1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right
-1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left
-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f // bottom-left
};
VertexArray::VertexArray()
{
glCreateVertexArrays(1, &VAO_ID);
VBO_ID = 0;
EBO_ID = 0;
num_indices = 0;
num_vertices = 0;
}
VertexArray::~VertexArray()
{
glDeleteVertexArrays(1, &VAO_ID);
}
void VertexArray::draw()
{
bind();
if (VBO_ID && !EBO_ID) // only have vertex buffer
{
glDrawArrays(GL_TRIANGLES, 0, num_vertices);
}
else if (VBO_ID && EBO_ID)
{
glDrawElements(GL_TRIANGLE_STRIP, num_indices, GL_UNSIGNED_INT, (void *)0);
}
unbind();
}
void VertexArray::drawInstance(size_t instance_num)
{
bind();
if (VBO_ID && !EBO_ID) // only have vertex buffer
{
glDrawArraysInstanced(GL_TRIANGLES, 0, num_vertices, instance_num);
}
else if (VBO_ID && EBO_ID)
{
glDrawElementsInstanced(GL_TRIANGLES, num_indices, GL_INT, (void *)0, instance_num);
}
unbind();
}
void VertexArray::initAsQuad()
{
if (EBO_ID || VBO_ID)
return;
genArrayBuffer(
sizeof(quadVertices),
quadVertices,
VertexAttributeConfig::genConfig<float, GL_FLOAT>({2, 2})
);
}
void VertexArray::initAsCube()
{
if (EBO_ID || VBO_ID)
return;
genArrayBuffer(
sizeof(cubeVertices),
cubeVertices,
VertexAttributeConfig::genConfig<float, GL_FLOAT>({ 3, 3, 2 })
);
}
void VertexArray::initAsSphere(size_t segmentX, size_t segmentY)
{
if (EBO_ID || VBO_ID)
return;
vector<glm::vec3> positions;
vector<glm::vec3> normals;
vector<glm::vec2> uvs;
vector<size_t> indices;
const float PI = 3.14159265359;
// calculate pos and uv
for (size_t i = 0; i <= segmentY; i++)
{
for (size_t j = 0; j <= segmentX; j++)
{
float x = (float)j / (float)segmentX;
float y = (float)i / (float)segmentY;
float theta = y * PI;
float phi = x * 2 * PI;
glm::vec3 pos;
pos.x = cos(phi) * sin(theta);
pos.y = cos(theta);
pos.z = sin(phi) * sin(theta);
positions.push_back(pos);
normals.push_back(pos);
uvs.push_back(glm::vec2(x, y));
}
}
// calculate indices
for (size_t y = 0; y < segmentY; y++)
{
if (y % 2 == 0)
{
for (int x = 0; x <= segmentX; x++)
{
indices.push_back( y * (segmentX + 1) + x);
indices.push_back((y + 1) * (segmentX + 1) + x);
}
}
else
{
for (int x = segmentX; x >= 0; x--)
{
indices.push_back((y + 1) * (segmentX + 1) + x);
indices.push_back(y * (segmentX + 1) + x);
}
}
}
num_vertices = positions.size();
num_indices = indices.size();
size_t position_size, normal_size, uv_size, index_size;
position_size = positions.size() * sizeof(glm::vec3);
normal_size = normals.size() * sizeof(glm::vec3);
uv_size = uvs.size() * sizeof(glm::vec2);
index_size = indices.size() * sizeof(size_t);
bind();
glGenBuffers(1, &VBO_ID);
glBindBuffer(GL_ARRAY_BUFFER, VBO_ID);
glBufferData(GL_ARRAY_BUFFER, position_size + normal_size + uv_size, nullptr, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, position_size, positions.data());
glBufferSubData(GL_ARRAY_BUFFER, position_size, normal_size, normals.data());
glBufferSubData(GL_ARRAY_BUFFER, position_size + normal_size, uv_size, uvs.data());
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void *)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void *)position_size);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void *)(position_size + normal_size));
glGenBuffers(1, &EBO_ID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO_ID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_size, indices.data(), GL_STATIC_DRAW);
unbind();
}
void VertexArray::genArrayBuffer(size_t size, void* data, const std::vector<VertexAttributeConfig>& configs)
{
assert(configs.size());
glCreateBuffers(1, &VBO_ID);
glNamedBufferStorage(VBO_ID, size, data, GL_DYNAMIC_STORAGE_BIT);
glVertexArrayVertexBuffer(VAO_ID, 0, VBO_ID, 0, configs[0].stride);
for (int i = 0; i < configs.size(); i++)
{
auto& config = configs[i];
glEnableVertexArrayAttrib(VAO_ID, i);
glVertexArrayAttribFormat(VAO_ID, i, config.size, config.type, config.normalized, (size_t)(config.pointer));
glVertexArrayAttribBinding(VAO_ID, i, 0);
}
if (configs.size())
num_vertices = size / configs[0].stride;
}
void VertexArray::genElementBuffer()
{
// TODO :
glCreateBuffers(1, &EBO_ID);
}
| 32.030702 | 126 | 0.606737 | hkzhugc |
3d2d90b556cf380b03ecc3f04b4e1bc43112a254 | 524 | cpp | C++ | AtCoder/abc028/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc028/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc028/b/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() {
string s; cin >> s;
vector<int> v(6, 0);
for (int i = 0; i < s.length(); i++) {
if (s[i] == 'A') v[0]++;
if (s[i] == 'B') v[1]++;
if (s[i] == 'C') v[2]++;
if (s[i] == 'D') v[3]++;
if (s[i] == 'E') v[4]++;
if (s[i] == 'F') v[5]++;
}
for (int i = 0; i < 6; i++) {
if (i == 5) cout << v[i] << endl;
else cout << v[i] << " ";
}
}
| 23.818182 | 42 | 0.375954 | H-Tatsuhiro |
3d3144e9ccc4e484e2d835b7502f739cccc29e8c | 4,481 | hpp | C++ | src/common/KokkosKernels_SparseUtils_cusparse.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 156 | 2017-03-01T23:38:10.000Z | 2022-03-27T21:28:03.000Z | src/common/KokkosKernels_SparseUtils_cusparse.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 1,257 | 2017-03-03T15:25:16.000Z | 2022-03-31T19:46:09.000Z | src/common/KokkosKernels_SparseUtils_cusparse.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 76 | 2017-03-01T17:03:59.000Z | 2022-03-03T21:04:41.000Z | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef _KOKKOSKERNELS_SPARSEUTILS_CUSPARSE_HPP
#define _KOKKOSKERNELS_SPARSEUTILS_CUSPARSE_HPP
#ifdef KOKKOSKERNELS_ENABLE_TPL_CUSPARSE
#include "cusparse.h"
namespace KokkosSparse {
namespace Impl {
inline void cusparse_internal_error_throw(cusparseStatus_t cusparseStatus,
const char *name,
const char *file,
const int line) {
std::ostringstream out;
#if defined(CUSPARSE_VERSION) && (10300 <= CUSPARSE_VERSION)
out << name << " error( " << cusparseGetErrorName(cusparseStatus)
<< "): " << cusparseGetErrorString(cusparseStatus);
#else
out << name << " error( ";
switch(cusparseStatus) {
case CUSPARSE_STATUS_NOT_INITIALIZED:
out << "CUSPARSE_STATUS_NOT_INITIALIZED): cusparse handle was not created correctly.";
break;
case CUSPARSE_STATUS_ALLOC_FAILED:
out << "CUSPARSE_STATUS_ALLOC_FAILED): you might tried to allocate too much memory";
break;
case CUSPARSE_STATUS_INVALID_VALUE:
out << "CUSPARSE_STATUS_INVALID_VALUE)";
break;
case CUSPARSE_STATUS_ARCH_MISMATCH:
out << "CUSPARSE_STATUS_ARCH_MISMATCH)";
break;
case CUSPARSE_STATUS_MAPPING_ERROR:
out << "CUSPARSE_STATUS_MAPPING_ERROR)";
break;
case CUSPARSE_STATUS_EXECUTION_FAILED:
out << "CUSPARSE_STATUS_EXECUTION_FAILED)";
break;
case CUSPARSE_STATUS_INTERNAL_ERROR:
out << "CUSPARSE_STATUS_INTERNAL_ERROR)";
break;
case CUSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED:
out << "CUSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED)";
break;
case CUSPARSE_STATUS_ZERO_PIVOT:
out << "CUSPARSE_STATUS_ZERO_PIVOT)";
break;
default:
out << "unrecognized error code): this is bad!";
break;
}
#endif // CUSPARSE_VERSION
if (file) {
out << " " << file << ":" << line;
}
throw std::runtime_error(out.str());
}
inline void cusparse_internal_safe_call(cusparseStatus_t cusparseStatus,
const char* name,
const char* file = nullptr,
const int line = 0) {
if (CUSPARSE_STATUS_SUCCESS != cusparseStatus) {
cusparse_internal_error_throw(cusparseStatus, name, file, line);
}
}
// The macro below defines is the public interface for the safe cusparse calls.
// The functions themselves are protected by impl namespace.
#define KOKKOS_CUSPARSE_SAFE_CALL(call) \
KokkosSparse::Impl::cusparse_internal_safe_call(call, #call, __FILE__, __LINE__)
} // namespace Impl
} // namespace KokkosSparse
#endif // KOKKOSKERNELS_ENABLE_TPL_CUSPARSE
#endif // _KOKKOSKERNELS_SPARSEUTILS_CUSPARSE_HPP
| 35.563492 | 90 | 0.714126 | dialecticDolt |
3d3181e4208c7009fc1b1340d10e5779be25da11 | 533 | cpp | C++ | src/midi_command_tempo.cpp | craigstjean/miditabs | 0e8e22ab948883d1fe62ff669b472615739c5fa5 | [
"BSD-3-Clause"
] | null | null | null | src/midi_command_tempo.cpp | craigstjean/miditabs | 0e8e22ab948883d1fe62ff669b472615739c5fa5 | [
"BSD-3-Clause"
] | null | null | null | src/midi_command_tempo.cpp | craigstjean/miditabs | 0e8e22ab948883d1fe62ff669b472615739c5fa5 | [
"BSD-3-Clause"
] | null | null | null | #include "midi_command_tempo.h"
void MidiCommandTempo::execute(std::shared_ptr<MidiContext> context)
{
int tick = context->track_tick(context->current_track);
for (auto i = 0; i < context->track_count(); ++i)
{
smf::MidiEvent tempo_event;
tempo_event.tick = tick;
tempo_event.setMetaTempo(tempo);
context->midifile()->addEvent(tempo_event);
}
context->current_tempo = tempo;
}
void MidiCommandTempo::os(std::ostream &out) const
{
out << "tempo: {value: " << tempo << "}";
}
| 25.380952 | 68 | 0.645403 | craigstjean |
3d333ab8aabbda7ce88b3270521ab4ca68e61a96 | 1,408 | cpp | C++ | lib/common/src/Logging.cpp | CodeRancher/offcenter_trading | 68526fdc0f27d611f748b2fa20f49e743d3ee5eb | [
"Apache-2.0"
] | null | null | null | lib/common/src/Logging.cpp | CodeRancher/offcenter_trading | 68526fdc0f27d611f748b2fa20f49e743d3ee5eb | [
"Apache-2.0"
] | 4 | 2021-12-27T17:56:21.000Z | 2022-01-05T00:05:01.000Z | lib/common/src/Logging.cpp | CodeRancher/offcenter_trading | 68526fdc0f27d611f748b2fa20f49e743d3ee5eb | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Scott Brauer
*
* Licensed under the Apache License, Version 2.0 (the );
* 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 BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file Logging.cpp
* @author Scott Brauer
* @date 09-23-2021
*/
#include "offcenter/trading/common/Logging.hpp"
namespace offcenter {
namespace trading {
namespace common {
namespace logging {
/**
* Calculates the logger ID for broker, brokerSource, instrument, and granularity.
*
* @param broker Broker
* @param brokerSource Broker data source
* @param instrument Instrument
* @param granularity Granularity
*
* @return Combined string of all elements
*/
const std::string loggerID(
const std::string& broker,
const std::string& brokerSource,
const std::string& instrument,
const std::string& granularity)
{
return broker + "." + brokerSource + "." + instrument + "." + granularity;
}
} /* namespace logging */
} /* namespace common */
} /* namespace trading */
} /* namespace offcenter */
| 26.566038 | 82 | 0.713068 | CodeRancher |
3d371a9c9533f5ae8fce1b422670d3e146bb7f84 | 11,764 | cpp | C++ | src/plugins/imagefilter_texturelayer/filter.cpp | deiflou/anitools | 9728f7569b59aa261dcaffc8332a1b02c2cd5fbe | [
"MIT"
] | 6 | 2015-05-07T18:44:34.000Z | 2018-12-12T15:57:40.000Z | src/plugins/imagefilter_texturelayer/filter.cpp | deiflou/anitools | 9728f7569b59aa261dcaffc8332a1b02c2cd5fbe | [
"MIT"
] | null | null | null | src/plugins/imagefilter_texturelayer/filter.cpp | deiflou/anitools | 9728f7569b59aa261dcaffc8332a1b02c2cd5fbe | [
"MIT"
] | 2 | 2019-03-18T05:31:34.000Z | 2019-11-19T21:17:54.000Z | //
// MIT License
//
// Copyright (c) Deif Lou
//
// 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 <QRegularExpression>
#include <QPainter>
#include "filter.h"
#include "filterwidget.h"
#include <imgproc/util.h>
#include <imgproc/pixelblending.h>
#include <imgproc/lut.h>
Filter::Filter() :
mImage(),
mPosition(Front),
mColorCompositionMode(ColorCompositionMode_Normal),
mOpacity(100)
{
}
Filter::~Filter()
{
}
ImageFilter *Filter::clone()
{
Filter * f = new Filter();
f->mImage = mImage;
f->mPosition = mPosition;
f->mColorCompositionMode = mColorCompositionMode;
f->mOpacity = mOpacity;
f->mTransformations = mTransformations;
f->mBypasses = mBypasses;
return f;
}
extern "C" QHash<QString, QString> getIBPPluginInfo();
QHash<QString, QString> Filter::info()
{
return getIBPPluginInfo();
}
QImage Filter::process(const QImage &inputImage)
{
if (inputImage.isNull() || inputImage.format() != QImage::Format_ARGB32)
return inputImage;
// Create texture
QImage texture(inputImage.width(), inputImage.height(), QImage::Format_ARGB32);
QBrush brush(mImage);
QTransform tfm;
QPainter p(&texture);
for (int i = mTransformations.size() - 1; i >= 0; i--)
{
if (mTransformations.at(i).type == Translation)
tfm.translate(mTransformations.at(i).x, mTransformations.at(i).y);
else if (mTransformations.at(i).type == Scaling)
tfm.scale(mTransformations.at(i).x / 100., mTransformations.at(i).y / 100.);
else if (mTransformations.at(i).type == Rotation)
tfm.rotate(-mTransformations.at(i).z);
else
tfm.shear(mTransformations.at(i).x / 100., mTransformations.at(i).y / 100.);
}
tfm.translate(-mImage.width() / 2, -mImage.height() / 2);
brush.setTransform(tfm);
p.setRenderHint(QPainter::Antialiasing);
p.setRenderHint(QPainter::SmoothPixmapTransform);
p.setBrushOrigin(inputImage.width() >> 1, inputImage.height() >> 1);
p.fillRect(texture.rect(), brush);
// Paint Texture
QImage i = QImage(inputImage.width(), inputImage.height(), QImage::Format_ARGB32);
register BGRA * src = (BGRA *)texture.bits(), * dst = (BGRA *)inputImage.bits(), * blend = (BGRA *)i.bits();
register int totalPixels = i.width() * i.height();
const int opacity = qRound(mOpacity * 255 / 100.);
if (mPosition == Front)
{
while (totalPixels--)
{
src->a = lut01[src->a][opacity];
blendColors[mColorCompositionMode](*src, *dst, *blend);
src++;
dst++;
blend++;
}
}
else if (mPosition == Inside)
{
if (mColorCompositionMode == ColorCompositionMode_Normal)
{
while (totalPixels--)
{
src->a = lut01[src->a][opacity];
blendSourceAtopDestination(*src, *dst, *blend);
src++;
dst++;
blend++;
}
}
else
{
while (totalPixels--)
{
src->a = lut01[src->a][opacity];
blendColors[mColorCompositionMode](*src, *dst, *blend);
blendSourceAtopDestination(*blend, *dst, *blend);
src++;
dst++;
blend++;
}
}
}
else
{
while (totalPixels--)
{
src->a = lut01[src->a][opacity];
blendDestinationOverSource(*src, *dst, *blend);
src++;
dst++;
blend++;
}
}
return i;
}
bool Filter::loadParameters(QSettings &s)
{
QVariant v;
QString positionStr;
QString colorCompositionModeStr;
QImage image;
Position position;
ColorCompositionMode colorCompositionMode;
int opacity;
QString tfmStr;
QStringList tfmList1, tfmList2;
QList<AffineTransformation> transformations;
QList<bool> bypasses;
AffineTransformation transformation;
bool bypass;
bool ok;
v = s.value("image", QImage());
if (!v.isValid() || !v.canConvert<QImage>())
image = QImage();
else
image = v.value<QImage>();
positionStr = s.value("position", "front").toString();
if (positionStr == "front")
position = Front;
else if (positionStr == "behind")
position = Behind;
else if (positionStr == "inside")
position = Inside;
else
return false;
colorCompositionModeStr = s.value("colorcompositionmode", "normal").toString();
colorCompositionMode = colorCompositionModeStringToEnum(colorCompositionModeStr);
if (colorCompositionMode == ColorCompositionMode_Unsupported)
return false;
opacity = s.value("opacity", 100).toInt(&ok);
if (!ok || opacity < 0 || opacity > 100)
return false;
tfmStr = s.value("geometrictransformations").toString();
tfmList1 = tfmStr.split(QRegularExpression("\\s*,\\s*"), QString::SkipEmptyParts);
for (int i = 0; i < tfmList1.size(); i++)
{
tfmList2 = tfmList1.at(i).split(QRegularExpression("\\s+"), QString::SkipEmptyParts);
if (tfmList2.size() != 3 && tfmList2.size() != 4)
return false;
if (tfmList2.at(0) == "translation")
transformation.type = Translation;
else if (tfmList2.at(0) == "scaling")
transformation.type = Scaling;
else if (tfmList2.at(0) == "rotation")
transformation.type = Rotation;
else if (tfmList2.at(0) == "shearing")
transformation.type = Shearing;
else
return false;
if (tfmList2.at(1) == "false")
bypass = false;
else if (tfmList2.at(1) == "true")
bypass = true;
else
return false;
if (tfmList2.size() == 3)
{
transformation.z = tfmList2.at(2).toDouble(&ok);
if (!ok)
return false;
transformation.x = transformation.y = 0;
}
else
{
transformation.x = tfmList2.at(2).toDouble(&ok);
if (!ok)
return false;
transformation.y = tfmList2.at(3).toDouble(&ok);
if (!ok)
return false;
transformation.z = 0;
}
transformations.append(transformation);
bypasses.append(bypass);
}
setImage(image);
setPosition(position);
setColorCompositionMode(colorCompositionMode);
setOpacity(opacity);
setTransformations(transformations, bypasses);
return true;
}
bool Filter::saveParameters(QSettings &s)
{
QStringList tfms;
if (mTransformations.size() > 0)
{
AffineTransformation t;
for (int i = 0; i < mTransformations.size(); i++)
{
t = mTransformations.at(i);
if (t.type == Translation)
tfms.append(QString("translation ") +
(mBypasses.at(i) ? "true " : "false ") +
QString::number(t.x, 'f', 2) + " " +
QString::number(t.y, 'f', 2));
else if (t.type == Scaling)
tfms.append(QString("scaling ") +
(mBypasses.at(i) ? "true " : "false ") +
QString::number(t.x, 'f', 2) + " " +
QString::number(t.y, 'f', 2));
else if (t.type == Rotation)
tfms.append(QString("rotation ") +
(mBypasses.at(i) ? "true " : "false ") +
QString::number(t.z, 'f', 2));
else
tfms.append(QString("shearing ") +
(mBypasses.at(i) ? "true " : "false ") +
QString::number(t.x, 'f', 2) + " " +
QString::number(t.y, 'f', 2));
}
}
s.setValue("image", mImage);
s.setValue("position", mPosition == Front ? "front" : (mPosition == Behind ? "behind" : "inside"));
s.setValue("colorcompositionmode", colorCompositionModeEnumToString(mColorCompositionMode));
s.setValue("opacity", mOpacity);
s.setValue("geometrictransformations", tfms.join(", "));
return true;
}
QWidget *Filter::widget(QWidget *parent)
{
FilterWidget * fw = new FilterWidget(parent);
fw->setImage(mImage);
fw->setPosition(mPosition);
fw->setColorCompositionMode(mColorCompositionMode);
fw->setOpacity(mOpacity);
fw->setTransformations(mTransformations, mBypasses);
connect(this, SIGNAL(imageChanged(QImage)), fw, SLOT(setImage(QImage)));
connect(this, SIGNAL(positionChanged(Filter::Position)), fw, SLOT(setPosition(Filter::Position)));
connect(this, SIGNAL(colorCompositionModeChanged(ColorCompositionMode)),
fw, SLOT(setColorCompositionMode(ColorCompositionMode)));
connect(this, SIGNAL(opacityChanged(int)), fw, SLOT(setOpacity(int)));
connect(this, SIGNAL(transformationsChanged(QList<AffineTransformation>,QList<bool>)),
fw, SLOT(setTransformations(QList<AffineTransformation>,QList<bool>)));
connect(fw, SIGNAL(imageChanged(QImage)), this, SLOT(setImage(QImage)));
connect(fw, SIGNAL(positionChanged(Filter::Position)), this, SLOT(setPosition(Filter::Position)));
connect(fw, SIGNAL(colorCompositionModeChanged(ColorCompositionMode)),
this, SLOT(setColorCompositionMode(ColorCompositionMode)));
connect(fw, SIGNAL(opacityChanged(int)), this, SLOT(setOpacity(int)));
connect(fw, SIGNAL(transformationsChanged(QList<AffineTransformation>,QList<bool>)),
this, SLOT(setTransformations(QList<AffineTransformation>,QList<bool>)));
return fw;
}
void Filter::setImage(const QImage &i)
{
if (i == mImage)
return;
mImage = i;
emit imageChanged(i);
emit parametersChanged();
}
void Filter::setPosition(Filter::Position v)
{
if (v == mPosition)
return;
mPosition = v;
emit positionChanged(v);
emit parametersChanged();
}
void Filter::setColorCompositionMode(ColorCompositionMode v)
{
if (v == mColorCompositionMode)
return;
mColorCompositionMode = v;
emit colorCompositionModeChanged(v);
emit parametersChanged();
}
void Filter::setOpacity(int v)
{
if (v == mOpacity)
return;
mOpacity = v;
emit opacityChanged(v);
emit parametersChanged();
}
void Filter::setTransformations(const QList<AffineTransformation> &t, const QList<bool> &b)
{
if (t == mTransformations && b == mBypasses)
return;
mTransformations = t;
mBypasses = b;
emit transformationsChanged(t, b);
emit parametersChanged();
}
| 32.768802 | 112 | 0.600221 | deiflou |
3d3a96804f5a336b976e1e6e51c866f9c83bd1c7 | 1,857 | cpp | C++ | src/components/net/fabric/unit_test/patience.cpp | fQuinzan/mcas | efaf438eb20cffa18b13f176c74a2b3153f89c07 | [
"Apache-2.0"
] | 60 | 2020-04-28T08:15:07.000Z | 2022-03-08T10:35:15.000Z | src/components/net/fabric/unit_test/patience.cpp | fQuinzan/mcas | efaf438eb20cffa18b13f176c74a2b3153f89c07 | [
"Apache-2.0"
] | 66 | 2020-09-03T23:40:48.000Z | 2022-03-07T20:34:52.000Z | src/components/net/fabric/unit_test/patience.cpp | fQuinzan/mcas | efaf438eb20cffa18b13f176c74a2b3153f89c07 | [
"Apache-2.0"
] | 13 | 2019-11-02T06:30:36.000Z | 2022-01-26T01:56:42.000Z | /*
Copyright [2017-2019] [IBM Corporation]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "patience.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#pragma GCC diagnostic ignored "-Wsign-compare"
#include <gtest/gtest.h>
#pragma GCC diagnostic pop
#include <api/fabric_itf.h> /* IFabric, IFabric_client, IFabric_client_grouped */
#include <system_error>
component::IFabric_client * open_connection_patiently(component::IFabric_endpoint_unconnected_client *aep_)
{
component::IFabric_client *cnxn = nullptr;
int try_count = 0;
while ( ! cnxn )
{
try
{
cnxn = aep_->make_open_client();
}
catch ( std::system_error &e )
{
if ( e.code().value() != ECONNREFUSED )
{
throw;
}
}
++try_count;
}
EXPECT_LT(0U, cnxn->max_message_size());
return cnxn;
}
component::IFabric_client_grouped *open_connection_grouped_patiently(component::IFabric_endpoint_unconnected_client *aep_)
{
component::IFabric_client_grouped *cnxn = nullptr;
int try_count = 0;
while ( ! cnxn )
{
try
{
cnxn = aep_->make_open_client_grouped();
}
catch ( std::system_error &e )
{
if ( e.code().value() != ECONNREFUSED )
{
throw;
}
}
++try_count;
}
EXPECT_LT(0U, cnxn->max_message_size());
return cnxn;
}
| 26.913043 | 122 | 0.682822 | fQuinzan |
3d3aa0927631e336549d23b7193c4de50b200666 | 1,217 | cpp | C++ | goodEatsSystem/src/Chef.cpp | PashaBarahimi/GoodEatsWeb | a8c173298323b072c973a8218bb63485fc1aba33 | [
"MIT"
] | null | null | null | goodEatsSystem/src/Chef.cpp | PashaBarahimi/GoodEatsWeb | a8c173298323b072c973a8218bb63485fc1aba33 | [
"MIT"
] | null | null | null | goodEatsSystem/src/Chef.cpp | PashaBarahimi/GoodEatsWeb | a8c173298323b072c973a8218bb63485fc1aba33 | [
"MIT"
] | null | null | null | #include "include/Chef.hpp"
#include "include/AlgorithmSideFunctions.hpp"
Chef::Chef(const std::string& username, const std::string& password) : username_(username), password_(password) { }
void Chef::addRecipe(Recipe* recipe)
{
recipes_.insert(std::upper_bound(recipes_.begin(), recipes_.end(), recipe, compareByName<Recipe*>), recipe);
}
void Chef::removeRecipe(Recipe* recipe)
{
for (unsigned i = 0; i < recipes_.size(); i++)
if (recipe == recipes_[i])
{
recipes_.erase(recipes_.begin() + i);
return;
}
}
bool Chef::doesRecipeExist(Recipe* recipe) const
{
for (Recipe* item : recipes_)
if (recipe == item)
return true;
return false;
}
double Chef::getRatings() const
{
double sum = 0;
int counter = 0;
for (Recipe* recipe : recipes_)
if (static_cast<int>(recipe->getRating()) != 0)
{
sum += recipe->getRating();
counter++;
}
if (counter == 0)
return 0;
sum /= counter;
double tenXRate = 10 * sum;
tenXRate = ceil(tenXRate);
return tenXRate / 10;
}
std::vector<Recipe::InterfaceRecipe> Chef::getInterfaceRecipes() const
{
std::vector<Recipe::InterfaceRecipe> recipes;
for (Recipe* rec : recipes_)
recipes.push_back(rec->getInterfaceRecipe());
return recipes;
}
| 22.537037 | 115 | 0.685292 | PashaBarahimi |
3d3c6593e10a6cffac2e3be3914b18bc7f84b394 | 1,216 | cpp | C++ | src/tools/checkstyle/test.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/tools/checkstyle/test.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/tools/checkstyle/test.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /* Test-file for coding style checker
* Copyright 2010, Haiku, Inc.
* Distributed under the terms of the MIT Licence
*/
// DETECTED problems
// Line longer than 80 chars
int
someveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryverylongFunctionName( int aLongParameter)
{
// Identantion with spaces instead of tabs
int a;
int b;
int c;
// Missing space after control statement
if(condition);
//Missing space at comment start
// Operator without spaces
if (a>b);
// Operator at end of line
if (a >
b)
j =
k +
i;
// Wrong line breaks around else
if (test)
{
}
else
{
}
// Less than two lines between functions
}
// Missing space before opening brace
int
aFunction(char param){
// More than two lines between blocks
}
// CORRECT things that should not be detected as violations
#include <dir/path.h>
// Not matched by 'operator at end of line'
// Below this are FALSE POSITIVES (think of it as a TODO list)
// Test-file
// Matched by 'space around operator' (should not be matched in comments)
// NOT DETECTED violations
int func()
{
if (a)
{
// The brace should be on the same line as the if
}
// Everything related to naming conventions
}
| 16.888889 | 113 | 0.706414 | Kirishikesan |
3d3c726d1b927ab53bf7a6f18573d4f41db9fc1b | 2,183 | cpp | C++ | practice/sample2.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | practice/sample2.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | practice/sample2.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define fori(i,a,b) for (long long int i = a; i <= b ; ++i)
#define ford(i,a,b) for(long long int i = a;i >= b ; --i)
#define mk make_pair
#define mod 1000000007
#define pb push_back
#define ll long long
#define ld long double
#define MAXN (ll)1e6+5
#define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().cnt())
#define pi pair<long long int,long long int>
#define sc second
#define fs first
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n, q, l, r;
cin >> n;
vector<ll> x(n+1,0), y(n+1,0);
vector<ll> preX(n+1,0), preY(n+1,0);
vector<ll> preX1(n+1,0), preY1(n+1,0);
fori(i,1,n) {
cin >> x[i] >> y[i];
}
fori(i,1,n) {
if (i == n)
preX[i] = (x[i]*y[1])%mod;
else
preX[i] = (x[i]*y[i+1])%mod;
}
fori(i,1,n) {
if (i == n)
preY[i] = (x[1]*y[i])%mod;
else
preY[i] = (x[i+1]*y[i])%mod;
}
fori(i,1,n) {
preX1[i] = (preX1[i-1]+preX[i])%mod;
// cout << i << " preX1 " << preX1[i] << endl;
}
fori(i,1,n) {
preY1[i] = (preY1[i-1]+preY[i])%mod;
// cout << i << " preY1 " << preY1[i] << endl;
}
//total area of the polygon
ll total = abs(preX1[n] - preY1[n]);
total = total%mod;
//cout << total << endl;
cin >> q;
while (q--) {
cin >> l >> r;
if (l > r) {
swap(l,r);
//cout << r-1 << " so " << l << " " << preX1[r-1] << " " << preX1[l-1] << endl;
ll sum1 = ((preX1[r-1]-preX1[l-1])%mod + x[r]*y[l])%mod;
ll sum2 = ((preY1[r-1]-preY1[l-1])%mod + y[r]*x[l])%mod;
//cout << sum1 << " is sum1 and the next is sum2 " << sum2 << endl;
ll sum3 = abs(sum1 - sum2)%mod;
cout << (total - sum3)%mod << endl;
} else if (l < r) {
//cout << r-1 << " so " << l << " " << preX1[r-1] << " " << preX1[l-1] << endl;
ll sum1 = ((preX1[r-1]-preX1[l-1])%mod + x[r]*y[l])%mod;
ll sum2 = ((preY1[r-1]-preY1[l-1])%mod + y[r]*x[l])%mod;
//cout << sum1 << " is sum1 and the next is sum2 " << sum2 << endl;
ll sum3 = abs(sum1 - sum2)%mod;
cout << sum3 << endl;
} else {
cout << 0 << endl;
}
}
return 0;
}
| 24.806818 | 89 | 0.496106 | xenowits |
3d3cbcdfe9fa044b30509207118e69e958eb93f1 | 1,714 | cpp | C++ | Array/1313. Decompress Run-Length Encoded List.cpp | KardseT/LeetCode | f020cff23f7d3ef8599b9e72bf5c2095bf069d01 | [
"MIT"
] | null | null | null | Array/1313. Decompress Run-Length Encoded List.cpp | KardseT/LeetCode | f020cff23f7d3ef8599b9e72bf5c2095bf069d01 | [
"MIT"
] | null | null | null | Array/1313. Decompress Run-Length Encoded List.cpp | KardseT/LeetCode | f020cff23f7d3ef8599b9e72bf5c2095bf069d01 | [
"MIT"
] | null | null | null | // 1313. Decompress Run-Length Encoded List
// Easy
// We are given a list nums of integers representing a list compressed with run-length encoding.
// Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
// Return the decompressed list.
// Example 1:
// Input: nums = [1,2,3,4]
// Output: [2,4,4,4]
// Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
// The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
// At the end the concatenation [2] + [4,4,4] is [2,4,4,4].
// Example 2:
// Input: nums = [1,1,2,3]
// Output: [1,3,3]
// Constraints:
// 2 <= nums.length <= 100
// nums.length % 2 == 0
// 1 <= nums[i] <= 100
class Solution {
public:
vector<int> decompressRLElist(vector<int>& nums) {
vector<int> output;
for (int i=0; i < nums.size(); i+=2)
{
for (int j=0; j < nums[i]; ++j)
output.push_back(nums[i+1]);
}
return output;
}
};
// Runtime: 44 ms, faster than 78.12% of C++ online submissions for Decompress Run-Length Encoded List.
// Memory Usage: 8.4 MB, less than 100.00% of C++ online submissions for Decompress Run-Length Encoded List.
class Solution {
public:
vector<int> decompressRLElist(vector<int>& nums) {
vector<int> output;
for (int i=0; i < nums.size(); i+=2)
output.insert(output.end(), nums[i], nums[i+1]);
return output;
}
};
// Related Topics
// Array | 27.645161 | 266 | 0.614936 | KardseT |
3d3dc327947482dc6dc8fa038371a9792e962493 | 10,542 | cpp | C++ | src/state.cpp | nilern/kauno | a82f43bc535378afe9ce427ffb16921bf966fd47 | [
"MIT"
] | null | null | null | src/state.cpp | nilern/kauno | a82f43bc535378afe9ce427ffb16921bf966fd47 | [
"MIT"
] | null | null | null | src/state.cpp | nilern/kauno | a82f43bc535378afe9ce427ffb16921bf966fd47 | [
"MIT"
] | null | null | null | #include "state.hpp"
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <cstdalign>
#include <utility>
#include <algorithm>
#include "arrays.hpp"
#include "typesmap.hpp"
#include "locals.hpp"
#include "fn.hpp"
namespace kauno {
static inline AnySRef builtin_prn(State& state) {
State_print_builtin(state, stdout, state.peek());
puts("");
state.pop_nth(1); // Pop self
return state.peek(); // FIXME
}
State::State(size_t heap_size, size_t stack_size_) :
heap(heap_size),
stack_size(stack_size_),
stack((char*)malloc(stack_size)),
data_sp(stack + stack_size),
type_sp((DynRef*)stack),
type_hashes_(std::mt19937_64(std::random_device()())),
symbols_(),
globals(),
Type(ORef<struct Type>(nullptr)),
Field(ORef<struct Type>(nullptr)),
UInt8(ORef<struct Type>(nullptr)),
Int64(ORef<struct Type>(nullptr)),
USize(ORef<struct Type>(nullptr)),
Bool(ORef<struct Type>(nullptr)),
Symbol(ORef<struct Type>(nullptr)),
Var(ORef<struct Type>(nullptr)),
AstFn(ORef<struct Type>(nullptr)),
Call(ORef<struct Type>(nullptr)),
CodePtr(ORef<struct Type>(nullptr)),
Fn(ORef<struct Type>(nullptr)),
Closure(ORef<struct Type>(nullptr)),
NoneType(ORef<struct Type>(nullptr)),
RefArray(ORef<struct Type>(nullptr)),
NRefArray(ORef<struct Type>(nullptr)),
TypesMap(ORef<struct Type>(nullptr)),
Locals(ORef<struct Type>(nullptr)),
None(ORef<struct None>(nullptr))
{
// Sentinel to simplify (and optimize) popping:
*type_sp = DynRef((ORef<void>*)data_sp);
++type_sp;
size_t const Type_fields_count = 6;
size_t const Type_size = sizeof(struct Type) + Type_fields_count*sizeof(Field);
struct Type* tmp_Type = (struct Type*)malloc(Type_size);
*tmp_Type = Type::create_indexed(*this, alignof(struct Type), sizeof(struct Type), Type_fields_count);
size_t const Field_fields_count = 4;
size_t const Field_size = sizeof(struct Type) + Field_fields_count*sizeof(Field);
struct Type* const tmp_Field = (struct Type*)malloc(Field_size);
*tmp_Field = Type::create_record(*this, alignof(struct Field), sizeof(struct Field), true, Field_fields_count);
tmp_Type->fields[5] = (struct Field){NRef(tmp_Field), offsetof(struct Type, fields)};
Type = ORef((struct Type*)heap.alloc_indexed(tmp_Type, Type_fields_count));
Type.set_type(Type);
*Type.data() = *tmp_Type;
Type.data()->fields[5] = tmp_Type->fields[5];
Field = ORef((struct Type*)heap.alloc_indexed(tmp_Type, Field_fields_count));
Field.set_type(Type);
*Field.data() = *tmp_Field;
USize = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0));
*USize.data() = Type::create_bits(*this, alignof(size_t), sizeof(size_t), true);
Bool = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0));
*Bool.data() = Type::create_bits(*this, alignof(bool), sizeof(bool), true);
Type.data()->fields[0] = (struct Field){NRef(USize), offsetof(struct Type, align)};
Type.data()->fields[1] = (struct Field){NRef(USize), offsetof(struct Type, min_size)};
Type.data()->fields[2] = (struct Field){NRef(Bool), offsetof(struct Type, inlineable)};
Type.data()->fields[3] = (struct Field){NRef(Bool), offsetof(struct Type, is_bits)};
Type.data()->fields[4] = (struct Field){NRef(Bool), offsetof(struct Type, has_indexed)};
Type.data()->fields[5] = (struct Field){NRef(Field), offsetof(struct Type, fields)};
Field.data()->fields[0] = (struct Field){NRef(Type), offsetof(struct Field, type)};
Field.data()->fields[1] = (struct Field){NRef(USize), offsetof(struct Field, offset)};
Field.data()->fields[2] = (struct Field){NRef(USize), offsetof(struct Field, size)};
Field.data()->fields[3] = (struct Field){NRef(Bool), offsetof(struct Field, inlined)};
free(tmp_Type);
free(tmp_Field);
UInt8 = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0));
*UInt8.data() = Type::create_bits(*this, alignof(uint8_t), sizeof(uint8_t), true);
Int64 = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0));
*Int64.data() = Type::create_bits(*this, alignof(int64_t), sizeof(int64_t), true);
size_t const Symbol_fields_count = 2;
Symbol = ORef((struct Type*)heap.alloc_indexed(Type.data(), Symbol_fields_count));
*Symbol.data() = Type::create_indexed(*this, alignof(struct Symbol), sizeof(struct Symbol), Symbol_fields_count);
Symbol.data()->fields[0] = (struct Field){NRef(USize), offsetof(struct Symbol, hash)};
Symbol.data()->fields[1] = (struct Field){NRef(UInt8), offsetof(struct Symbol, name)};
size_t const Var_fields_count = 1;
Var = ORef((struct Type*)heap.alloc_indexed(Type.data(), Var_fields_count));
*Var.data() = Type::create_record(*this, alignof(struct Var), sizeof(struct Var), false, Var_fields_count);
Var.data()->fields[0] = (struct Field){NRef<struct Type>(), offsetof(struct Var, value)};
size_t const Call_fields_count = 2;
Call = ORef((struct Type*)heap.alloc_indexed(Type.data(), Call_fields_count));
*Call.data() = Type::create_indexed(*this, alignof(kauno::ast::Call), sizeof(kauno::ast::Call), Call_fields_count);
Call.data()->fields[0] = (struct Field){NRef<struct Type>(), offsetof(kauno::ast::Call, callee)};
Call.data()->fields[1] = (struct Field){NRef<struct Type>(), offsetof(kauno::ast::Call, args)};
CodePtr = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0));
*CodePtr.data() = Type::create_bits(*this, alignof(kauno::fn::CodePtr), sizeof(kauno::fn::CodePtr), true);
size_t const Fn_fields_count = 1;
Fn = ORef((struct Type*)heap.alloc_indexed(Type.data(), Fn_fields_count));
*Fn.data() = Type::create_record(*this, alignof(kauno::fn::Fn), sizeof(kauno::fn::Fn), true, Fn_fields_count);
Fn.data()->fields[0] = (struct Field){NRef(CodePtr), offsetof(kauno::fn::Fn, code)};
size_t const None_fields_count = 0;
NoneType = ORef((struct Type*)heap.alloc_indexed(Type.data(), None_fields_count));
*NoneType.data() = Type::create_record(*this, alignof(struct None), sizeof(struct None), true, None_fields_count);
size_t const RefArray_fields_count = 1;
RefArray = ORef((struct Type*)heap.alloc_indexed(Type.data(), RefArray_fields_count));
*RefArray.data() = Type::create_indexed(*this, alignof(kauno::arrays::RefArray<ORef<void>>), sizeof(kauno::arrays::RefArray<ORef<void>>),
RefArray_fields_count);
RefArray.data()->fields[0] = (struct Field){NRef<struct Type>(),
offsetof(kauno::arrays::RefArray<ORef<void>>, elements)};
size_t const NRefArray_fields_count = 1;
NRefArray = ORef((struct Type*)heap.alloc_indexed(Type.data(), NRefArray_fields_count));
*NRefArray.data() = Type::create_indexed(*this, alignof(kauno::arrays::NRefArray<ORef<void>>), sizeof(kauno::arrays::NRefArray<ORef<void>>),
NRefArray_fields_count);
NRefArray.data()->fields[0] = (struct Field){NRef<struct Type>(),
offsetof(kauno::arrays::NRefArray<ORef<void>>, elements)};
TypesMap = kauno::TypesMap::create_reified(*this);
AstFn = ast::Fn::create_reified(*this);
Locals = Locals::create_reified(*this);
Closure = fn::Closure::create_reified(*this);
None = ORef(static_cast<struct None*>(heap.alloc(NoneType.data())));
Handle<struct Type> const Type_handle = push_outlined(ORef(Type));
Handle<struct Symbol> const Type_symbol = Symbol_new(*this, "Type", 4);
Handle<struct Var> const Type_var = Var_new(*this, Type_handle.as_void());
globals.insert(Type_symbol.oref(), Type_var.oref());
popn(3);
ORef<kauno::fn::Fn> const prn = ORef((kauno::fn::Fn*)heap.alloc(Fn.data()));
*prn.data() = (kauno::fn::Fn){
.code = builtin_prn,
.domain_count = 1,
.domain = {}
};
prn.data()->domain[0] = None.as_void();
Handle<kauno::fn::Fn> const prn_handle = push_outlined(ORef(prn));
Handle<struct Symbol> const prn_symbol = Symbol_new(*this, "prn", 3);
Handle<struct Var> const prn_var = Var_new(*this, prn_handle.as_void());
globals.insert(prn_symbol.oref(), prn_var.oref());
popn(3);
}
AnySRef State::peek() {
assert((char*)type_sp > stack);
return AnySRef(type_sp - 1);
}
AnySRef State::peek_nth(size_t n) {
assert((char*)type_sp - n >= stack);
return AnySRef(type_sp - 1 - n);
}
DynRef* State::peekn(size_t n) {
assert((char*)type_sp - n >= stack);
return type_sp - n;
}
void State::popn(size_t n) {
assert((char*)(type_sp - n) > stack);
type_sp -= n;
data_sp = (char*)((type_sp - 1)->stack_ptr());
}
void State::pop() { popn(1); }
void State::popn_nth(size_t i, size_t n) {
assert(n <= i + 1);
assert((char*)(type_sp - i) > stack);
size_t const top_count = i + 1 - n;
DynRef* it = type_sp - top_count;
type_sp -= i + 1;
data_sp = (char*)((type_sp - 1)->stack_ptr());
for (size_t j = 0; j < top_count; ++j, ++it) {
it->repush(*this);
}
}
void State::pop_nth(size_t i) { popn_nth(i, 1); }
static inline void State_print_builtin(State const& state, FILE* dest, AnySRef value) {
ORef<Type> type = value.type();
void* data = value.data();
if (type == state.Type) {
fprintf(dest, "<Type @ %p>", data);
} else if (type == state.Field) {
fprintf(dest, "<Field @ %p>", data);
} else if (type == state.Symbol) {
Symbol* symbol = (Symbol*)data;
fputc('\'', dest);
for (size_t i = 0; i < symbol->name_size; ++i) {
fputc(symbol->name[i], dest);
}
} else if (type == state.Var) {
fputs("<Var>", dest);
} else if (type == state.AstFn) {
fprintf(dest, "<AstFn @ %p>", data);
} else if (type == state.Call) {
fprintf(dest, "<Call @ %p>", data);
} else if (type == state.Fn) {
fprintf(dest, "<Fn @ %p>", data);
} else if (type == state.CodePtr) {
fprintf(dest, "<CodePtr @ %p>", data);
} else if (type == state.Closure) {
fprintf(dest, "<Closure @ %p>", data);
} else if (type == state.UInt8) {
fprintf(dest, "%u", *(uint8_t*)data);
} else if (type == state.Int64) {
fprintf(dest, "%ld", *(int64_t*)data);
} else if (type == state.USize) {
fprintf(dest, "%zu", *(size_t*)data);
} else if (type == state.Bool) {
fputs(*(bool*)data ? "True" : "False", dest);
} else {
fprintf(dest, "<??? @ %p>", data);
}
}
}
| 38.474453 | 144 | 0.640106 | nilern |
3d426e9e65cfca10d0bdad8a776ed89badb9682e | 449 | cpp | C++ | Online Judges/SPOJ/ARRAYSUB/2395824_AC_540ms_6451kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | 4 | 2017-02-20T17:41:14.000Z | 2019-07-15T14:15:34.000Z | Online Judges/SPOJ/ARRAYSUB/2395824_AC_540ms_6451kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | Online Judges/SPOJ/ARRAYSUB/2395824_AC_540ms_6451kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int n,a[1010101],k;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cin>>k;
int mx=0;
for(int i=0;i<k;i++)
{
mx=max(mx,a[i]);
}
for(int i=0;i<n-k+1;i++)
{
if(a[i+k-1]>mx)
{
mx=a[i+k-1];
}
else if(mx==a[i-1])
{
mx=a[i];
for(int j=i+1;j<i+k;j++)
{
mx=max(mx,a[j]);
}
}
cout<<mx<<' ';
}
cout<<endl;
return 0;
}
| 11.512821 | 27 | 0.478842 | moni-roy |
3d42dbe987be220b187869508bf8a1b3cedcac31 | 1,704 | cpp | C++ | bind/imf_deepscanlineoutputpart.cpp | scott-wilson/openexr-bind | dcbc3c6c5d665545638e5ef55410d43a15bce081 | [
"Apache-2.0"
] | 7 | 2021-06-04T20:59:16.000Z | 2022-02-11T01:00:42.000Z | bind/imf_deepscanlineoutputpart.cpp | scott-wilson/openexr-bind | dcbc3c6c5d665545638e5ef55410d43a15bce081 | [
"Apache-2.0"
] | 35 | 2021-05-14T04:28:22.000Z | 2021-12-30T12:08:40.000Z | bind/imf_deepscanlineoutputpart.cpp | scott-wilson/openexr-bind | dcbc3c6c5d665545638e5ef55410d43a15bce081 | [
"Apache-2.0"
] | 5 | 2021-05-15T04:02:56.000Z | 2021-07-02T05:38:01.000Z | #include <OpenEXR/ImfDeepScanLineOutputPart.h>
#include <cppmm_bind.hpp>
namespace cppmm_bind {
namespace OPENEXR_IMF_INTERNAL_NAMESPACE {
namespace Imf = ::OPENEXR_IMF_INTERNAL_NAMESPACE;
struct DeepScanLineOutputPart {
using BoundType = Imf::DeepScanLineOutputPart;
IMF_EXPORT
DeepScanLineOutputPart(Imf::MultiPartOutputFile& multiPartFile,
int partNumber);
IMF_EXPORT
const char* fileName() const;
IMF_EXPORT
const Imf::Header& header() const;
IMF_EXPORT
void setFrameBuffer(const Imf::DeepFrameBuffer& frameBuffer)
CPPMM_THROWS(Iex::ArgExc, IEX_INVALID_ARGUMENT);
IMF_EXPORT
const Imf::DeepFrameBuffer& frameBuffer() const;
IMF_EXPORT
void writePixels(int numScanLines) CPPMM_THROWS(Iex::IoExc, IEX_IO)
CPPMM_THROWS(Iex::ArgExc, IEX_INVALID_ARGUMENT)
CPPMM_THROWS(Iex::BaseExc, IEX_BASE);
IMF_EXPORT
int currentScanLine() const;
IMF_EXPORT
void copyPixels(Imf::DeepScanLineInputFile& in)
CPPMM_RENAME(copyPixels_from_file)
CPPMM_THROWS(Iex::ArgExc, IEX_INVALID_ARGUMENT)
CPPMM_THROWS(Iex::LogicExc, IEX_LOGIC_ERROR);
IMF_EXPORT
void copyPixels(Imf::DeepScanLineInputPart& in)
CPPMM_RENAME(copyPixels_from_part)
CPPMM_THROWS(Iex::ArgExc, IEX_INVALID_ARGUMENT)
CPPMM_THROWS(Iex::LogicExc, IEX_LOGIC_ERROR);
IMF_EXPORT
void updatePreviewImage(const Imf::PreviewRgba newPixels[])
CPPMM_THROWS(Iex::BaseExc, IEX_BASE)
CPPMM_THROWS(Iex::LogicExc, IEX_LOGIC_ERROR);
} CPPMM_OPAQUEBYTES;
} // namespace OPENEXR_IMF_INTERNAL_NAMESPACE
} // namespace cppmm_bind
| 28.4 | 71 | 0.716549 | scott-wilson |
3d43cdeba498bf65152e0c057b55c3615fc30f92 | 3,071 | cpp | C++ | src/passes/pass.cpp | ionlang/ir-c | f5be3d0a6bed76b3fe354018045b82ded7d792ae | [
"Unlicense"
] | 3 | 2019-07-11T14:41:28.000Z | 2019-07-12T10:29:08.000Z | src/passes/pass.cpp | ionlang/ir-c | f5be3d0a6bed76b3fe354018045b82ded7d792ae | [
"Unlicense"
] | 22 | 2019-12-05T04:43:34.000Z | 2020-11-05T23:29:25.000Z | src/passes/pass.cpp | ionlang/ir-c | f5be3d0a6bed76b3fe354018045b82ded7d792ae | [
"Unlicense"
] | 3 | 2020-07-20T19:20:26.000Z | 2020-10-12T15:24:47.000Z | #include <ionir/passes/pass.h>
namespace ionir {
Pass::Pass(std::shared_ptr<ionshared::PassContext> context) noexcept :
ionshared::BasePass<Construct>(std::move(context)) {
//
}
void Pass::visit(std::shared_ptr<Construct> construct) {
construct->accept(*this);
this->visitChildren(construct);
}
void Pass::visitChildren(std::shared_ptr<Construct> construct) {
// TODO: Will it cause StackOverflow error with large ASTs?
Ast children = construct->getChildrenNodes();
/**
* After visiting the construct, attempt to
* visit all its children as well.
*/
for (const auto& child : children) {
// TODO: CRITICAL: What if 'child' (AstNode) is not boxed under Construct?
this->visit(child);
}
}
void Pass::visitFunction(std::shared_ptr<Function> construct) {
//
}
void Pass::visitExtern(std::shared_ptr<Extern> construct) {
//
}
void Pass::visitBasicBlock(std::shared_ptr<BasicBlock> construct) {
//
}
void Pass::visitPrototype(std::shared_ptr<Prototype> construct) {
//
}
void Pass::visitIntegerLiteral(std::shared_ptr<LiteralInteger> construct) {
//
}
void Pass::visitCharLiteral(std::shared_ptr<LiteralChar> construct) {
//
}
void Pass::visitStringLiteral(std::shared_ptr<LiteralString> construct) {
//
}
void Pass::visitBooleanLiteral(std::shared_ptr<LiteralBoolean> construct) {
//
}
void Pass::visitAllocaInst(std::shared_ptr<InstAlloca> construct) {
//
}
void Pass::visitReturnInst(std::shared_ptr<InstReturn> construct) {
//
}
void Pass::visitBranchInst(std::shared_ptr<InstBranch> construct) {
//
}
void Pass::visitCallInst(std::shared_ptr<InstCall> construct) {
//
}
void Pass::visitStoreInst(std::shared_ptr<InstStore> construct) {
//
}
void Pass::visitJumpInst(std::shared_ptr<InstJump> construct) {
//
}
void Pass::visitCompareInst(std::shared_ptr<InstCompare> construct) {
//
}
void Pass::visitCastInst(std::shared_ptr<InstCast> construct) {
//
}
void Pass::visitOperationValue(std::shared_ptr<OperationValue> construct) {
//
}
void Pass::visitGlobal(std::shared_ptr<Global> construct) {
//
}
void Pass::visitIntegerType(std::shared_ptr<TypeInteger> construct) {
//
}
void Pass::visitDecimalType(std::shared_ptr<TypeDecimal> construct) {
//
}
void Pass::visitVoidType(std::shared_ptr<TypeVoid> construct) {
//
}
void Pass::visitBooleanType(std::shared_ptr<TypeBoolean> construct) {
//
}
void Pass::visitPointerType(std::shared_ptr<TypePointer> construct) {
//
}
void Pass::visitModule(std::shared_ptr<Module> construct) {
//
}
void Pass::visitErrorMarker(std::shared_ptr<ErrorMarker> construct) {
//
}
void Pass::visitIdentifier(std::shared_ptr<Identifier> construct) {
//
}
void Pass::visitStructType(std::shared_ptr<TypeStruct> construct) {
//
}
void Pass::visitStructDefinition(std::shared_ptr<StructDefinition> construct) {
//
}
}
| 21.935714 | 81 | 0.669489 | ionlang |
3d452f4e374cf346d1d036ad22831286aebe9ab2 | 436 | hpp | C++ | include/ring_buffer/details/clz.hpp | Wizermil/ring_buffer | 71ee2bb59aa268b462c43ed466d114c32f39dd19 | [
"MIT"
] | null | null | null | include/ring_buffer/details/clz.hpp | Wizermil/ring_buffer | 71ee2bb59aa268b462c43ed466d114c32f39dd19 | [
"MIT"
] | null | null | null | include/ring_buffer/details/clz.hpp | Wizermil/ring_buffer | 71ee2bb59aa268b462c43ed466d114c32f39dd19 | [
"MIT"
] | null | null | null | #pragma once
#include <ring_buffer/details/config.hpp>
namespace wiz::details::bit {
RING_BUFFER_HIDE_FROM_ABI constexpr int clz(unsigned x) noexcept { return __builtin_clz(x); }
RING_BUFFER_HIDE_FROM_ABI constexpr int clz(unsigned long x) noexcept { return __builtin_clzl(x); }
RING_BUFFER_HIDE_FROM_ABI constexpr int clz(unsigned long long x) noexcept { return __builtin_clzll(x); }
} // namespace wiz::details::bit
| 31.142857 | 109 | 0.766055 | Wizermil |
3d4c7001300fec428fa66d91d6bb10c5cd946c06 | 714 | hpp | C++ | robots/robots.hpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | 1 | 2017-10-24T21:43:43.000Z | 2017-10-24T21:43:43.000Z | robots/robots.hpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | 3 | 2017-12-02T08:15:29.000Z | 2018-06-05T19:35:56.000Z | robots/robots.hpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
namespace robots {
/// Solves the problem of destroying robots
class Robots {
using uint = unsigned int;
uint amountOfRobots = 0;
std::vector<bool> withRobot;
std::vector<std::vector<uint> > graph;
bool dfs(uint pos, bool color, std::vector<uint> & colors) noexcept;
public:
Robots() = default;
~Robots() = default;
/// Add a vertice to the graph
/// The smallest free number is assigned to it
void addVertices(uint cnt) noexcept;
/// Set a robot to the vertice
void setRobot(uint pos) noexcept;
/// Add an edge between two vertices
void addEdge(uint first, uint second) noexcept;
/// Checks whether robots can destroy each other
bool solve() noexcept;
};
}
| 21 | 69 | 0.710084 | uncerso |
3d4eedecab5d149018b6fc6786c77dfa2b69df38 | 3,345 | hpp | C++ | core/src/Concurrency/WorkStealingDeque.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 36 | 2015-03-12T10:42:36.000Z | 2022-01-12T04:20:40.000Z | core/src/Concurrency/WorkStealingDeque.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 1 | 2015-12-17T00:25:43.000Z | 2016-02-20T12:00:57.000Z | core/src/Concurrency/WorkStealingDeque.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 6 | 2017-06-17T07:57:53.000Z | 2019-04-09T21:11:24.000Z | /*
* Copyright (c) 2013, Hernan Saez
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CRIMILD_CORE_CONCURRENCY_WORK_STEALING_QUEUE_
#define CRIMILD_CORE_CONCURRENCY_WORK_STEALING_QUEUE_
#include "Foundation/SharedObject.hpp"
#include <vector>
#include <list>
#include <mutex>
namespace crimild {
/**
\brief A double-ended queue implemeting the work stealing pattern
*/
template< class T >
class WorkStealingQueue : public SharedObject {
using Mutex = std::mutex;
using Lock = std::lock_guard< Mutex >;
public:
WorkStealingQueue( void )
{
}
~WorkStealingQueue( void )
{
}
size_t size( void )
{
Lock lock( _mutex );
return _elems.size();
}
bool empty( void )
{
return size() == 0;
}
void clear( void )
{
Lock lock( _mutex );
_elems.clear();
}
/**
\brief Adds an element to the private end of the queue (LIFO)
*/
void push( T const &elem )
{
Lock lock( _mutex );
_elems.push_back( elem );
}
/**
\brief Retrieves an element from the private end of the queue (LIFO)
\warning You should check if the collection is empty before calling this method.
*/
T pop( void )
{
Lock lock( _mutex );
if ( _elems.size() == 0 ) {
return nullptr;
}
auto e = _elems.back();
_elems.pop_back();
return e;
}
/**
\brief Retrieves an element from the public end of the queue (FIFO)
\warning You should check if the collection is empty before calling this method
*/
T steal( void )
{
Lock lock( _mutex );
if ( _elems.size() == 0 ) {
return nullptr;
}
auto e = _elems.front();
_elems.pop_front();
return e;
}
private:
std::list< T > _elems;
std::mutex _mutex;
};
}
#endif
| 25.534351 | 85 | 0.666966 | hhsaez |
3d503972a27766dc485dce2235b71ab7dbf26d4e | 2,983 | hpp | C++ | include/customWidgets.hpp | mousepawgames/infiltrator | b99152c31bebb683ea28c990e7d10e8bee0ffeb5 | [
"MIT"
] | null | null | null | include/customWidgets.hpp | mousepawgames/infiltrator | b99152c31bebb683ea28c990e7d10e8bee0ffeb5 | [
"MIT"
] | null | null | null | include/customWidgets.hpp | mousepawgames/infiltrator | b99152c31bebb683ea28c990e7d10e8bee0ffeb5 | [
"MIT"
] | null | null | null | #ifndef CUSTOMWIDGETS_H
#define CUSTOMWIDGETS_H
#include <glibmm.h>
#include <gtkmm/box.h>
#include <gtkmm/button.h>
#include <gtkmm/entry.h>
#include <gtkmm/grid.h>
#include <gtkmm/label.h>
#include <gtkmm/liststore.h>
#include <gtkmm/notebook.h>
#include <gtkmm/scrolledwindow.h>
#include <gtkmm/spinbutton.h>
#include <gtkmm/treeview.h>
#include <gtkmm/window.h>
#include <iostream>
#include <agentDatabase.hpp>
class NumberEntry : public Gtk::Entry
{
public:
NumberEntry(){}
void on_insert_text(const Glib::ustring&, int*);
~NumberEntry(){}
private:
bool contains_only_numbers(const Glib::ustring&);
};
class TimeSelectWindow : public Gtk::Window
{
public:
enum TimeSelectMode
{
TIME_INTERCEPT,
TIME_ENCRYPT,
TIME_TRANSFER
};
/**A constructor for popupWindow
\param the Glib::ustring of the window's title
\param the Glib::ustring of the window's message
\param true in intercepting, false if encrypting
\param agent being targeted
\param agent setting the intercept/encrypt*/
TimeSelectWindow(Glib::ustring, Glib::ustring, AgentDatabase*, TimeSelectMode, int, int);
private:
AgentDatabase *db;
int targetID;
int fromID;
Gtk::Button btn_OK,
btn_Cancel;
/*NumberEntry txt_time;*/
Gtk::SpinButton spn_time;
Gtk::Label lbl_message;
Gtk::Box box_main,
box_message,
box_time,
box_buttons;
/**closes the popup window*/
void closeWindow();
/**Takes intercept time and starts a countdown to intercept codes from selected person.*/
void processIntercept();
/**Takes encrypt time and starts a countdown to protect against intercepts for selected person*/
void processEncrypt();
/**Takes transfer time and transfer it to the selected teammate.*/
void processTransfer();
};
class TitleLabel : public Gtk::Label
{
public:
TitleLabel();
~TitleLabel(){}
};
class RulesNotebook : public Gtk::Notebook
{
public:
RulesNotebook();
~RulesNotebook(){}
private:
class MarkupTextView : public Gtk::ScrolledWindow
{
public:
MarkupTextView();
Gtk::Label label;
void set_markup(Glib::ustring str){label.set_markup(str);}
~MarkupTextView(){}
};
MarkupTextView view_about;
MarkupTextView view_objectives;
MarkupTextView view_setup;
MarkupTextView view_gamescreen;
MarkupTextView view_gettingstarted;
MarkupTextView view_codes;
MarkupTextView view_winning;
MarkupTextView view_tricks;
MarkupTextView view_teams;
MarkupTextView view_infiltrator;
MarkupTextView view_tech;
};
#endif // CUSTOMWIDGETS_H
| 27.118182 | 104 | 0.624874 | mousepawgames |
3d50b7065737a577030b503e50480d9a2b218d4b | 18,731 | cpp | C++ | thirdparty/qtiplot/qtiplot/src/plot2D/QwtPieCurve.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 6 | 2018-09-05T12:41:59.000Z | 2021-07-01T05:34:23.000Z | thirdparty/qtiplot/qtiplot/src/plot2D/QwtPieCurve.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-02-07T19:09:21.000Z | 2015-08-14T03:15:42.000Z | thirdparty/qtiplot/qtiplot/src/plot2D/QwtPieCurve.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-03-25T15:50:31.000Z | 2017-12-06T12:16:47.000Z | /***************************************************************************
File : QwtPieCurve.cpp
Project : QtiPlot
--------------------------------------------------------------------
Copyright : (C) 2004 - 2008 by Ion Vasilie
Email (use @ for *) : ion_vasilief*yahoo.fr
Description : Pie plot class
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301 USA *
* *
***************************************************************************/
#include "QwtPieCurve.h"
#include "../ColorBox.h"
#include "../Table.h"
#include "../PenStyleBox.h"
#include <QPaintDevice>
#include <QPainter>
#include <QPainterPath>
#include <QVarLengthArray>
QwtPieCurve::QwtPieCurve(Table *t, const QString& name, int startRow, int endRow):
DataCurve(t, QString(), name, startRow, endRow),
d_pie_ray(50),
d_first_color(0),
d_start_azimuth(270),
d_view_angle(33),
d_thickness(33),
d_horizontal_offset(0),
d_edge_dist(25),
d_counter_clockwise(false),
d_auto_labeling(true),
d_values(false),
d_percentages(true),
d_categories(false),
d_fixed_labels_pos(true)
{
setPen(QPen(QColor(Qt::black), 1, Qt::SolidLine));
setBrush(QBrush(Qt::SolidPattern));
setStyle(QwtPlotCurve::UserCurve);
setType(Graph::Pie);
setPlotStyle(Graph::Pie);
d_table_rows = QVarLengthArray<int>(0);
}
void QwtPieCurve::clone(QwtPieCurve* c)
{
if (!c)
return;
d_pie_ray = c->radius();
d_first_color = c->firstColor();
d_start_azimuth = c->startAzimuth();
d_view_angle = c->viewAngle();
d_thickness = c->thickness();
d_horizontal_offset = c->horizontalOffset();
d_edge_dist = c->labelsEdgeDistance();
d_counter_clockwise = c->counterClockwise();
d_auto_labeling = c->labelsAutoFormat();
d_values = c->labelsValuesFormat();
d_percentages = c->labelsPercentagesFormat();
d_categories = c->labelCategories();
d_fixed_labels_pos = c->fixedLabelsPosition();
d_table_rows = c->d_table_rows;
QList <PieLabel *> lst = c->labelsList();
foreach(PieLabel *t, lst){
PieLabel *nl = addLabel(t, true);
if (nl && t->isHidden())
nl->hide();
}
}
void QwtPieCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
{
int size = dataSize();
if ( !painter || size <= 0 )
return;
if (to < 0)
to = size - 1;
if (size > 1)
drawSlices(painter, xMap, yMap, from, to);
else
drawDisk(painter, xMap, yMap);
}
void QwtPieCurve::drawDisk(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const
{
const double x_width = fabs(xMap.p1() - xMap.p2());
const double x_center = (xMap.p1() + xMap.p2())*0.5 + d_horizontal_offset*0.01*x_width;
const double y_center = (yMap.p1() + yMap.p2())*0.5;
const double ray_x = d_pie_ray*0.005*qMin(x_width, fabs(yMap.p1() - yMap.p2()));
const double view_angle_rad = d_view_angle*M_PI/180.0;
const double ray_y = ray_x*sin(view_angle_rad);
const double thick = 0.01*d_thickness*ray_x*cos(view_angle_rad);
QRectF pieRect;
pieRect.setX(x_center - ray_x);
pieRect.setY(y_center - ray_y);
pieRect.setWidth(2*ray_x);
pieRect.setHeight(2*ray_y);
QRectF pieRect2 = pieRect;
pieRect2.translate(0, thick);
painter->save();
painter->setPen(QwtPlotCurve::pen());
painter->setBrush(QBrush(color(0), QwtPlotCurve::brush().style()));
QPointF start(x_center + ray_x, y_center);
QPainterPath path(start);
path.lineTo(start.x(), start.y() + thick);
path.arcTo(pieRect2, 0, -180.0);
QPointF aux = path.currentPosition();
path.lineTo(aux.x(), aux.y() - thick);
path.arcTo(pieRect, -180.0, 180.0);
painter->drawPath(path);
painter->drawEllipse(pieRect);
if (d_texts_list.size() > 0){
PieLabel* l = d_texts_list[0];
if (l){
QString s;
if (d_auto_labeling){
if (d_categories)
s += QString::number(d_table_rows[0]) + "\n";
if (d_values && d_percentages)
s += ((Graph *)plot())->locale().toString(y(0), 'g', 4) + " (100%)";
else if (d_values)
s += ((Graph *)plot())->locale().toString(y(0), 'g', 4);
else if (d_percentages)
s += "100%";
l->setText(s);
if (l->isHidden())
l->show();
} else
l->setText(l->customText());
if (d_fixed_labels_pos){
double a_deg = d_start_azimuth + 180.0;
if (a_deg > 360)
a_deg -= 360;
double a_rad = a_deg*M_PI/180.0;
double rx = ray_x*(1 + 0.01*d_edge_dist);
const double x = x_center + rx*cos(a_rad);
double ry = ray_y*(1 + 0.01*d_edge_dist);
double y = y_center + ry*sin(a_rad);
if (a_deg > 0 && a_deg < 180)
y += thick;
double dx = xMap.invTransform(x - l->width()/2);
double dy = yMap.invTransform(y - l->height()/2);
l->setOriginCoord(dx, dy);
}
}
}
painter->restore();
}
void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
{
const double x_width = fabs(xMap.p1() - xMap.p2());
const double x_center = (xMap.p1() + xMap.p2())*0.5 + d_horizontal_offset*0.01*x_width;
const double y_center = (yMap.p1() + yMap.p2())*0.5;
const double ray_x = d_pie_ray*0.005*qMin(x_width, fabs(yMap.p1() - yMap.p2()));
const double view_angle_rad = d_view_angle*M_PI/180.0;
const double ray_y = ray_x*sin(view_angle_rad);
const double thick = 0.01*d_thickness*ray_x*cos(view_angle_rad);
QRectF pieRect;
pieRect.setX(x_center - ray_x);
pieRect.setY(y_center - ray_y);
pieRect.setWidth(2*ray_x);
pieRect.setHeight(2*ray_y);
QRectF pieRect2 = pieRect;
pieRect2.translate(0, thick);
double sum = 0.0;
for (int i = from; i <= to; i++)
sum += y(i);
const int sign = d_counter_clockwise ? 1 : -1;
const int size = dataSize();
double *start_angle = new double[size];
double *end_angle = new double[size];
double aux_angle = d_start_azimuth;
for (int i = from; i <= to; i++){
double a = -sign*y(i)/sum*360.0;
start_angle[i] = aux_angle;
double end = aux_angle + a;
if (end >= 360)
end -= 360;
else if (end < 0)
end += 360;
end_angle[i] = end;
aux_angle = end;
}
int angle = (int)(5760 * d_start_azimuth/360.0);
if (d_counter_clockwise)
angle = (int)(5760 * (1 - d_start_azimuth/360.0));
painter->save();
QLocale locale = ((Graph *)plot())->multiLayer()->locale();
for (int i = from; i <= to; i++){
const double yi = y(i);
const double q = yi/sum;
const int value = (int)(q*5760);
painter->setPen(QwtPlotCurve::pen());
painter->setBrush(QBrush(color(i), QwtPlotCurve::brush().style()));
double deg = q*360;
double start_3D_view_angle = start_angle[i];
double end_3D_view_angle = end_angle[i];
if (d_counter_clockwise){
start_3D_view_angle = end_angle[i];
end_3D_view_angle = start_angle[i];
}
bool draw3D = false;
if (deg <= 180 && start_3D_view_angle >= 0 && start_3D_view_angle < 180){
if ((end_3D_view_angle > 180 && end_3D_view_angle > start_3D_view_angle)){
deg = 180 - start_3D_view_angle;
end_3D_view_angle = 180.0;
}
draw3D = true;
} else if (start_3D_view_angle >= 180 && end_3D_view_angle < start_3D_view_angle){
if (end_3D_view_angle > 180)
end_3D_view_angle = 180;
deg = end_3D_view_angle;
start_3D_view_angle = 0;
draw3D = true;
} else if (deg > 180 && start_3D_view_angle >= 180){
deg = 180;
end_3D_view_angle = 180;
start_3D_view_angle = 0;
draw3D = true;
}
if (draw3D){
double rad = start_3D_view_angle/180.0*M_PI;
QPointF start(x_center + ray_x*cos(rad), y_center + ray_y*sin(rad));
QPainterPath path(start);
path.lineTo(start.x(), start.y() + thick);
path.arcTo(pieRect2, -start_3D_view_angle, -deg);
QPointF aux = path.currentPosition();
path.lineTo(aux.x(), aux.y() - thick);
path.arcTo(pieRect, -end_3D_view_angle, deg);
painter->drawPath(path);
} else {
if (start_3D_view_angle >= 0 && start_3D_view_angle < 180){
if (end_3D_view_angle > 180)
end_3D_view_angle = 0;
double rad = start_3D_view_angle/180.0*M_PI;
QPointF start(x_center + ray_x*cos(rad), y_center + ray_y*sin(rad));
QPainterPath path(start);
path.lineTo(start.x(), start.y() + thick);
deg = 180 - start_3D_view_angle;
path.arcTo(pieRect2, -start_3D_view_angle, -deg);
QPointF aux = path.currentPosition();
path.lineTo(aux.x(), aux.y() - thick);
path.arcTo(pieRect, -180, deg);
painter->drawPath(path);
path.moveTo(QPointF(x_center + ray_x, y_center));
aux = path.currentPosition();
path.lineTo(aux.x(), aux.y() + thick);
path.arcTo(pieRect2, 0, -end_3D_view_angle);
aux = path.currentPosition();
path.lineTo(aux.x(), aux.y() - thick);
path.arcTo(pieRect, -end_3D_view_angle, end_3D_view_angle);
painter->drawPath(path);
}
}
painter->drawPie(pieRect, sign*angle, sign*value);
angle += value;
if (i >= d_texts_list.size())
continue;
PieLabel* l = d_texts_list[i];
if (l){
QString s;
if (d_auto_labeling){
if (d_categories)
s += QString::number(d_table_rows[i]) + "\n";
if (d_values && d_percentages)
s += locale.toString(yi, 'g', 4) + " (" + locale.toString(q*100, 'g', 4) + "%)";
else if (d_values)
s += locale.toString(yi, 'g', 4);
else if (d_percentages)
s += locale.toString(q*100, 'g', 4) + "%";
l->setText(s);
if (l->isHidden())
l->show();
} else
l->setText(l->customText());
if (d_fixed_labels_pos){
double a_deg = start_angle[i] - sign*q*180.0;
if (a_deg > 360)
a_deg -= 360.0;
double a_rad = a_deg*M_PI/180.0;
double rx = ray_x*(1 + 0.01*d_edge_dist);
const double x = x_center + rx*cos(a_rad);
double ry = ray_y*(1 + 0.01*d_edge_dist);
double y = y_center + ry*sin(a_rad);
if (a_deg > 0 && a_deg < 180)
y += thick;
double dx = xMap.invTransform(x - l->width()/2);
double dy = yMap.invTransform(y - l->height()/2);
l->setOriginCoord(dx, dy);
}
}
}
painter->restore();
delete [] start_angle;
delete [] end_angle;
}
QColor QwtPieCurve::color(int i) const
{
return ColorBox::color((d_first_color + i) % ColorBox::numPredefinedColors());
}
void QwtPieCurve::setBrushStyle(const Qt::BrushStyle& style)
{
QBrush br = QwtPlotCurve::brush();
if (br.style() == style)
return;
br.setStyle(style);
setBrush(br);
}
void QwtPieCurve::loadData()
{
Graph *d_plot = (Graph *)plot();
QLocale locale = d_plot->multiLayer()->locale();
QVarLengthArray<double> X(abs(d_end_row - d_start_row) + 1);
d_table_rows.resize(abs(d_end_row - d_start_row) + 1);
int size = 0;
int ycol = d_table->colIndex(title().text());
for (int i = d_start_row; i <= d_end_row; i++ ){
QString xval = d_table->text(i, ycol);
bool valid_data = true;
if (!xval.isEmpty()){
X[size] = locale.toDouble(xval, &valid_data);
if (valid_data){
d_table_rows[size] = i + 1;
size++;
}
}
}
X.resize(size);
d_table_rows.resize(size);
setData(X.data(), X.data(), size);
int labels = d_texts_list.size();
//If there are no labels (initLabels() wasn't called yet) or if we have enough labels: do nothing!
if(d_texts_list.isEmpty() || labels == size)
return;
//Else add new pie labels.
for (int i = labels; i < size; i++ ){
PieLabel* l = new PieLabel(d_plot, this);
d_texts_list << l;
l->hide();
}
}
PieLabel* QwtPieCurve::addLabel(PieLabel *l, bool clone)
{
if (!l)
return 0;
Graph *g = (Graph *)plot();
if (clone){
PieLabel *newLabel = new PieLabel(g, this);
newLabel->clone(l);
newLabel->setCustomText(l->customText());
d_texts_list << newLabel;
if (l->text().isEmpty())
newLabel->hide();
return newLabel;
} else {
l->setPieCurve(this);
d_texts_list << l;
if (l->text().isEmpty())
l->hide();
}
return l;
}
void QwtPieCurve::initLabels()
{
int size = abs(d_end_row - d_start_row) + 1;
int dataPoints = dataSize();
double sum = 0.0;
for (int i = 0; i < dataPoints; i++)
sum += y(i);
Graph *d_plot = (Graph *)plot();
QLocale locale = d_plot->multiLayer()->locale();
for (int i = 0; i <size; i++ ){
PieLabel* l = new PieLabel(d_plot, this);
d_texts_list << l;
if (i < dataPoints)
l->setText(locale.toString(y(i)/sum*100, 'g', 4) + "%");
else
l->hide();
}
}
PieLabel::PieLabel(Graph *plot, QwtPieCurve *pie):LegendWidget(plot),
d_pie_curve(pie),
d_custom_text(QString::null)
{
setBackgroundColor(QColor(255, 255, 255, 0));
setFrameStyle(0);
plot->add(this, false);
}
QString PieLabel::customText()
{
if (d_custom_text.isEmpty())
return text();
return d_custom_text;
}
void PieLabel::closeEvent(QCloseEvent* e)
{
setText(QString::null);
hide();
e->ignore();
}
QString PieLabel::saveToString()
{
if (!d_pie_curve)
return LegendWidget::saveToString();
if (text().isEmpty())
return QString::null;
QString s = "<PieText>\n";
s += "<index>" + QString::number(d_pie_curve->labelsList().indexOf(this)) + "</index>\n";
s += FrameWidget::saveToString();
s += "<Text>\n" + text() + "\n</Text>\n";
QFont f = font();
s += "<Font>" + f.family() + "\t";
s += QString::number(f.pointSize())+"\t";
s += QString::number(f.weight())+"\t";
s += QString::number(f.italic())+"\t";
s += QString::number(f.underline())+"\t";
s += QString::number(f.strikeOut())+"</Font>\n";
s += "<TextColor>" + textColor().name()+"</TextColor>\n";
QColor bc = backgroundColor();
s += "<Background>" + bc.name() + "</Background>\n";
s += "<Alpha>" + QString::number(bc.alpha()) + "</Alpha>\n";
s += "<Angle>" + QString::number(angle()) + "</Angle>\n";
return s + "</PieText>\n";
}
void PieLabel::restore(Graph *g, const QStringList& lst)
{
PieLabel *l = NULL;
QStringList::const_iterator line;
QColor backgroundColor = Qt::white, textColor = Qt::black;
QFont f = QFont();
double x = 0.0, y = 0.0;
QString text;
int frameStyle = 0, angle = 0;
QPen framePen = QPen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
for (line = lst.begin(); line != lst.end(); line++){
QString s = *line;
if (s.contains("<index>")){
int index = s.remove("<index>").remove("</index>").toInt();
QwtPieCurve *pie = (QwtPieCurve *)g->curve(0);
if(pie){
QList<PieLabel *> labels = pie->labelsList();
if (index >= 0 && index < labels.size())
l = labels.at(index);
}
} else if (s.contains("<Frame>"))
frameStyle = s.remove("<Frame>").remove("</Frame>").toInt();
else if (s.contains("<Color>"))
framePen.setColor((QColor(s.remove("<Color>").remove("</Color>"))));
else if (s.contains("<FrameWidth>"))
framePen.setWidth(s.remove("<FrameWidth>").remove("</FrameWidth>").toInt());
else if (s.contains("<LineStyle>"))
framePen.setStyle(PenStyleBox::penStyle(s.remove("<LineStyle>").remove("</LineStyle>").toInt()));
else if (s.contains("<x>"))
x = s.remove("<x>").remove("</x>").toDouble();
else if (s.contains("<y>"))
y = s.remove("<y>").remove("</y>").toDouble();
else if (s.contains("<Text>")){
QStringList txt;
while ( s != "</Text>" ){
s = *(++line);
txt << s;
}
txt.pop_back();
text = txt.join("\n");
} else if (s.contains("<Font>")){
QStringList lst = s.remove("<Font>").remove("</Font>").split("\t");
f = QFont(lst[0], lst[1].toInt(), lst[2].toInt(), lst[3].toInt());
f.setUnderline(lst[4].toInt());
f.setStrikeOut(lst[5].toInt());
} else if (s.contains("<TextColor>"))
textColor = QColor(s.remove("<TextColor>").remove("</TextColor>"));
else if (s.contains("<Background>"))
backgroundColor = QColor(s.remove("<Background>").remove("</Background>"));
else if (s.contains("<Alpha>"))
backgroundColor.setAlpha(s.remove("<Alpha>").remove("</Alpha>").toInt());
else if (s.contains("<Angle>"))
angle = s.remove("<Angle>").remove("</Angle>").toInt();
}
if (l){
l->setFrameStyle(frameStyle);
l->setFramePen(framePen);
l->setText(text);
l->setFont(f);
l->setTextColor(textColor);
l->setBackgroundColor(backgroundColor);
l->setAngle(angle);
l->setOriginCoord(x, y);
}
}
| 32.861404 | 121 | 0.559767 | hoehnp |
3d51c7983e152fb7ebb899aa17f569f836d3f915 | 2,193 | cpp | C++ | common/utility/src/Random.cpp | cbtek/SourceGen | 6593300c658529acb06b83982bbc9e698c270aeb | [
"MIT"
] | null | null | null | common/utility/src/Random.cpp | cbtek/SourceGen | 6593300c658529acb06b83982bbc9e698c270aeb | [
"MIT"
] | 3 | 2017-07-12T17:10:52.000Z | 2017-09-21T19:06:59.000Z | common/utility/src/Random.cpp | cbtek/SourceGen | 6593300c658529acb06b83982bbc9e698c270aeb | [
"MIT"
] | null | null | null | /**
MIT License
Copyright (c) 2016 cbtek
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 "Random.h"
namespace cbtek {
namespace common {
namespace utility {
Random::Random(long seed) : m_ix(9123),m_iy(8844),m_iz(20846)
{
reseed(seed);
m_mx=1/30269.0;m_my=1/30307.0;m_mz=1/30323.0;
}
void Random::reseed(long seed)
{
srand(seed);
m_ix=rand();
m_iy=rand();
m_iz=rand();
}
double Random::random()
{
m_ix = fmod(171*m_ix,30269);
m_iy = fmod(172*m_iy,20207);
m_iz = fmod(170*m_iz,30323);
double modValue=(((double)m_ix)*m_mx+((double)m_iy)*m_my+((double)m_iz)*m_mz);
double value = fmod(modValue,1.);
if (value < 0)
{
value*=-1;
}
return value;
}
int Random::next(int mn, int mx)
{
if (mn==mx)return mn;
int max=mx;
int min=mn;
max++;
if (min < 0)
{
min*=-1;
max = max + min;
double rng=random();
int value = (int)((rng*(max)));
return (value-min);
}
double rng=random();
return (int)(rng*(max-min))+min;
}
int Random::next(int max)
{
return next(0,max);
}
}}}//namespace
| 26.107143 | 83 | 0.657091 | cbtek |
3d51edcab14180336fe7a0ec20437ab8fa878aff | 5,581 | cpp | C++ | test/asmjit_test_instinfo.cpp | clayne/asmjit | a4cb51b532af0f8137c4182914244c3b05d7745f | [
"Zlib"
] | 2,354 | 2016-07-13T16:08:25.000Z | 2022-03-31T13:28:02.000Z | test/asmjit_test_instinfo.cpp | clayne/asmjit | a4cb51b532af0f8137c4182914244c3b05d7745f | [
"Zlib"
] | 223 | 2016-07-14T17:32:11.000Z | 2022-03-31T23:02:01.000Z | test/asmjit_test_instinfo.cpp | clayne/asmjit | a4cb51b532af0f8137c4182914244c3b05d7745f | [
"Zlib"
] | 386 | 2016-07-23T09:02:14.000Z | 2022-03-09T14:04:43.000Z | // This file is part of AsmJit project <https://asmjit.com>
//
// See asmjit.h or LICENSE.md for license and copyright information
// SPDX-License-Identifier: Zlib
#include <asmjit/core.h>
#if !defined(ASMJIT_NO_X86)
#include <asmjit/x86.h>
#endif
#include <stdio.h>
using namespace asmjit;
static char accessLetter(bool r, bool w) noexcept {
return r && w ? 'X' : r ? 'R' : w ? 'W' : '_';
}
static void printInfo(Arch arch, const BaseInst& inst, const Operand_* operands, size_t opCount) {
StringTmp<512> sb;
// Read & Write Information
// ------------------------
InstRWInfo rw;
InstAPI::queryRWInfo(arch, inst, operands, opCount, &rw);
#ifndef ASMJIT_NO_LOGGING
Formatter::formatInstruction(sb, FormatFlags::kNone, nullptr, arch, inst, operands, opCount);
#else
sb.append("<Logging-Not-Available>");
#endif
sb.append("\n");
sb.append(" Operands:\n");
for (uint32_t i = 0; i < rw.opCount(); i++) {
const OpRWInfo& op = rw.operand(i);
sb.appendFormat(" [%u] Op=%c Read=%016llX Write=%016llX Extend=%016llX",
i,
accessLetter(op.isRead(), op.isWrite()),
op.readByteMask(),
op.writeByteMask(),
op.extendByteMask());
if (op.isMemBaseUsed()) {
sb.appendFormat(" Base=%c", accessLetter(op.isMemBaseRead(), op.isMemBaseWrite()));
if (op.isMemBasePreModify())
sb.appendFormat(" <PRE>");
if (op.isMemBasePostModify())
sb.appendFormat(" <POST>");
}
if (op.isMemIndexUsed()) {
sb.appendFormat(" Index=%c", accessLetter(op.isMemIndexRead(), op.isMemIndexWrite()));
}
sb.append("\n");
}
// CPU Flags (Read/Write)
// ----------------------
if ((rw.readFlags() | rw.writeFlags()) != CpuRWFlags::kNone) {
sb.append(" Flags: \n");
struct FlagMap {
CpuRWFlags flag;
char name[4];
};
static const FlagMap flagMap[] = {
{ CpuRWFlags::kX86_CF, "CF" },
{ CpuRWFlags::kX86_OF, "OF" },
{ CpuRWFlags::kX86_SF, "SF" },
{ CpuRWFlags::kX86_ZF, "ZF" },
{ CpuRWFlags::kX86_AF, "AF" },
{ CpuRWFlags::kX86_PF, "PF" },
{ CpuRWFlags::kX86_DF, "DF" },
{ CpuRWFlags::kX86_IF, "IF" },
{ CpuRWFlags::kX86_AC, "AC" },
{ CpuRWFlags::kX86_C0, "C0" },
{ CpuRWFlags::kX86_C1, "C1" },
{ CpuRWFlags::kX86_C2, "C2" },
{ CpuRWFlags::kX86_C3, "C3" }
};
sb.append(" ");
for (uint32_t f = 0; f < 13; f++) {
char c = accessLetter((rw.readFlags() & flagMap[f].flag) != CpuRWFlags::kNone,
(rw.writeFlags() & flagMap[f].flag) != CpuRWFlags::kNone);
if (c != '_')
sb.appendFormat("%s=%c ", flagMap[f].name, c);
}
sb.append("\n");
}
// CPU Features
// ------------
CpuFeatures features;
InstAPI::queryFeatures(arch, inst, operands, opCount, &features);
#ifndef ASMJIT_NO_LOGGING
if (!features.empty()) {
sb.append(" Features:\n");
sb.append(" ");
bool first = true;
CpuFeatures::Iterator it(features.iterator());
while (it.hasNext()) {
uint32_t featureId = uint32_t(it.next());
if (!first)
sb.append(" & ");
Formatter::formatFeature(sb, arch, featureId);
first = false;
}
sb.append("\n");
}
#endif
printf("%s\n", sb.data());
}
template<typename... Args>
static void printInfoSimple(Arch arch,InstId instId, InstOptions options, Args&&... args) {
BaseInst inst(instId);
inst.addOptions(options);
Operand_ opArray[] = { std::forward<Args>(args)... };
printInfo(arch, inst, opArray, sizeof...(args));
}
template<typename... Args>
static void printInfoExtra(Arch arch, InstId instId, InstOptions options, const BaseReg& extraReg, Args&&... args) {
BaseInst inst(instId);
inst.addOptions(options);
inst.setExtraReg(extraReg);
Operand_ opArray[] = { std::forward<Args>(args)... };
printInfo(arch, inst, opArray, sizeof...(args));
}
static void testX86Arch() {
#if !defined(ASMJIT_NO_X86)
using namespace x86;
Arch arch = Arch::kX64;
printInfoSimple(arch, Inst::kIdAdd, InstOptions::kNone, eax, ebx);
printInfoSimple(arch, Inst::kIdLods, InstOptions::kNone, eax, dword_ptr(rsi));
printInfoSimple(arch, Inst::kIdPshufd, InstOptions::kNone, xmm0, xmm1, imm(0));
printInfoSimple(arch, Inst::kIdPabsb, InstOptions::kNone, mm1, mm2);
printInfoSimple(arch, Inst::kIdPabsb, InstOptions::kNone, xmm1, xmm2);
printInfoSimple(arch, Inst::kIdPextrw, InstOptions::kNone, eax, mm1, imm(0));
printInfoSimple(arch, Inst::kIdPextrw, InstOptions::kNone, eax, xmm1, imm(0));
printInfoSimple(arch, Inst::kIdPextrw, InstOptions::kNone, ptr(rax), xmm1, imm(0));
printInfoSimple(arch, Inst::kIdVpdpbusd, InstOptions::kNone, xmm0, xmm1, xmm2);
printInfoSimple(arch, Inst::kIdVpdpbusd, InstOptions::kX86_Vex, xmm0, xmm1, xmm2);
printInfoSimple(arch, Inst::kIdVaddpd, InstOptions::kNone, ymm0, ymm1, ymm2);
printInfoSimple(arch, Inst::kIdVaddpd, InstOptions::kNone, ymm0, ymm30, ymm31);
printInfoSimple(arch, Inst::kIdVaddpd, InstOptions::kNone, zmm0, zmm1, zmm2);
printInfoExtra(arch, Inst::kIdVaddpd, InstOptions::kNone, k1, zmm0, zmm1, zmm2);
printInfoExtra(arch, Inst::kIdVaddpd, InstOptions::kX86_ZMask, k1, zmm0, zmm1, zmm2);
#endif
}
int main() {
printf("AsmJit Instruction Info Test-Suite v%u.%u.%u\n",
unsigned((ASMJIT_LIBRARY_VERSION >> 16) ),
unsigned((ASMJIT_LIBRARY_VERSION >> 8) & 0xFF),
unsigned((ASMJIT_LIBRARY_VERSION ) & 0xFF));
printf("\n");
testX86Arch();
return 0;
}
| 30.664835 | 116 | 0.623186 | clayne |
3d57a98f65827c5eed3086f37bd2006c5e2e8017 | 5,765 | cpp | C++ | dependencies/PyMesh/src/IO/MSHWriter.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | 5 | 2018-06-04T19:52:02.000Z | 2022-01-22T09:04:00.000Z | dependencies/PyMesh/src/IO/MSHWriter.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | null | null | null | dependencies/PyMesh/src/IO/MSHWriter.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | null | null | null | /* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */
#include "MSHWriter.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <Core/Exception.h>
#include <Mesh.h>
#include "MshSaver.h"
using namespace PyMesh;
namespace MSHWriterHelper {
bool positive_orientated(
const Vector3F& v1, const Vector3F& v2,
const Vector3F& v3, const Vector3F& v4) {
return (v2 - v1).cross(v3 - v1).dot(v4 - v1) >= 0.0;
}
void correct_tet_orientation(const VectorF& vertices, VectorI& voxels) {
const size_t num_voxels = voxels.size() / 4;
for (size_t i=0; i<num_voxels; i++) {
const VectorI tet = voxels.segment(i*4, 4);
const Vector3F& v1 = vertices.segment(tet[0]*3, 3);
const Vector3F& v2 = vertices.segment(tet[1]*3, 3);
const Vector3F& v3 = vertices.segment(tet[2]*3, 3);
const Vector3F& v4 = vertices.segment(tet[3]*3, 3);
if (!positive_orientated(v1, v2, v3, v4)) {
voxels[i*4] = tet[1];
voxels[i*4+1] = tet[0];
}
}
}
MshSaver::ElementType get_face_type(size_t vertex_per_face) {
MshSaver::ElementType type;
switch (vertex_per_face) {
case 3:
type = MshSaver::TRI;
break;
case 4:
type = MshSaver::QUAD;
break;
default:
throw NotImplementedError("Unsupported face type");
break;
}
return type;
}
MshSaver::ElementType get_voxel_type(size_t vertex_per_voxel) {
MshSaver::ElementType type;
switch (vertex_per_voxel) {
case 4:
type = MshSaver::TET;
break;
case 8:
type = MshSaver::HEX;
break;
default:
throw NotImplementedError("Unsupported voxel type");
break;
}
return type;
}
}
using namespace MSHWriterHelper;
void MSHWriter::with_attribute(const std::string& attr_name) {
m_attr_names.push_back(attr_name);
}
void MSHWriter::write_mesh(Mesh& mesh) {
if (mesh.get_num_voxels() == 0) {
write_surface_mesh(mesh);
} else {
write_volume_mesh(mesh);
}
}
void MSHWriter::write(const VectorF& vertices, const VectorI& faces, const VectorI& voxels,
size_t dim, size_t vertex_per_face, size_t vertex_per_voxel) {
MshSaver saver(m_filename, !m_in_ascii);
MshSaver::ElementType type;
if (voxels.size() == 0) {
type = get_face_type(vertex_per_face);
saver.save_mesh(vertices, faces, dim, type);
} else {
type = get_voxel_type(vertex_per_voxel);
saver.save_mesh(vertices, voxels, dim, type);
}
if (m_attr_names.size() != 0) {
std::cerr << "Warning: all attributes are ignored." << std::endl;
}
}
void MSHWriter::write_surface_mesh(Mesh& mesh) {
MshSaver saver(m_filename, !m_in_ascii);
size_t dim = mesh.get_dim();
size_t num_vertices = mesh.get_num_vertices();
size_t num_faces = mesh.get_num_faces();
size_t vertex_per_face = mesh.get_vertex_per_face();
saver.save_mesh(mesh.get_vertices(), mesh.get_faces(), dim,
get_face_type(vertex_per_face));
for (AttrNames::const_iterator itr = m_attr_names.begin();
itr != m_attr_names.end(); itr++) {
if (!mesh.has_attribute(*itr)) {
std::cerr << "Error: Attribute \"" << *itr<< "\" does not exist."
<< std::endl;
continue;
}
VectorF& attr = mesh.get_attribute(*itr);
write_attribute(saver, *itr, attr, dim, num_vertices, num_faces);
}
}
void MSHWriter::write_volume_mesh(Mesh& mesh) {
MshSaver saver(m_filename, !m_in_ascii);
size_t dim = mesh.get_dim();
size_t num_vertices = mesh.get_num_vertices();
size_t num_voxels = mesh.get_num_voxels();
size_t vertex_per_voxel = mesh.get_vertex_per_voxel();
saver.save_mesh(mesh.get_vertices(), mesh.get_voxels(), dim,
get_voxel_type(vertex_per_voxel));
for (AttrNames::const_iterator itr = m_attr_names.begin();
itr != m_attr_names.end(); itr++) {
if (!mesh.has_attribute(*itr)) {
std::cerr << "Error: Attribute \"" << *itr<< "\" does not exist."
<< std::endl;
continue;
}
VectorF& attr = mesh.get_attribute(*itr);
write_attribute(saver, *itr, attr, dim, num_vertices, num_voxels);
}
}
void MSHWriter::write_attribute(MshSaver& saver, const std::string& name,
VectorF& value, size_t dim, size_t num_vertices, size_t num_elements) {
size_t attr_size = value.size();
if (attr_size == num_vertices) {
saver.save_scalar_field(name, value);
} else if (attr_size == num_vertices * dim) {
saver.save_vector_field(name, value);
} else if (attr_size == num_vertices * (dim * (dim+1)) / 2 &&
attr_size % num_elements != 0) {
throw NotImplementedError("Per-vertex tensor field is not supported.");
} else if (attr_size == num_elements) {
saver.save_elem_scalar_field(name, value);
} else if (attr_size == num_elements * dim) {
saver.save_elem_vector_field(name, value);
} else if (attr_size == num_elements * (dim * (dim + 1)) / 2) {
saver.save_elem_tensor_field(name, value);
} else {
std::stringstream err_msg;
err_msg << "Attribute " << name << " has length " << attr_size << std::endl;
err_msg << "Unable to interpret the attribute type.";
std::cerr << "Warning: ";
std::cerr << err_msg.str() << std::endl;
}
}
| 33.132184 | 91 | 0.593235 | aprieels |
3d5ee2d326c15b3272690bdeec6bab5df65723a1 | 493 | cpp | C++ | module-services/service-eink/messages/PrepareDisplayEarlyRequest.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-services/service-eink/messages/PrepareDisplayEarlyRequest.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-services/service-eink/messages/PrepareDisplayEarlyRequest.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "PrepareDisplayEarlyRequest.hpp"
namespace service::eink
{
PrepareDisplayEarlyRequest::PrepareDisplayEarlyRequest(::gui::RefreshModes refreshMode) : refreshMode{refreshMode}
{}
auto PrepareDisplayEarlyRequest::getRefreshMode() const noexcept -> ::gui::RefreshModes
{
return refreshMode;
}
} // namespace service::eink
| 30.8125 | 118 | 0.736308 | bitigchi |
87cd1e4d0bf748e83996eb33a10dc83ae7fe5d80 | 27,476 | cpp | C++ | Sample/MultiPipelines/MultiPipelines.cpp | po2xel/vkpp | 04cf67cefa4e967fc234378da06366d66447c335 | [
"MIT"
] | 5 | 2017-04-05T13:29:40.000Z | 2018-04-10T21:04:51.000Z | Sample/MultiPipelines/MultiPipelines.cpp | po2xel/vkpp | 04cf67cefa4e967fc234378da06366d66447c335 | [
"MIT"
] | null | null | null | Sample/MultiPipelines/MultiPipelines.cpp | po2xel/vkpp | 04cf67cefa4e967fc234378da06366d66447c335 | [
"MIT"
] | null | null | null | #include "MultiPipelines.h"
#include <iostream>
namespace vkpp::sample
{
decltype(auto) SetEnabledFeatures(const vkpp::PhysicalDeviceFeatures& aPhysicalDeviceFeatures)
{
vkpp::PhysicalDeviceFeatures lEnabledFeatures{};
// Fill mode non-solid is required for wire frame display.
if (aPhysicalDeviceFeatures.fillModeNonSolid)
{
lEnabledFeatures.fillModeNonSolid = VK_TRUE;
// Wide lines must be present for line width > 1.0f.
if (aPhysicalDeviceFeatures.wideLines)
lEnabledFeatures.wideLines = VK_TRUE;
}
return lEnabledFeatures;
}
MultiPipelines::MultiPipelines(CWindow& aWindow, const char* apApplicationName, uint32_t aApplicationVersion, const char* apEngineName, uint32_t aEngineVersion)
: ExampleBase(aWindow, apApplicationName, aApplicationVersion, apEngineName, aEngineVersion),
CWindowEvent(aWindow),
mModel(*this, mLogicalDevice, mPhysicalDeviceMemoryProperties),
mDepthResource(mLogicalDevice, mPhysicalDeviceMemoryProperties),
mUniformBufferResource(mLogicalDevice, mPhysicalDeviceMemoryProperties)
{
mResizedFunc = [this](Sint32 /*aWidth*/, Sint32 /*aHeight*/)
{
// Ensure all operations on the device have been finished before destroying resources.
mLogicalDevice.Wait();
// Re-create swapchain.
CreateSwapchain(mSwapchain);
mDepthResource.Reset();
CreateDepthResource();
// Re-create framebuffers.
for (auto& lFramebuffer : mFramebuffers)
mLogicalDevice.DestroyFramebuffer(lFramebuffer);
mFramebuffers.clear();
CreateFramebuffer();
// Command buffers need to be recreated as they reference to the destroyed framebuffer.
mLogicalDevice.FreeCommandBuffers(mCmdPool, mCmdDrawBuffers);
AllocateDrawCmdBuffers();
BuildCommandBuffers();
};
CreateCommandPool();
AllocateDrawCmdBuffers();
CreateRenderPass();
CreateDepthResource();
CreateSemaphores();
CreateFences();
CreateFramebuffer();
mModel.LoadMode("model/treasure_smooth.dae");
CreateSetLayout();
CreatePipelineLayout();
CreateGraphicsPipelines();
CreateUniformBuffer();
UpdateUniformBuffer();
CreateDescriptorPool();
AllocateDescriptorSet();
UpdateDescriptorSet();
BuildCommandBuffers();
theApp.RegisterUpdateEvent([this](void)
{
Update();
});
}
MultiPipelines::~MultiPipelines(void)
{
mLogicalDevice.Wait();
// mLogicalDevice.FreeDescriptorSet(mDescriptorPool, mDescriptorSet);
mLogicalDevice.DestroyDescriptorPool(mDescriptorPool);
mLogicalDevice.DestroyPipeline(mPipelines.toon);
mLogicalDevice.DestroyPipeline(mPipelines.wireframe);
mLogicalDevice.DestroyPipeline(mPipelines.phong);
mLogicalDevice.DestroyPipelineLayout(mPipelineLayout);
mLogicalDevice.DestroyDescriptorSetLayout(mSetLayout);
for (auto& lFramebuffer : mFramebuffers)
mLogicalDevice.DestroyFramebuffer(lFramebuffer);
mLogicalDevice.DestroyRenderPass(mRenderPass);
// mDepthResource.Reset();
for (auto& lFence : mWaitFences)
mLogicalDevice.DestroyFence(lFence);
mLogicalDevice.DestroySemaphore(mRenderCompleteSemaphore);
mLogicalDevice.DestroySemaphore(mPresentCompleteSemaphore);
mLogicalDevice.FreeCommandBuffers(mCmdPool, mCmdDrawBuffers);
mLogicalDevice.DestroyCommandPool(mCmdPool);
}
void MultiPipelines::CreateCommandPool(void)
{
const vkpp::CommandPoolCreateInfo lCmdCreateInfo
{
mGraphicsQueue.familyIndex,
vkpp::CommandPoolCreateFlagBits::eResetCommandBuffer
};
mCmdPool = mLogicalDevice.CreateCommandPool(lCmdCreateInfo);
}
void MultiPipelines::AllocateDrawCmdBuffers(void)
{
const vkpp::CommandBufferAllocateInfo lCmdAllocateInfo
{
mCmdPool,
static_cast<uint32_t>(mSwapchain.buffers.size()),
};
// Create one command buffer for each swapchain image and reuse for renderering.
mCmdDrawBuffers = mLogicalDevice.AllocateCommandBuffers(lCmdAllocateInfo);
}
void MultiPipelines::CreateRenderPass(void)
{
const std::array<vkpp::AttachementDescription, 2> lAttachementDescriptions
{ {
// Color Attachment.
{
mSwapchain.surfaceFormat.format,
vkpp::SampleCountFlagBits::e1,
vkpp::AttachmentLoadOp::eClear,
vkpp::AttachmentStoreOp::eStore,
vkpp::ImageLayout::eUndefined, vkpp::ImageLayout::ePresentSrcKHR
},
// Depth Attachment.
{
vkpp::Format::eD32sFloatS8uInt,
vkpp::SampleCountFlagBits::e1,
vkpp::AttachmentLoadOp::eClear, vkpp::AttachmentStoreOp::eDontCare,
vkpp::ImageLayout::eUndefined, vkpp::ImageLayout::eDepthStencilAttachmentOptimal
}
}};
// Setup color attachment reference.
constexpr vkpp::AttachmentReference lColorRef
{
0, vkpp::ImageLayout::eColorAttachmentOptimal
};
// Setup depth attachment reference.
constexpr vkpp::AttachmentReference lDepthRef
{
1, vkpp::ImageLayout::eDepthStencilAttachmentOptimal
};
constexpr std::array<vkpp::SubpassDescription, 1> lSubpassDesc
{ {
{
vkpp::PipelineBindPoint::eGraphics,
0, nullptr,
1, lColorRef.AddressOf(),
nullptr,
lDepthRef.AddressOf()
}
} };
constexpr std::array<vkpp::SubpassDependency, 2> lSubpassDependencies
{{
{
vkpp::subpass::External, 0,
vkpp::PipelineStageFlagBits::eBottomOfPipe, vkpp::PipelineStageFlagBits::eColorAttachmentOutput,
vkpp::AccessFlagBits::eMemoryRead, vkpp::AccessFlagBits::eColorAttachmentWrite,
vkpp::DependencyFlagBits::eByRegion
},
{
0, vkpp::subpass::External,
vkpp::PipelineStageFlagBits::eColorAttachmentOutput, vkpp::PipelineStageFlagBits::eBottomOfPipe,
vkpp::AccessFlagBits::eColorAttachmentWrite, vkpp::AccessFlagBits::eMemoryRead,
vkpp::DependencyFlagBits::eByRegion
}
}};
const vkpp::RenderPassCreateInfo lRenderPassCreateInfo
{
lAttachementDescriptions,
lSubpassDesc,
lSubpassDependencies
};
mRenderPass = mLogicalDevice.CreateRenderPass(lRenderPassCreateInfo);
}
void MultiPipelines::CreateDepthResource(void)
{
const vkpp::ImageCreateInfo lImageCreateInfo
{
vkpp::ImageType::e2D,
vkpp::Format::eD32sFloatS8uInt,
mSwapchain.extent,
vkpp::ImageUsageFlagBits::eDepthStencilAttachment
};
vkpp::ImageViewCreateInfo lImageViewCreateInfo
{
vkpp::ImageViewType::e2D,
vkpp::Format::eD32sFloatS8uInt,
{
vkpp::ImageAspectFlagBits::eDepth | vkpp::ImageAspectFlagBits::eStencil,
0, 1,
0, 1
}
};
mDepthResource.Reset(lImageCreateInfo, lImageViewCreateInfo, vkpp::MemoryPropertyFlagBits::eDeviceLocal);
}
void MultiPipelines::CreateFramebuffer(void)
{
for (auto& lSwapchainRes : mSwapchain.buffers)
{
const std::array<vkpp::ImageView, 2> lAttachments
{
lSwapchainRes.view,
mDepthResource.view
};
const vkpp::FramebufferCreateInfo lFramebufferCreateInfo
{
mRenderPass,
lAttachments,
mSwapchain.extent.width,
mSwapchain.extent.height
};
mFramebuffers.emplace_back(mLogicalDevice.CreateFramebuffer(lFramebufferCreateInfo));
}
}
void MultiPipelines::CreateUniformBuffer(void)
{
// Prepare and initialize an uniform buffer block containing shader uniforms.
vkpp::BufferCreateInfo lBufferCreateInfo
{
sizeof(UniformBufferObject),
vkpp::BufferUsageFlagBits::eUniformBuffer
};
mUniformBufferResource.Reset(lBufferCreateInfo, vkpp::MemoryPropertyFlagBits::eHostVisible | vkpp::MemoryPropertyFlagBits::eHostCoherent);
}
void MultiPipelines::UpdateUniformBuffer(void)
{
const auto lWidth = mSwapchain.extent.width;
const auto lHeight = mSwapchain.extent.height;
const glm::vec3 lCameraPos;
const glm::vec3 lRotation{ -25.0f, 15.0f, 0.0f };
const auto lZoom = -15.5f;
mMVPMatrix.projection = glm::perspective(glm::radians(60.0f), static_cast<float>(lWidth / 3.0f) / static_cast<float>(lHeight), 0.1f, 256.0f);
const auto& viewMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, 0.0f, lZoom));
mMVPMatrix.modelView = viewMatrix * glm::translate(glm::mat4(), lCameraPos);
mMVPMatrix.modelView = glm::rotate(mMVPMatrix.modelView, glm::radians(lRotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
mMVPMatrix.modelView = glm::rotate(mMVPMatrix.modelView, glm::radians(lRotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
mMVPMatrix.modelView = glm::rotate(mMVPMatrix.modelView, glm::radians(lRotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
auto lMappedMemory = mLogicalDevice.MapMemory(mUniformBufferResource.memory, 0, sizeof(UniformBufferObject));
std::memcpy(lMappedMemory, &mMVPMatrix, sizeof(UniformBufferObject));
// Note: Since we requested a host coherent memory for the uniform buffer, the write is instantly visible to the GPU.
mLogicalDevice.UnmapMemory(mUniformBufferResource.memory);
}
void MultiPipelines::CreateSetLayout(void)
{
constexpr vkpp::DescriptorSetLayoutBinding lSetLayoutBinding
{
0, vkpp::DescriptorType::eUniformBuffer,
1, vkpp::ShaderStageFlagBits::eVertex
};
constexpr vkpp::DescriptorSetLayoutCreateInfo lSetLayoutCreateInfo
{
1, lSetLayoutBinding.AddressOf()
};
mSetLayout = mLogicalDevice.CreateDescriptorSetLayout(lSetLayoutCreateInfo);
}
void MultiPipelines::CreatePipelineLayout(void)
{
const vkpp::PipelineLayoutCreateInfo lLayoutCreateInfo
{
1, mSetLayout.AddressOf()
};
mPipelineLayout = mLogicalDevice.CreatePipelineLayout(lLayoutCreateInfo);
}
void MultiPipelines::CreateGraphicsPipelines(void)
{
std::array<vkpp::PipelineShaderStageCreateInfo, 2> lShaderStageCreateInfos
{{
{
vkpp::ShaderStageFlagBits::eVertex
},
{
vkpp::ShaderStageFlagBits::eFragment
}
} };
constexpr std::array<vkpp::VertexInputBindingDescription, 1> lVertexInputBindingDescriptions{ VertexData::GetBindingDescription() };
constexpr auto lVertexAttributeDescriptions = VertexData::GetAttributeDescriptions();
const vkpp::PipelineVertexInputStateCreateInfo lInputStateCreateInfo
{
lVertexInputBindingDescriptions,
lVertexAttributeDescriptions
};
constexpr vkpp::PipelineInputAssemblyStateCreateInfo lInputAssemblyStateCreateInfo
{
vkpp::PrimitiveTopology::eTriangleList
};
constexpr vkpp::PipelineViewportStateCreateInfo lViewportStateCreateInfo
{
1, 1
};
vkpp::PipelineRasterizationStateCreateInfo lRasterizationStateCreateInfo
{
DepthClamp::Disable, RasterizerDiscard::Disable,
vkpp::PolygonMode::eFill,
vkpp::CullModeFlagBits::eBack,
vkpp::FrontFace::eClockwise,
DepthBias::Disable,
0.0f, 0.0f, 0.0f,
1.0f
};
constexpr vkpp::PipelineMultisampleStateCreateInfo lMultisampleStateCreateInfo;
constexpr vkpp::PipelineDepthStencilStateCreateInfo lDepthStencilStateCreateInfo
{
DepthTest::Enable, DepthWrite::Enable,
vkpp::CompareOp::eLessOrEqual
};
constexpr vkpp::PipelineColorBlendAttachmentState lColorBlendAttachmentState;
const vkpp::PipelineColorBlendStateCreateInfo lColorBlendStateCreateInfo
{
1, lColorBlendAttachmentState.AddressOf()
};
constexpr std::array<vkpp::DynamicState, 3> lDynamicStates
{
vkpp::DynamicState::eViewport,
vkpp::DynamicState::eScissor,
vkpp::DynamicState::eLineWidth
};
const vkpp::PipelineDynamicStateCreateInfo lDynamicStateCreateInfo{ lDynamicStates };
vkpp::GraphicsPipelineCreateInfo lGraphicsPipelineCreateInfo
{
2, lShaderStageCreateInfos.data(),
lInputStateCreateInfo.AddressOf(),
lInputAssemblyStateCreateInfo.AddressOf(),
nullptr,
lViewportStateCreateInfo.AddressOf(),
lRasterizationStateCreateInfo.AddressOf(),
lMultisampleStateCreateInfo.AddressOf(),
lDepthStencilStateCreateInfo.AddressOf(),
lColorBlendStateCreateInfo.AddressOf(),
lDynamicStateCreateInfo.AddressOf(),
mPipelineLayout,
mRenderPass,
0
};
// Create the graphics pipeline state objects.
// This pipeline is used as the base for other pipelines (derivatives).
// Pipeline derivatives can be used for pipelines that shader most of their states.
// Depending on the implementation, this may result in better performance for pipeline switching and faster creation time.
lGraphicsPipelineCreateInfo.flags = vkpp::PipelineCreateFlagBits::eAllowDerivatives;
// Textured pipeline.
// Phong shading pipeline.
lShaderStageCreateInfos[0].module = CreateShaderModule("Shader/SPV/phong.vert.spv");
lShaderStageCreateInfos[1].module = CreateShaderModule("Shader/SPV/phong.frag.spv");
mPipelines.phong = mLogicalDevice.CreateGraphicsPipeline(lGraphicsPipelineCreateInfo);
mLogicalDevice.DestroyShaderModule(lShaderStageCreateInfos[0].module);
mLogicalDevice.DestroyShaderModule(lShaderStageCreateInfos[1].module);
// All pipelines created after the base pipeline will be derivatives.
lGraphicsPipelineCreateInfo.flags = vkpp::PipelineCreateFlagBits::eDerivative;
// Base pipeline will be out first created pipeline.
lGraphicsPipelineCreateInfo.basePipelineHandle = mPipelines.phong;
// It is only allowed to either use a handle or index for the base pipeline.
// As we use the handle, we must set the index to -1.
lGraphicsPipelineCreateInfo.basePipelineIndex = -1;
// Toon Shading pipeline.
lShaderStageCreateInfos[0].module = CreateShaderModule("Shader/SPV/toon.vert.spv");
lShaderStageCreateInfos[1].module = CreateShaderModule("Shader/SPV/toon.frag.spv");
mPipelines.toon = mLogicalDevice.CreateGraphicsPipeline(lGraphicsPipelineCreateInfo);
mLogicalDevice.DestroyShaderModule(lShaderStageCreateInfos[0].module);
mLogicalDevice.DestroyShaderModule(lShaderStageCreateInfos[1].module);
// Pipeline for wire frame rendering.
// Non-solid rendering is not a mandatory Vulkan feature.
if(mEnabledFeatures.fillModeNonSolid)
{
lRasterizationStateCreateInfo.polygonMode = PolygonMode::eLine;
lShaderStageCreateInfos[0].module = CreateShaderModule("Shader/SPV/wireframe.vert.spv");
lShaderStageCreateInfos[1].module = CreateShaderModule("Shader/SPV/wireframe.frag.spv");
mPipelines.wireframe = mLogicalDevice.CreateGraphicsPipeline(lGraphicsPipelineCreateInfo);
mLogicalDevice.DestroyShaderModule(lShaderStageCreateInfos[0].module);
mLogicalDevice.DestroyShaderModule(lShaderStageCreateInfos[1].module);
}
}
void MultiPipelines::CreateDescriptorPool(void)
{
constexpr vkpp::DescriptorPoolSize lPoolSize
{
vkpp::DescriptorType::eUniformBuffer,
1
};
constexpr vkpp::DescriptorPoolCreateInfo lPoolCreateInfo
{
1, lPoolSize.AddressOf(),
2
};
mDescriptorPool = mLogicalDevice.CreateDescriptorPool(lPoolCreateInfo);
}
void MultiPipelines::AllocateDescriptorSet(void)
{
const vkpp::DescriptorSetAllocateInfo lSetAllocateInfo
{
mDescriptorPool,
1, mSetLayout.AddressOf()
};
mDescriptorSet = mLogicalDevice.AllocateDescriptorSet(lSetAllocateInfo);
}
void MultiPipelines::UpdateDescriptorSet(void) const
{
const vkpp::DescriptorBufferInfo lDescriptorBufferInfo
{
mUniformBufferResource.buffer,
0,
sizeof(UniformBufferObject)
};
const vkpp::WriteDescriptorSetInfo lWriteDescriptorSetInfo
{
mDescriptorSet,
0,
vkpp::DescriptorType::eUniformBuffer,
lDescriptorBufferInfo
};
mLogicalDevice.UpdateDescriptorSet(lWriteDescriptorSetInfo);
}
vkpp::CommandBuffer MultiPipelines::BeginOneTimeCommandBuffer(void) const
{
const vkpp::CommandBufferAllocateInfo lCmdBufferAllocateInfo
{
mCmdPool,
1 // Command buffer count.
};
auto lCmdBuffer = mLogicalDevice.AllocateCommandBuffer(lCmdBufferAllocateInfo);
constexpr vkpp::CommandBufferBeginInfo lCmdBufferBeginInfo{ vkpp::CommandBufferUsageFlagBits::eOneTimeSubmit };
lCmdBuffer.Begin(lCmdBufferBeginInfo);
return lCmdBuffer;
}
void MultiPipelines::EndOneTimeCommandBuffer(const vkpp::CommandBuffer& aCmdBuffer) const
{
aCmdBuffer.End();
const vkpp::SubmitInfo lSubmitInfo{ aCmdBuffer };
// Create fence to ensure that the command buffer has finished executing.
constexpr vkpp::FenceCreateInfo lFenceCreateInfo;
const auto& lFence = mLogicalDevice.CreateFence(lFenceCreateInfo);
// Submit to the queue.
mGraphicsQueue.handle.Submit(lSubmitInfo, lFence);
// Wait for the fence to signal that command buffer has finished executing.
mLogicalDevice.WaitForFence(lFence);
mLogicalDevice.DestroyFence(lFence);
mLogicalDevice.FreeCommandBuffer(mCmdPool, aCmdBuffer);
}
void MultiPipelines::CopyBuffer(vkpp::Buffer& aDstBuffer, const Buffer& aSrcBuffer, DeviceSize aSize) const
{
const auto& lCmdBuffer = BeginOneTimeCommandBuffer();
const vkpp::BufferCopy lBufferCopy
{
0, 0,
aSize
};
lCmdBuffer.Copy(aDstBuffer, aSrcBuffer, lBufferCopy);
EndOneTimeCommandBuffer(lCmdBuffer);
}
void MultiPipelines::BuildCommandBuffers(void)
{
constexpr vkpp::CommandBufferBeginInfo lCmdBufferBeginInfo;
constexpr std::array<vkpp::ClearValue, 2> lClearValues
{ {
{ 0.129411f, 0.156862f, 0.188235f, 1.0f },
{ 1.0f, 0.0f }
} };
for (std::size_t lIndex = 0; lIndex < mCmdDrawBuffers.size(); ++lIndex)
{
vkpp::RenderPassBeginInfo lRenderPassBeginInfo
{
mRenderPass,
mFramebuffers[lIndex],
{
{0, 0},
mSwapchain.extent
},
lClearValues
};
const auto& lDrawCmdBuffer = mCmdDrawBuffers[lIndex];
lDrawCmdBuffer.Begin(lCmdBufferBeginInfo);
lDrawCmdBuffer.BeginRenderPass(lRenderPassBeginInfo);
lDrawCmdBuffer.BindVertexBuffer(mModel.vertices.buffer, 0);
lDrawCmdBuffer.BindIndexBuffer(mModel.indices.buffer, 0, vkpp::IndexType::eUInt32);
vkpp::Viewport lViewport
{
0.0f, 0.0f,
static_cast<float>(mSwapchain.extent.width), static_cast<float>(mSwapchain.extent.height)
};
lDrawCmdBuffer.SetViewport(lViewport);
const vkpp::Rect2D lScissor
{
{0, 0},
mSwapchain.extent
};
lDrawCmdBuffer.SetScissor(lScissor);
lDrawCmdBuffer.BindGraphicsDescriptorSet(mPipelineLayout, 0, mDescriptorSet);
// Left: Solid colored.
lViewport.width /= 3.0f;
lDrawCmdBuffer.SetViewport(lViewport);
lDrawCmdBuffer.BindGraphicsPipeline(mPipelines.phong);
lDrawCmdBuffer.DrawIndexed(mModel.indexCount);
// Center: Toon.
lViewport.x = lViewport.width;
lDrawCmdBuffer.SetViewport(lViewport);
lDrawCmdBuffer.BindGraphicsPipeline(mPipelines.toon);
// Line Width > 1.0f only if wide lines feature is supported.
if (mEnabledFeatures.wideLines)
lDrawCmdBuffer.SetLineWidth(2.0f);
lDrawCmdBuffer.DrawIndexed(mModel.indexCount);
// Right: Wireframe.
if (mEnabledFeatures.fillModeNonSolid)
{
lViewport.x = lViewport.width * 2;
lDrawCmdBuffer.SetViewport(lViewport);
lDrawCmdBuffer.BindGraphicsPipeline(mPipelines.wireframe);
lDrawCmdBuffer.DrawIndexed(mModel.indexCount);
}
lDrawCmdBuffer.EndRenderPass();
lDrawCmdBuffer.End();
}
}
void MultiPipelines::Update()
{
auto lIndex = mLogicalDevice.AcquireNextImage(mSwapchain.handle, mPresentCompleteSemaphore);
mLogicalDevice.WaitForFence(mWaitFences[lIndex]);
mLogicalDevice.ResetFence(mWaitFences[lIndex]);
constexpr vkpp::PipelineStageFlags lWaitDstStageMask{ vkpp::PipelineStageFlagBits::eColorAttachmentOutput };
const vkpp::SubmitInfo lSubmitInfo
{
1, mPresentCompleteSemaphore.AddressOf(), // Wait Semaphores.
&lWaitDstStageMask,
1, mCmdDrawBuffers[lIndex].AddressOf(),
1, mRenderCompleteSemaphore.AddressOf() // Signal Semaphores
};
mPresentQueue.handle.Submit(lSubmitInfo, mWaitFences[lIndex]);
const vkpp::khr::PresentInfo lPresentInfo
{
1, mRenderCompleteSemaphore.AddressOf(),
1, mSwapchain.handle.AddressOf(), &lIndex
};
mPresentQueue.handle.Present(lPresentInfo);
}
void MultiPipelines::CreateSemaphores(void)
{
constexpr vkpp::SemaphoreCreateInfo lSemaphoreCreateInfo;
// Semaphore used to ensure that image presentation is complete before starting to submit again.
mPresentCompleteSemaphore = mLogicalDevice.CreateSemaphore(lSemaphoreCreateInfo);
// Semaphore used to ensure that all commands submitted have been finished before submitting the image to the presentation queue.
mRenderCompleteSemaphore = mLogicalDevice.CreateSemaphore(lSemaphoreCreateInfo);
}
void MultiPipelines::CreateFences(void)
{
// Create in signaled state so we don't wait on the first render of each command buffer.
constexpr vkpp::FenceCreateInfo lFenceCreateInfo{ vkpp::FenceCreateFlagBits::eSignaled };
for (std::size_t lIndex = 0; lIndex < mCmdDrawBuffers.size(); ++lIndex)
mWaitFences.emplace_back(mLogicalDevice.CreateFence(lFenceCreateInfo));
}
Model::Model(const MultiPipelines& aMultiPipelineSample, const vkpp::LogicalDevice& aDevice, const vkpp::PhysicalDeviceMemoryProperties& aPhysicalDeviceMemProperties)
: multiPipelineSample(aMultiPipelineSample), device(aDevice), memProperties(aPhysicalDeviceMemProperties), vertices(aDevice, aPhysicalDeviceMemProperties), indices(aDevice, aPhysicalDeviceMemProperties)
{}
void Model::LoadMode(const std::string& aFilename, unsigned int aImporterFlags)
{
Assimp::Importer lImporter;
auto lpAIScene = lImporter.ReadFile(aFilename, aImporterFlags);
assert(lpAIScene != nullptr);
std::vector<float> lVertexBuffer;
std::vector<uint32_t> lIndexBuffer;
for (unsigned int lIndex = 0; lIndex < lpAIScene->mNumMeshes; ++lIndex)
{
const auto lpAIMesh = lpAIScene->mMeshes[lIndex];
modelParts.emplace_back(vertexCount, lpAIMesh->mNumVertices, indexCount, lpAIMesh->mNumFaces * 3);
vertexCount += lpAIScene->mMeshes[lIndex]->mNumVertices;
indexCount += lpAIScene->mMeshes[lIndex]->mNumFaces * 3;
aiColor3D lColor;
lpAIScene->mMaterials[lpAIMesh->mMaterialIndex]->Get(AI_MATKEY_COLOR_DIFFUSE, lColor);
const aiVector3D lZero3D;
for (unsigned int lVtxIndex = 0; lVtxIndex < lpAIMesh->mNumVertices; ++lVtxIndex)
{
// Vertex positions.
const auto lPos = lpAIMesh->mVertices[lVtxIndex];
lVertexBuffer.emplace_back(lPos.x);
lVertexBuffer.emplace_back(-lPos.y);
lVertexBuffer.emplace_back(lPos.z);
// Vertex normals.
const auto lNormal = lpAIMesh->mNormals[lVtxIndex];
lVertexBuffer.emplace_back(lNormal.x);
lVertexBuffer.emplace_back(-lNormal.y);
lVertexBuffer.emplace_back(lNormal.z);
// Vertex texture coordinates.
const auto lTexCoord = lpAIMesh->HasTextureCoords(0) ? lpAIMesh->mTextureCoords[0][lVtxIndex] : lZero3D;
lVertexBuffer.emplace_back(lTexCoord.x);
lVertexBuffer.emplace_back(lTexCoord.y);
// Vertex color.
lVertexBuffer.emplace_back(lColor.r);
lVertexBuffer.emplace_back(lColor.g);
lVertexBuffer.emplace_back(lColor.b);
dim.max.x = std::max(lPos.x, dim.max.x);
dim.max.y = std::max(lPos.x, dim.max.y);
dim.max.z = std::max(lPos.x, dim.max.z);
dim.min.x = std::min(lPos.x, dim.min.x);
dim.min.y = std::min(lPos.x, dim.min.y);
dim.min.z = std::min(lPos.x, dim.min.z);
}
dim.size = dim.max - dim.min;
auto lIndexBase = static_cast<uint32_t>(lIndexBuffer.size());
for (unsigned int lIdxIndex = 0; lIdxIndex < lpAIMesh->mNumFaces; ++lIdxIndex)
{
const auto& lFace = lpAIMesh->mFaces[lIdxIndex];
if (lFace.mNumIndices != 3)
continue;
lIndexBuffer.emplace_back(lIndexBase + lFace.mIndices[0]);
lIndexBuffer.emplace_back(lIndexBase + lFace.mIndices[1]);
lIndexBuffer.emplace_back(lIndexBase + lFace.mIndices[2]);
}
}
// Use Staging buffers to move vertex and index buffer to device local memory.
// Vertex Buffer.
auto lVtxBufferSize = static_cast<uint32_t>(lVertexBuffer.size()) * sizeof(float);
const vkpp::BufferCreateInfo lVtxStagingCreateInfo
{
lVtxBufferSize,
vkpp::BufferUsageFlagBits::eTransferSrc
};
BufferResource lStagingVtxBufferRes{ device, memProperties };
lStagingVtxBufferRes.Reset(lVtxStagingCreateInfo, vkpp::MemoryPropertyFlagBits::eHostVisible | vkpp::MemoryPropertyFlagBits::eHostCoherent);
auto lMappedMem = device.MapMemory(lStagingVtxBufferRes.memory, 0, lVtxBufferSize);
std::memcpy(lMappedMem, lVertexBuffer.data(), lVtxBufferSize);
device.UnmapMemory(lStagingVtxBufferRes.memory);
// Index Buffer.
auto lIdxBufferSize = static_cast<uint32_t>(lIndexBuffer.size()) * sizeof(uint32_t);
const vkpp::BufferCreateInfo lIdxStagingCreateInfo
{
lIdxBufferSize,
vkpp::BufferUsageFlagBits::eTransferSrc
};
BufferResource lStagingIdxBufferRes{ device, memProperties };
lStagingIdxBufferRes.Reset(lIdxStagingCreateInfo, vkpp::MemoryPropertyFlagBits::eHostVisible | vkpp::MemoryPropertyFlagBits::eHostCoherent);
lMappedMem = device.MapMemory(lStagingIdxBufferRes.memory, 0, lIdxBufferSize);
std::memcpy(lMappedMem, lIndexBuffer.data(), lIdxBufferSize);
device.UnmapMemory(lStagingIdxBufferRes.memory);
// Create device local target buffers.
// Vertex Buffer.
const vkpp::BufferCreateInfo lVtxCreateInfo
{
lVtxBufferSize,
vkpp::BufferUsageFlagBits::eVertexBuffer | vkpp::BufferUsageFlagBits::eTransferDst
};
vertices.Reset(lVtxCreateInfo, vkpp::MemoryPropertyFlagBits::eDeviceLocal);
// Index Buffer.
const vkpp::BufferCreateInfo lIdxCreateInfo
{
lIdxBufferSize,
vkpp::BufferUsageFlagBits::eIndexBuffer | vkpp::BufferUsageFlagBits::eTransferDst
};
indices.Reset(lIdxCreateInfo, vkpp::MemoryPropertyFlagBits::eDeviceLocal);
multiPipelineSample.CopyBuffer(vertices.buffer, lStagingVtxBufferRes.buffer, lVtxBufferSize);
multiPipelineSample.CopyBuffer(indices.buffer, lStagingIdxBufferRes.buffer, lIdxBufferSize);
}
} // End of namespace vkpp::sample. | 32.787589 | 206 | 0.70396 | po2xel |
87d4991530f3e0f2f835f9213fb87f8ac0f1af25 | 2,483 | cpp | C++ | RealSpace2/Samples/rs2testwf.cpp | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | RealSpace2/Samples/rs2testwf.cpp | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | RealSpace2/Samples/rs2testwf.cpp | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | #include <windows.h>
#include "MDebug.h"
#include "RealSpace2.h"
#include "RMaterialList.h"
#include "RRoam.h"
_USING_NAMESPACE_REALSPACE2
Landscape g_map;
const int size=1024;
unsigned char buffer[size*size+size*2];
RRESULT InitScene(void *param)
{
InitLog();
FILE *file=fopen("Height1024.raw","rb");
fread(buffer+size,size*size,1,file);
fclose(file);
// Copy the last row of the height map into the extra first row.
memcpy( buffer, buffer + size * size, size );
// Copy the first row of the height map into the extra last row.
memcpy( buffer + size * size + size, buffer + size, size );
g_map.Init(buffer);
RSetCamera(rvector(10,10,100),rvector(0,0,0),rvector(0,0,1));
RSetProjection(pi/3,0.1f,3000.f);
return R_OK;
}
RRESULT CloseScene(void *param)
{
g_map.Destroy();
return R_OK;
}
#define IsKeyDown(key) ((GetAsyncKeyState(key) & 0x8000)!=0)
#pragma comment(lib,"winmm.lib")
_NAMESPACE_REALSPACE2_BEGIN
extern float gClipAngle ;
_NAMESPACE_REALSPACE2_END
void Update()
{
static DWORD thistime,lasttime=timeGetTime(),elapsed;
thistime = timeGetTime();
elapsed = (thistime - lasttime)*(IsKeyDown(VK_SHIFT)?5:1);
lasttime = thistime;
static float rotatez=0.7f,rotatex=2.5f;
float fRotateStep=elapsed*0.001f;
float fMoveStep=elapsed*0.1f;
if(IsKeyDown(VK_LEFT)) rotatez-=fRotateStep;
if(IsKeyDown(VK_RIGHT)) rotatez+=fRotateStep;
if(IsKeyDown(VK_UP)) rotatex-=fRotateStep;
if(IsKeyDown(VK_DOWN)) rotatex+=fRotateStep;
rvector pos=RCameraPosition,dir=rvector(cosf(rotatez)*sinf(rotatex),sinf(rotatez)*sinf(rotatex),cosf(rotatex));
D3DXVec3Normalize(&dir,&dir);
rvector right;
D3DXVec3Cross(&right,&dir,&rvector(0,0,1));
D3DXVec3Normalize(&right,&right);
if(IsKeyDown('W')) pos+=fMoveStep*dir;
if(IsKeyDown('S')) pos-=fMoveStep*dir;
if(IsKeyDown('A')) pos+=fMoveStep*right;
if(IsKeyDown('D')) pos-=fMoveStep*right;
if(IsKeyDown(VK_SPACE)) pos+=fMoveStep*rvector(0,0,1);
gClipAngle +=2.1f;
gClipAngle=fmodf(gClipAngle,180);
rvector at=pos+dir;
//at.z=0;
RSetCamera(pos,at,rvector(0,0,1));
// mlog("%3.3f %3.3f\n",rotatex,rotatez);
}
RRESULT RenderScene(void *param)
{
Update();
g_map.Reset();
g_map.Tessellate();
g_map.Render();
return R_OK;
}
int PASCAL WinMain(HINSTANCE this_inst, HINSTANCE prev_inst, LPSTR cmdline, int cmdshow)
{
RSetFunction(RF_CREATE,InitScene);
RSetFunction(RF_RENDER,RenderScene);
RSetFunction(RF_DESTROY ,CloseScene);
return RMain("rs2test",this_inst,prev_inst,cmdline,cmdshow);
}
| 23.205607 | 112 | 0.730971 | WhyWolfie |
87d4acf297378085da459b640471a243fe6a2f92 | 1,178 | hpp | C++ | include/opengv/optimization_tools/objective_function_tools/Plane3P3DRegistrationFunctionInfo.hpp | mateus03/2018AMMPoseSolver | 787886846199cd0864c4e59a6545c40c3120010a | [
"BSD-3-Clause"
] | null | null | null | include/opengv/optimization_tools/objective_function_tools/Plane3P3DRegistrationFunctionInfo.hpp | mateus03/2018AMMPoseSolver | 787886846199cd0864c4e59a6545c40c3120010a | [
"BSD-3-Clause"
] | null | null | null | include/opengv/optimization_tools/objective_function_tools/Plane3P3DRegistrationFunctionInfo.hpp | mateus03/2018AMMPoseSolver | 787886846199cd0864c4e59a6545c40c3120010a | [
"BSD-3-Clause"
] | null | null | null | #ifndef PLANE3P3DREGISTRATIONFUNCTIONINFO_H
#define PLANE3P3DREGISTRATIONFUNCTIONINFO_H
#include <opengv/optimization_tools/objective_function_tools/ObjectiveFunctionInfo.hpp>
#include <opengv/registration/PlaneRegistrationAdapter.hpp>
#include <opengv/types.hpp>
#include <iostream>
class Plane3P3DRegistrationFunctionInfo : public ObjectiveFunctionInfo {
public:
Plane3P3DRegistrationFunctionInfo(const opengv::registration::PlaneRegistrationAdapter & adapter);
~Plane3P3DRegistrationFunctionInfo();
double objective_function_value(const opengv::rotation_t & rotation,
const opengv::translation_t & translation);
opengv::rotation_t rotation_gradient(const opengv::rotation_t & rotation,
const opengv::translation_t & translation);
opengv::translation_t translation_gradient(const opengv::rotation_t & rotation,
const opengv::translation_t & translation);
private:
Eigen::Matrix<double,3,3> Mt;
Eigen::Matrix<double,3,9> Mrt;
Eigen::Matrix<double,9,9> Mr;
Eigen::Matrix<double,1,1> pp;
Eigen::Matrix<double,9,1> vr;
Eigen::Matrix<double,3,1> vt;
size_t numPlanes;
double cP;
};
#endif
| 34.647059 | 100 | 0.760611 | mateus03 |
87d79b889f4a0561b15409ad00d9b4c124d107ab | 5,193 | cpp | C++ | nodes/VelocityEstimationNode_ConstAccUKF.cpp | RobertMilijas/uav_ros_general | d9ef09e2da4802891296a9410e5031675c09c066 | [
"BSD-3-Clause"
] | 1 | 2021-12-20T13:43:22.000Z | 2021-12-20T13:43:22.000Z | nodes/VelocityEstimationNode_ConstAccUKF.cpp | RobertMilijas/uav_ros_general | d9ef09e2da4802891296a9410e5031675c09c066 | [
"BSD-3-Clause"
] | 4 | 2020-12-21T15:15:13.000Z | 2021-06-16T10:40:29.000Z | nodes/VelocityEstimationNode_ConstAccUKF.cpp | RobertMilijas/uav_ros_general | d9ef09e2da4802891296a9410e5031675c09c066 | [
"BSD-3-Clause"
] | 2 | 2021-02-15T13:35:18.000Z | 2021-05-24T12:44:18.000Z | #include <boost/array.hpp>
#include <uav_ros_lib/estimation/constant_acceleration_ukf.hpp>
#include <geometry_msgs/PoseStamped.h>
#include <list>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
int main(int argc, char **argv) {
ros::init(argc, argv, "velocity_estimation_node");
ros::NodeHandle nhPrivate("~");
ros::NodeHandle nh;
ConstantAccelerationUKF kWrapperXPos("const_acc_x", nhPrivate);
ConstantAccelerationUKF kWrapperYPos("const_acc_y", nhPrivate);
ConstantAccelerationUKF kWrapperZPos("const_acc_z", nhPrivate);
geometry_msgs::PoseStamped poseMsg;
bool newMeasurementFlag = false;
const auto poseCb = [&](const geometry_msgs::PoseStampedConstPtr &msg) {
poseMsg = *msg;
newMeasurementFlag = true;
};
sensor_msgs::Imu myImuMsg;
sensor_msgs::Imu oldImuMsg;
const auto imuCb = [&](const sensor_msgs::ImuConstPtr &msg) {
// Only do acceleration correction when acceleration measurement changes
if (oldImuMsg.linear_acceleration.x != msg->linear_acceleration.x ||
oldImuMsg.linear_acceleration.y != msg->linear_acceleration.y ||
oldImuMsg.linear_acceleration.z != msg->linear_acceleration.z) {
myImuMsg = *msg;
auto quat = Eigen::Quaternionf(msg->orientation.w, msg->orientation.x,
msg->orientation.y, msg->orientation.z);
auto lin_acc = Eigen::Vector3f(msg->linear_acceleration.x,
msg->linear_acceleration.y,
msg->linear_acceleration.z);
auto correct_acc = quat * lin_acc;
myImuMsg.linear_acceleration.x = correct_acc.x();
myImuMsg.linear_acceleration.y = correct_acc.y();
myImuMsg.linear_acceleration.z = correct_acc.z();
}
oldImuMsg = *msg;
};
auto imuSub = nh.subscribe<sensor_msgs::Imu>("imu", 1, imuCb);
auto odomPub = nh.advertise<nav_msgs::Odometry>("odometry", 1);
auto imuPub = nh.advertise<sensor_msgs::Imu>("/imu_est", 1);
static constexpr auto dt = 0.02;
static constexpr auto throttle_time = 2.0;
const auto timerCb = [&](const ros::TimerEvent & /* unused */) {
kWrapperXPos.estimateState(
dt, {poseMsg.pose.position.x, myImuMsg.linear_acceleration.x},
newMeasurementFlag);
kWrapperYPos.estimateState(
dt, {poseMsg.pose.position.y, myImuMsg.linear_acceleration.y},
newMeasurementFlag);
kWrapperZPos.estimateState(
dt,
{poseMsg.pose.position.z, (myImuMsg.linear_acceleration.z - 9.80689)},
newMeasurementFlag);
nav_msgs::Odometry kalmanOdomMsg;
kalmanOdomMsg.header.stamp = poseMsg.header.stamp;
kalmanOdomMsg.header.frame_id = poseMsg.header.frame_id;
kalmanOdomMsg.pose.pose.position.x = kWrapperXPos.getState()[0];
kalmanOdomMsg.pose.pose.position.y = kWrapperYPos.getState()[0];
kalmanOdomMsg.pose.pose.position.z = kWrapperZPos.getState()[0];
kalmanOdomMsg.pose.pose.orientation = poseMsg.pose.orientation;
kalmanOdomMsg.twist.twist.linear.x = kWrapperXPos.getState()[1];
kalmanOdomMsg.twist.twist.linear.y = kWrapperYPos.getState()[1];
kalmanOdomMsg.twist.twist.linear.z = -kWrapperZPos.getState()[1];
kalmanOdomMsg.pose.covariance[0] = kWrapperXPos.getStateCovariance()(0, 0);
kalmanOdomMsg.pose.covariance[1] = kWrapperYPos.getStateCovariance()(0, 0);
kalmanOdomMsg.pose.covariance[2] = kWrapperZPos.getStateCovariance()(0, 0);
kalmanOdomMsg.pose.covariance[3] = kWrapperXPos.getStateCovariance()(1, 1);
kalmanOdomMsg.pose.covariance[4] = kWrapperYPos.getStateCovariance()(1, 1);
kalmanOdomMsg.pose.covariance[5] = kWrapperZPos.getStateCovariance()(1, 1);
kalmanOdomMsg.pose.covariance[6] = kWrapperXPos.getStateCovariance()(2, 2);
kalmanOdomMsg.pose.covariance[7] = kWrapperYPos.getStateCovariance()(2, 2);
kalmanOdomMsg.pose.covariance[8] = kWrapperZPos.getStateCovariance()(2, 2);
kalmanOdomMsg.pose.covariance[9] = kWrapperXPos._nis;
kalmanOdomMsg.pose.covariance[10] = kWrapperYPos._nis;
kalmanOdomMsg.pose.covariance[11] = kWrapperZPos._nis;
odomPub.publish(kalmanOdomMsg);
sensor_msgs::Imu estImuMsg;
estImuMsg.header.frame_id = myImuMsg.header.frame_id;
estImuMsg.header.stamp = myImuMsg.header.stamp;
estImuMsg.linear_acceleration.x = kWrapperXPos.getState()[2];
estImuMsg.linear_acceleration.y = kWrapperYPos.getState()[2];
estImuMsg.linear_acceleration.z = kWrapperZPos.getState()[2];
estImuMsg.angular_velocity.x = myImuMsg.linear_acceleration.x;
estImuMsg.angular_velocity.y = myImuMsg.linear_acceleration.y;
estImuMsg.angular_velocity.z = myImuMsg.linear_acceleration.z;
imuPub.publish(estImuMsg);
if (newMeasurementFlag) {
newMeasurementFlag = false;
}
};
auto poseSub =
nh.subscribe<geometry_msgs::PoseStamped>("poseStamped", 1, poseCb);
while (poseSub.getNumPublishers() == 0) {
ROS_WARN_STREAM("Waiting for " << poseSub.getTopic()
<< " topic publisher.");
ros::Duration(0.5).sleep();
}
ROS_INFO("Starting velocity_estimation_node...");
auto kalmanTimer = nh.createTimer(ros::Duration(dt), timerCb);
ros::spin();
} | 45.552632 | 79 | 0.706528 | RobertMilijas |
87dbdaefa11f64f8a235df3256b97dcb289d2165 | 9,678 | hh | C++ | src/mmutil_filter_row.hh | YPARK/mmutil | 21729fc50ac4cefff58c1b71e8c5740d2045b111 | [
"MIT"
] | null | null | null | src/mmutil_filter_row.hh | YPARK/mmutil | 21729fc50ac4cefff58c1b71e8c5740d2045b111 | [
"MIT"
] | null | null | null | src/mmutil_filter_row.hh | YPARK/mmutil | 21729fc50ac4cefff58c1b71e8c5740d2045b111 | [
"MIT"
] | null | null | null | #include <getopt.h>
#include "mmutil.hh"
#include "mmutil_io.hh"
#include "mmutil_stat.hh"
#include "mmutil_score.hh"
#ifndef MMUTIL_FILTER_ROW_HH_
#define MMUTIL_FILTER_ROW_HH_
template <typename OPTIONS>
int filter_row_by_score(OPTIONS &options);
struct filter_row_options_t {
typedef enum { NNZ, MEAN, CV, SD } row_score_t;
const std::vector<std::string> SCORE_NAMES;
explicit filter_row_options_t()
: SCORE_NAMES { "NNZ", "MEAN", "CV", "SD" }
{
mtx_file = "";
row_file = "";
col_file = "";
output = "output";
Ntop = 0;
cutoff = 0;
COL_NNZ_CUTOFF = 0;
row_score = NNZ;
}
Index Ntop;
Scalar cutoff;
Index COL_NNZ_CUTOFF;
row_score_t row_score;
std::string mtx_file;
std::string row_file;
std::string col_file;
std::string output;
void set_row_score(const std::string _score)
{
for (int j = 0; j < SCORE_NAMES.size(); ++j) {
if (SCORE_NAMES.at(j) == _score) {
row_score = static_cast<row_score_t>(j);
break;
}
}
}
};
struct select_cv_t {
inline Vec operator()(Vec &mu, Vec &sig, Vec &cv, Vec &nnz) { return cv; }
};
struct select_mean_t {
inline Vec operator()(Vec &mu, Vec &sig, Vec &cv, Vec &nnz) { return mu; }
};
struct select_sd_t {
inline Vec operator()(Vec &mu, Vec &sig, Vec &cv, Vec &nnz) { return sig; }
};
struct select_nnz_t {
inline Vec operator()(Vec &mu, Vec &sig, Vec &cv, Vec &nnz) { return nnz; }
};
/**
* @param select_row_score
* @param options
* @return temp_mtx_file
*/
template <typename FUN, typename OPTIONS>
std::string
_filter_row_by_score(FUN select_row_score, OPTIONS &options)
{
using namespace mmutil::io;
std::vector<std::string> rows;
CHECK(read_vector_file(options.row_file, rows));
Vec mu, sig, cv;
Index max_row, max_col;
std::vector<Index> Nvec;
std::tie(mu, sig, cv, Nvec, max_row, max_col) =
compute_mtx_row_stat(options.mtx_file);
Vec nvec = eigen_vector_<Index, Scalar>(Nvec);
Vec row_scores = select_row_score(mu, sig, cv, nvec);
using copier_t =
triplet_copier_remapped_rows_t<obgzf_stream, Index, Scalar>;
using index_map_t = copier_t::index_map_t;
const Index nmax =
(options.Ntop > 0) ? std::min(options.Ntop, max_row) : max_row;
auto order = eigen_argsort_descending(row_scores);
TLOG("row scores: " << row_scores(order.at(0)) << " ~ "
<< row_scores(order.at(order.size() - 1)));
std::vector<std::string> out_rows;
out_rows.reserve(nmax);
Index NNZ = 0;
Index Nrow = 0;
index_map_t remap;
for (Index i = 0; i < nmax; ++i) {
const Index j = order.at(i);
const Scalar s = row_scores(j);
if (s < options.cutoff)
break;
out_rows.emplace_back(rows.at(j));
NNZ += Nvec.at(j);
remap[j] = i;
Nrow++;
}
TLOG("Filter in " << Nrow << " rows with " << NNZ << " elements");
if (NNZ < 1)
ELOG("Found no element to write out");
std::string temp_mtx_file = options.output + "_temp.mtx.gz";
std::string output_row_file = options.output + ".rows.gz";
if (file_exists(temp_mtx_file)) {
WLOG("Delete this pre-existing temporary file: " << temp_mtx_file);
std::remove(temp_mtx_file.c_str());
}
copier_t copier(temp_mtx_file, remap, NNZ);
visit_matrix_market_file(options.mtx_file, copier);
write_vector_file(output_row_file, out_rows);
return temp_mtx_file;
}
/**
* @param mtx_temp_file
* @param options
*/
template <typename OPTIONS>
int
squeeze_columns(const std::string mtx_temp_file, OPTIONS &options)
{
using namespace mmutil::io;
std::vector<std::string> cols;
CHECK(read_vector_file(options.col_file, cols));
using copier_t =
triplet_copier_remapped_cols_t<obgzf_stream, Index, Scalar>;
using index_map_t = copier_t::index_map_t;
Index max_row, max_col;
std::vector<Index> nnz_col;
std::tie(std::ignore, std::ignore, std::ignore, nnz_col, max_row, max_col) =
compute_mtx_col_stat(mtx_temp_file);
index_map_t remap;
Index Ncol = 0;
Index NNZ = 0;
std::vector<std::string> out_cols;
for (Index i = 0; i < max_col; ++i) {
const Scalar nnz = nnz_col.at(i);
if (nnz > options.COL_NNZ_CUTOFF) {
remap[i] = Ncol;
out_cols.emplace_back(cols.at(i));
++Ncol;
NNZ += nnz_col.at(i);
}
}
TLOG("Found " << Ncol << " columns with the nnz > "
<< options.COL_NNZ_CUTOFF << " from the total " << max_col
<< " columns");
ERR_RET(NNZ < 1, "Found no element to write out");
std::string output_mtx_file = options.output + ".mtx.gz";
copier_t copier(output_mtx_file, remap, NNZ);
visit_matrix_market_file(mtx_temp_file, copier);
if (file_exists(mtx_temp_file)) {
std::remove(mtx_temp_file.c_str());
}
std::string output_col_file = options.output + ".cols.gz";
write_vector_file(output_col_file, out_cols);
return EXIT_SUCCESS;
}
template <typename OPTIONS>
int
filter_row_by_score(OPTIONS &options)
{
std::string mtx_temp_file;
switch (options.row_score) {
case filter_row_options_t::NNZ:
mtx_temp_file = _filter_row_by_score(select_nnz_t {}, options);
break;
case filter_row_options_t::MEAN:
mtx_temp_file = _filter_row_by_score(select_mean_t {}, options);
break;
case filter_row_options_t::SD:
mtx_temp_file = _filter_row_by_score(select_sd_t {}, options);
break;
case filter_row_options_t::CV:
mtx_temp_file = _filter_row_by_score(select_cv_t {}, options);
break;
default:
break;
}
return squeeze_columns(mtx_temp_file, options);
}
template <typename OPTIONS>
int
parse_filter_row_options(const int argc, //
const char *argv[], //
OPTIONS &options)
{
const char *_usage =
"\n"
"[Arguments]\n"
"--mtx (-m) : data MTX file (M x N)\n"
"--data (-m) : data MTX file (M x N)\n"
"--row (-f) : row file (M x 1)\n"
"--feature (-f) : row file (M x 1)\n"
"--col (-c) : data column file (N x 1)\n"
"--out (-o) : Output file header\n"
"\n"
"[Options]\n"
"\n"
"--score (-S) : a type of row scores {NNZ, MEAN, CV}\n"
"--ntop (-t) : number of top features\n"
"--cutoff (-k) : cutoff of row-wise scores\n"
"--col_cutoff (-C) : column's #non-zero cutoff\n"
"\n"
"[Output]\n"
"${out}.mtx.gz, ${out}.rows.gz, ${out}.cols.gz\n"
"\n";
const char *const short_opts = "m:c:f:o:t:k:C:S:";
const option long_opts[] = {
{ "mtx", required_argument, nullptr, 'm' }, //
{ "data", required_argument, nullptr, 'm' }, //
{ "feature", required_argument, nullptr, 'f' }, //
{ "row", required_argument, nullptr, 'f' }, //
{ "col", required_argument, nullptr, 'c' }, //
{ "out", required_argument, nullptr, 'o' }, //
{ "output", required_argument, nullptr, 'o' }, //
{ "ntop", required_argument, nullptr, 't' }, //
{ "Ntop", required_argument, nullptr, 't' }, //
{ "nTop", required_argument, nullptr, 't' }, //
{ "cutoff", required_argument, nullptr, 'k' }, //
{ "Cutoff", required_argument, nullptr, 'k' }, //
{ "col_cutoff", required_argument, nullptr, 'C' }, //
{ "col_nnz_cutoff", required_argument, nullptr, 'C' }, //
{ "score", required_argument, nullptr, 'S' }, //
{ nullptr, no_argument, nullptr, 0 }
};
while (true) {
const auto opt = getopt_long(argc, //
const_cast<char **>(argv), //
short_opts, //
long_opts, //
nullptr);
if (-1 == opt)
break;
switch (opt) {
case 'm':
options.mtx_file = std::string(optarg);
break;
case 'f':
options.row_file = std::string(optarg);
break;
case 'c':
options.col_file = std::string(optarg);
break;
case 'o':
options.output = std::string(optarg);
break;
case 'S':
options.set_row_score(std::string(optarg));
break;
case 't':
options.Ntop = std::stoi(optarg);
break;
case 'k':
options.cutoff = std::stof(optarg);
break;
case 'C':
options.COL_NNZ_CUTOFF = std::stoi(optarg);
break;
case 'h': // -h or --help
case '?': // Unrecognized option
std::cerr << _usage << std::endl;
return EXIT_FAILURE;
default: //
;
}
}
ERR_RET(!file_exists(options.mtx_file), "No MTX data file");
ERR_RET(!file_exists(options.col_file), "No COL data file");
ERR_RET(!file_exists(options.row_file), "No ROW data file");
ERR_RET(options.Ntop <= 0 && options.cutoff <= 0,
"Must have positive Ntop or cutoff value");
return EXIT_SUCCESS;
}
#endif
| 27.971098 | 80 | 0.553007 | YPARK |
87df44c7848b0548eda13ec89b3c9bb17ae09b19 | 690 | hpp | C++ | src/PeriTypes/Sensor.hpp | nemo9955/RemPeripherals | b1c97f209965ed0dd4cebfe5dbfc3298bf8e5860 | [
"Apache-2.0"
] | null | null | null | src/PeriTypes/Sensor.hpp | nemo9955/RemPeripherals | b1c97f209965ed0dd4cebfe5dbfc3298bf8e5860 | [
"Apache-2.0"
] | null | null | null | src/PeriTypes/Sensor.hpp | nemo9955/RemPeripherals | b1c97f209965ed0dd4cebfe5dbfc3298bf8e5860 | [
"Apache-2.0"
] | null | null | null | #ifndef SENSOR_HPP
#define SENSOR_HPP
#include <stdint.h>
#include "SimpleList.h"
#include "SensorReading.hpp"
class Sensor
{
public:
Sensor()
{
sensorsList.push_back(this);
};
virtual uint32_t get_peri_uuid() = 0;
virtual const char *get_sensor_name() const = 0;
virtual int read_values() = 0;
virtual int reading_interval() = 0;
virtual void reset_interval() { cooldown_time = millis() + reading_interval(); };
virtual bool ready_to_read() { return millis() >= cooldown_time; };
virtual SensorReading **get_readings() = 0;
static SimpleList<Sensor *> sensorsList;
private:
uint32_t cooldown_time;
protected:
};
#endif | 20.294118 | 85 | 0.675362 | nemo9955 |
87e331558166674138bd74c4bbfc5ac03acb220d | 758 | cpp | C++ | relacy/dyn_thread.cpp | pereckerdal/relacy | 05d8a8fbb0b3600ff5bf34da0bab2bb148dff059 | [
"BSD-3-Clause"
] | 1 | 2020-05-30T13:06:12.000Z | 2020-05-30T13:06:12.000Z | relacy/dyn_thread.cpp | pereckerdal/relacy | 05d8a8fbb0b3600ff5bf34da0bab2bb148dff059 | [
"BSD-3-Clause"
] | null | null | null | relacy/dyn_thread.cpp | pereckerdal/relacy | 05d8a8fbb0b3600ff5bf34da0bab2bb148dff059 | [
"BSD-3-Clause"
] | null | null | null | /* Relacy Race Detector
* Copyright (c) 2008-2013, Dmitry S. Vyukov
* All rights reserved.
* This software is provided AS-IS with no warranty, either express or implied.
* This software is distributed under a license and may not be copied,
* modified or distributed except as expressly authorized under the
* terms of the license contained in the file LICENSE in this distribution.
*/
#include "dyn_thread.hpp"
#include "context_base.hpp"
namespace rl
{
dyn_thread::dyn_thread()
{
handle_ = 0;
}
void dyn_thread::start(void*(*fn)(void*), void* arg)
{
RL_VERIFY(handle_ == 0);
handle_ = ctx().create_thread(fn, arg);
}
void dyn_thread::join()
{
RL_VERIFY(handle_);
handle_->wait(false, false, $);
handle_ = 0;
}
}
| 21.055556 | 80 | 0.691293 | pereckerdal |
87e46074782715fbcf6ee032cd28ab6c633b4cb2 | 341 | cpp | C++ | src/Main.cpp | SMelanko/BattleCity | 7d0042561f97ee9d1b61e027b1dd451494eaefee | [
"MIT"
] | null | null | null | src/Main.cpp | SMelanko/BattleCity | 7d0042561f97ee9d1b61e027b1dd451494eaefee | [
"MIT"
] | null | null | null | src/Main.cpp | SMelanko/BattleCity | 7d0042561f97ee9d1b61e027b1dd451494eaefee | [
"MIT"
] | null | null | null | #include "include/Game.h"
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
try {
return Game{ argc, argv }.exec();
} catch (const std::exception& e) {
qDebug() << e.what();
} catch (...) {
qDebug() << QStringLiteral("Unhandled exception has been occurred");
}
}
| 20.058824 | 70 | 0.656891 | SMelanko |
87e6e92b2418a88e84995b5f494038971eb851d8 | 1,201 | cpp | C++ | src/0844/0844-Backspace-String-Compare-UnitTest.cpp | coldnew/leetcode-solutions | 3bc7943f8341397840ecd34aefc5af6e52b09b4e | [
"Unlicense"
] | 2 | 2022-03-10T17:06:18.000Z | 2022-03-11T08:52:00.000Z | src/0844/0844-Backspace-String-Compare-UnitTest.cpp | coldnew/leetcode-solutions | 3bc7943f8341397840ecd34aefc5af6e52b09b4e | [
"Unlicense"
] | null | null | null | src/0844/0844-Backspace-String-Compare-UnitTest.cpp | coldnew/leetcode-solutions | 3bc7943f8341397840ecd34aefc5af6e52b09b4e | [
"Unlicense"
] | null | null | null | #include "0844-Backspace-String-Compare.cpp"
#include <gtest/gtest.h>
#define LEETCODE_TEST(SolutionX) \
TEST(BackspaceStringCompareTest, SolutionX##_01) { \
SolutionX solution; \
std::string s = "ab#c"; \
std::string t = "ad#c"; \
EXPECT_TRUE(solution.backspaceCompare(s, t)); \
} \
\
TEST(BackspaceStringCompareTest, SolutionX##_02) { \
SolutionX solution; \
std::string s = "ab##"; \
std::string t = "c#d#"; \
EXPECT_TRUE(solution.backspaceCompare(s, t)); \
} \
\
TEST(BackspaceStringCompareTest, SolutionX##_03) { \
SolutionX solution; \
std::string s = "a#c"; \
std::string t = "b"; \
EXPECT_FALSE(solution.backspaceCompare(s, t)); \
}
LEETCODE_TEST(Solution1)
| 44.481481 | 54 | 0.38801 | coldnew |
87e78c9c01ef814c78bb1b960e17f9b5ea84f227 | 6,971 | hpp | C++ | system/GlobalAllocator.hpp | EvilMcJerkface/grappa | 69f2f3674d6f8e512e0bf55264bb75b972fd82de | [
"BSD-3-Clause"
] | 144 | 2015-01-16T01:53:24.000Z | 2022-02-27T21:59:09.000Z | system/GlobalAllocator.hpp | EvilMcJerkface/grappa | 69f2f3674d6f8e512e0bf55264bb75b972fd82de | [
"BSD-3-Clause"
] | 79 | 2015-01-01T00:32:30.000Z | 2021-07-06T12:26:08.000Z | system/GlobalAllocator.hpp | EvilMcJerkface/grappa | 69f2f3674d6f8e512e0bf55264bb75b972fd82de | [
"BSD-3-Clause"
] | 53 | 2015-02-02T17:55:46.000Z | 2022-03-08T09:35:16.000Z | ////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2015, University of Washington and Battelle
// Memorial Institute. 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 University of Washington, Battelle
// Memorial Institute, or the names of their contributors may be
// used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// UNIVERSITY OF WASHINGTON OR BATTELLE MEMORIAL INSTITUTE BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
////////////////////////////////////////////////////////////////////////
#ifndef __GLOBAL_ALLOCATOR_HPP__
#define __GLOBAL_ALLOCATOR_HPP__
#include <iostream>
#include <glog/logging.h>
#include <boost/scoped_ptr.hpp>
#include "Allocator.hpp"
#include "DelegateBase.hpp"
class GlobalAllocator;
extern GlobalAllocator * global_allocator;
/// Global memory allocator
class GlobalAllocator {
private:
boost::scoped_ptr< Allocator > a_p_;
/// allocate some number of bytes from local heap
/// (should be called only on node responsible for allocator)
GlobalAddress< void > local_malloc( size_t size ) {
intptr_t address = reinterpret_cast< intptr_t >( a_p_->malloc( size ) );
GlobalAddress< void > ga = GlobalAddress< void >::Raw( address );
return ga;
}
// // allocate some number of some type
// template< typename T >
// GlobalAddress< T > local_malloc( size_t count ) {
// intptr_t address = reinterpret_cast< intptr_t >( a->malloc( sizeof( T ) * count ) );
// GlobalAddress< T > ga = GlobalAddress< T >::Raw( address );
// return ga;
// }
// release data at pointer in local heap
/// (should be called only on node responsible for allocator)
void local_free( GlobalAddress< void > address ) {
void * va = reinterpret_cast< void * >( address.raw_bits() );
a_p_->free( va );
}
public:
/// Construct global allocator. Allocates no storage, just controls
/// ownership of memory region.
/// @param base base address of region to allocate from
/// @param size number of bytes available for allocation
GlobalAllocator( GlobalAddress< void > base, size_t size )
: a_p_( 0 == Grappa::mycore() // node 0 does all allocation for now
? new Allocator( base, size )
: NULL )
{
// TODO: this won't work with pools....
assert( !global_allocator );
global_allocator = this;
}
//
// basic operations
//
/// delegate malloc
static GlobalAddress< void > remote_malloc( size_t size_bytes ) {
// ask node 0 to allocate memory
auto allocated_address = Grappa::impl::call( 0, [size_bytes] {
DVLOG(5) << "got malloc request for size " << size_bytes;
GlobalAddress< void > a = global_allocator->local_malloc( size_bytes );
DVLOG(5) << "malloc returning pointer " << a.pointer();
return a;
});
return allocated_address;
}
/// delegate free
/// TODO: should free block?
static void remote_free( GlobalAddress< void > address ) {
// ask node 0 to free memory
auto allocated_address = Grappa::impl::call( 0, [address] {
DVLOG(5) << "got free request for descriptor " << address;
global_allocator->local_free( address );
return true;
});
}
//
// debugging
//
/// human-readable allocator state (not to be called directly---called by 'operator<<' overload)
std::ostream& dump( std::ostream& o ) const {
if( a_p_ ) {
return o << "{GlobalAllocator: " << *a_p_ << "}";
} else {
return o << "{delegated GlobalAllocator}";
}
}
/// Number of bytes available for allocation;
size_t total_bytes() const { return a_p_->total_bytes(); }
/// Number of bytes allocated
size_t total_bytes_in_use() const { return a_p_->total_bytes_in_use(); }
};
std::ostream& operator<<( std::ostream& o, const GlobalAllocator& a );
/// @addtogroup Memory
/// @{
namespace Grappa {
/// Allocate bytes from the global shared heap.
template< typename T = int8_t >
GlobalAddress<T> global_alloc(size_t count) {
CHECK_GT(count, 0) << "allocation must be greater than 0";
return static_cast<GlobalAddress<T>>(GlobalAllocator::remote_malloc(sizeof(T)*count));
}
/// Free memory allocated from global shared heap.
template< typename T >
void global_free(GlobalAddress<T> address) {
GlobalAllocator::remote_free(static_cast<GlobalAddress<void>>(address));
}
/// Allocate space for a T at the same localizable global address on all cores
/// (must currently round up to a multiple of block_size plus an additional block
/// to ensure there is a valid address range no matter which core allocation starts on).
template< typename T, Core MASTER_CORE = 0 >
GlobalAddress<T> symmetric_global_alloc() {
static_assert(sizeof(T) % block_size == 0,
"must pad global proxy to multiple of block_size, or use GRAPPA_BLOCK_ALIGNED");
// allocate enough space that we are guaranteed to get one on each core at same location
auto qac = global_alloc<char>(cores()*(sizeof(T)+block_size));
while (qac.core() != MASTER_CORE) qac++;
auto qa = static_cast<GlobalAddress<T>>(qac);
CHECK_EQ(qa, qa.block_min());
CHECK_EQ(qa.core(), MASTER_CORE);
return qa;
}
} // namespace Grappa
/// Use this macro to allocate space for a variable at the same
/// address on all cores.
///
/// NOTE: the variable declared will be zero-initialized on all
/// cores. Assiging a nonzero initial value is not guaranteed to work;
/// constructors are not guaranteed to run. You should initialize the
/// variable yourself the first time you use it, or with an
/// on_all_cores().
#define symmetric_static static
/// @}
#endif
| 35.93299 | 98 | 0.682972 | EvilMcJerkface |
87e7b9dffaa130bdb830863c5ca11e02d1e1fb36 | 5,176 | cpp | C++ | src/viplist.cpp | Nakeib/RonClient | 9e816c580ec2a6f1b15fdefd8e15ad62647ca29f | [
"MIT"
] | 11 | 2020-11-07T19:35:24.000Z | 2021-08-19T12:25:27.000Z | src/viplist.cpp | Nakeib/RonClient | 9e816c580ec2a6f1b15fdefd8e15ad62647ca29f | [
"MIT"
] | null | null | null | src/viplist.cpp | Nakeib/RonClient | 9e816c580ec2a6f1b15fdefd8e15ad62647ca29f | [
"MIT"
] | 5 | 2020-11-06T20:52:11.000Z | 2021-02-25T11:02:31.000Z | /* -------------------------------------------------------------------------- */
/* ------------- RonClient --- Oficial client for RonOTS servers ------------ */
/* -------------------------------------------------------------------------- */
#include "viplist.h"
#include "allocator.h"
#include "creature.h"
#include "window.h"
#include "tools.h"
// ---- VIPList ---- //
VIPList::VIPList() {
container = NULL;
}
VIPList::~VIPList() { }
void VIPList::AddCreature(unsigned int creatureID, std::string creatureName, bool online) {
LOCKCLASS lockClass(lockVIPList);
if (online) {
std::map<unsigned int, std::string>::iterator it = viplist_online.find(creatureID);
if (it == viplist_online.end())
viplist_online[creatureID] = creatureName;
}
else {
std::map<unsigned int, std::string>::iterator it = viplist_offline.find(creatureID);
if (it == viplist_offline.end())
viplist_offline[creatureID] = creatureName;
}
}
void VIPList::LoginCreature(unsigned int creatureID) {
LOCKCLASS lockClass(lockVIPList);
std::map<unsigned int, std::string>::iterator it = viplist_offline.find(creatureID);
if (it != viplist_offline.end()) {
AddCreature(it->first, it->second, true);
viplist_offline.erase(it);
}
}
void VIPList::LogoutCreature(unsigned int creatureID) {
LOCKCLASS lockClass(lockVIPList);
std::map<unsigned int, std::string>::iterator it = viplist_online.find(creatureID);
if (it != viplist_online.end()) {
AddCreature(it->first, it->second, false);
viplist_online.erase(it);
}
}
void VIPList::RemoveCreature(unsigned int creatureID) {
LOCKCLASS lockClass(lockVIPList);
std::map<unsigned int, std::string>::iterator it = viplist_offline.find(creatureID);
if (it != viplist_offline.end())
viplist_offline.erase(it);
it = viplist_online.find(creatureID);
if (it != viplist_online.end())
viplist_online.erase(it);
}
void VIPList::ClearVIPList() {
LOCKCLASS lockClass(lockVIPList);
viplist_offline.clear();
viplist_online.clear();
}
unsigned int VIPList::GetCreatureID(std::string creatureName) {
LOCKCLASS lockClass(lockVIPList);
std::map<unsigned int, std::string>::iterator it = viplist_offline.begin();
for (it; it != viplist_offline.end(); it++) {
if (it->second == creatureName)
return it->first;
}
it = viplist_online.begin();
for (it; it != viplist_online.end(); it++) {
if (it->second == creatureName)
return it->first;
}
return 0;
}
std::string VIPList::GetCreatureName(unsigned int creatureID) {
LOCKCLASS lockClass(lockVIPList);
std::map<unsigned int, std::string>::iterator it = viplist_offline.find(creatureID);
if (it != viplist_offline.end())
return it->second;
it = viplist_online.find(creatureID);
if (it != viplist_online.end())
return it->second;
return "";
}
void VIPList::SetContainer(WindowElementContainer* container) {
LOCKCLASS lockClass(lockVIPList);
this->container = container;
}
void VIPList::UpdateContainer() {
LOCKCLASS lockClass1(Windows::lockWindows);
LOCKCLASS lockClass2(lockVIPList);
if (!container)
return;
container->DeleteAllElements();
Window* window = container->GetWindow();
window->SetActiveElement(NULL);
POINT size = window->GetSize(true);
WindowElementVIP* vip = new(M_PLACE) WindowElementVIP;
vip->Create(0, 0, 0, 0xFFFF, 0xFFFF, false, false, window->GetWindowTemplate());
vip->SetVIPList(this);
vip->SetCreatureID(0x00);
window->AddElement(vip);
std::map<std::string, unsigned int> s_online;
std::map<std::string, unsigned int> s_offline;
std::map<unsigned int, std::string>::iterator _it = viplist_online.begin();
for (_it; _it != viplist_online.end(); _it++)
s_online[_it->second] = _it->first;
_it = viplist_offline.begin();
for (_it; _it != viplist_offline.end(); _it++)
s_offline[_it->second] = _it->first;
int posY = 0;
std::map<std::string, unsigned int>::iterator it = s_online.begin();
for (it; it != s_online.end(); it++) {
std::string creatureName = it->first;
unsigned int creatureID = it->second;
WindowElementText* text = new(M_PLACE) WindowElementText;
text->Create(0, 5, posY, 0xFFFF, window->GetWindowTemplate());
text->SetText(creatureName);
text->SetColor(0.0f, 1.0f, 0.0f);
text->SetBorder(1);
posY += 15;
WindowElementVIP* vip = new(M_PLACE) WindowElementVIP;
vip->Create(0, 0, posY - 15, 0xFFFF, 15, false, false, window->GetWindowTemplate());
vip->SetVIPList(this);
vip->SetCreatureID(creatureID);
container->AddElement(text);
container->AddElement(vip);
}
it = s_offline.begin();
for (it; it != s_offline.end(); it++) {
std::string creatureName = it->first;
unsigned int creatureID = it->second;
WindowElementText* text = new(M_PLACE) WindowElementText;
text->Create(0, 5, posY, 0xFFFF, window->GetWindowTemplate());
text->SetText(creatureName);
text->SetColor(0.8f, 0.0f, 0.0f);
text->SetBorder(1);
posY += 15;
WindowElementVIP* vip = new(M_PLACE) WindowElementVIP;
vip->Create(0, 0, posY - 15, 0xFFFF, 15, false, false, window->GetWindowTemplate());
vip->SetVIPList(this);
vip->SetCreatureID(creatureID);
container->AddElement(text);
container->AddElement(vip);
}
container->SetIntSize(0, posY);
}
| 27.386243 | 91 | 0.680255 | Nakeib |
87e7be107549467a30f19389059476637237fe6f | 4,317 | cc | C++ | caffe2/operators/summarize_op_hipdev.cc | ashishfarmer/rocm-caffe2 | 097fe3f71b0e4311340ff7eb797ed6c351073d54 | [
"Apache-2.0"
] | 12 | 2018-04-14T22:00:51.000Z | 2018-07-26T16:44:20.000Z | caffe2/operators/summarize_op_hipdev.cc | ashishfarmer/rocm-caffe2 | 097fe3f71b0e4311340ff7eb797ed6c351073d54 | [
"Apache-2.0"
] | 27 | 2018-04-14T06:44:22.000Z | 2018-08-01T18:02:39.000Z | caffe2/operators/summarize_op_hipdev.cc | ashishfarmer/rocm-caffe2 | 097fe3f71b0e4311340ff7eb797ed6c351073d54 | [
"Apache-2.0"
] | 2 | 2018-04-16T20:46:16.000Z | 2018-06-01T21:00:10.000Z | /**
* Copyright (c) 2016-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/device_vector.h>
#include <thrust/transform_reduce.h>
#include <thrust/system/cuda/execution_policy.h>
#include "caffe2/operators/summarize_op.h"
#include "caffe2/core/context_hip.h"
namespace caffe2 {
namespace {
// structure used to accumulate the moments and other statistical properties
// encountered so far.
template <typename T>
struct SummaryStatsData
{
T n;
T min;
T max;
T mean;
T M2;
// initialize to the identity element
void initialize()
{
n = mean = M2 = 0;
min = std::numeric_limits<T>::max();
max = std::numeric_limits<T>::min();
}
T variance() { return (n == 1 ? 0 : M2 / (n - 1)); }
};
// stats_unary_op is a functor that takes in a value x and
// returns a variace_data whose mean value is initialized to x.
template <typename T>
struct summary_stats_unary_op
{
__host__ __device__ SummaryStatsData<T> operator()(const T& x) const
{
SummaryStatsData<T> result;
result.n = 1;
result.min = x;
result.max = x;
result.mean = x;
result.M2 = 0;
return result;
}
};
// summary_stats_binary_op is a functor that accepts two SummaryStatsData
// structs and returns a new SummaryStatsData which are an
// approximation to the summary_stats for
// all values that have been agregated so far
template <typename T>
struct summary_stats_binary_op : public thrust::binary_function<const SummaryStatsData<T>&,
const SummaryStatsData<T>&,
SummaryStatsData<T>>
{
__host__ __device__ SummaryStatsData<T> operator()(const SummaryStatsData<T>& x,
const SummaryStatsData<T>& y) const
{
SummaryStatsData<T> result;
T n = x.n + y.n;
T delta = y.mean - x.mean;
T delta2 = delta * delta;
result.n = n;
result.min = thrust::min(x.min, y.min);
result.max = thrust::max(x.max, y.max);
result.mean = x.mean + delta * y.n / n;
result.M2 = x.M2 + y.M2;
result.M2 += delta2 * x.n * y.n / n;
return result;
}
};
} // namespace
template <>
bool SummarizeOp<float, HIPContext>::RunOnDevice()
{
auto& X = Input(0);
const int N = X.size();
DCHECK_GT(N, 0);
// TODO(Yangqing): Any better way to avoid having to const cast?
thrust::device_ptr<float> Xdata(const_cast<float*>(X.data<float>()));
summary_stats_unary_op<float> unary_op;
summary_stats_binary_op<float> binary_op;
SummaryStatsData<float> init;
init.initialize();
// compute summary statistics
SummaryStatsData<float> result = thrust::transform_reduce(
#if THRUST_VERSION >= 100800
thrust::cuda::par.on(context_.hip_stream()),
#endif // THRUST_VERSION >= 100800
Xdata,
Xdata + N,
unary_op,
init,
binary_op);
float standard_deviation = std::sqrt(result.variance());
if(to_file_)
{
(*log_file_) << result.min << " " << result.max << " " << result.mean << " "
<< standard_deviation << std::endl;
}
if(OutputSize())
{
auto* Y = OperatorBase::Output<TensorHIP>(0);
Y->Resize(4);
float output_buffer[NUM_STATS] = {result.min, result.max, result.mean, standard_deviation};
context_.Copy<float, CPUContext, HIPContext>(
NUM_STATS, output_buffer, Y->mutable_data<float>());
}
return true;
}
REGISTER_HIP_OPERATOR(Summarize, SummarizeOp<float, HIPContext>);
} // namespace caffe2
| 31.510949 | 99 | 0.615242 | ashishfarmer |
87ee1f1ce6d84e0e971d1f07d3d50b2a8b9e0431 | 671 | cpp | C++ | Source/SFXUtilities/Utilities/FMathUtils.cpp | pro100watt/VolumetricAmbientDemo | 3a0f877e51ca59984c1638a6592c55b5bb8e56b1 | [
"MIT"
] | null | null | null | Source/SFXUtilities/Utilities/FMathUtils.cpp | pro100watt/VolumetricAmbientDemo | 3a0f877e51ca59984c1638a6592c55b5bb8e56b1 | [
"MIT"
] | null | null | null | Source/SFXUtilities/Utilities/FMathUtils.cpp | pro100watt/VolumetricAmbientDemo | 3a0f877e51ca59984c1638a6592c55b5bb8e56b1 | [
"MIT"
] | null | null | null | #include "FMathUtils.h"
#include "Math/Vector2D.h"
namespace Utils
{
namespace FMathExt
{
bool IsInsideTriangle2D(const FVector2D& A, const FVector2D& B, const FVector2D& C, const FVector2D& Point)
{
FVector2D ALocal = A - C;
FVector2D BLocal = B - C;
FVector2D PointLocal = Point - C;
return IsInsideTriangleLocal2D(ALocal, BLocal, PointLocal);
}
bool IsInsideTriangleLocal2D(const FVector2D& A, const FVector2D& B, const FVector2D& Point)
{
float LCross = A ^ Point;
float RCross = Point ^ B;
ensure(LCross >= 0.f && RCross >= 0.f);
float InvHalfArea = 1.f / (A ^ B);
return 1.f >= InvHalfArea * (LCross + RCross);
}
}
} | 22.366667 | 109 | 0.66766 | pro100watt |
87f25ce11aa13e0204711b73553d5baa425c2f36 | 1,137 | cc | C++ | mycode/cpp/rvlue_SmartPointer/smartPointer.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | 2 | 2020-12-09T09:55:51.000Z | 2021-01-08T11:38:22.000Z | mycode/cpp/rvlue_SmartPointer/smartPointer.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | mycode/cpp/rvlue_SmartPointer/smartPointer.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | #include <iostream>
using std::cout;
using std::endl;
template<typename T>
class SmartPointer {
public:
SmartPointer(T* p) : _p(p) {}
T* operator->() {
return _p;
}
T& operator*() {
return *_p;
}
T* get() {
return _p;
}
void reset(T* p) {
delete _p;
_p = p;
}
~SmartPointer() {
if(_p) {
delete _p;
}
}
private:
T* _p;
};
class Point
{
public:
Point(int ix = 0, int iy = 0)
: _ix(ix)
, _iy(iy)
{
cout << "Point(int,int)" << endl;
}
friend std::ostream & operator<<(std::ostream & os, const Point & rhs);
void print() const
{
cout << "(" << _ix
<< "," << _iy
<< ")" << endl;
}
~Point(){ cout << "~Point()" << endl; }
private:
int _ix;
int _iy;
};
std::ostream & operator<<(std::ostream & os, const Point & rhs)
{
os << "(" << rhs._ix
<< "," << rhs._iy
<< ")";
return os;
}
int main() {
SmartPointer<Point> pointer(new Point(1, 2));
cout << *pointer << endl;
return 0;
}
| 14.766234 | 75 | 0.441513 | stdbilly |
87f3f49a9bb513dc0ecbbba5b880c84e82e815db | 1,607 | cpp | C++ | Source/TreeSearch/PriorProbability.cpp | StuartRiffle/corvid | 21fbea9bf585f3713354f33a205e9fd8b96da555 | [
"MIT"
] | 6 | 2019-05-29T03:22:41.000Z | 2021-03-02T09:08:16.000Z | Source/TreeSearch/PriorProbability.cpp | StuartRiffle/corvid | 21fbea9bf585f3713354f33a205e9fd8b96da555 | [
"MIT"
] | 1 | 2019-05-29T16:15:55.000Z | 2019-05-29T16:15:55.000Z | Source/TreeSearch/PriorProbability.cpp | StuartRiffle/corvid | 21fbea9bf585f3713354f33a205e9fd8b96da555 | [
"MIT"
] | null | null | null | // JAGLAVAK CHESS ENGINE (c) 2019 Stuart Riffle
#include "Jaglavak.h"
#include "TreeSearch.h"
#include "FEN.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace boost;
namespace pt = property_tree;
#include "RpcClient.h"
void TreeSearch::EstimatePriors( TreeNode* node )
{
CallRef call( new RpcCall() );
call->_ServerType = "inference";
call->_Inputs.put( "type", "estimate_priors" );
call->_Inputs.put( "position", SerializePosition( node->_Pos ) );
_RpcClient->Call( call );
while( !call->_Done )
{
// ------------------------
_SearchFibers.YieldFiber();
// ------------------------
}
if( call->_Success )
{
vector< string > moveList = SplitString( call->_Outputs.get< string >( "moves" ) );
vector< string > valueList = SplitString( call->_Outputs.get< string >( "values" ) );
assert( moveList.size() == valueList.size() );
assert( moveList.size() == node->_Branch.size() );
map< string, float > moveValue;
for( int i = 0; i < (int) moveList.size(); i++ )
moveValue[moveList[i]] = (float) atof( valueList[i].c_str() );
for( int i = 0; i < node->_Branch.size(); i++ )
node->_Branch[i]._Prior = moveValue[SerializeMoveSpec( node->_Branch[i]._Move )];
}
float scaleNoise = _Settings->Get< float >( "Search.PriorNoise" );
for( int i = 0; i < node->_Branch.size(); i++ )
{
float noise = _RandomGen.GetNormal() * scaleNoise;
node->_Branch[i]._Prior += noise;
}
}
| 29.759259 | 93 | 0.583696 | StuartRiffle |
87f975ec8a77a7396a33f198ac3a8e6207b29056 | 2,776 | hpp | C++ | include/response.hpp | pgul/fastlst | ce07baa06b0063f4c9e1374f24e67e1316ee5af4 | [
"BSD-3-Clause"
] | 2 | 2018-01-14T02:49:46.000Z | 2021-04-11T11:29:11.000Z | include/response.hpp | pgul/fastlst | ce07baa06b0063f4c9e1374f24e67e1316ee5af4 | [
"BSD-3-Clause"
] | null | null | null | include/response.hpp | pgul/fastlst | ce07baa06b0063f4c9e1374f24e67e1316ee5af4 | [
"BSD-3-Clause"
] | 1 | 2018-01-10T19:44:14.000Z | 2018-01-10T19:44:14.000Z | /*****************************************************************************/
/* */
/* (C) Copyright 1991-1997 Alberto Pasquale */
/* */
/* A L L R I G H T S R E S E R V E D */
/* */
/*****************************************************************************/
/* */
/* This source code is NOT in the public domain and it CANNOT be used or */
/* distributed without written permission from the author. */
/* */
/*****************************************************************************/
/* */
/* How to contact the author: Alberto Pasquale of 2:332/504@fidonet */
/* Viale Verdi 106 */
/* 41100 Modena */
/* Italy */
/* */
/*****************************************************************************/
/* RESPONSE.Hpp */
#ifndef RESPONSE_HPP
#define RESPONSE_HPP
#include <time.h>
#include <stdarg.h>
#include "types.hpp"
extern "C" {
#include <smapi/msgapi.h>
};
class _RSP {
public:
HAREA msg; /* Area handle */
XMSG rsphd; /* MSG header for response */
char *rsptxt; /* text (ASCIIZ); text + tear + Origin (MsgSize+160) */
char *origin; // Origin
uint rsplen; /* Lenght of rsptxt */
uint part; /* Part # of message response */
uint partpos; /* "Part #" ofset in subject */
long unix4ascii; // Unix time for ASCII field, to avoid false DUPES with Squish
_RSP (void);
~_RSP (void);
};
// if origin == NULL -> no origin
_RSP *writerspheader (HAREA msg, char *from, ADR *fmadr, char *to, ADR *toadr,
char *subject, word flags, char *origin);
void vwritersp (_RSP *rsp, char *strfmt, va_list args);
void writersp (_RSP *rsp, char *strfmt,...);
// if rsp == NULL, the function returns immediately, with no error
void closersp (_RSP *rsp, BOOL thrash = FALSE);
void getmsgdate(struct _stamp *date, time_t timer);
dword uid (void);
void SetOrigin (char *buffer, char *origin, ADR *adr);
#endif
| 41.432836 | 90 | 0.355187 | pgul |
87f9a50ea207400c103ebda8ea094d0cdd32ac8c | 1,818 | cpp | C++ | dad.cpp | nmoehrle/dad | 3f6453368a7ca709ae58be1cf8bb3a66dee71ea9 | [
"BSD-3-Clause"
] | 1 | 2020-11-23T17:31:08.000Z | 2020-11-23T17:31:08.000Z | dad.cpp | nmoehrle/dad | 3f6453368a7ca709ae58be1cf8bb3a66dee71ea9 | [
"BSD-3-Clause"
] | null | null | null | dad.cpp | nmoehrle/dad | 3f6453368a7ca709ae58be1cf8bb3a66dee71ea9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2018, Nils Moehrle
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#include <QApplication>
#include <QDrag>
#include <QFileInfo>
#include <QLabel>
#include <QMimeData>
#include <QSizePolicy>
#include <QTextStream>
#include <QUrl>
class Draggable : public QLabel
{
QList<QUrl> urls;
void mousePressEvent(QMouseEvent *event)
{
auto *drag = new QDrag(this);
auto *mimeData = new QMimeData;
mimeData->setUrls(urls);
drag->setMimeData(mimeData);
Qt::DropAction dropAction = drag->exec();
}
public:
Draggable(const QList<QUrl>&& urls, QWidget * parent = 0)
: QLabel(parent), urls(urls)
{
this->setText(QString("%1 file%2").arg(
QString::number(urls.size()),
(urls.size() == 1) ? "" : "s")
);
this->setAlignment(Qt::AlignCenter);
this->setContentsMargins(0, 0, 0, 0);
this->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
}
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QList<QUrl> urls;
if (argc > 1 || (argc == 2 && QString(argv[1]) == "-"))
{
for (int i = 1; i < argc; ++i)
{
QFileInfo fileInfo(argv[i]);
urls.append(QUrl::fromLocalFile(fileInfo.absoluteFilePath()));
}
}
else
{
QTextStream stream(stdin);
QString line;
while (stream.readLineInto(&line))
{
QFileInfo fileInfo(line);
urls.append(QUrl::fromLocalFile(fileInfo.absoluteFilePath()));
}
}
Draggable draggable(std::move(urls));
draggable.show();
return app.exec();
}
| 23.61039 | 90 | 0.588559 | nmoehrle |
87fa386fcae8872b4912d097c8eb152807332d1a | 103,061 | cpp | C++ | src/clocktree.cpp | eric830303/MAUI-Making-Aging-Useful-Intentionally- | 0a55385057708b08d83169b32475266c093b94bc | [
"MIT"
] | null | null | null | src/clocktree.cpp | eric830303/MAUI-Making-Aging-Useful-Intentionally- | 0a55385057708b08d83169b32475266c093b94bc | [
"MIT"
] | null | null | null | src/clocktree.cpp | eric830303/MAUI-Making-Aging-Useful-Intentionally- | 0a55385057708b08d83169b32475266c093b94bc | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////
//
// Source File
//
// File name: clocktree.cpp
// Author: Ting-Wei Chang
// Date: 2017-07
//
//////////////////////////////////////////////////////////////
#include "clocktree.h"
#include <iterator>
#include <fstream>
#include <queue>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/stat.h>
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Skip the line when parsing the timing report
//
/////////////////////////////////////////////////////////////////////
bool ClockTree::ifSkipLine(string line)
{
if(line.empty())
return true;
else if(line.find("(net)") != string::npos)
return true;
else if(line.find("-----") != string::npos)
return true;
else if(line.find("Path Group:") != string::npos)
return true;
else if(line.find("Path Type:") != string::npos)
return true;
else if(line.find("Point") != string::npos)
return true;
else if(line.find("clock reconvergence pessimism") != string::npos)
return true;
else if(line.find("clock network delay (propagated)") != string::npos)
return true;
else
return false;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Count each type of critical paths and disable unused critical path
//
/////////////////////////////////////////////////////////////////////
void ClockTree::pathTypeChecking(void)
{
switch(this->_pathlist.back()->getPathType())
{
case PItoFF:
this->_pitoffnum++;
if(this->_pathselect == 2)
this->_pathlist.back()->setPathType(NONE);
else
this->_pathusednum++;
break;
case FFtoPO:
this->_fftoponum++;
if((this->_pathselect == 2) || (this->_pathselect == 1))
this->_pathlist.back()->setPathType(NONE);
else
this->_pathusednum++;
break;
case FFtoFF:
this->_fftoffnum++;
this->_pathusednum++;
break;
default:
break;
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Record the clock path of the startpoint/endpoint
// Input parameter:
// who: 's' => startpoint
// 'e' => endpoint
//
/////////////////////////////////////////////////////////////////////
void ClockTree::recordClockPath(char who)
{
CriticalPath *path = this->_pathlist.back();
ClockTreeNode *node = nullptr;
switch(who)
{
// startpoint
case 's':
node = path->getStartPonitClkPath().at(0);
while(node != nullptr)
{
node = node->getParent();
path->getStartPonitClkPath().resize(path->getStartPonitClkPath().size()+1);
path->getStartPonitClkPath().back() = node;
}
path->getStartPonitClkPath().pop_back();
reverse(path->getStartPonitClkPath().begin(), path->getStartPonitClkPath().end());
path->getStartPonitClkPath().shrink_to_fit();
break;
// endpoint
case 'e':
node = path->getEndPonitClkPath().at(0);
while(node != nullptr)
{
node = node->getParent();
path->getEndPonitClkPath().resize(path->getEndPonitClkPath().size()+1);
path->getEndPonitClkPath().back() = node;
}
path->getEndPonitClkPath().pop_back();
reverse(path->getEndPonitClkPath().begin(), path->getEndPonitClkPath().end());
path->getEndPonitClkPath().shrink_to_fit();
break;
default:
break;
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Record the last common node of the clock tree, i.e., the first
// node has children from clock source
//
/////////////////////////////////////////////////////////////////////
void ClockTree::checkFirstChildrenFormRoot(void)
{
ClockTreeNode *findnode = this->_clktreeroot;
while(1)
{
if(findnode->getChildren().size() == 1)
findnode = findnode->getChildren().at(0);
else
{
long count = 0;
ClockTreeNode *recordnode = nullptr;
for(long loop = 0;loop < findnode->getChildren().size();loop++)
{
if(findnode->getChildren().at(loop)->ifUsed() == 1)
{
count++;
recordnode = findnode->getChildren().at(loop);
}
}
if(count == 1)
findnode = recordnode;
else
break;
}
}
this->_firstchildrennode = findnode;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Initial the upper and lower bound of Tc using in the Binary search
// The higher boundary for non-aging and the lower boundary for aging
//
/////////////////////////////////////////////////////////////////////
void ClockTree::initTcBound(void)
{
this->_tcupbound = ceilNPrecision( this->_tc * ((this->_aging) ? getAgingRateByDutyCycle(0.5) : 1.4), 1 );
this->_tclowbound = floorNPrecision(this->_tc * 2 - this->_tcupbound, 1 );
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Generate all DCC constraint clauses according to every combinations
// Input parameter:
// comblist: combinations (2 dimension array)
//
/////////////////////////////////////////////////////////////////////
void ClockTree::genDccConstraintClause( vector<vector<long> > *comblist )
{
for( long loop1 = 0; loop1 < comblist->size(); loop1++ )
{
if( comblist->at(loop1).size() == 2 )
{
// Generate 4 clauses based on two clock nodes
string clause1, clause2, clause3, clause4;
long nodenum1 = comblist->at(loop1).at(0), nodenum2 = comblist->at(loop1).at(1);
clause1 = to_string((nodenum1 * -1)) + " " + to_string((nodenum2 * -1)) + " 0";
clause2 = to_string((nodenum1 * -1)) + " " + to_string(((nodenum2 + 1) * -1)) + " 0";
clause3 = to_string(((nodenum1 + 1) * -1)) + " " + to_string((nodenum2 * -1)) + " 0";
clause4 = to_string(((nodenum1 + 1) * -1)) + " " + to_string(((nodenum2 + 1) * -1)) + " 0";
if(this->_dccconstraintlist.size() < (this->_dccconstraintlist.max_size()-4))
{
this->_dccconstraintlist.insert(clause1);
this->_dccconstraintlist.insert(clause2);
this->_dccconstraintlist.insert(clause3);
this->_dccconstraintlist.insert(clause4);
}
else
{
cerr << "\033[32m[Info]: DCC Constraint List Full!\033[0m\n";
return;
}
}
// Deal with the combination containing the number of nodes greater than two
// (reduce to two nodes)
else
{
vector<long> gencomb, simplify = comblist->at(loop1);
vector<vector<long> > simplifylist;
for(long loop2 = 0;loop2 <= (simplify.size()-2);loop2++)
combination(loop2+1, simplify.size(), 1, gencomb, &simplifylist);
updateCombinationList(&simplify, &simplifylist);
this->genDccConstraintClause(&simplifylist);
}
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Update the clause according to the type of DCC
// None => 00
// 20% DCC => 01
// 40% DCC => 10
// 80% DCC => 11
// Input parameter:
// dcctype: 0 => None
// 20 => 20% DCC
// 40 => 40% DCC
// 80 => 80% DCC
//
/////////////////////////////////////////////////////////////////////
void ClockTree::writeClauseByDccType( ClockTreeNode *node, string *clause, int dcctype )
{
if((node == nullptr) || (clause == nullptr) || !node->ifPlacedDcc())
return ;
long nodenum = node->getNodeNumber();
switch(dcctype)
{
case 0:
*clause += to_string(nodenum) + " " + to_string(nodenum + 1) + " ";
break;
case 20:
*clause += to_string(nodenum) + " " + to_string((nodenum + 1) * -1) + " ";
break;
case 40:
*clause += to_string(nodenum * -1) + " " + to_string(nodenum + 1) + " ";
break;
case 80:
*clause += to_string(nodenum * -1) + " " + to_string((nodenum + 1) * -1) + " ";
break;
default:
break;
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Update timing information of the critical path in a given DCC
// deployment
// Input parameter:
// update: 0 => do not update
// 1 => update
//
/////////////////////////////////////////////////////////////////////
double ClockTree::updatePathTimingWithDcc(CriticalPath *path, bool update)
{
if((this->_besttc == 0) || (path == nullptr))
return -1;
if(update)
this->_tc = this->_besttc;
ClockTreeNode *sdccnode = nullptr, *edccnode = nullptr;
vector<ClockTreeNode *> tmp;
double slack = 9999;
switch(path->getPathType())
{
// Path type: input to FF
case PItoFF:
edccnode = path->findDccInClockPath('e');
if(edccnode == nullptr)
slack = this->assessTimingWithoutDcc(path, 0, update);
else
{
vector<double> cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), edccnode);
slack = this->assessTimingWithDcc(path, 0, cjtime.front(), 0 ,0, nullptr, nullptr, tmp, tmp, 0, update);
}
break;
// Path type: FF to output
case FFtoPO:
sdccnode = path->findDccInClockPath('s');
if(sdccnode == nullptr)
slack = this->assessTimingWithoutDcc(path, 0, update);
else
{
vector<double> citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), sdccnode);
slack = this->assessTimingWithDcc(path, citime.front(), 0, 0 ,0, nullptr, nullptr, tmp, tmp, 0, update);
}
break;
// Path type: FF to FF
case FFtoFF:
sdccnode = path->findDccInClockPath('s');
edccnode = path->findDccInClockPath('e');
if((sdccnode == nullptr) && (edccnode == nullptr))
slack = this->assessTimingWithoutDcc(path, 0, update);
else
{
vector<double> citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), sdccnode);
vector<double> cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), edccnode);
slack = this->assessTimingWithDcc(path, citime.front(), cjtime.front(), 0 ,0, nullptr, nullptr, tmp, tmp, 0, update);
}
break;
default:
break;
}
return slack;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Delete the whole clock tree for releasing memory
//
/////////////////////////////////////////////////////////////////////
void ClockTree::deleteClockTree(void)
{
if(this->_clktreeroot == nullptr)
return;
queue<ClockTreeNode *> nodequeue;
ClockTreeNode *deletenode = nullptr;
nodequeue.push(this->_clktreeroot);
// BFS
while(!nodequeue.empty())
{
if(!nodequeue.front()->getChildren().empty())
{
for(auto const &nodeptr : nodequeue.front()->getChildren())
nodequeue.push(nodeptr);
}
deletenode = nodequeue.front();
nodequeue.pop();
delete deletenode;
}
this->_clktreeroot = nullptr;
this->_firstchildrennode = nullptr;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Dump all DCC information (location and type) to a file
// Reperent in: buffer_name DCC_type
//
/////////////////////////////////////////////////////////////////////
void ClockTree::dumpDccListToFile(void)
{
if(!this->_dumpdcc)
return;
fstream dccfile;
if(this->_dumpdcc && !isDirectoryExist(this->_outputdir))
mkdir(this->_outputdir.c_str(), 0775);
string filename = this->_outputdir + this->_timingreportdesign + ".dcc";
dccfile.open(filename, ios::out | fstream::trunc);
if(!dccfile.is_open())
{
cerr << "\033[31m[Error]: Cannot open " << filename << "\033[0m\n";
dccfile.close();
return;
}
if(!this->_dumpdcc || this->_dcclist.empty())
dccfile << "\n";
else
for(auto const& node: this->_dcclist)
dccfile << node.first << " " << node.second->getDccType() << "\n";
dccfile.close();
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Dump all clock gating cell information (location and gating
// probability) to a file
// Reperent in: buffer_name gating_probability
//
/////////////////////////////////////////////////////////////////////
void ClockTree::dumpClockGatingListToFile(void)
{
if(!this->_dumpcg)
return;
fstream cgfile;
if(this->_dumpcg && !isDirectoryExist(this->_outputdir))
mkdir(this->_outputdir.c_str(), 0775);
string filename = this->_outputdir + this->_timingreportdesign + ".cg";
cgfile.open(filename, ios::out | fstream::trunc);
if(!cgfile.is_open())
{
cerr << "\033[31m[Error]: Cannot open " << filename << "\033[0m\n";
cgfile.close();
return;
}
if(!this->_dumpcg || this->_cglist.empty())
cgfile << "\n";
else
for(auto const& node: this->_cglist)
cgfile << node.first << " " << node.second->getGatingProbability() << "\n";
cgfile.close();
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Private Method
// Dump all inserted buffer information (location and buffer delay)
// to a file
// Reperent in: buffer_name buffer_delay
//
/////////////////////////////////////////////////////////////////////
void ClockTree::dumpBufferInsertionToFile(void)
{
if(!this->_dumpbufins || (this->_insertbufnum == 0))
return;
fstream bufinsfile;
if(this->_dumpbufins && !isDirectoryExist(this->_outputdir))
mkdir(this->_outputdir.c_str(), 0775);
string filename = this->_outputdir + this->_timingreportdesign + ".bufins";
bufinsfile.open(filename, ios::out | fstream::trunc);
if(!bufinsfile.is_open())
{
cerr << "\033[31m[Error]: Cannot open " << filename << "\033[0m\n";
bufinsfile.close();
return;
}
if(!this->_dumpbufins || (this->_insertbufnum == 0))
bufinsfile << "\n";
else
{
for(auto const& node: this->_buflist)
if(node.second->ifInsertBuffer())
bufinsfile << node.first << " " << node.second->getInsertBufferDelay() << "\n";
for(auto const& node: this->_ffsink)
if(node.second->ifInsertBuffer())
bufinsfile << node.first << " " << node.second->getInsertBufferDelay() << "\n";
}
bufinsfile.close();
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Destructor
//
/////////////////////////////////////////////////////////////////////
ClockTree::~ClockTree(void)
{
this->deleteClockTree();
for(long loop = 0;loop < this->_pathlist.size();loop++)
this->_pathlist.at(loop)->~CriticalPath();
this->_pathlist.clear();
this->_pathlist.shrink_to_fit();
this->_ffsink.clear();
this->_buflist.clear();
this->_cglist.clear();
this->_dcclist.clear();
this->_dccconstraintlist.clear();
this->_timingconstraintlist.clear();
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Check the commands from input
// Input parameter:
// message: error message
//
/////////////////////////////////////////////////////////////////////
int ClockTree::checkParameter(int argc, char **argv, string *message)
{
if( argc == 1 )
{
*message = "\033[31m[ERROR]: Missing operand!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
for(int loop = 1;loop < argc;loop++)
{
if(( strcmp(argv[loop], "-h") == 0 ) || ( strcmp(argv[loop], "--help") == 0) )
{
message->clear();
return -1;
}
else if(strcmp(argv[loop], "-nondcc") == 0)
this->_placedcc = 0; // Do not insert DCC
else if(strcmp(argv[loop], "-nonaging") == 0)
this->_aging = 0; // Non-aging
else if(strcmp(argv[loop], "-mindcc") == 0)
this->_mindccplace = 1; // Minimize DCC deployment
else if(strcmp(argv[loop], "-tc_recheck") == 0)
this->_tcrecheck = 1; // Recheck Tc
else if(strcmp(argv[loop], "-print=Clause") == 0)
this->_printClause = 1; // Recheck Tc
else if(strcmp(argv[loop], "-print=Node") == 0)
this->_printClkNode = 1; // Recheck Tc
else if(strcmp(argv[loop], "-mask_leng") == 0)
{
if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) < 0) || (stod(string(argv[loop+1])) > 1))
{
*message = "\033[31m[ERROR]: Wrong length of mask!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_maskleng = stod(string(argv[loop+1]));
loop++;
}
else if(strcmp(argv[loop], "-mask_level") == 0)
{
if(!isRealNumber(string(argv[loop+1])) || (stol(string(argv[loop+1])) < 0))
{
*message = "\033[31m[ERROR]: Wrong level of mask!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_masklevel = stol(string(argv[loop+1]));
loop++;
}
else if(strcmp(argv[loop], "-agingrate_tcq") == 0)
{
if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) <= 0))
{
*message = "\033[31m[ERROR]: Wrong aging rate of tcq!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_agingtcq = stod(string(argv[loop+1]));
loop++;
}
else if(strcmp(argv[loop], "-agingrate_dij") == 0)
{
if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) <= 0))
{
*message = "\033[31m[ERROR]: Wrong aging rate of dij!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_agingdij = stod(string(argv[loop+1]));
loop++;
}
else if(strcmp(argv[loop], "-agingrate_tsu") == 0)
{
if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) <= 0))
{
*message = "\033[31m[ERROR]: Wrong aging rate of tsu!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_agingtsu = stod(string(argv[loop+1]));
loop++;
}
else if(strcmp(argv[loop], "-cg_percent") == 0)
{
if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) < 0) || (stod(string(argv[loop+1])) > 1))
{
*message = "\033[31m[ERROR]: Wrong percent of clock gating cells replacement!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_cgpercent = stod(string(argv[loop+1]));
loop++;
}
else if(strcmp(argv[loop], "-gp_upbound") == 0)
{
if(!isRealNumber(string(argv[loop+1])) || (stoi(string(argv[loop+1])) < 0) || (stoi(string(argv[loop+1])) > 100))
{
*message = "\033[31m[ERROR]: Wrong upperbound probability of clock gating!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_gpupbound = stoi(string(argv[loop+1]));
loop++;
}
else if(strcmp(argv[loop], "-gp_lowbound") == 0)
{
if(!isRealNumber(string(argv[loop+1])) || (stoi(string(argv[loop+1])) < 0) || (stoi(string(argv[loop+1])) > 100))
{
*message = "\033[31m[ERROR]: Wrong lowerbound probability of clock gating!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_gplowbound = stoi(string(argv[loop+1]));
loop++;
}
else if(strncmp(argv[loop], "-path=", 6) == 0)
{
vector<string> strspl = stringSplit(string(argv[loop]), "=");
if(strspl.back().compare("all") == 0)
this->_pathselect = 0; // PItoFF, FFtoPO, and FFtoFF
else if(strspl.back().compare("pi_ff") == 0)
this->_pathselect = 1; // PItoFF and FFtoFF
else if(strspl.back().compare("onlyff") == 0)
this->_pathselect = 2; // FFtoFF
else
{
*message = "\033[31m[ERROR]: Wrong path selection!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
}
else if(strncmp(argv[loop], "-clockgating=", 13) == 0)
{
vector<string> strspl = stringSplit(string(argv[loop]), "=");
if(strspl.back().compare("no") == 0)
this->_clkgating = 0; // Do not replace buffers
else if(strspl.back().compare("yes") == 0)
this->_clkgating = 1; // Replace buffers
else
{
*message = "\033[31m[ERROR]: Wrong clock gating setting!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
}
else if(strncmp(argv[loop], "-gatingfile=", 12) == 0)
{
vector<string> strspl = stringSplit(string(argv[loop]), "=");
if(!isFileExist(strspl.back()))
{
*message = "\033[31m[ERROR]: Gating file not found!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
this->_cgfilename.assign(strspl.back());
}
else if(strncmp(argv[loop], "-bufinsert=", 11) == 0)
{
vector<string> strspl = stringSplit(string(argv[loop]), "=");
if(strspl.back().compare("insert") == 0)
this->_bufinsert = 1; // Insert buffers
else if(strspl.back().compare("min_insert") == 0)
this->_bufinsert = 2; // Insert buffers and minimize buffer insertion
else
{
*message = "\033[31m[ERROR]: Wrong Buffer insertion setting!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
}
else if(strncmp(argv[loop], "-dump=", 6) == 0)
{
vector<string> strspl = stringSplit(string(argv[loop]), "=");
if(strspl.back().compare("dcc") == 0)
this->_dumpdcc = 1; // Dump DCC list
else if(strspl.back().compare("cg") == 0)
this->_dumpcg = 1; // Dump clock gating cell list
else if(strspl.back().compare("buf_ins") == 0)
this->_dumpbufins = 1; // Dump inserted buffer list
else if(strspl.back().compare("all") == 0)
{
this->_dumpdcc = 1;
this->_dumpcg = 1;
this->_dumpbufins = 1;
}
}
else if(isFileExist(string(argv[loop])))
{
// Check if the timing report exist or not
if(!this->_timingreportfilename.empty())
{
*message = "\033[31m[ERROR]: Too many timing reports!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
char path[100] = {'\0'}, *pathptr = nullptr;
this->_timingreport.assign(argv[loop]);
vector<string> strspl = stringSplit(this->_timingreport, "/");
this->_timingreportfilename.assign(strspl.back());
realpath(argv[loop], path);
pathptr = strrchr(path, '/');
path[pathptr - path + 1] = '\0';
this->_timingreportloc.assign(path);
}
else
{
*message = "\033[31m[ERROR]: Missing operand!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
}
if(_timingreportfilename.empty())
{
*message = "\033[31m[ERROR]: Missing timing report!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
if(this->_gplowbound > this->_gpupbound)
{
*message = "\033[31m[ERROR]: Lower bound probability can't greater than upper bound!!\033[0m\n";
*message += "Try \"--help\" for more information.\n";
return -1;
}
if(!this->_aging)
{
// Non-aging for Tcq, Dij, and Tsu
this->_agingtcq = 1, this->_agingdij = 1, this->_agingtsu = 1;
}
return 0;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Parse the timing report
//
/////////////////////////////////////////////////////////////////////
void ClockTree::parseTimingReport(void)
{
fstream tim_max;
long pathnum = -1, maxlevel = -1;
bool startscratchfile = false, pathstart = false, firclkedge = false;
double clksourlate = 0, clktime = 0;
string line;
ClockTreeNode *parentnode = nullptr;
tim_max.open(this->_timingreport, ios::in);
if(!tim_max.is_open())
{
cerr << "\033[31m[Error]: Cannot open " << this->_timingreport << "\033[0m\n";
tim_max.close();
abort();
}
while(!tim_max.eof())
{
getline(tim_max, line);
if(line.find("Design :") != string::npos)
{
vector<string> strspl;
strspl = stringSplit(line, " ");
this->_timingreportdesign = strspl.at(2);
}
if((startscratchfile == false) && (line.find("Startpoint") != string::npos))
{
startscratchfile = true;
cout << "\033[32m[Info]: Bilding clock tree...\033[0m\n";
}
if(startscratchfile)
{
// End of the timing report
if((line.length() == 1) && (line.compare("1") == 0))
{
startscratchfile = false;
cout << "\033[32m[Info]: Clock tree complete.\033[0m\n";
break;
}
if(this->ifSkipLine(line))
continue;
else
{
vector<string> strspl;
strspl = stringSplit(line, " ");
if(strspl.empty())
continue;
if(line.find("Startpoint") != string::npos)
{
int type = NONE;
if(strspl.size() > 2)
{
if(line.find("input port") != string::npos)
type = PItoPO;
else if(line.find("flip-flop") != string::npos)
type = FFtoPO;
}
else
{
getline(tim_max, line);
if(line.find("input port") != string::npos)
type = PItoPO;
else if(line.find("flip-flop") != string::npos)
type = FFtoPO;
}
pathnum++;
CriticalPath *path = new CriticalPath(strspl.at(1), type, pathnum);
this->_pathlist.resize(this->_pathlist.size()+1);
this->_pathlist.back() = path;
}
else if(line.find("Endpoint") != string::npos)
{
CriticalPath *path = this->_pathlist.back();
path->setEndPointName(strspl.at(1));
if(strspl.size() > 2)
{
if(line.find("flip-flop") != string::npos)
path->setPathType(path->getPathType()+1);
}
else
{
getline(tim_max, line);
if(line.find("flip-flop") != string::npos)
path->setPathType(path->getPathType()+1);
}
this->pathTypeChecking();
}
else if(line.find("(rise edge)") != string::npos)
{
if(this->_clktreeroot == nullptr)
{
ClockTreeNode *node = new ClockTreeNode(nullptr, this->_totalnodenum, 0, 1);
node->getGateData()->setGateName(strspl.at(1));
node->getGateData()->setWireTime(stod(strspl.at(4)));
node->getGateData()->setGateTime(stod(strspl.at(4)));
// Assign two numbers to a node
this->_totalnodenum += 2;
this->_clktreeroot = node;
//this->_buflist.insert(pair<string, ClockTreeNode *> (strspl.at(1), node));
}
if(firclkedge)
{
firclkedge = false;
this->_origintc = stod(strspl.at(5)) - clktime;
}
else
{
firclkedge = true;
clktime = stod(strspl.at(5));
}
}
else if(line.find("clock source latency") != string::npos)
clksourlate = stod(strspl.at(3));
else if(line.find("data arrival time") != string::npos)
this->_pathlist.back()->setArrivalTime(stod(strspl.at(3)));
else if(line.find("data required time") != string::npos)
this->_pathlist.back()->setRequiredTime(stod(strspl.at(3)) + abs(this->_pathlist.back()->getClockUncertainty()));
else if(line.find("input external delay") != string::npos)
{
if((this->_pathlist.back()->getPathType() == PItoPO) || (this->_pathlist.back()->getPathType() == PItoFF))
this->_pathlist.back()->setTinDelay(stod(strspl.at(3)));
}
else if(line.find("output external delay") != string::npos)
{
// Assign to Tsu
if((this->_pathlist.back()->getPathType() == PItoPO) || (this->_pathlist.back()->getPathType() == FFtoPO))
this->_pathlist.back()->setTsu(stod(strspl.at(3)));
}
else if(line.find("clock uncertainty") != string::npos)
this->_pathlist.back()->setClockUncertainty(stod(strspl.at(2)));
else if(line.find("library setup time") != string::npos)
this->_pathlist.back()->setTsu(stod(strspl.at(3)));
// Clock source
else if(line.find("(in)") != string::npos)
{
if(strspl.at(0).compare(this->_clktreeroot->getGateData()->getGateName()) == 0) // clock input
parentnode = this->_clktreeroot;
else if(strspl.at(0).compare(this->_pathlist.back()->getStartPointName()) == 0) // input port
{
pathstart = true;
GateData *pathnode = new GateData(this->_pathlist.back()->getStartPointName(), stod(strspl.at(3)), 0);
this->_pathlist.back()->getGateList().resize(this->_pathlist.back()->getGateList().size()+1);
this->_pathlist.back()->getGateList().back() = pathnode;
}
}
else if(line.find("slack (") != string::npos)
{
this->_pathlist.back()->setSlack(stod(strspl.at(2)) + abs(this->_pathlist.back()->getClockUncertainty()));
switch(this->_pathlist.back()->getPathType())
{
case PItoFF:
this->recordClockPath('e');
break;
case FFtoPO:
this->recordClockPath('s');
break;
case FFtoFF:
this->recordClockPath('s');
this->recordClockPath('e');
break;
default:
break;
}
this->_pathlist.back()->getGateList().shrink_to_fit();
pathstart = false, firclkedge = false, parentnode = nullptr;
}
else
{
CriticalPath *path = this->_pathlist.back();
vector<string> namespl;
bool scratchnextline = false;
namespl = stringSplit(strspl.at(0), "/");
if(line.find("/") != string::npos)
scratchnextline = true;
// Deal with combinational logic nodes
if(pathstart)
{
GateData *pathnode = new GateData(namespl.at(0), stod(strspl.at(3)), 0);
if(namespl.at(0).compare(path->getEndPointName()) == 0)
{
pathstart = false;
path->setDij(stod(strspl.at(5)) - path->getCi() - path->getTcq() - path->getTinDelay());
}
if(scratchnextline && pathstart)
{
getline(tim_max, line);
strspl = stringSplit(line, " ");
pathnode->setGateTime(stod(strspl.at(3)));
}
path->getGateList().resize(path->getGateList().size()+1);
path->getGateList().back() = pathnode;
}
// Deal with clock tree buffers
else
{
ClockTreeNode *findnode = nullptr;
bool sameinsameout = false;
if((this->_pathlist.back()->getStartPointName().compare(path->getEndPointName()) == 0) && (path->getStartPonitClkPath().size() > 0))
sameinsameout = true;
// Meet the startpoint FF/input
if((namespl.at(0).compare(path->getStartPointName()) == 0) && (sameinsameout == false))
{
pathstart = true;
findnode = parentnode->searchChildren(namespl.at(0));
path->setCi(stod(strspl.at(5)));
if(findnode == nullptr)
{
ClockTreeNode *node = new ClockTreeNode(parentnode, this->_totalnodenum, parentnode->getDepth()+1);
node->getGateData()->setGateName(namespl.at(0));
node->getGateData()->setWireTime(stod(strspl.at(3)));
this->_ffsink.insert(pair<string, ClockTreeNode *> (namespl.at(0), node));
if((path->getPathType() == PItoPO) || (path->getPathType() == NONE))
node->setIfUsed(0);
parentnode->getChildren().resize(parentnode->getChildren().size()+1);
parentnode->getChildren().back() = node;
if(node->getDepth() > maxlevel)
maxlevel = node->getDepth();
// Assign two numbers to a node
this->_totalnodenum += 2;
findnode = node, parentnode = nullptr;
}
if(scratchnextline)
{
getline(tim_max, line);
strspl = stringSplit(line, " ");
findnode->getGateData()->setGateTime(stod(strspl.at(3)));
}
GateData *pathnode = new GateData(path->getStartPointName(), findnode->getGateData()->getWireTime(), findnode->getGateData()->getGateTime());
path->getGateList().resize(path->getGateList().size()+1);
path->getGateList().back() = pathnode;
path->getStartPonitClkPath().resize(path->getStartPonitClkPath().size()+1);
path->getStartPonitClkPath().back() = findnode;
if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF))
{
if(findnode->ifUsed() != 1)
this->_ffusednum++;
findnode->setIfUsed(1);
}
if((path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF))
path->setTcq(findnode->getGateData()->getGateTime());
}
// Meet the endpoint FF/output
else if(!firclkedge && (namespl.at(0).compare(path->getEndPointName()) == 0))
{
findnode = parentnode->searchChildren(namespl.at(0));
if(findnode == nullptr)
{
ClockTreeNode *node = new ClockTreeNode(parentnode, this->_totalnodenum, parentnode->getDepth()+1);
node->getGateData()->setGateName(namespl.at(0));
node->getGateData()->setWireTime(stod(strspl.at(3)));
this->_ffsink.insert(pair<string, ClockTreeNode *> (namespl.at(0), node));
if((path->getPathType() == PItoPO) || (path->getPathType() == NONE))
node->setIfUsed(0);
parentnode->getChildren().resize(parentnode->getChildren().size()+1);
parentnode->getChildren().back() = node;
if(node->getDepth() > maxlevel)
maxlevel = node->getDepth();
// Assign two numbers to a node
this->_totalnodenum += 2;
findnode = node, parentnode = nullptr;
}
path->getEndPonitClkPath().resize(path->getEndPonitClkPath().size()+1);
path->getEndPonitClkPath().back() = findnode;
path->setCj(stod(strspl.at(5)) - this->_origintc);
if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF))
{
if(findnode->ifUsed() != 1)
this->_ffusednum++;
findnode->setIfUsed(1);
}
}
// Meet clock buffers
else
{
findnode = parentnode->searchChildren(namespl.at(0));
if(findnode == nullptr)
{
ClockTreeNode *node = new ClockTreeNode(parentnode, this->_totalnodenum, parentnode->getDepth()+1);
node->getGateData()->setGateName(namespl.at(0));
node->getGateData()->setWireTime(stod(strspl.at(3)));
this->_buflist.insert(pair<string, ClockTreeNode *> (namespl.at(0), node));
if((path->getPathType() == PItoPO) || (path->getPathType() == NONE))
node->setIfUsed(0);
parentnode->getChildren().resize(parentnode->getChildren().size()+1);
parentnode->getChildren().back() = node;
// Assign two numbers to a node
this->_totalnodenum += 2;
if(scratchnextline)
{
getline(tim_max, line);
strspl = stringSplit(line, " ");
node->getGateData()->setGateTime(stod(strspl.at(3)));
}
findnode = node, parentnode = node;
}
else
{
parentnode = findnode;
if(scratchnextline)
getline(tim_max, line);
}
if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF))
{
if(findnode->ifUsed() != 1)
this->_bufferusednum++;
findnode->setIfUsed(1);
}
}
}
}
}
}
}
tim_max.close();
this->_totalnodenum /= 2;
this->_maxlevel = maxlevel;
this->checkFirstChildrenFormRoot();
this->_outputdir = "./" + this->_timingreportdesign + "_output/";
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Replace buffers to clock gating cells
//
/////////////////////////////////////////////////////////////////////
void ClockTree::clockGatingCellReplacement(void)
{
if( !this->_clkgating )
return;
// Get the replacement from cg file if the cg file exist
if(!this->_cgfilename.empty())
{
fstream cgfile;
string line;
cout << "\033[32m[Info]: Open the setting file of clock gating cells.\033[0m\n";
cgfile.open(this->_cgfilename, ios::in);
if(!cgfile.is_open())
{
cerr << "\033[31m[Error]: Cannot open " << this->_cgfilename << "\033[0m\n";
cgfile.close();
return;
}
cout << "\033[32m[Info]: Replacing some buffers to clock gating cells...\033[0m\n";
while(!cgfile.eof())
{
getline(cgfile, line);
if(line.empty())
continue;
vector<string> strspl = stringSplit(line, " ");
map<string, ClockTreeNode *>::iterator findptr = this->_buflist.find(strspl.at(0));
if(findptr != this->_buflist.end())
{
if((strspl.size() == 2) && isRealNumber(strspl.at(1)))
findptr->second->setGatingProbability(stod(strspl.at(1)));
else
findptr->second->setGatingProbability(genRandomNum("float", this->_gpupbound, this->_gplowbound, 2));
findptr->second->setIfClockGating(1);
this->_cglist.insert(pair<string, ClockTreeNode *> (findptr->second->getGateData()->getGateName(), findptr->second));
}
}
cgfile.close();
}
// Replace buffers randomly to clock gating cells
else
{
cout << "\033[32m[Info]: Replacing some buffers to clock gating cells...\033[0m\n";
map<string, ClockTreeNode *> buflist(this->_buflist);
map<string, ClockTreeNode *>::iterator nodeitptr = buflist.begin();
for(long loop1 = 0;loop1 < (long)(this->_bufferusednum * this->_cgpercent);loop1++)
{
if(buflist.empty() || ((long)(this->_bufferusednum * this->_cgpercent) == 0))
break;
long rannum = (long)genRandomNum("integer", 0, buflist.size()-1);
nodeitptr = buflist.begin(), advance(nodeitptr, rannum);
ClockTreeNode *picknode = nodeitptr->second;
if((picknode->ifUsed() == 1) && (picknode->ifClockGating() == 0))
{
bool breakflag = true;
for(auto const &nodeptr : picknode->getChildren())
{
if(!nodeptr->getChildren().empty())
{
breakflag = false;
break;
}
}
if(breakflag)
{
loop1--;
buflist.erase(nodeitptr);
continue;
}
map<string, ClockTreeNode *>::iterator findptr;
// Replace the buffer if it has brothers/sisters
if((picknode->getParent()->getChildren().size() > 1) || (picknode->getParent() == this->_clktreeroot))
{
picknode->setIfClockGating(1);
picknode->setGatingProbability(genRandomNum("float", this->_gplowbound, this->_gpupbound, 2));
this->_cglist.insert(pair<string, ClockTreeNode *> (picknode->getGateData()->getGateName(), picknode));
}
// Deal with the buffer if it does not has brothers/sisters
// Replace the parent buffer of the buffer
else
{
findptr = buflist.find(picknode->getParent()->getGateData()->getGateName());
if(findptr != buflist.end())
{
ClockTreeNode *nodeptr = picknode->getParent();
while((nodeptr->getParent()->getChildren().size() == 1) && (nodeptr->getParent() != this->_clktreeroot))
nodeptr = nodeptr->getParent();
nodeptr->setIfClockGating(1);
nodeptr->setGatingProbability(genRandomNum("float", this->_gplowbound, this->_gpupbound, 2));
this->_cglist.insert(pair<string, ClockTreeNode *> (nodeptr->getGateData()->getGateName(), nodeptr));
while(nodeptr != picknode)
{
findptr = buflist.find(nodeptr->getGateData()->getGateName());
if(findptr != buflist.end())
buflist.erase(findptr);
nodeptr = nodeptr->getChildren().front();
}
}
else
loop1--;
}
buflist.erase(picknode->getGateData()->getGateName());
if(picknode->getChildren().size() == 1)
{
findptr = buflist.find(picknode->getChildren().front()->getGateData()->getGateName());
if(findptr != buflist.end())
buflist.erase(findptr);
}
}
else
{
loop1--;
buflist.erase(nodeitptr);
}
}
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Adjust the primitive Tc in the timing report to a suitable Tc
// using in the start of Binary search
//
/////////////////////////////////////////////////////////////////////
void ClockTree::adjustOriginTc(void)
{
double minslack = 999, tcdiff = 0;
CriticalPath *minslackpath = nullptr;
// Find the critical path dominating Tc
for( auto const &pathptr : this->_pathlist )
{
if(( pathptr->getPathType() == NONE) || pathptr->getPathType() == PItoPO )
continue;
if( min(pathptr->getSlack(), minslack ) != minslack )
{
minslack = min(pathptr->getSlack(), minslack);
minslackpath = pathptr;
}
}
if( minslack < 0 )
tcdiff = abs(minslackpath->getSlack());
else if(minslack > (this->_origintc * (roundNPrecision(getAgingRateByDutyCycle(0.5), PRECISION) - 1)))
tcdiff = (this->_origintc - floorNPrecision(((this->_origintc - minslackpath->getSlack()) * 1.2), PRECISION)) * -1;
if( tcdiff != 0 )
{
// Update the required time and slack of each critical path
for(auto const &pathptr : this->_pathlist )
{
if( (pathptr->getPathType() == NONE) || (pathptr->getPathType() == PItoPO) )
continue;
pathptr->setRequiredTime(pathptr->getRequiredTime() + tcdiff);
pathptr->setSlack(pathptr->getSlack() + tcdiff);
}
}
// Adjust Tc
this->_tc = this->_origintc + tcdiff;
// Initial the boundary of Tc using in Binary search
this->initTcBound();
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Prohibit DCCs inserting below the mask
//
/////////////////////////////////////////////////////////////////////
void ClockTree::dccPlacementByMasked(void)
{
if( !this->_placedcc )//-nondcc
return ;
long pathcount = 0;
for( auto const &pathptr : this->_pathlist )
{
//if(pathcount > (long)(this->_pathusednum * PATHMASKPERCENT))
// break;
bool dealstart = 0, dealend = 0 ;
ClockTreeNode *sameparent = this->_firstchildrennode;
switch( pathptr->getPathType() )
{
// Path type: input to FF
case PItoFF:
dealend = 1 ;
break;
// Path type: FF to output
case FFtoPO:
dealstart = 1 ;
break;
// Path type: FF to FF
case FFtoFF:
if( pathptr->isEndPointSameAsStartPoint() )
{
pathcount++ ;
continue ;
}
sameparent = pathptr->findLastSameParentNode();
dealstart = 1 ;
dealend = 1 ;
break ;
default:
continue;
}
pathcount++;
// Deal with the clock path of the startpoint
if( dealstart )
{
vector< ClockTreeNode * > starttemp = pathptr->getStartPonitClkPath();//return by reference
starttemp.pop_back() ;
//front = root, back = FF
reverse( starttemp.begin(), starttemp.end() );
//front = FF, back = root
// Ignore the common nodes
while( 1 )
{
if( starttemp.back() != sameparent )
starttemp.pop_back();
else if(starttemp.back() == sameparent)
{
starttemp.pop_back();
reverse(starttemp.begin(), starttemp.end());
break;
}
}
long clkpathlen = (long)(starttemp.size() * this->_maskleng);
// Mask by length
for( long loop = 0;loop < clkpathlen;loop++ )//when loop=0, it mean same parent-1
starttemp.pop_back() ;
// Mask by level
for( auto const &nodeptr : starttemp )
if( nodeptr->getDepth() <= (this->_maxlevel - this->_masklevel) )
nodeptr->setIfPlaceDcc(1);
}
// Deal with the clock path of the endpoint
if( dealend )
{
vector<ClockTreeNode *> endtemp = pathptr->getEndPonitClkPath();//return by reference
endtemp.pop_back();//delete FF?
//endtemp[0]=root, endtemp[tail]=FF+1
reverse(endtemp.begin(), endtemp.end());
//endtemp[0]=FF+1, endtemp[tail]=root
// Ignore the common nodes
while(1)
{
if( endtemp.back() != sameparent )
endtemp.pop_back();
else if( endtemp.back() == sameparent )
{
endtemp.pop_back();
reverse(endtemp.begin(), endtemp.end());
//endtemp[0]=sameparent-1, endtemp[tail]=FF+1
break;
}
}
long clkpathlen = (long)(endtemp.size() * this->_maskleng);
// Mask by length
for( long loop = 0;loop < clkpathlen;loop++ )
endtemp.pop_back();
// Mask by level
for( auto const &nodeptr : endtemp )
if(nodeptr->getDepth() <= (this->_maxlevel - this->_masklevel))
nodeptr->setIfPlaceDcc(1);
}
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// DCC constraint and generate clauses
//
/////////////////////////////////////////////////////////////////////
void ClockTree::dccConstraint(void)
{
if( !this->_placedcc )
{
this->_nonplacedccbufnum = this->_buflist.size();
return;
}
// Generate two clauses for the clock tree root (clock source)
if( this->_dccconstraintlist.size() < (this->_dccconstraintlist.max_size()-2) )
{
string clause1 = to_string(this->_clktreeroot->getNodeNumber() * -1) + " 0";
string clause2 = to_string((this->_clktreeroot->getNodeNumber() + 1) * -1) + " 0";
this->_dccconstraintlist.insert(clause1);
this->_dccconstraintlist.insert(clause2);
}
else
{
cerr << "\033[32m[Info]: DCC Constraint List Full!\033[0m\n";
return;
}
// Generate two clauses for each buffer can not insert DCC
for( auto const& node: this->_buflist )//_buflist = map< string, clknode * >
{
if( !node.second->ifPlacedDcc() )
{
string clause1, clause2;
clause1 = to_string(node.second->getNodeNumber() * -1) + " 0";
clause2 = to_string((node.second->getNodeNumber() + 1) * -1) + " 0";
if(this->_dccconstraintlist.size() < (this->_dccconstraintlist.max_size()-2))
{
this->_dccconstraintlist.insert(clause1);
this->_dccconstraintlist.insert(clause2);
}
else
{
cerr << "\033[32m[Info]: DCC Constraint List Full!\033[0m\n";
return;
}
}
}
this->_nonplacedccbufnum = (this->_dccconstraintlist.size() / 2) - 1;
// Generate clauses based on DCC constraint in each clock path
for( auto const& node: this->_ffsink )
{
//-- Don't Put DCC ahead of FF
string clause1, clause2;
clause1 = to_string(node.second->getNodeNumber() * -1) + " 0";
clause2 = to_string((node.second->getNodeNumber() + 1) * -1) + " 0";
if(this->_dccconstraintlist.size() < (this->_dccconstraintlist.max_size()-2))
{
this->_dccconstraintlist.insert(clause1);
this->_dccconstraintlist.insert(clause2);
}
else
{
cerr << "\033[32m[Info]: DCC Constraint List Full!\033[0m\n";
return;
}
ClockTreeNode *nodeptr = node.second->getParent() ;//FF's parent
vector<long> path, gencomb;
vector<vector<long> > comblist;
while( nodeptr != this->_firstchildrennode )
{
if( nodeptr->ifPlacedDcc() )
path.push_back( nodeptr->getNodeNumber() );
nodeptr = nodeptr->getParent();
}
path.shrink_to_fit();
reverse(path.begin(), path.end());
// Combination of DCC constraint
// Can't Put more than 2 DCC along the same clock path
for( long loop = 0; loop <= ((long)path.size()) - 2; loop++ )
combination( loop+1, (int)(path.size()), 1, gencomb, &comblist );
updateCombinationList( &path, &comblist );
// Generate clauses
this->genDccConstraintClause(&comblist);
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Generate all kinds of DCC deployment (location of DCC excluding
// the types of DCC) in each critical path
//
/////////////////////////////////////////////////////////////////////
void ClockTree::genDccPlacementCandidate(void)
{
if( !this->_placedcc )
return ;
for( auto const& path: this->_pathlist )
if( (path->getPathType() != NONE) && (path->getPathType() != PItoPO) )
path->setDccPlacementCandidate();
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Timing constraint and generate clauses based on each DCC
// deployment
//
/////////////////////////////////////////////////////////////////////
double ClockTree::timingConstraint(void)
{
printf( YELLOW"\t[Timing Constraint] " RESET"Tc range: %f - %f ...\033[0m\n", this->_tclowbound, this->_tcupbound ) ;
double slack = 0 ;
double minslack = 100 ;//Eric
this->_timingconstraintlist.clear();//set<string>
for( auto const& path: this->_pathlist )
{
if( (path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF) )
continue;
// Assess if the critical path occurs timing violation without inserting any DCC
slack = this->assessTimingWithoutDcc(path);
// Assess if the critical path occurs timing violation when inserting DCCs
if( this->_placedcc )//-nodcc
this->assessTimingWithDcc(path);
/*Senior
if( (slack < 0) && (!this->_placedcc) )
return slack;
*/
minslack = (slack<minslack)?(slack):(minslack);
}
return minslack;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Assess if the critical path occurs timing violation without
// inserting any DCC (violating the setup time requirement)
// Input parameter:
// genclause: 0 => Do not generate a clause
// 1 (default) => Generate clauses (default)
// update: 0 (default) => Do not update the timing information of critical path
// 1 => Update the timing information of critical path
/////////////////////////////////////////////////////////////////////
double ClockTree::assessTimingWithoutDcc( CriticalPath *path, bool genclause, bool update )
{
/* Note:
writeClauseByDccType( nodeptr, &clause, 0 ), the last arg is 0, because as title imply
we access timing without Dcc
*/
if( path == nullptr )
return -1 ;
//------ Declare ------------------------------------------------------------------
double newslack = 0 ;
double dataarrtime = 0 ;
double datareqtime = 0 ;
//------- Ci & Cj ------------------------------------------------------------------
this->calculateClockLatencyWithoutDcc( path, &datareqtime, &dataarrtime );
if( update )
{
path->setCi(dataarrtime) ;
path->setCj(datareqtime) ;
}
//------- Require time --------------------------------------------------------------
datareqtime += (path->getTsu() * this->_agingtsu) + this->_tc;
//------- Arrival time --------------------------------------------------------------
dataarrtime += path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij);
newslack = datareqtime - dataarrtime ;
if( update )
{
path->setArrivalTime(dataarrtime) ;
path->setRequiredTime(datareqtime);
path->setSlack(newslack) ;
}
//-------- Timing Violation ---------------------------------------------------------
if( (newslack < 0) && this->_placedcc && genclause)
{
string clause;
//---- PItoFF or FFtoPO --------------------------------------------------------
if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO))
{
vector<ClockTreeNode *> clkpath = ((path->getPathType() == PItoFF) ? path->getEndPonitClkPath() : path->getStartPonitClkPath());
//- Generate Clause --------------------------------------------------------
for( auto const& nodeptr: clkpath )
{
if( nodeptr->ifPlacedDcc() ) this->writeClauseByDccType( nodeptr, &clause, 0 ) ;
}
}
else if( path->getPathType() == FFtoFF )//-- FFtoFF -----------------------------
{
ClockTreeNode *sameparent = path->findLastSameParentNode();
//- Generate Clause/Left ----------------------------------------------------
long sameparentloc = path->nodeLocationInClockPath('s', sameparent);
for( auto const& nodeptr: path->getStartPonitClkPath() )
if( nodeptr->ifPlacedDcc() )
this->writeClauseByDccType( nodeptr, &clause, 0 ) ;
//- Generate Clause/Right ---------------------------------------------------
for( long loop = (sameparentloc + 1);loop < path->getEndPonitClkPath().size(); loop++ )
if( path->getEndPonitClkPath().at(loop)->ifPlacedDcc() )
this->writeClauseByDccType( path->getEndPonitClkPath().at(loop), &clause, 0 );
}
clause += "0";
if( this->_timingconstraintlist.size() < (this->_timingconstraintlist.max_size()-1) )
this->_timingconstraintlist.insert(clause) ;
else
cerr << "\033[32m[Info]: Timing Constraint List Full!\033[0m\n";
}
return newslack;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// According to each DCC deployment, calculate the Ci and Cj and
// assess if the critical path occurs timing violation when inserting
// DCCs (violating the setup time requirement)
//
/////////////////////////////////////////////////////////////////////
void ClockTree::assessTimingWithDcc(CriticalPath *path)
{
if(path == nullptr)
return;
vector<vector<ClockTreeNode *> > dcccandi = path->getDccPlacementCandi();
// Consider every DCC deployment of this critical path
for( long loop = 0; loop < dcccandi.size(); loop++ )
{
vector<double> citime, cjtime;
// Path type: input to FF
if( path->getPathType() == PItoFF )
{
// Calculate the Cj
cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), dcccandi.at(loop).front());//return a vector
// Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC//back()?
//Error here (maybe), argc is not consistent
this->assessTimingWithDcc(path, 0, cjtime.at(0), 20, -1, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath());
this->assessTimingWithDcc(path, 0, cjtime.at(1), 40, -1, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath());
this->assessTimingWithDcc(path, 0, cjtime.at(2), 80, -1, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath());
}
// Path type: FF to output
else if( path->getPathType() == FFtoPO )
{
// Calculate the Ci
citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), dcccandi.at(loop).front());
// Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC
this->assessTimingWithDcc(path, citime.at(0), 0, 20, -1, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath());
this->assessTimingWithDcc(path, citime.at(1), 0, 40, -1, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath());
this->assessTimingWithDcc(path, citime.at(2), 0, 80, -1, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath());
}
// Path type: FF to FF
else if( path->getPathType() == FFtoFF )
{
long candilocleft = path->nodeLocationInClockPath('s', dcccandi.at(loop).back() /*Clk node*/ );//location id, 's' mean start clk path
long candilocright = path->nodeLocationInClockPath('e', dcccandi.at(loop).back() /*Clk node*/ );//location id, 'e' mean end clk path
long sameparentloc = path->nodeLocationInClockPath('s', path->findLastSameParentNode());
// Insert one DCC
if( dcccandi.at(loop).size() == 1 )
{
// Insert DCC on common node
if((candilocleft != -1) && (candilocleft <= sameparentloc))
{
// Calculate the Ci and Cj
citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), dcccandi.at(loop).front());
cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), dcccandi.at(loop).front());
//citime.at(0), put 20% DCC on the location of dcccandi.at(loop).front()
//citime.at(1), put 40% DCC on the location of dcccandi.at(loop).front()
//citime.at(2), put 80% DCC on the location of dcccandi.at(loop).front()
// Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC
this->assessTimingWithDcc(path, citime.at(0), cjtime.at(0), 20, 20, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(1), cjtime.at(1), 40, 40, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(2), cjtime.at(2), 80, 80, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath());
}
// Insert DCC on the branch part of right clk path:OK
else if( candilocleft < candilocright )
{
double newcitime = 0;
// Calculate the Ci and Cj
this->calculateClockLatencyWithoutDcc( path, nullptr, &newcitime );
cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), dcccandi.at(loop).front());
// Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC
// Generate clause here:
this->assessTimingWithDcc(path, newcitime, cjtime.at(0), 20, 0, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath(), path->getStartPonitClkPath());
this->assessTimingWithDcc(path, newcitime, cjtime.at(1), 40, 0, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath(), path->getStartPonitClkPath());
this->assessTimingWithDcc(path, newcitime, cjtime.at(2), 80, 0, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath(), path->getStartPonitClkPath());
}
// Insert DCC on the branch part of left clk path:OK
else if(candilocleft > candilocright)
{
double newcjtime = 0;
// Calculate the Ci and Cj
this->calculateClockLatencyWithoutDcc(path, &newcjtime, nullptr);
citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), dcccandi.at(loop).front());
// Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC
this->assessTimingWithDcc(path, citime.at(0), newcjtime, 20, 0, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(1), newcjtime, 40, 0, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(2), newcjtime, 80, 0, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath());
}
}
// Insert two DCCs:OK
else if( dcccandi.at(loop).size() == 2 )
{
// Calculate the Ci and Cj
citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), dcccandi.at(loop).front());
cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), dcccandi.at(loop).back());
// Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC and 20%/40%/80% DCC
// Total 9 combinations
this->assessTimingWithDcc(path, citime.at(0), cjtime.at(0), 20, 20, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(0), cjtime.at(1), 20, 40, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(0), cjtime.at(2), 20, 80, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(1), cjtime.at(0), 40, 20, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(1), cjtime.at(1), 40, 40, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(1), cjtime.at(2), 40, 80, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(2), cjtime.at(0), 80, 20, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(2), cjtime.at(1), 80, 40, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
this->assessTimingWithDcc(path, citime.at(2), cjtime.at(2), 80, 80, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath());
}
}
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Assess if the critical path occurs timing violation when inserting
// DCCs (violating the setup time requirement)
// Input parameter:
// citime: clock latency of startpoint
// cjtime: clock latency of endpoint
// dcctype1: type of DCC 1
// dcctype2: type of DCC 2
// candinode1: pointer of DCC 1 (location)
// candinode2: pointer of DCC 2 (location)
// clkpath1: clock path 1 containing DCC 1
// clkpath2: clock path 2 containing DCC 2
// genclause: 0 => do not generate a clause
// 1 (default)=> generate a clause
// update: 0 (default) => do not update the timing information of critical path
// 1 => update the timing information of critical path
//
/////////////////////////////////////////////////////////////////////
double ClockTree::assessTimingWithDcc( CriticalPath *path, double citime, double cjtime, int dcctype1, int dcctype2,
ClockTreeNode *candinode1, ClockTreeNode *candinode2,
vector<ClockTreeNode *> clkpath1, vector<ClockTreeNode *> clkpath2,
bool genclause, bool update )
{
double newslack = 0, dataarrtime = 0, datareqtime = 0;
// Require time
datareqtime = cjtime + (path->getTsu() * this->_agingtsu) + this->_tc;
// Arrival time
dataarrtime = citime + path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij);
newslack = datareqtime - dataarrtime;
if( update )
{
path->setCi(citime), path->setCj(cjtime);
path->setArrivalTime(dataarrtime) ;
path->setRequiredTime(datareqtime) ;
path->setSlack(newslack) ;
}
//---- Timing violationprint -----------
if( (newslack < 0) && genclause )
{
string clause;
// Deal with two type of critical path (PItoFF and FFtoPO)
if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO))
{
// Generate the clause
for( auto const& nodeptr: clkpath1 )
{
if((nodeptr != candinode1) && nodeptr->ifPlacedDcc())
this->writeClauseByDccType(nodeptr, &clause, 0);
else if((nodeptr == candinode1) && nodeptr->ifPlacedDcc())
this->writeClauseByDccType(nodeptr, &clause, dcctype1);
}
}
// Deal with the FF to FF critical path
else if( path->getPathType() == FFtoFF )
{
ClockTreeNode *sameparent = path->findLastSameParentNode();
long sameparentloc = path->nodeLocationInClockPath('s', sameparent);
// Generate the clause based on the clock path 1
for( auto const& nodeptr: clkpath1 )
{
if((nodeptr != candinode1) && nodeptr->ifPlacedDcc())
this->writeClauseByDccType(nodeptr, &clause, 0);
else if((nodeptr == candinode1) && nodeptr->ifPlacedDcc())
this->writeClauseByDccType(nodeptr, &clause, dcctype1);
}
// Generate the clause based on the branch clock path 2
for(long loop = (sameparentloc + 1);loop < clkpath2.size();loop++)
{
if(candinode2 == nullptr)
this->writeClauseByDccType(clkpath2.at(loop), &clause, 0);
else
{
if((clkpath2.at(loop) != candinode2) && (clkpath2.at(loop)->ifPlacedDcc()))
this->writeClauseByDccType(clkpath2.at(loop), &clause, 0);
else if((clkpath2.at(loop) == candinode2) && (clkpath2.at(loop)->ifPlacedDcc()))
this->writeClauseByDccType(clkpath2.at(loop), &clause, dcctype2);
}
}
}
clause += "0";
if(this->_timingconstraintlist.size() < (this->_timingconstraintlist.max_size()-1))
this->_timingconstraintlist.insert(clause);
else
cerr << "\033[32m[Info]: Timing Constraint List Full!\033[0m\n";
}
return newslack;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Calculate the clock latency of the startpoint/endpoint without
// any inserted DCCs
// Input parameter:
// datareqtime: clock latency of the endpoint
// dataarrtime: clock latency of the startpoint
//
/////////////////////////////////////////////////////////////////////
void ClockTree::calculateClockLatencyWithoutDcc(CriticalPath *path, double *datareqtime, double *dataarrtime)
{
if(path == nullptr)
return;
bool dealstart = 0, dealend = 0;
double agingrate = 1;
switch(path->getPathType())
{
// Path type: input to FF
case PItoFF:
dealend = 1;
break;
// Path type: FF to output
case FFtoPO:
dealstart = 1;
break;
// Path type: FF to FF
case FFtoFF:
dealstart = 1;
dealend = 1;
break;
default:
break;
}
// Calculate the clock latency of the startpoint
if(dealstart && (dataarrtime != nullptr))
{
double dutycycle = 0.5;
vector<ClockTreeNode *> sclkpath = path->getStartPonitClkPath();
if(this->_aging)
agingrate = getAgingRateByDutyCycle(dutycycle);
for(long loop = 0;loop < (sclkpath.size() - 1);loop++)
{
*dataarrtime += (sclkpath.at(loop)->getGateData()->getWireTime() + sclkpath.at(loop)->getGateData()->getGateTime()) * agingrate;
// Meet the clock gating cells
if(sclkpath.at(loop)->ifClockGating() && this->_aging)
{
dutycycle = dutycycle * (1 - sclkpath.at(loop)->getGatingProbability());
agingrate = getAgingRateByDutyCycle(dutycycle);
}
}
*dataarrtime += sclkpath.back()->getGateData()->getWireTime() * agingrate;
}
// Calculate the clock latency of the endpoint
if(dealend && (datareqtime != nullptr))
{
double dutycycle = 0.5;
vector<ClockTreeNode *> eclkpath = path->getEndPonitClkPath();
if(this->_aging)
agingrate = getAgingRateByDutyCycle(dutycycle);
for(long loop = 0;loop < (eclkpath.size() - 1);loop++)
{
*datareqtime += (eclkpath.at(loop)->getGateData()->getWireTime() + eclkpath.at(loop)->getGateData()->getGateTime()) * agingrate;
// Meet the clock gating cells
if(eclkpath.at(loop)->ifClockGating() && this->_aging)
{
dutycycle = dutycycle * (1 - eclkpath.at(loop)->getGatingProbability());
agingrate = getAgingRateByDutyCycle(dutycycle);
}
}
*datareqtime += eclkpath.back()->getGateData()->getWireTime() * agingrate;
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Calculate the clock latency of the startpoint/endpoint based on
// specific dcc deployment
// Input parameter:
// clkpath: clock path of the critical path
// candinode: pointer of DCC (location)
//
/////////////////////////////////////////////////////////////////////
vector<double> ClockTree::calculateClockLatencyWithDcc( vector<ClockTreeNode *> clkpath, ClockTreeNode *candinode )
{
vector<double> clklatency(3, 0) ;//Calculate 3 possible latency of 3 DCC
vector<double> oneclklatency(1, 0);
bool isfront = 1 ;
double minbufdelay = 999 ;
double dutycycle20 = 0.5, dutycycle40 = 0.5, dutycycle80 = 0.5, dutycycleondcc = 0.5;
double agingrate20dcc = getAgingRateByDutyCycle(dutycycle20);
double agingrate40dcc = agingrate20dcc ;
double agingrate80dcc = agingrate20dcc ;
for( long loop = 0; loop < (clkpath.size() - 1); loop++ )
{
ClockTreeNode *node = clkpath.at(loop);
//wire_delay + gate_delay
double buftime = node->getGateData()->getWireTime() + node->getGateData()->getGateTime();
// Find the minimization delay of buffer in the clock path
if( node != this->_clktreeroot )
minbufdelay = min( buftime, minbufdelay );
// The node before the DCC (dir: root->FF)
if( isfront )
{
if((node != candinode) && (node->ifClockGating()))
dutycycleondcc = dutycycleondcc * (1 - node->getGatingProbability());
// Meet the DCC
else if(node == candinode)
{
isfront = 0;
dutycycle20 = 0.2 ; dutycycle40 = 0.4 ; dutycycle80 = 0.8 ;
agingrate20dcc = getAgingRateByDutyCycle(dutycycle20);
agingrate40dcc = getAgingRateByDutyCycle(dutycycle40);
agingrate80dcc = getAgingRateByDutyCycle(dutycycle80);
}
}
clklatency.at(0) += buftime * agingrate20dcc;
clklatency.at(1) += buftime * agingrate40dcc;
clklatency.at(2) += buftime * agingrate80dcc;
// Meet the clock gating cells
if(node->ifClockGating())
{
dutycycle20 = dutycycle20 * (1 - node->getGatingProbability());
dutycycle40 = dutycycle40 * (1 - node->getGatingProbability());
dutycycle80 = dutycycle80 * (1 - node->getGatingProbability());
agingrate20dcc = getAgingRateByDutyCycle(dutycycle20);
agingrate40dcc = getAgingRateByDutyCycle(dutycycle40);
agingrate80dcc = getAgingRateByDutyCycle(dutycycle80);
}
}
clklatency.at(0) += clkpath.back()->getGateData()->getWireTime() * agingrate20dcc;
clklatency.at(1) += clkpath.back()->getGateData()->getWireTime() * agingrate40dcc;
clklatency.at(2) += clkpath.back()->getGateData()->getWireTime() * agingrate80dcc;
if( candinode != nullptr )
{
double dccagingrate = getAgingRateByDutyCycle(dutycycleondcc);
clklatency.at(0) += minbufdelay * dccagingrate * DCCDELAY20PA;
clklatency.at(1) += minbufdelay * dccagingrate * DCCDELAY40PA;
clklatency.at(2) += minbufdelay * dccagingrate * DCCDELAY80PA;
if(candinode->getDccType() == 20)
oneclklatency.front() = clklatency.front();
else if(candinode->getDccType() == 40)
oneclklatency.front() = clklatency.at(1);
else if(candinode->getDccType() == 80)
oneclklatency.front() = clklatency.back();
}
if(oneclklatency.front() != 0)
return oneclklatency;
else
return clklatency;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Dump all clauses (DCC constraints and timing constraints) to a
// file
//
/////////////////////////////////////////////////////////////////////
void ClockTree::dumpClauseToCnfFile(void)
{
if( !this->_placedcc ) return ;
fstream cnffile ;
string cnfinput = this->_outputdir + "cnfinput_" + to_string(this->_tc);
if( !isDirectoryExist(this->_outputdir) )
mkdir(this->_outputdir.c_str(), 0775);
if( !isFileExist(cnfinput) )
{
printf( YELLOW"\t[CNF] " RESET"Encoded as %s...\033[0m\n", cnfinput.c_str());
cnffile.open(cnfinput, ios::out | fstream::trunc);
if( !cnffile.is_open() )
{
cerr << RED"\t[Error]: Cannot open " << cnfinput << "\033[0m\n";
cnffile.close();
return;
}
//--- DCC constraint ---------------------------------
for( auto const& clause: this->_dccconstraintlist ) { cnffile << clause << "\n" ; }
//--- Timing constraint -------------------------------
for( auto const& clause: this->_timingconstraintlist ) { cnffile << clause << "\n" ; }
cnffile.close();
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Call MiniSat
//
/////////////////////////////////////////////////////////////////////
void ClockTree::execMinisat(void)
{
if(!this->_placedcc)
return;
// MiniSat input file
string cnfinput = this->_outputdir + "cnfinput_" + to_string(this->_tc);
// MiniSat output file
string cnfoutput = this->_outputdir + "cnfoutput_" + to_string(this->_tc);
if(!isDirectoryExist(this->_outputdir))
mkdir(this->_outputdir.c_str(), 0775);
if(isFileExist(cnfinput))
{
this->_minisatexecnum++;
//string execmd = "minisat " + cnfinput + " " + cnfoutput;
//system(execmd.c_str());
// Fork a process
pid_t childpid = fork();
if(childpid == -1)
cerr << RED"[Error]: Cannot fork child process!\033[0m\n";
else if(childpid == 0)
{
// Child process
string minisatfile = this->_outputdir + "minisat_output";
int fp = open(minisatfile.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0664);
if(fp == -1)
cerr << RED"[Error]: Cannot dump the executive output of minisat!\033[0m\n";
else
{
dup2(fp, STDOUT_FILENO);
dup2(fp, STDERR_FILENO);
close(fp);
}
//this->~ClockTree();
// Call MiniSat
if(execlp("./minisat", "./minisat", cnfinput.c_str(), cnfoutput.c_str(), (char *)0) == -1)
{
cerr << RED"[Error]: Cannot execute minisat!\033[0m\n";
this->_minisatexecnum--;
}
exit(0);
}
else
{
// Parent process
int exitstatus;
waitpid(childpid, &exitstatus, 0);
}
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Change the boundary of Binary search and search for the optimal Tc
//
/////////////////////////////////////////////////////////////////////
void ClockTree::tcBinarySearch(double slack)
{
// Place DCCs
if( this->_placedcc )
{
fstream cnffile;
string line, cnfoutput = this->_outputdir + "cnfoutput_" + to_string(this->_tc);//Minisat results
if( !isFileExist(cnfoutput) )
return;
cnffile.open(cnfoutput, ios::in);
if( !cnffile.is_open() )
{
cerr << RED"\t[Error]: Cannot open " << cnfoutput << "\033[0m\n";
cnffile.close();
return;
}
getline(cnffile, line);
// Change the lower boundary
if((line.size() == 5) && (line.find("UNSAT") != string::npos))
{
this->_tclowbound = this->_tc;
this->_tc = ceilNPrecision((this->_tcupbound + this->_tclowbound) / 2, PRECISION);
printf( YELLOW"\t[Minisat] " RESET "Return: " RED"UNSAT \033[0m\n" ) ;
printf( YELLOW"\t[Binary Search] " RESET"Next Tc range: %f - %f \033[0m\n", _tclowbound, _tcupbound ) ;
}
// Change the upper boundary
else if((line.size() == 3) && (line.find("SAT") != string::npos))
{
this->_besttc = this->_tc;
this->_tcupbound = this->_tc;
this->_tc = floorNPrecision((this->_tcupbound + this->_tclowbound) / 2, PRECISION);
printf( YELLOW"\t[Minisat] " RESET"Return: " GREEN"SAT \033[0m\n" ) ;
printf( YELLOW"\t[Binary Search] " RESET"Next Tc range: %f - %f \033[0m\n", _tclowbound, _tcupbound ) ;
}
cnffile.close();
}
// Do not place DCCs
else if(!this->_placedcc)
{
// Change the lower boundary
if(slack <= 0)
{
this->_tclowbound = this->_tc;
this->_tc = ceilNPrecision((this->_tcupbound + this->_tclowbound) / 2, PRECISION);
}
// Change the upper boundary
else if(slack > 0)
{
this->_besttc = this->_tc;
this->_tcupbound = this->_tc;
this->_tc = floorNPrecision((this->_tcupbound + this->_tclowbound) / 2, PRECISION);
}
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Update timing information of all critical path based on the
// optimal Tc
//
/////////////////////////////////////////////////////////////////////
void ClockTree::updateAllPathTiming(void)
{
if( this->_besttc == 0 )
return;
double minslack = 9999;
this->_tc = this->_besttc;
// Place DCCs
if( this->_placedcc )
{
for( auto const& node: this->_buflist )
node.second->setIfPlaceDcc(0) ;
fstream cnffile;
string line = "" ;
string lastsatfile = this->_outputdir + "cnfoutput_" + to_string(this->_tc);
if( !isFileExist(lastsatfile) )
{
cerr << "\033[31m[Error]: File \"" << lastsatfile << "\" does not found!\033[0m\n";
return;
}
cnffile.open(lastsatfile, ios::in);
if(!cnffile.is_open())
{
cerr << "\033[31m[Error]: Cannot open " << lastsatfile << "\033[0m\n";
cnffile.close();
return;
}
// Get the DCC deployment from the MiniSat output file
getline(cnffile, line);
if( (line.size() == 3) && (line.find("SAT") != string::npos) )
{
getline( cnffile, line ) ;
vector<string> strspl = stringSplit(line, " ");
for( long loop = 0; ; loop += 2 )
{
if( stoi( strspl[loop] ) == 0 )
break ;
if( (stoi(strspl.at(loop)) > 0) || (stoi(strspl.at(loop + 1)) > 0) )
{
ClockTreeNode *findnode = this->searchClockTreeNode(abs(stoi(strspl.at(loop))));
if( findnode != nullptr )
{
findnode->setIfPlaceDcc(1);
findnode->setDccType(stoi(strspl.at(loop)), stoi(strspl.at(loop + 1)));
this->_dcclist.insert(pair<string, ClockTreeNode *> (findnode->getGateData()->getGateName(), findnode));
}
}
}
}
else
{
cerr << "\033[31m[Error]: File \"" << lastsatfile << "\" is not SAT!\033[0m\n";
return;
}
cnffile.close();
for( auto const& path: this->_pathlist )
{
if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF))
continue;
// Update timing information
double slack = this->updatePathTimingWithDcc(path, 1);
if( slack < minslack )
{
this->_mostcriticalpath = path;
minslack = min( slack, minslack );
}
}
}
// Do not place DCCs
else
{
for(auto const& path: this->_pathlist)
{
if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF))
continue;
// Update timing information
double slack = this->assessTimingWithoutDcc(path, 0, 1);
if( slack < minslack )
{
this->_mostcriticalpath = path;
minslack = min(slack, minslack);
}
}
}
// Count the DCCs inserting at final buffer
for(auto const& node: this->_dcclist)
if(node.second->ifPlacedDcc() && node.second->isFinalBuffer())
this->_dccatlastbufnum++;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Minimize the DCC deployment based on the optimal Tc
//
/////////////////////////////////////////////////////////////////////
void ClockTree::minimizeDccPlacement(void)
{
if(!this->_mindccplace || !this->_placedcc || (this->_besttc == 0))
return;
cout << "\033[32m[Info]: Minimizing DCC Placement...\033[0m\n";
cout << "\033[32m Before DCC Placement Minimization\033[0m\n";
this->printDccList();
map<string, ClockTreeNode *> dcclist = this->_dcclist;
map<string, ClockTreeNode *>::iterator finddccptr;
// Reserve the DCCs locate before the critical path dominating the optimal Tc
for(auto const& path: this->_pathlist)
{
ClockTreeNode *sdccnode = nullptr, *edccnode = nullptr;
// If DCC locate in the clock path of startpoint
sdccnode = path->findDccInClockPath('s');
// If DCC locate in the clock path of endpoint
edccnode = path->findDccInClockPath('e');
if(sdccnode != nullptr)
{
finddccptr = dcclist.find(sdccnode->getGateData()->getGateName());
if(finddccptr != dcclist.end())
dcclist.erase(finddccptr);
}
if(edccnode != nullptr)
{
finddccptr = dcclist.find(edccnode->getGateData()->getGateName());
if(finddccptr != dcclist.end())
dcclist.erase(finddccptr);
}
if( path == this->_mostcriticalpath)
break;
}
for(auto const& node: dcclist)
node.second->setIfPlaceDcc(0);
this->_tc = this->_besttc;
// Greedy minimization
while(1)
{
if(dcclist.empty())
break;
bool endflag = 1, findstartpath = 1;
// Reserve one of the rest of DCCs above if one of critical paths occurs timing violation
for(auto const& path: this->_pathlist)
{
if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF))
continue;
// Assess if the critical path occurs timing violation in the DCC deployment
double slack = this->updatePathTimingWithDcc(path, 0);
if(slack < 0)
{
endflag = 0;
for(auto const& node: dcclist)
if(node.second->ifPlacedDcc())
dcclist.erase(node.first);
// Reserve the DCC locate in the clock path of endpoint
for(auto const& node: path->getEndPonitClkPath())
{
finddccptr = dcclist.find(node->getGateData()->getGateName());
if((finddccptr != dcclist.end()) && !finddccptr->second->ifPlacedDcc())
{
finddccptr->second->setIfPlaceDcc(1);
findstartpath = 0;
}
}
// Reserve the DCC locate in the clock path of startpoint
if(findstartpath)
{
for(auto const& node: path->getStartPonitClkPath())
{
finddccptr = dcclist.find(node->getGateData()->getGateName());
if((finddccptr != dcclist.end()) && !finddccptr->second->ifPlacedDcc())
finddccptr->second->setIfPlaceDcc(1);
}
}
break;
}
}
if(endflag)
break;
}
for(auto const& node: this->_dcclist)
{
if(!node.second->ifPlacedDcc())
{
node.second->setDccType(0);
this->_dcclist.erase(node.first);
}
}
this->_dccatlastbufnum = 0;
// Count the DCCs inserting at final buffer
for(auto const& node: this->_dcclist)
if(node.second->ifPlacedDcc() && node.second->isFinalBuffer())
this->_dccatlastbufnum++;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Recheck the optimal Tc if it is minimum
//
/////////////////////////////////////////////////////////////////////
void ClockTree::tcRecheck(void)
{
if(!this->_tcrecheck || (this->_besttc == 0))
return;
cout << "\033[32m[Info]: Rechecking Tc...\033[0m\n";
cout << "\033[32m Before Tc Rechecked\033[0m\n";
cout << "\t*** Optimal tc : \033[36m" << this->_besttc << "\033[0m\n";
if(this->_mostcriticalpath->getSlack() < 0)
this->_besttc += ceilNPrecision(abs(this->_mostcriticalpath->getSlack()), PRECISION);
double oribesttc = this->_besttc;
while(1)
{
bool endflag = 0;
// Decrease the optimal Tc
this->_tc = this->_besttc - (1 / pow(10, PRECISION));
if(this->_tc < 0)
break;
// Assess if the critical path occurs timing violation
for(auto const& path: this->_pathlist)
{
if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF))
continue;
double slack = 0;
if(this->_placedcc)
slack = this->updatePathTimingWithDcc(path, 0);
else
slack = this->assessTimingWithoutDcc(path, 0, 0);
if(slack < 0)
{
endflag = 1;
break;
}
}
if(endflag)
break;
this->_besttc = this->_tc;
}
if(oribesttc == this->_besttc)
return;
this->_tc = this->_besttc;
// Update timing information of all critical path based on the new optimal Tc
for(auto const& path: this->_pathlist)
{
if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF))
continue;
if(this->_placedcc)
this->updatePathTimingWithDcc(path, 1);
else
this->assessTimingWithoutDcc(path, 0, 1);
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Insert buffers based on the optimal Tc determined by DCC insertion
//
/////////////////////////////////////////////////////////////////////
void ClockTree::bufferInsertion(void)
{
if((this->_bufinsert < 1) || (this->_bufinsert > 2))
return;
cout << "\033[32m[Info]: Inserting Buffer (Tc = " << this->_besttc << " )...\033[0m\n";
this->_tc = this->_besttc;
for(int counter = 1;;counter++)
{
bool insertflag = 0;
for(auto const& path : this->_pathlist)
{
if((path->getPathType() == NONE) || (path->getPathType() == PItoPO))
continue;
double dataarrtime = 0, datareqtime = 0;
// Calculate the Ci and Cj
this->calculateClockLatencyWithoutDcc(path, &datareqtime, &dataarrtime);
// Require time
datareqtime += (path->getTsu() * this->_agingtsu) + this->_tc;
// Arrival time
dataarrtime += path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij);
if((path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF))
if(!path->getStartPonitClkPath().empty() && path->getStartPonitClkPath().back()->ifInsertBuffer())
dataarrtime += path->getStartPonitClkPath().back()->getInsertBufferDelay();
if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoFF))
if(!path->getEndPonitClkPath().empty() && path->getEndPonitClkPath().back()->ifInsertBuffer())
datareqtime += path->getEndPonitClkPath().back()->getInsertBufferDelay();
// Timing violation
if((datareqtime - dataarrtime) < 0)
{
if(path->getPathType() == FFtoPO)
{
this->_insertbufnum = 0;
return;
}
else
{
// Insert buffer
insertflag = 1;
if(!path->getEndPonitClkPath().back()->ifInsertBuffer())
this->_insertbufnum++;
path->getEndPonitClkPath().back()->setIfInsertBuffer(1);
double delay = path->getEndPonitClkPath().back()->getInsertBufferDelay();
delay = max(delay, (dataarrtime - datareqtime));
path->getEndPonitClkPath().back()->setInsertBufferDelay(delay);
}
}
}
if(!insertflag)
break;
// Check 3 times
if((counter == 3) && insertflag)
{
this->_insertbufnum = 0;
break;
}
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Minimize the inserted buffers
//
/////////////////////////////////////////////////////////////////////
void ClockTree::minimizeBufferInsertion(void)
{
if((this->_bufinsert != 2) || (this->_insertbufnum < 2))
return;
cout << "\033[32m[Info]: Minimizing Buffer Insertion...\033[0m\n";
cout << "\033[32m Before Buffer Insertion Minimization\033[0m\n";
this->printBufferInsertedList();
queue<ClockTreeNode *> nodequeue;
nodequeue.push(this->_firstchildrennode);
// BFS
while(!nodequeue.empty())
{
if(!nodequeue.front()->getChildren().empty())
for(auto const &nodeptr : nodequeue.front()->getChildren())
nodequeue.push(nodeptr);
if(nodequeue.front()->isFFSink())
{
nodequeue.pop();
continue;
}
vector<ClockTreeNode *> ffchildren = this->getFFChildren(nodequeue.front());
set<double, greater<double>> bufdelaylist;
bool continueflag = 0, insertflag = 1;
double adddelay = 0;
// Do not reduce the buffers
for(auto const& nodeptr : ffchildren)
{
if(nodeptr->ifInsertBuffer())
bufdelaylist.insert(nodeptr->getInsertBufferDelay());
else
{
continueflag = 1;
break;
}
}
if(continueflag || bufdelaylist.empty())
{
nodequeue.pop();
continue;
}
// Assess if the buffers can be reduced
for(auto const& bufdelay : bufdelaylist)
{
for(auto const& nodeptr : ffchildren)
{
// Get the critical path by startpoint
vector<CriticalPath *> findpath = this->searchCriticalPath('s', nodeptr->getGateData()->getGateName());
for(auto const& path : findpath)
{
double dataarrtime = 0, datareqtime = 0;
// Calculate the Ci and Cj
this->calculateClockLatencyWithoutDcc(path, &datareqtime, &dataarrtime);
// Require time
datareqtime += (path->getTsu() * this->_agingtsu) + this->_tc;
// Arrival time
dataarrtime += path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij);
for(auto const& clknodeptr : path->getEndPonitClkPath())
{
if((clknodeptr == nodequeue.front()) && (bufdelay >= path->getEndPonitClkPath().back()->getInsertBufferDelay()))
datareqtime += (bufdelay - path->getEndPonitClkPath().back()->getInsertBufferDelay());
if(clknodeptr->ifInsertBuffer())
datareqtime += clknodeptr->getInsertBufferDelay();
}
for(auto const& clknodeptr : path->getStartPonitClkPath())
if(clknodeptr->ifInsertBuffer())
dataarrtime += clknodeptr->getInsertBufferDelay();
if(bufdelay >= nodeptr->getInsertBufferDelay())
dataarrtime += (bufdelay - nodeptr->getInsertBufferDelay());
// Timing violation
if((datareqtime - dataarrtime) < 0)
{
insertflag = 0;
break;
}
}
findpath.clear();
// Get the critical path by endpoint
findpath = this->searchCriticalPath('e', nodeptr->getGateData()->getGateName());
for(auto const& path : findpath)
{
double dataarrtime = 0, datareqtime = 0;
// Calculate the Ci and Cj
this->calculateClockLatencyWithoutDcc(path, &datareqtime, &dataarrtime);
// Require time
datareqtime += (path->getTsu() * this->_agingtsu) + this->_tc;
// Arrival time
dataarrtime += path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij);
for(auto const& clknodeptr : path->getStartPonitClkPath())
{
if((clknodeptr == nodequeue.front()) && (bufdelay >= path->getStartPonitClkPath().back()->getInsertBufferDelay()))
datareqtime += (bufdelay - path->getStartPonitClkPath().back()->getInsertBufferDelay());
if(clknodeptr->ifInsertBuffer())
datareqtime += clknodeptr->getInsertBufferDelay();
}
for(auto const& clknodeptr : path->getEndPonitClkPath())
if(clknodeptr->ifInsertBuffer())
dataarrtime += clknodeptr->getInsertBufferDelay();
if(bufdelay >= nodeptr->getInsertBufferDelay())
dataarrtime += (bufdelay - nodeptr->getInsertBufferDelay());
// Timing violation
if((datareqtime - dataarrtime) < 0)
{
insertflag = 0;
break;
}
}
if(!insertflag)
break;
}
if(insertflag)
{
adddelay = bufdelay;
break;
}
}
// Reduce the buffers
if(insertflag && (adddelay != 0))
{
nodequeue.front()->setIfInsertBuffer(1);
nodequeue.front()->setInsertBufferDelay(adddelay);
this->_insertbufnum++;
for(auto const& nodeptr : ffchildren)
{
if(nodeptr->ifInsertBuffer())
{
double delay = nodeptr->getInsertBufferDelay() - adddelay;
nodeptr->setInsertBufferDelay(delay);
if(delay <= 0)
{
this->_insertbufnum--;
nodeptr->setIfInsertBuffer(0);
nodeptr->setInsertBufferDelay(0);
}
}
}
}
nodequeue.pop();
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Search the node in clock tree with the specific gate name
// Input parameter:
// gatename: specific buffer/FF name
//
/////////////////////////////////////////////////////////////////////
ClockTreeNode *ClockTree::searchClockTreeNode(string gatename)
{
if(gatename.compare(this->_clktreeroot->getGateData()->getGateName()) == 0)
return this->_clktreeroot;
// Search in buffer list
map<string, ClockTreeNode *>::iterator findnode = this->_buflist.find(gatename);
if(findnode != this->_buflist.end())
return findnode->second;
// Search in FF list
findnode = this->_ffsink.find(gatename);
if( findnode != this->_buflist.end() )
return findnode->second;
return NULL ;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Search the node in clock tree with the specific node number
// Input parameter:
// nodenum: specific clock tree node number
//
/////////////////////////////////////////////////////////////////////
ClockTreeNode *ClockTree::searchClockTreeNode(long nodenum)
{
if(nodenum < 0)
return nullptr;
ClockTreeNode *findnode = nullptr;
// Search in buffer list
for(auto const& node: this->_buflist)
{
if(node.second->getNodeNumber() == nodenum)
{
findnode = node.second;
break;
}
}
if(findnode != nullptr)
return findnode;
// Search in FF list
for(auto const& node: this->_ffsink)
{
if(node.second->getNodeNumber() == nodenum)
{
findnode = node.second;
break;
}
}
return findnode;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Search the critical path with the specific startpoint/endpoint
// Input parameter:
// selection: 's' => startpoint
// 'e' => endpoint
// pointname: specific name of startpoint/endpoint
//
/////////////////////////////////////////////////////////////////////
vector<CriticalPath *> ClockTree::searchCriticalPath(char selection, string pointname)
{
vector<CriticalPath *> findpathlist;
if((selection != 's') || (selection != 'e'))
return findpathlist;
for(auto const &pathptr : this->_pathlist)
{
if((pathptr->getPathType() == NONE) || (pathptr->getPathType() == PItoPO))
continue;
string name = "";
switch(selection)
{
// startpoint
case 's':
name = pathptr->getStartPointName();
break;
// endpoint
case 'e':
name = pathptr->getEndPointName();
break;
default:
break;
}
if(pointname.compare(name) == 0)
{
findpathlist.resize(findpathlist.size() + 1);
findpathlist.back() = pathptr;
}
}
return findpathlist;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Report all FFs under the specific clock tree node
//
/////////////////////////////////////////////////////////////////////
vector<ClockTreeNode *> ClockTree::getFFChildren(ClockTreeNode *node)
{
vector<ClockTreeNode *> ffchildren;
if((node == nullptr) || node->isFFSink())
return ffchildren;
queue<ClockTreeNode *> nodequeue;
nodequeue.push(node);
// BFS
while(!nodequeue.empty())
{
if(!nodequeue.front()->getChildren().empty())
for(auto const &nodeptr : nodequeue.front()->getChildren())
nodequeue.push(nodeptr);
if(nodequeue.front()->isFFSink() && nodequeue.front()->ifUsed())
{
ffchildren.resize(ffchildren.size() + 1);
ffchildren.back() = nodequeue.front();
}
nodequeue.pop();
}
return ffchildren;
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Dump to files
// 1. DCC
// 2. Clock gating cell
// 3. Insserted buffer
//
/////////////////////////////////////////////////////////////////////
void ClockTree::dumpToFile(void)
{
this->dumpDccListToFile();
this->dumpClockGatingListToFile();
this->dumpBufferInsertionToFile();
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Print whole clock tree presented in depth
//
/////////////////////////////////////////////////////////////////////
void ClockTree::printClockTree(void)
{
cout << "\033[34m----- [ Clock Tree ] -----\033[0m\n";
if(this->_clktreeroot == nullptr)
{
cout << "\t[Info]: Empty clock tree.\n";
cout << "\033[34m----- [ Clock Tree End ] -----\033[0m\n";
return;
}
long bufnum = 0, ffnum = 0;
queue<ClockTreeNode *> nodequeue;
nodequeue.push(this->_clktreeroot);
cout << "Depth: Node_name(Node_num, if_used, is_cg" << ((this->_placedcc) ? ", place_dcc)\n" : ")\n");
cout << "Depth: (buffer_num, ff_num)\n";
cout << this->_clktreeroot->getDepth() << ": ";
// BFS
while(!nodequeue.empty())
{
long nowdepth = nodequeue.front()->getDepth();
cout << nodequeue.front()->getGateData()->getGateName() << "(" << nodequeue.front()->getNodeNumber() << ", ";
cout << nodequeue.front()->ifUsed() << ", " << nodequeue.front()->ifClockGating();
(this->_placedcc) ? cout << ", " << nodequeue.front()->ifPlacedDcc() << ")" : cout << ")";
if((nodequeue.front() != this->_clktreeroot) && nodequeue.front()->ifUsed())
(nodequeue.front()->isFFSink()) ? ffnum++ : bufnum++;
if(!nodequeue.front()->getChildren().empty())
for(auto const &nodeptr : nodequeue.front()->getChildren())
nodequeue.push(nodeptr);
nodequeue.pop();
if(!nodequeue.empty())
{
if(nowdepth == nodequeue.front()->getDepth())
cout << ", ";
else
{
cout << "\n" << nowdepth << ": (" << bufnum << ", " << ffnum << ")\n";
bufnum = 0, ffnum = 0;
cout << nodequeue.front()->getDepth() << ": ";
}
}
}
cout << "\n" << this->_maxlevel << ": (" << bufnum << ", " << ffnum << ")\n";
cout << "\033[34m----- [ Clock Tree End ] -----\033[0m\n";
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Print one of critical path with given specific critical path
// number
// Input parameter:
// pathnum: specific critical path number
// verbose: 0 => briefness
// 1 => detail
//
/////////////////////////////////////////////////////////////////////
void ClockTree::printSingleCriticalPath(long pathnum, bool verbose)
{
cout << "\033[34m----- [ Single Critical Path ] -----\033[0m\n";
if((pathnum < 0) || (pathnum > this->_pathlist.size()))
cout << "\033[34m[Info]: Path NO." << pathnum << " doesn't exist.\033[0m\n";
else
this->_pathlist.at(pathnum)->printCriticalPath(verbose);
cout << "\033[34m----- [ Single Critical Path end ] -----\033[0m\n";
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Print one of critical path with given a specific
// startpoint/endpoint
// Input parameter:
// selection: 's' => startpoint
// 'e' => endpoint
// pointname: specific name of startpoint/endpoint
// verbose: 0 => briefness
// 1 => detail
//
/////////////////////////////////////////////////////////////////////
void ClockTree::printSingleCriticalPath(char selection, string pointname, bool verbose)
{
cout << "\033[34m----- [ Single Critical Path ] -----\033[0m\n";
vector<CriticalPath *> findpathlist = this->searchCriticalPath(selection, pointname);
if(findpathlist.empty())
cout << "\033[34m[Info]: Ponit name " << pointname << " of path doesn't exist.\033[0m\n";
else
for(auto const& path : findpathlist)
path->printCriticalPath(verbose);
cout << "\033[34m----- [ Single Critical Path end ] -----\033[0m\n";
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Print all critical path information
//
/////////////////////////////////////////////////////////////////////
void ClockTree::printAllCriticalPath(void)
{
cout << "\033[34m----- [ All Critical Paths List ] -----\033[0m\n";
if(this->_pathlist.empty())
{
cout << "\t\033[34m[Info]: Non critical path.\033[0m\n";
cout << "\033[34m----- [ Critical Paths List End ] -----\033[0m\n";
return;
}
for(auto const& pathptr : this->_pathlist)
pathptr->printCriticalPath(0);
cout << "\033[34m----- [ Critical Path List End ] -----\033[0m\n";
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Print all DCC information (location and type)
//
/////////////////////////////////////////////////////////////////////
void ClockTree::printDccList(void)
{
if( !this->_placedcc)
return;
cout << "\t*** # of inserted DCCs : " << this->_dcclist.size() << "\n";
cout << "\t*** # of DCCs placed at last buffer: " << this->_dccatlastbufnum << "\n";
cout << "\t*** Inserted DCCs List : " ;
if( !this->_placedcc || this->_dcclist.empty() )
cout << "N/A\n";
else{
for( auto const& node: this->_dcclist )
cout << node.first << "(" << node.second->getNodeNumber() << ","<< node.second->getDccType() << ((node.second != this->_dcclist.rbegin()->second) ? "), " : ")\n");
cout << endl ;
for( auto const& node: this->_dcclist )
printf("%ld -1 %f\n", (node.second->getNodeNumber()-1)/2*3+1, (double)node.second->getDccType()/100 );
}
cout << "\t*** DCCs Placed at Last Buffer : ";
if(!this->_placedcc || (this->_dccatlastbufnum == 0))
cout << "N/A\n";
else
{
bool firstprint = true;
for(auto const& node: this->_dcclist)
{
if(node.second->isFinalBuffer())
{
if( firstprint ) firstprint = false ;
else cout << "), " ;
cout << node.first << "(" << node.second->getNodeNumber() << ","<< node.second->getDccType();
}
}
cout << ")\n";
}
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Print all clock gating cell information (location and gating
// probability)
//
/////////////////////////////////////////////////////////////////////
void ClockTree::printClockGatingList(void)
{
cout << "\t*** Clock Gating Cells List : ";
if(!this->_clkgating || this->_cglist.empty())
cout << "N/A\n";
else
for(auto const& node: this->_cglist)
cout << node.first << "(" << node.second->getGatingProbability() << ((node.second != this->_cglist.rbegin()->second) ? "), " : ")\n");
}
/////////////////////////////////////////////////////////////////////
//
// ClockTree Class - Public Method
// Print all inserted buffer information (location and buffer delay)
//
/////////////////////////////////////////////////////////////////////
void ClockTree::printBufferInsertedList(void)
{
if((this->_bufinsert < 1) || (this->_bufinsert > 2))
return;
cout << "\t*** # of inserted buffers : " << this->_insertbufnum << "\n";
cout << "\t*** Inserted Buffers List : ";
if((this->_bufinsert < 1) || (this->_bufinsert > 2) || (this->_insertbufnum == 0))
cout << "N/A\n";
else
{
long counter = 0;
// Buffer list
for(auto const& node: this->_buflist)
{
if(node.second->ifInsertBuffer())
{
counter++;
cout << node.first << "(" << node.second->getInsertBufferDelay();
cout << ((counter != this->_insertbufnum) ? "), " : ")\n");
}
}
// FF list
for(auto const& node: this->_ffsink)
{
if(node.second->ifInsertBuffer())
{
counter++;
cout << node.first << "(" << node.second->getInsertBufferDelay();
cout << ((counter != this->_insertbufnum) ? "), " : ")\n");
}
}
}
}
void ClockTree::printClockNode()
{
//---- Iteration ----------------------------------------------------------------
int nodeID = 0 ;
ClockTreeNode *node = NULL ;
while( true )
{
printf( "---------------------- " CYAN"Print Topology " RESET"----------------------------\n" );
printf(" Clk_Name( nodeID, parentID, " GREEN"O" RESET"/" RED"X" RESET" )\n");
printf( GREEN" O" RESET": those clk nodes that are Not masked\n");
printf( RED " X" RESET": those clk nodes that are masked\n");
printf(" number <= 0 : leave the loop\n");
printf(" number > 0 : The ID of clock node\n");
printf(" Please type the clknode ID:");
cin >> nodeID ;
if( nodeID < 0 ) break ;
else
{
node = searchClockTreeNode( nodeID ) ;
if( node == NULL )
cerr << RED"[ERROR]" RESET<< "The node ID " << nodeID << " is not identified\n" ;
else
printClockNode( node, 0 ) ;
}
}
}
void ClockTree::printClockNode( ClockTreeNode*node, int layer )
{
if( node == NULL ) return ;
else
{
if( node->ifPlacedDcc() == false )
printf( "%s( %4ld, %4ld, " RED "X" RESET" ) ", node->getGateData()->getGateName().c_str(), node->getNodeNumber(), node->getParent()->getNodeNumber());
else
printf( "%s( %4ld, %4ld, " GREEN"O" RESET" ) ", node->getGateData()->getGateName().c_str(), node->getNodeNumber(), node->getParent()->getNodeNumber());
for( int j = 0 ; j < node->getChildren().size(); j++ )
{
if( j != 0 ) printNodeLayerSpace( layer + 1 ) ;
printClockNode( node->getChildren().at(j), layer+1 ) ;
}
cout << endl ;
}
}
void ClockTree::printNodeLayerSpace( int layer )
{
for( int i = 0 ; i < layer ; i++ ) printf( " " );
}
void ClockTree::dumpDcctoFile()
{
FILE *fPtr;
string filename = this->_outputdir + "Dcc_master_" + to_string( this->_tc ) + ".txt";
fPtr = fopen( filename.c_str(), "w" );
if( !fPtr )
{
cerr << RED"[Error]" RESET "Cannot open the DCC VTA file\n" ;
return ;
}
fprintf( fPtr, "Tc %f\n", this->_tc );
for( auto node: this->_buflist )
{
if( node.second->ifPlacedDcc() )
fprintf( fPtr, "%ld -1 %f\n", (node.second->getNodeNumber()-1)/2*3+1, ((float)node.second->getDccType())/100 );
}
fclose(fPtr);
}
| 35.090569 | 183 | 0.585905 | eric830303 |
e2008d82df1cc5f4c02624bdc9428e0024ff98f2 | 3,374 | cpp | C++ | src/ModbusComms/ModbusException.cpp | zhanghongzhi1234/ModbusServerAgent | 2e3bc1e7ef9830331bc2aae697000fecc924a715 | [
"Apache-2.0"
] | null | null | null | src/ModbusComms/ModbusException.cpp | zhanghongzhi1234/ModbusServerAgent | 2e3bc1e7ef9830331bc2aae697000fecc924a715 | [
"Apache-2.0"
] | null | null | null | src/ModbusComms/ModbusException.cpp | zhanghongzhi1234/ModbusServerAgent | 2e3bc1e7ef9830331bc2aae697000fecc924a715 | [
"Apache-2.0"
] | null | null | null | #include "ModbusException.h"
#include "../Utilities/TAAssert.h"
#include <sstream>
#include <string>
#ifdef _WIN32
#include <yvals.h> // warning numbers get enabled in yvals.h
#pragma warning(disable: 4715) // not all control paths return a value
#endif //_WIN32
using TA_Base_Core::BaseException;
using namespace std;
namespace TA_Base_Bus
{
const char ModbusException::FUNCTION_TIMEOUT_ERR = 0x00;
const char ModbusException::ILLEGAL_FUNCTION_ERR = 0x01;
const char ModbusException::ILLEGAL_DATA_ADDRESS_ERR = 0x02;
const char ModbusException::ILLEGAL_DATA_VALUE_ERR = 0x03;
const char ModbusException::SLAVE_DEVICE_FAILURE_ERR = 0x04;
const char ModbusException::ACKNOWLEDGE_ERR = 0x05;
const char ModbusException::SLAVE_DEVICE_BUSY_ERR = 0x06;
const char ModbusException::MEMORY_PARITY_ERR = 0x08;
const char ModbusException::GATEWAY_PATH_UNAVAILABLE_ERR = 0x0A;
const char ModbusException::TARGET_FAILED_TO_RESPOND_ERR = 0x0B;
ModbusException::ModbusException(char errorCode) throw()
: BaseException(getDescription(errorCode)),
m_type(getType(errorCode))
{
}
ModbusException::ModbusException(const std::string& message,
const EModbusFail type) throw()
: BaseException(message), m_type(type)
{
}
ModbusException::~ModbusException() throw()
{
}
string ModbusException::getDescription(char errorCode)
{
stringstream err;
switch (errorCode)
{
case FUNCTION_TIMEOUT_ERR:
return string("The function code executed is timed out in the modbus device.");
case ILLEGAL_FUNCTION_ERR:
return string("The function code requested is not supported in the modbus device.");
case ILLEGAL_DATA_ADDRESS_ERR:
return string("The data address requested does not exist in the modbus device.");
case ILLEGAL_DATA_VALUE_ERR:
return string("The data value is not valid.");
case SLAVE_DEVICE_FAILURE_ERR:
return string("Unrecoverable error occurred in the modbus device.");
case ACKNOWLEDGE_ERR:
return string("The command is in progress.");
case SLAVE_DEVICE_BUSY_ERR:
return string("The modbus device is busy and the command can not be enacted.");
case MEMORY_PARITY_ERR:
return string("A memory parity error occurred in the modbus device.");
case GATEWAY_PATH_UNAVAILABLE_ERR:
return string("The modbus gateway could not connect to the modbus device.");
case TARGET_FAILED_TO_RESPOND_ERR:
return string("The modbus gateway did not get a response from the modbus device.");
default:
err << "Unknown Modbus Error Code 0x" << hex << (0xff & int(errorCode));
return err.str();
}
}
ModbusException::EModbusFail ModbusException::getType(char errorCode)
{
switch (errorCode)
{
case FUNCTION_TIMEOUT_ERR:
return REPLY_TIMEOUT;
case ILLEGAL_FUNCTION_ERR:
return ILLEGAL_FUNCTION;
case ILLEGAL_DATA_ADDRESS_ERR:
return ILLEGAL_DATA_ADDRESS;
case ILLEGAL_DATA_VALUE_ERR:
return ILLEGAL_DATA_VALUE;
case SLAVE_DEVICE_FAILURE_ERR:
return SLAVE_DEVICE_FAILURE;
case ACKNOWLEDGE_ERR:
return ACKNOWLEDGE;
case SLAVE_DEVICE_BUSY_ERR:
return SLAVE_DEVICE_BUSY;
case MEMORY_PARITY_ERR:
return MEMORY_PARITY;
case GATEWAY_PATH_UNAVAILABLE_ERR:
return GATEWAY_PATH_UNAVAILABLE;
case TARGET_FAILED_TO_RESPOND_ERR:
return TARGET_FAILED_TO_RESPOND;
default:
return UNKNOWN_MODBUS_EXCEPTION;
}
}
}
| 25.755725 | 87 | 0.763485 | zhanghongzhi1234 |
e203ea0a1c00fa15d3876e1ffe8d401c16c18701 | 416 | hpp | C++ | path.hpp | andybarry/peekmill | d990877ef943a791f66d19ed897f1421b8e6e0ea | [
"BSD-3-Clause"
] | 1 | 2016-08-22T13:46:32.000Z | 2016-08-22T13:46:32.000Z | path.hpp | andybarry/peekmill | d990877ef943a791f66d19ed897f1421b8e6e0ea | [
"BSD-3-Clause"
] | null | null | null | path.hpp | andybarry/peekmill | d990877ef943a791f66d19ed897f1421b8e6e0ea | [
"BSD-3-Clause"
] | null | null | null | #ifndef PATH_HPP
#define PATH_HPP
#include <opencv2/core/core.hpp>
#include <vector>
#include <iostream>
using namespace std;
using namespace cv;
class Path{
private:
Point2f path_start_;
float units_;
vector<Point2f> coords_; //like java generics
public:
Point2f GetPathStart(){return path_start_;}
float GetUnits(){return units_;}
Mat Draw(Mat image_in);
Path();//add parameters
};
#endif
| 16 | 47 | 0.725962 | andybarry |
e2050c55b5ad0efa8af19c8c4913c54c1a7d0cf0 | 4,341 | cpp | C++ | lib/ZumoShield/ZumoShieldEncoders.cpp | Wataru-Oshima-Tokyo/zumoShield | 7d1c24c8fc6e3c95fe326923cf48215604ad3fc7 | [
"MIT"
] | null | null | null | lib/ZumoShield/ZumoShieldEncoders.cpp | Wataru-Oshima-Tokyo/zumoShield | 7d1c24c8fc6e3c95fe326923cf48215604ad3fc7 | [
"MIT"
] | null | null | null | lib/ZumoShield/ZumoShieldEncoders.cpp | Wataru-Oshima-Tokyo/zumoShield | 7d1c24c8fc6e3c95fe326923cf48215604ad3fc7 | [
"MIT"
] | null | null | null | // Copyright Pololu Corporation. For more information, see http://www.pololu.com/
#include <ZumoShieldEncoders.h>
#include <FastGPIO.h>
#include <avr/interrupt.h>
#include <Arduino.h>
#define LEFT_XOR 8
#define LEFT_B IO_E2
#define RIGHT_XOR 7
#define RIGHT_B 23
#define RIGHT_CNT_FLAG 0x0001
#define LEFT_CNT_FLAG 0x0002
static volatile bool lastLeftA;
static volatile bool lastLeftB;
static volatile bool lastRightA;
static volatile bool lastRightB;
static volatile bool errorLeft;
static volatile bool errorRight;
// These count variables are uint16_t instead of int16_t because
// signed integer overflow is undefined behavior in C++.
static volatile uint16_t countLeft;
static volatile uint16_t countRight;
// int countLeft=0;
// int countRight=0;
int flag = 0;
ISR(TIMER1_CAPT_vect)
{
bit_is_clear(TIFR1, ICF1);
if (digitalRead(5) == HIGH) {
countRight++;
} else {
countRight--;
}
flag |= RIGHT_CNT_FLAG;
}
ISR(TIMER3_CAPT_vect)
{
bit_is_clear(TIFR3, ICF3);
if (digitalRead(11) == LOW) {
countLeft++;
} else {
countLeft--;
}
flag |= LEFT_CNT_FLAG;
}
// static void rightISR()
// {
// bool newRightB = FastGPIO::Pin<RIGHT_B>::isInputHigh();
// bool newRightA = FastGPIO::Pin<RIGHT_XOR>::isInputHigh() ^ newRightB;
// countRight += (newRightA ^ lastRightB) - (lastRightA ^ newRightB);
// if((lastRightA ^ newRightA) & (lastRightB ^ newRightB))
// {
// errorRight = true;
// }
// lastRightA = newRightA;
// lastRightB = newRightB;
// }
void ZumoShieldEncoders::init2()
{
// Set the pins as pulled-up inputs.
FastGPIO::Pin<LEFT_XOR>::setInputPulledUp();
FastGPIO::Pin<LEFT_B>::setInputPulledUp();
FastGPIO::Pin<RIGHT_XOR>::setInputPulledUp();
FastGPIO::Pin<RIGHT_B>::setInputPulledUp();
// Enable pin-change interrupt on PB4 for left encoder, and disable other
// pin-change interrupts.
PCICR = (1 << PCIE0);
PCMSK0 = (1 << PCINT4);
PCIFR = (1 << PCIF0); // Clear its interrupt flag by writing a 1.
/*
* ICP1はアナログコンパレータと機能を兼用しているので
* それをDISABLEとする。
* 「0」でENABLE、「1」でDISABLE
*/
ACSR = 0x80;
ADCSRB = 0x00;
DIDR1 = 0x00;
/*
* ICP1(インプットキャプチャー)の設定
*/
TCCR1A= 0x00;
TCCR1B = 0x41; // Disable Input Capture Noise Canceler
// Input Capture Edge : RISE
TIMSK1 = 0x20; // Enable Input Capture Interrupt
/*
* ICP3(インプットキャプチャー)の設定
*/
TCCR3A= 0x00;
TCCR3B = 0x41; // Disable Input Capture Noise Canceler
// Input Capture Edge : RISE
TIMSK3 = 0x20; // Enable Input Capture Interrupt
/*
* DEBUGにシリアルモニタを使用
*/
// Enable interrupt on PE6 for the right encoder. We use attachInterrupt
// instead of defining ISR(INT6_vect) ourselves so that this class will be
// compatible with other code that uses attachInterrupt.
//attachInterrupt(4, rightISR, CHANGE);
// Initialize the variables. It's good to do this after enabling the
// interrupts in case the interrupts fired by accident as we were enabling
// them.
lastLeftB = FastGPIO::Pin<LEFT_B>::isInputHigh();
lastLeftA = FastGPIO::Pin<LEFT_XOR>::isInputHigh() ^ lastLeftB;
countLeft = 0;
errorLeft = 0;
lastRightB = FastGPIO::Pin<RIGHT_B>::isInputHigh();
lastRightA = FastGPIO::Pin<RIGHT_XOR>::isInputHigh() ^ lastRightB;
countRight = 0;
errorRight = 0;
}
int16_t ZumoShieldEncoders::getCountsLeft()
{
init();
cli();
int16_t counts = countLeft;
sei();
return counts;
}
int16_t ZumoShieldEncoders::getCountsRight()
{
init();
cli();
int16_t counts = countRight;
sei();
return counts;
}
int16_t ZumoShieldEncoders::getCountsAndResetLeft()
{
init();
cli();
int16_t counts = countLeft;
countLeft = 0;
sei();
return counts;
}
int16_t ZumoShieldEncoders::getCountsAndResetRight()
{
init();
cli();
int16_t counts = countRight;
countRight = 0;
sei();
return counts;
}
bool ZumoShieldEncoders::checkErrorLeft()
{
init();
bool error = errorLeft;
errorLeft = 0;
return error;
}
bool ZumoShieldEncoders::checkErrorRight()
{
init();
bool error = errorRight;
errorRight = 0;
return error;
}
| 23.464865 | 82 | 0.647086 | Wataru-Oshima-Tokyo |
e205c4c55429116611d8dde8aa76508a5d462f35 | 1,692 | cc | C++ | src/common/base/time_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 1,821 | 2020-04-08T00:45:27.000Z | 2021-09-01T14:56:25.000Z | src/common/base/time_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 142 | 2020-04-09T06:23:46.000Z | 2021-08-24T06:02:12.000Z | src/common/base/time_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 105 | 2021-09-08T10:26:50.000Z | 2022-03-29T09:13:36.000Z | /*
* Copyright 2018- The Pixie Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <gtest/gtest.h>
#include "src/common/base/time.h"
#include "src/common/testing/testing.h"
namespace px {
TEST(StringToRange, basic) {
ASSERT_OK_AND_ASSIGN(auto output_pair, StringToTimeRange("5,20"));
EXPECT_EQ(5, output_pair.first);
EXPECT_EQ(20, output_pair.second);
}
TEST(StringToRange, invalid_format) { ASSERT_NOT_OK(StringToTimeRange("hi")); }
TEST(StringToTime, basic) {
EXPECT_OK_AND_EQ(StringToTimeInt("-2m"), -120000000000);
EXPECT_OK_AND_EQ(StringToTimeInt("2m"), 120000000000);
EXPECT_OK_AND_EQ(StringToTimeInt("-10s"), -10000000000);
EXPECT_OK_AND_EQ(StringToTimeInt("10d"), 864000000000000);
EXPECT_OK_AND_EQ(StringToTimeInt("5h"), 18000000000000);
EXPECT_OK_AND_EQ(StringToTimeInt("10ms"), 10000000);
}
TEST(StringToTime, invalid_format) { EXPECT_FALSE(StringToTimeInt("hello").ok()); }
TEST(PrettyDuration, strings) {
EXPECT_EQ("1.23 \u03BCs", PrettyDuration(1230));
EXPECT_EQ("14.56 ms", PrettyDuration(14561230));
EXPECT_EQ("14.56 s", PrettyDuration(14561230000));
}
} // namespace px
| 32.538462 | 83 | 0.74409 | hangqiu |
e206e29c72baee3fd6a679c5b12cfab20e8e7c49 | 418 | cpp | C++ | Challenges/C++/ex2.cpp | ifyGecko/RE_Challenges | a7a86481d9a75d0dde81de77716ea42c81ce3d69 | [
"Unlicense"
] | 5 | 2019-08-24T00:19:42.000Z | 2020-09-26T14:21:07.000Z | Challenges/C++/ex2.cpp | DJN1/RE_Challenges-1 | 4bc66ed6d8765f044322b297b69a156e2385d19f | [
"Unlicense"
] | 1 | 2022-02-16T18:05:15.000Z | 2022-02-16T18:05:15.000Z | Challenges/C++/ex2.cpp | DJN1/RE_Challenges-1 | 4bc66ed6d8765f044322b297b69a156e2385d19f | [
"Unlicense"
] | 9 | 2019-08-31T21:10:31.000Z | 2020-09-14T23:13:10.000Z | #include<iostream>
#include<cstdlib>
using namespace std;
class a{
public:
int b;
a(){ b=2019; };
};
int main(int argc, char** argv){
a c;
if(argc !=2){
cout << "Usage: ./prog input\n";
cout << "Hint: ./prog -h\n";
}else if(argv[1]==string("-h")){
cout << "Classes might need to undergo construction.\n";
}else{
atoi(argv[1])==c.b?cout << "Score!\n":cout << "Fail!\n";
}
return 0;
}
| 17.416667 | 60 | 0.557416 | ifyGecko |
e20956abe78d0338cd55dac2fa01cca43e31856c | 503 | cc | C++ | function_ref/snippets/snippet-function_ref-spec-rev.cc | descender76/cpp_proposals | 2eb7e2f59257b376dadd1b66464e076c3de23ab1 | [
"BSL-1.0"
] | 1 | 2022-01-21T20:10:46.000Z | 2022-01-21T20:10:46.000Z | function_ref/snippets/snippet-function_ref-spec-rev.cc | descender76/cpp_proposals | 2eb7e2f59257b376dadd1b66464e076c3de23ab1 | [
"BSL-1.0"
] | null | null | null | function_ref/snippets/snippet-function_ref-spec-rev.cc | descender76/cpp_proposals | 2eb7e2f59257b376dadd1b66464e076c3de23ab1 | [
"BSL-1.0"
] | null | null | null | //
namespace std
{
template <typename Signature>
class function_ref
{
void* erased_object;
R(*erased_function)(void*, Args...);
// `R`, and `Args...` are the return type, and the parameter-type-list,
// of the function type `Signature`, respectively.
public:
function_ref(void* obj_, R (*callback_)(void*,Args...)) noexcept : erased_object{obj_}, erased_function{callback_} {}
function_ref(const function_ref&) noexcept = default;
// ... | 31.4375 | 125 | 0.630219 | descender76 |
e20b30fbf131c7e7f69f867433bdfef197d5a881 | 1,195 | hpp | C++ | kjoin/src/util/util_func.hpp | lanpay-lulu/CPP-Intersection | 2326a9f46a4d75d11ca0e20adab91b0acb8bcea0 | [
"MIT"
] | null | null | null | kjoin/src/util/util_func.hpp | lanpay-lulu/CPP-Intersection | 2326a9f46a4d75d11ca0e20adab91b0acb8bcea0 | [
"MIT"
] | null | null | null | kjoin/src/util/util_func.hpp | lanpay-lulu/CPP-Intersection | 2326a9f46a4d75d11ca0e20adab91b0acb8bcea0 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <fstream>
#include <sys/time.h>
namespace wshfunc{
size_t get_line_cnt(std::string & filename) {
std::ifstream infile(filename);
size_t cnt = std::count(std::istreambuf_iterator<char>(infile),
std::istreambuf_iterator<char>(), '\n');
infile.close();
return cnt;
}
bool is_file_empty(std::string & filename) {
std::string line;
std::ifstream fin(filename);
while (std::getline(fin, line)) {
if(line.length() > 2) {
fin.close();
return false;
}
}
fin.close();
return true;
}
size_t gettime() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000 + tv.tv_usec/1000;
}
std::vector<std::string> split(std::string str, std::string delimeter) {
std::vector<std::string> vec;
size_t startIndex = 0;
size_t endIndex = 0;
while( (endIndex = str.find(delimeter, startIndex)) < str.size() ) {
std::string val = str.substr(startIndex, endIndex - startIndex);
vec.push_back(val);
startIndex = endIndex + delimeter.size();
}
if(startIndex < str.size()) {
std::string val = str.substr(startIndex);
vec.push_back(val);
}
return vec;
}
}; // end of namespace | 22.54717 | 72 | 0.661088 | lanpay-lulu |
e20e3b57956618c03b09418745bb03ff0b3989bd | 4,484 | cpp | C++ | src/arch/android/platform_android.cpp | nebular/PixEngine_core | fc5f928641ed8c0d14254fdfc68973b3b144297f | [
"BSD-3-Clause"
] | 1 | 2020-10-23T21:16:49.000Z | 2020-10-23T21:16:49.000Z | src/arch/android/platform_android.cpp | nebular/PixEngine_core | fc5f928641ed8c0d14254fdfc68973b3b144297f | [
"BSD-3-Clause"
] | 2 | 2020-03-02T22:43:09.000Z | 2020-03-02T22:46:44.000Z | src/arch/android/platform_android.cpp | nebular/PixFu | fc5f928641ed8c0d14254fdfc68973b3b144297f | [
"BSD-3-Clause"
] | null | null | null | #ifdef ANDROID
//
// Created by rodo on 2020-01-24.
//
#include "Fu.hpp"
#include "Mouse.hpp"
#include "Keyboard.hpp"
#include "platform_android.hpp"
#include "OpenGlUtils.h"
#include "Utils.hpp"
#include "androidapi.h"
#include "VirtualKeys.hpp"
#include <iostream>
namespace Pix {
void LogV(const std::string &tag, std::string text) {
ALOGV("[V:%s] %s", tag.c_str(), text.c_str());
}
void LogE(const std::string &tag, std::string text) {
ALOGE("[E:%s] %s", tag.c_str(), text.c_str());
}
static constexpr int ACTION_UP = 1;
static constexpr int ACTION_DOWN = 0;
static constexpr int ACTION_MOVE = 2;
static constexpr int ACTION_CANCEL = 3;
// other than primary finger
static constexpr int ACTION_POINTER_DOWN = 5;
static constexpr int ACTION_POINTER_UP = 6;
PixFuPlatformAndroid::PixFuPlatformAndroid(Fu *bootInstance) {
OpenGlUtils::VERSION = "v300es";
pBootInstance = bootInstance;
}
PixFuPlatformAndroid::~PixFuPlatformAndroid() {
deinit();
}
bool PixFuPlatformAndroid::init(Fu *engine) {
Mouse::enable();
Keyboard::enable();
VirtualKeys::enable({ Colors::WHITE, 1, true});
cLoneKeys = VirtualKeys::instance();
cLoneKeys->reset();
return true;
}
std::pair<bool, bool> PixFuPlatformAndroid::events() {
// onpause will route here
bool focused = true; // window_is_focused();
bool active = true; // !get_window_is_closing();
return {active, focused};
}
void PixFuPlatformAndroid::commit() {
// no frame commit, android does that after returning from tick
}
void PixFuPlatformAndroid::deinit() {
// something will come here for sure
}
void PixFuPlatformAndroid::onFps(Fu *engine, int fps) {
std::string sTitle = "PixFu - FPS: " + std::to_string(fps);
}
void Mouse::poll() {
// already done
}
void Keyboard::poll() {
}
void Fu::start() {
// this platform does not run a loop
}
// called from Launcher to send a MotionEvent (Touch)
void PixFuPlatformAndroid::inputMotionEvent(MotionEvent_t event) {
Mouse *mouse = Mouse::instance();
if (mouse == nullptr) return;
// we have touch information
// lets simulate a mouse
//
// I tried an elaborate routine to simulate clicks on touch but it was getting too complicated and prone to fail
// I came up with this simple approach that kind of works pretty well. It uses LoneKeys to paint
// 2 virtual mouse buttons on screen, and multitouch is supported so you can move the pointer with one finger
// and use the buttons with other. For implementing another mouse behavior, you have all details in tCurrentMotionEvent
//
tCurrentMotionEvent = event;
int action = event.RawAction;
// Iterate through virtual keys and set their state.
// will return 0 -> key pressed with primary pointer (X0Y0), 1 -> with secondary (X1Y1), -1 No key pressed.
int keysRegion = cLoneKeys->input(tCurrentMotionEvent.X0, tCurrentMotionEvent.Y0,
tCurrentMotionEvent.X1, tCurrentMotionEvent.Y1,
tCurrentMotionEvent.Action == ACTION_UP);
bool twoFingers = event.PointersCount > 1;
// LogV ("ANDR", SF("Event: buttons %d, action %d, index %d", tCurrentMotionEvent.PointersCount, tCurrentMotionEvent.RawAction, tCurrentMotionEvent.PointerId));
switch (action) {
case ACTION_POINTER_UP:
for (int i = 0; i < mouse->BUTTONS; i++)
mouse->inputButton(i, false);
break;
case ACTION_UP:
case ACTION_CANCEL:
// end touch (no fingers on screen)
// reset virtual mouse button status
cLoneKeys->reset();
// break through to update coordinates and real state (that we have reset here)
case ACTION_DOWN:
case ACTION_POINTER_DOWN:
if (twoFingers)
for (int i = 0; i < mouse->BUTTONS; i++)
mouse->inputButton(i, cLoneKeys->GetFakeMouse(i));
case ACTION_MOVE:
// These actions update the engine mouse button status from
// our local copy in cLoneKeys
if (twoFingers)
for (int i = 0; i < mouse->BUTTONS; i++)
mouse->inputButton(i, cLoneKeys->GetFakeMouse(i));
// then updates the right coordinates: One of them is the finger in the buttons area,
// the other the pointer finger. We select the right one !
if (keysRegion != 0)
mouse->input(tCurrentMotionEvent.X0, tCurrentMotionEvent.Y0);
else if (twoFingers) // may happen that only one finger is pressing buttons but none is pointing
mouse->input(tCurrentMotionEvent.X1, tCurrentMotionEvent.Y1);
break;
default:
break;
}
}
}
#endif
| 25.919075 | 161 | 0.695584 | nebular |
e20f94442b3d6cf4ae6ef4cb320e22ad706dee5f | 11,268 | cpp | C++ | SphereNormals.cpp | Svengali/cblib | 77ddfd452cff842575750b9e6d792790f5ec5fee | [
"Zlib"
] | 1 | 2021-05-01T04:34:24.000Z | 2021-05-01T04:34:24.000Z | SphereNormals.cpp | Svengali/cblib | 77ddfd452cff842575750b9e6d792790f5ec5fee | [
"Zlib"
] | null | null | null | SphereNormals.cpp | Svengali/cblib | 77ddfd452cff842575750b9e6d792790f5ec5fee | [
"Zlib"
] | null | null | null | #include "SphereNormals.h"
/**
this is generated by gMakeSphere::Normals()
**/
START_CB
const int c_numSphereNormals = 258;
const int c_numSpherePositiveNormals = 42;
static const float c_sphereVerts[] =
{
0.426401f,0.639602f,0.639602f,
0.639602f,0.639602f,0.426401f,
0.639602f,0.426401f,0.639602f,
0.408248f,0.816497f,0.408248f,
0.816497f,0.408248f,0.408248f,
0.408248f,0.408248f,0.816497f,
0.577350f,0.788675f,0.211325f,
0.211325f,0.577350f,0.788675f,
0.577350f,0.211325f,0.788675f,
0.211325f,0.788675f,0.577350f,
0.788675f,0.577350f,0.211325f,
0.788675f,0.211325f,0.577350f,
0.208847f,0.404615f,0.890320f,
0.404615f,0.208847f,0.890320f,
0.890320f,0.404615f,0.208847f,
0.404615f,0.890320f,0.208847f,
0.890320f,0.208847f,0.404615f,
0.208847f,0.890320f,0.404615f,
0.198757f,0.198757f,0.959683f,
0.959683f,0.198757f,0.198757f,
0.198757f,0.959683f,0.198757f,
0.000000f,0.707107f,0.707107f,
0.707107f,0.707107f,0.000000f,
0.707107f,0.000000f,0.707107f,
0.555570f,0.831470f,0.000000f,
0.555570f,0.000000f,0.831470f,
0.000000f,0.555570f,0.831470f,
0.831470f,0.000000f,0.555570f,
0.831470f,0.555570f,0.000000f,
0.000000f,0.831470f,0.555570f,
0.923880f,0.382683f,0.000000f,
0.382683f,0.923880f,0.000000f,
0.382683f,0.000000f,0.923880f,
0.000000f,0.382683f,0.923880f,
0.923880f,0.000000f,0.382683f,
0.000000f,0.923880f,0.382683f,
0.195090f,0.980785f,0.000000f,
0.195090f,0.000000f,0.980785f,
0.000000f,0.195090f,0.980785f,
0.980785f,0.195090f,0.000000f,
0.000000f,0.980785f,0.195090f,
0.980785f,0.000000f,0.195090f,
0.577350f,-0.211325f,0.788675f,
0.788675f,0.577350f,-0.211325f,
0.577350f,0.788675f,-0.211325f,
0.788675f,-0.211325f,0.577350f,
-0.211325f,0.788675f,0.577350f,
-0.211325f,0.577350f,0.788675f,
0.404615f,0.890320f,-0.208847f,
0.404615f,-0.208847f,0.890320f,
0.890320f,0.404615f,-0.208847f,
0.890320f,-0.208847f,0.404615f,
-0.208847f,0.404615f,0.890320f,
-0.208847f,0.890320f,0.404615f,
0.000000f,0.000000f,1.000000f,
0.000000f,1.000000f,0.000000f,
1.000000f,0.000000f,0.000000f,
-0.198757f,0.959683f,0.198757f,
0.959683f,0.198757f,-0.198757f,
0.198757f,0.959683f,-0.198757f,
-0.198757f,0.198757f,0.959683f,
0.198757f,-0.198757f,0.959683f,
0.959683f,-0.198757f,0.198757f,
0.639602f,0.639602f,-0.426401f,
0.639602f,-0.426401f,0.639602f,
-0.426401f,0.639602f,0.639602f,
0.408248f,0.816497f,-0.408248f,
-0.408248f,0.408248f,0.816497f,
0.816497f,-0.408248f,0.408248f,
-0.408248f,0.816497f,0.408248f,
0.816497f,0.408248f,-0.408248f,
0.408248f,-0.408248f,0.816497f,
-0.404615f,0.890320f,0.208847f,
0.890320f,-0.404615f,0.208847f,
-0.404615f,0.208847f,0.890320f,
0.890320f,0.208847f,-0.404615f,
0.208847f,0.890320f,-0.404615f,
0.208847f,-0.404615f,0.890320f,
-0.639602f,0.426401f,0.639602f,
0.639602f,-0.639602f,0.426401f,
0.426401f,0.639602f,-0.639602f,
-0.639602f,0.639602f,0.426401f,
0.426401f,-0.639602f,0.639602f,
0.639602f,0.426401f,-0.639602f,
0.211325f,-0.577350f,0.788675f,
-0.577350f,0.211325f,0.788675f,
0.211325f,0.788675f,-0.577350f,
0.788675f,0.211325f,-0.577350f,
0.788675f,-0.577350f,0.211325f,
-0.577350f,0.788675f,0.211325f,
0.408248f,0.408248f,-0.816497f,
-0.816497f,0.408248f,0.408248f,
0.408248f,-0.816497f,0.408248f,
0.211325f,-0.788675f,0.577350f,
0.211325f,0.577350f,-0.788675f,
0.577350f,-0.788675f,0.211325f,
-0.788675f,0.577350f,0.211325f,
-0.788675f,0.211325f,0.577350f,
0.577350f,0.211325f,-0.788675f,
0.404615f,-0.890320f,0.208847f,
0.208847f,-0.890320f,0.404615f,
0.208847f,0.404615f,-0.890320f,
-0.890320f,0.404615f,0.208847f,
0.404615f,0.208847f,-0.890320f,
-0.890320f,0.208847f,0.404615f,
-0.959683f,0.198757f,0.198757f,
0.198757f,-0.959683f,0.198757f,
0.198757f,0.198757f,-0.959683f,
0.000000f,0.980785f,-0.195090f,
0.000000f,-0.195090f,0.980785f,
-0.195090f,0.000000f,0.980785f,
0.980785f,0.000000f,-0.195090f,
0.980785f,-0.195090f,0.000000f,
-0.195090f,0.980785f,0.000000f,
0.923880f,0.000000f,-0.382683f,
0.923880f,-0.382683f,0.000000f,
-0.382683f,0.000000f,0.923880f,
0.000000f,-0.382683f,0.923880f,
0.000000f,0.923880f,-0.382683f,
-0.382683f,0.923880f,0.000000f,
0.000000f,0.831470f,-0.555570f,
0.000000f,-0.555570f,0.831470f,
0.831470f,-0.555570f,0.000000f,
-0.555570f,0.000000f,0.831470f,
0.831470f,0.000000f,-0.555570f,
-0.555570f,0.831470f,0.000000f,
0.000000f,0.707107f,-0.707107f,
0.707107f,0.000000f,-0.707107f,
-0.707107f,0.000000f,0.707107f,
0.000000f,-0.707107f,0.707107f,
-0.707107f,0.707107f,0.000000f,
0.707107f,-0.707107f,0.000000f,
-0.831470f,0.555570f,0.000000f,
-0.831470f,0.000000f,0.555570f,
0.555570f,-0.831470f,0.000000f,
0.555570f,0.000000f,-0.831470f,
0.000000f,-0.831470f,0.555570f,
0.000000f,0.555570f,-0.831470f,
0.382683f,-0.923880f,0.000000f,
0.382683f,0.000000f,-0.923880f,
0.000000f,-0.923880f,0.382683f,
-0.923880f,0.382683f,0.000000f,
0.000000f,0.382683f,-0.923880f,
-0.923880f,0.000000f,0.382683f,
-0.980785f,0.195090f,0.000000f,
-0.980785f,0.000000f,0.195090f,
0.000000f,0.195090f,-0.980785f,
0.195090f,0.000000f,-0.980785f,
0.195090f,-0.980785f,0.000000f,
0.000000f,-0.980785f,0.195090f,
-0.198757f,-0.198757f,0.959683f,
-0.198757f,0.959683f,-0.198757f,
0.959683f,-0.198757f,-0.198757f,
0.890320f,-0.404615f,-0.208847f,
0.890320f,-0.208847f,-0.404615f,
-0.404615f,0.890320f,-0.208847f,
-0.404615f,-0.208847f,0.890320f,
-0.208847f,0.890320f,-0.404615f,
-0.208847f,-0.404615f,0.890320f,
-0.211325f,-0.577350f,0.788675f,
-0.577350f,-0.211325f,0.788675f,
-0.211325f,0.788675f,-0.577350f,
0.788675f,-0.577350f,-0.211325f,
0.788675f,-0.211325f,-0.577350f,
-0.577350f,0.788675f,-0.211325f,
0.816497f,-0.408248f,-0.408248f,
-0.408248f,-0.408248f,0.816497f,
-0.408248f,0.816497f,-0.408248f,
-0.788675f,-0.211325f,0.577350f,
0.577350f,-0.211325f,-0.788675f,
0.577350f,-0.788675f,-0.211325f,
-0.788675f,0.577350f,-0.211325f,
-0.211325f,0.577350f,-0.788675f,
-0.211325f,-0.788675f,0.577350f,
-0.639602f,-0.426401f,0.639602f,
-0.426401f,-0.639602f,0.639602f,
0.639602f,-0.426401f,-0.639602f,
0.639602f,-0.639602f,-0.426401f,
-0.639602f,0.639602f,-0.426401f,
-0.426401f,0.639602f,-0.639602f,
0.404615f,-0.208847f,-0.890320f,
-0.208847f,-0.890320f,0.404615f,
-0.890320f,0.404615f,-0.208847f,
-0.890320f,-0.208847f,0.404615f,
-0.208847f,0.404615f,-0.890320f,
0.404615f,-0.890320f,-0.208847f,
0.408248f,-0.408248f,-0.816497f,
-0.816497f,0.408248f,-0.408248f,
-0.408248f,0.408248f,-0.816497f,
-0.816497f,-0.408248f,0.408248f,
0.408248f,-0.816497f,-0.408248f,
-0.408248f,-0.816497f,0.408248f,
0.426401f,-0.639602f,-0.639602f,
-0.639602f,0.426401f,-0.639602f,
-0.639602f,-0.639602f,0.426401f,
0.198757f,-0.198757f,-0.959683f,
-0.959683f,0.198757f,-0.198757f,
-0.198757f,-0.959683f,0.198757f,
0.198757f,-0.959683f,-0.198757f,
-0.198757f,0.198757f,-0.959683f,
-0.959683f,-0.198757f,0.198757f,
0.000000f,-1.000000f,0.000000f,
0.000000f,0.000000f,-1.000000f,
-1.000000f,0.000000f,0.000000f,
-0.890320f,0.208847f,-0.404615f,
-0.404615f,0.208847f,-0.890320f,
-0.404615f,-0.890320f,0.208847f,
0.208847f,-0.890320f,-0.404615f,
0.208847f,-0.404615f,-0.890320f,
-0.890320f,-0.404615f,0.208847f,
-0.577350f,-0.788675f,0.211325f,
0.211325f,-0.788675f,-0.577350f,
0.211325f,-0.577350f,-0.788675f,
-0.788675f,-0.577350f,0.211325f,
-0.577350f,0.211325f,-0.788675f,
-0.788675f,0.211325f,-0.577350f,
-0.195090f,0.000000f,-0.980785f,
0.000000f,-0.980785f,-0.195090f,
0.000000f,-0.195090f,-0.980785f,
-0.980785f,-0.195090f,0.000000f,
-0.195090f,-0.980785f,0.000000f,
-0.980785f,0.000000f,-0.195090f,
-0.923880f,-0.382683f,0.000000f,
-0.382683f,-0.923880f,0.000000f,
0.000000f,-0.382683f,-0.923880f,
0.000000f,-0.923880f,-0.382683f,
-0.382683f,0.000000f,-0.923880f,
-0.923880f,0.000000f,-0.382683f,
-0.555570f,0.000000f,-0.831470f,
0.000000f,-0.831470f,-0.555570f,
-0.555570f,-0.831470f,0.000000f,
-0.831470f,0.000000f,-0.555570f,
0.000000f,-0.555570f,-0.831470f,
-0.831470f,-0.555570f,0.000000f,
0.000000f,-0.707107f,-0.707107f,
-0.707107f,-0.707107f,0.000000f,
-0.707107f,0.000000f,-0.707107f,
-0.198757f,-0.959683f,-0.198757f,
-0.198757f,-0.198757f,-0.959683f,
-0.959683f,-0.198757f,-0.198757f,
-0.208847f,-0.890320f,-0.404615f,
-0.890320f,-0.404615f,-0.208847f,
-0.404615f,-0.890320f,-0.208847f,
-0.404615f,-0.208847f,-0.890320f,
-0.890320f,-0.208847f,-0.404615f,
-0.208847f,-0.404615f,-0.890320f,
-0.211325f,-0.788675f,-0.577350f,
-0.577350f,-0.788675f,-0.211325f,
-0.211325f,-0.577350f,-0.788675f,
-0.577350f,-0.211325f,-0.788675f,
-0.788675f,-0.577350f,-0.211325f,
-0.788675f,-0.211325f,-0.577350f,
-0.408248f,-0.408248f,-0.816497f,
-0.408248f,-0.816497f,-0.408248f,
-0.816497f,-0.408248f,-0.408248f,
-0.639602f,-0.639602f,-0.426401f,
-0.639602f,-0.426401f,-0.639602f,
-0.426401f,-0.639602f,-0.639602f
};
static const int c_numSphereVerts = sizeof(c_sphereVerts)/sizeof(c_sphereVerts[0]);
COMPILER_ASSERT(c_numSphereVerts == 3* c_numSphereNormals );
const Vec3 & GetSphereNormal(const int i)
{
ASSERT( i >= 0 && i < c_numSphereNormals );
const float * pF = c_sphereVerts + i*3;
return *( (const Vec3 *)pF );
}
const int c_numSphereNormalsSimple = 66;
static const float c_sphereVertsSimple[] =
{
0.408248f,0.408248f,0.816497f,
0.408248f,0.816497f,0.408248f,
0.816497f,0.408248f,0.408248f,
0.000000f,0.707107f,0.707107f,
0.707107f,0.000000f,0.707107f,
0.707107f,0.707107f,0.000000f,
0.000000f,0.382683f,0.923880f,
0.382683f,0.000000f,0.923880f,
0.000000f,0.923880f,0.382683f,
0.382683f,0.923880f,0.000000f,
0.923880f,0.000000f,0.382683f,
0.923880f,0.382683f,0.000000f,
1.000000f,0.000000f,0.000000f,
0.000000f,1.000000f,0.000000f,
0.000000f,0.000000f,1.000000f,
0.816497f,0.408248f,-0.408248f,
0.408248f,0.816497f,-0.408248f,
-0.408248f,0.816497f,0.408248f,
-0.408248f,0.408248f,0.816497f,
0.408248f,-0.408248f,0.816497f,
0.816497f,-0.408248f,0.408248f,
-0.816497f,0.408248f,0.408248f,
0.408248f,-0.816497f,0.408248f,
0.408248f,0.408248f,-0.816497f,
-0.382683f,0.000000f,0.923880f,
0.000000f,0.923880f,-0.382683f,
-0.382683f,0.923880f,0.000000f,
0.923880f,0.000000f,-0.382683f,
0.000000f,-0.382683f,0.923880f,
0.923880f,-0.382683f,0.000000f,
0.707107f,0.000000f,-0.707107f,
0.000000f,0.707107f,-0.707107f,
0.000000f,-0.707107f,0.707107f,
-0.707107f,0.707107f,0.000000f,
0.707107f,-0.707107f,0.000000f,
-0.707107f,0.000000f,0.707107f,
0.382683f,0.000000f,-0.923880f,
0.000000f,0.382683f,-0.923880f,
0.000000f,-0.923880f,0.382683f,
0.382683f,-0.923880f,0.000000f,
-0.923880f,0.382683f,0.000000f,
-0.923880f,0.000000f,0.382683f,
-0.408248f,-0.408248f,0.816497f,
-0.408248f,0.816497f,-0.408248f,
0.816497f,-0.408248f,-0.408248f,
0.408248f,-0.408248f,-0.816497f,
-0.408248f,0.408248f,-0.816497f,
0.408248f,-0.816497f,-0.408248f,
-0.816497f,0.408248f,-0.408248f,
-0.816497f,-0.408248f,0.408248f,
-0.408248f,-0.816497f,0.408248f,
-1.000000f,0.000000f,0.000000f,
0.000000f,0.000000f,-1.000000f,
0.000000f,-1.000000f,0.000000f,
-0.382683f,0.000000f,-0.923880f,
-0.923880f,0.000000f,-0.382683f,
-0.382683f,-0.923880f,0.000000f,
-0.923880f,-0.382683f,0.000000f,
0.000000f,-0.382683f,-0.923880f,
0.000000f,-0.923880f,-0.382683f,
-0.707107f,-0.707107f,0.000000f,
-0.707107f,0.000000f,-0.707107f,
0.000000f,-0.707107f,-0.707107f,
-0.816497f,-0.408248f,-0.408248f,
-0.408248f,-0.408248f,-0.816497f,
-0.408248f,-0.816497f,-0.408248f
};
const Vec3 & GetSphereNormalSimple(const int i)
{
ASSERT( i >= 0 && i < c_numSphereNormalsSimple );
const float * pF = c_sphereVertsSimple + i*3;
return *( (const Vec3 *)pF );
}
END_CB
| 30.454054 | 83 | 0.741392 | Svengali |
e20fe308ba9db266d014632a95718afebac3e0a7 | 4,067 | cpp | C++ | game/client/tfo/c_achievement_manager.cpp | BerntA/tfo-code | afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1 | [
"MIT"
] | 13 | 2016-04-05T23:23:16.000Z | 2022-03-20T11:06:04.000Z | game/client/tfo/c_achievement_manager.cpp | BerntA/tfo-code | afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1 | [
"MIT"
] | null | null | null | game/client/tfo/c_achievement_manager.cpp | BerntA/tfo-code | afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1 | [
"MIT"
] | 4 | 2016-04-05T23:23:19.000Z | 2021-05-16T05:09:46.000Z | //========= Copyright Bernt Andreas Eide, All rights reserved. ============//
//
// Purpose: Achievement handler & manager.
//
//=============================================================================//
#include "cbase.h"
#include "c_achievement_manager.h"
#include "hud.h"
#include "hud_macros.h"
#include "hudelement.h"
#include "hud_achievement.h"
// Contains a list of available achievements.
const char *GameAchievements[] =
{
"ACH_HEALTHKIT",
"ACH_WEAPON_SPECIAL_1",
"ACH_WEAPON_SPECIAL_2",
"ACH_WEAPON_SPECIAL_3",
"ACH_EASTER_SLENDER",
"ACH_TOURISTS_FRIEND",
"ACH_WEAPON_BASH",
"ACH_DARKBOOK",
"ACH_NPC_BURN",
"ACH_TOURISTS_BETRAY",
"ACH_VENGEANCE",
"ACH_ENDGAME",
};
CAchievementManager::CAchievementManager() : m_CallbackUserStatsReceived(this, &CAchievementManager::OnUserStatsReceived), m_CallbackAchievementStored(this, &CAchievementManager::OnAchievementStored)
{
}
CAchievementManager::~CAchievementManager()
{
}
// Check if we have all the available achievements.
bool CAchievementManager::HasAllAchievements(void)
{
int iCount = 0;
for (int i = 0; i < _ARRAYSIZE(GameAchievements); i++)
{
bool bAchieved = false;
steamapicontext->SteamUserStats()->GetAchievement(GameAchievements[i], &bAchieved);
if (bAchieved)
iCount++;
}
return (iCount >= _ARRAYSIZE(GameAchievements));
}
// Check if a certain achievement has been achieved by the user.
bool CAchievementManager::HasAchievement(const char *szAch, int iID)
{
if (iID >= _ARRAYSIZE(GameAchievements))
return false;
bool bAchieved = false;
const char *szAchievement = szAch;
if (!szAchievement)
szAchievement = GameAchievements[iID];
steamapicontext->SteamUserStats()->GetAchievement(szAchievement, &bAchieved);
return bAchieved;
}
// Set an achievement from 0 to 1 = set to achieved. YOU CAN'T SET THE ACHIEVEMENT PROGRESS HERE.
// To set the achievement progress you must first add a stat and link it to the achievement in Steamworks, increase the stat to see the progress update of the achievement in Steam, etc...
bool CAchievementManager::WriteToAchievement(const char *szAchievement)
{
if (!CanWriteToAchievement(szAchievement))
{
DevMsg("Failed to write to an achievement!\n");
return false;
}
// Do the change.
if (steamapicontext->SteamUserStats()->SetAchievement(szAchievement))
{
// Store the change.
if (!steamapicontext->SteamUserStats()->StoreStats())
DevMsg("Failed to store the achievement!\n");
steamapicontext->SteamUserStats()->RequestCurrentStats();
return true;
}
return false;
}
// Make sure that we can write to the achievements before we actually write so we don't crash the game.
bool CAchievementManager::CanWriteToAchievement(const char *szAchievement)
{
// Make sure that we're connected.
if (!engine->IsInGame())
return false;
// Make sure that we will not write to any achievements if we have cheats enabled.
ConVar *varCheats = cvar->FindVar("sv_cheats");
if (varCheats)
{
if (varCheats->GetBool())
return false;
}
// Make sure our interface is running.
if (!steamapicontext)
return false;
// Make sure that we're logged in.
if (!steamapicontext->SteamUserStats())
return false;
if (!steamapicontext->SteamUser())
return false;
if (!steamapicontext->SteamUser()->BLoggedOn())
return false;
bool bFound = false;
for (int i = 0; i < _ARRAYSIZE(GameAchievements); i++)
{
if (!strcmp(GameAchievements[i], szAchievement))
{
bFound = true;
break;
}
}
if (!bFound)
return false;
bool bAchieved = false;
steamapicontext->SteamUserStats()->GetAchievement(szAchievement, &bAchieved);
return !bAchieved;
}
void CAchievementManager::OnUserStatsReceived(UserStatsReceived_t *pCallback)
{
DevMsg("Loaded Stats and Achievements!\nResults %i\n", (int)pCallback->m_eResult);
}
void CAchievementManager::OnAchievementStored(UserAchievementStored_t *pCallback)
{
if (pCallback->m_nCurProgress == pCallback->m_nMaxProgress)
{
CHudAchievement *pHudHR = GET_HUDELEMENT(CHudAchievement);
if (pHudHR)
{
pHudHR->ShowAchievement();
}
}
} | 25.578616 | 199 | 0.722154 | BerntA |
e215335aafb37b69d3133fb403be1b810677aaea | 3,755 | cpp | C++ | macos/wrapper.cpp | lulitao1997/nixcrpkgs | 1f3045ed82dc31c35cff5fe8c1d9cdeeaee75691 | [
"MIT"
] | 105 | 2017-07-16T18:59:15.000Z | 2022-03-25T19:26:25.000Z | macos/wrapper.cpp | lulitao1997/nixcrpkgs | 1f3045ed82dc31c35cff5fe8c1d9cdeeaee75691 | [
"MIT"
] | 18 | 2017-01-21T03:25:51.000Z | 2020-09-13T22:51:52.000Z | macos/wrapper.cpp | lulitao1997/nixcrpkgs | 1f3045ed82dc31c35cff5fe8c1d9cdeeaee75691 | [
"MIT"
] | 10 | 2018-12-06T03:20:33.000Z | 2022-03-25T13:48:27.000Z | #include <vector>
#include <string>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
int do_exec(const std::string & compiler_name,
const std::vector<std::string> & args)
{
char ** exec_args = new char *[args.size() + 1];
size_t i = 0;
for (const std::string & arg : args)
{
exec_args[i++] = (char *)arg.c_str();
}
exec_args[i] = nullptr;
execvp(compiler_name.c_str(), exec_args);
int result = errno;
std::cerr << "execvp failed: " << compiler_name << ": "
<< strerror(result) << std::endl;
return 1;
}
int compiler_main(int argc, char ** argv,
const std::string & compiler_name)
{
std::vector<std::string> args;
args.push_back(compiler_name);
args.push_back("-target");
args.push_back(WRAPPER_HOST);
args.push_back("-mmacosx-version-min=" WRAPPER_OS_VERSION_MIN);
// The ld64 linker will just assume sdk_version is the same as
// macosx-version-min if we don't supply it. That probably will not
// do any harm.
// args.push_back("-Wl,-sdk_version," WRAPPER_SDK_VERSION);
// Suppress warnings about the -Wl arguments not being used when we're just
// compiling and not linking.
args.push_back("-Wno-unused-command-line-argument");
args.push_back("--sysroot");
args.push_back(WRAPPER_SDK_PATH);
// Causes clang to pass -demangle, -no_deduplicate, and other
// options that could be useful. Version 274.2 is the version number used here:
// https://github.com/tpoechtrager/osxcross/blob/474f359/build.sh#L140
if (WRAPPER_LINKER_VERSION[0])
{
args.push_back("-mlinker-version=" WRAPPER_LINKER_VERSION);
}
if (compiler_name == "clang++")
{
args.push_back("-stdlib=libc++");
args.push_back("-cxx-isystem");
args.push_back(WRAPPER_SDK_PATH "/usr/include/c++");
}
for (int i = 1; i < argc; ++i)
{
args.push_back(argv[i]);
}
return do_exec(compiler_name, args);
}
int c_compiler_main(int argc, char ** argv)
{
return compiler_main(argc, argv, "clang");
}
int cxx_compiler_main(int argc, char ** argv)
{
return compiler_main(argc, argv, "clang++");
}
int wrapper_main(int argc, char ** argv)
{
std::cout <<
"host: " WRAPPER_HOST "\n"
"path: " WRAPPER_PATH "\n"
"sdk_path: " WRAPPER_SDK_PATH "\n";
return 0;
}
struct {
const char * name;
int (*main_func)(int argc, char ** argv);
} prgms[] = {
{ WRAPPER_HOST "-gcc", c_compiler_main },
{ WRAPPER_HOST "-cc", c_compiler_main },
{ WRAPPER_HOST "-clang", c_compiler_main },
{ WRAPPER_HOST "-g++", cxx_compiler_main },
{ WRAPPER_HOST "-c++", cxx_compiler_main },
{ WRAPPER_HOST "-clang++", cxx_compiler_main },
{ WRAPPER_HOST "-wrapper", wrapper_main },
{ nullptr, nullptr },
};
const char * get_program_name(const char * path)
{
const char * p = strrchr(path, '/');
if (p) { path = p + 1; }
return path;
}
int main(int argc, char ** argv)
{
// We only want this wrapper and the compiler it invokes to access a certain
// set of tools that are determined at build time. Ignore whatever is on the
// user's path and use the path specified by our Nix expression instead.
int result = setenv("PATH", WRAPPER_PATH, 1);
if (result)
{
std::cerr << "wrapper failed to set PATH" << std::endl;
return 1;
}
result = setenv("COMPILER_RT_PATH", WRAPPER_COMPILER_RT_PATH, 1);
if (result)
{
std::cerr << "wrapper failed to set COMPILER_RT_PATH" << std::endl;
return 1;
}
std::string program_name = get_program_name(argv[0]);
for (auto * p = prgms; p->name; p++)
{
if (program_name == p->name)
{
return p->main_func(argc, argv);
}
}
std::cerr << "compiler wrapper invoked with unknown program name: "
<< argv[0] << std::endl;
return 1;
}
| 25.544218 | 82 | 0.65273 | lulitao1997 |
e21817e65b3c0693a268a50ca2b498418f37cadc | 2,520 | cpp | C++ | examples/geodesic.cpp | mcpca/fsm | df4081fa0e595284ddbb1f30f20c5fb2063aa41f | [
"MIT"
] | 2 | 2021-06-18T14:07:29.000Z | 2022-01-14T11:35:29.000Z | examples/geodesic.cpp | mcpca/fsm | df4081fa0e595284ddbb1f30f20c5fb2063aa41f | [
"MIT"
] | null | null | null | examples/geodesic.cpp | mcpca/fsm | df4081fa0e595284ddbb1f30f20c5fb2063aa41f | [
"MIT"
] | 2 | 2021-08-31T07:50:47.000Z | 2021-09-03T17:30:14.000Z | #include <cmath>
#include <iostream>
#include <numeric>
#include "marlin/solver.hpp"
#include "hdf5.hpp"
#include "timer.hpp"
int main()
{
#if MARLIN_N_DIMS == 2
constexpr char const* filename = "../data/geodesic.h5";
constexpr std::array<std::pair<marlin::scalar_t, marlin::scalar_t>,
marlin::dim>
vertices = { { { -0.5, 0.5 }, { -0.5, 0.5 } } };
constexpr std::array<int, marlin::dim> npts = { { 201, 201 } };
auto pt = [&vertices, &npts](auto x) {
std::array<marlin::scalar_t, marlin::dim> pt;
for(auto i = 0ul; i < marlin::dim; ++i)
{
pt[i] =
vertices[i].first +
x[i] * (vertices[i].second - vertices[i].first) / (npts[i] - 1);
}
return pt;
};
auto grad = [](auto const& x) {
return marlin::vector_t{
static_cast<marlin::scalar_t>(0.9 * 2 * M_PI *
std::cos(2 * M_PI * x[0]) *
std::sin(2 * M_PI * x[1])),
static_cast<marlin::scalar_t>(0.9 * 2 * M_PI *
std::sin(2 * M_PI * x[0]) *
std::cos(2 * M_PI * x[1]))
};
};
auto speed = [&grad](auto const& x, auto omega) -> marlin::scalar_t {
auto g = grad(x);
auto s = std::sin(omega);
auto ss = std::sin(2.0 * omega);
auto c = std::cos(omega);
auto num =
1 + g[0] * g[0] * s * s + g[1] * g[1] * c * c - g[0] * g[1] * ss;
auto den = 1 + g[0] * g[0] + g[1] * g[1];
return std::sqrt(num / den);
};
auto h = [&pt, &speed](auto x, auto const& p) -> marlin::scalar_t {
auto z = pt(x);
auto norm = std::sqrt(
std::inner_product(std::begin(p), std::end(p), std::begin(p), 0.0));
auto omega = std::atan2(p[1], p[0]);
return norm * speed(z, omega);
};
auto viscosity = [](auto) { return marlin::vector_t{ 1.0, 1.0 }; };
auto ds = h5io::read(filename, "cost_function");
marlin::solver::params_t params;
params.tolerance = 1.0e-4;
params.maxval = 2.0;
marlin::solver::solver_t s(std::move(ds.data), ds.size, vertices, params);
timer::timer_t t;
s.solve(h, viscosity);
std::cout << "Took " << t.get_elapsed_sec<double>() << " seconds."
<< std::endl;
h5io::write(filename, "value_function", s.steal(), ds.size);
#endif
return 0;
}
| 29.647059 | 80 | 0.476984 | mcpca |
e21a53f7247e971e87cee55a7f45bffde6146402 | 290 | cpp | C++ | c++11/understanding-cpp11/chapter4/4-3-2.cpp | cuiwm/choe_lib | 6992c7bf551e7d6d633399b21b028e6873d5e6e8 | [
"MIT"
] | null | null | null | c++11/understanding-cpp11/chapter4/4-3-2.cpp | cuiwm/choe_lib | 6992c7bf551e7d6d633399b21b028e6873d5e6e8 | [
"MIT"
] | null | null | null | c++11/understanding-cpp11/chapter4/4-3-2.cpp | cuiwm/choe_lib | 6992c7bf551e7d6d633399b21b028e6873d5e6e8 | [
"MIT"
] | null | null | null | #include <typeinfo>
#include <iostream>
using namespace std;
int main() {
int i;
decltype(i) j = 0;
cout << typeid(j).name() << endl; // 打印出"i", g++表示integer
float a;
double b;
decltype(a + b) c;
cout << typeid(c).name() << endl; // 打印出"d", g++表示double
}
| 19.333333 | 63 | 0.544828 | cuiwm |
e21e3f6d6e0229b9cd351032f27b23319402acc4 | 849 | cpp | C++ | venv/boost_1_73_0/libs/assert/test/source_location_test2.cpp | uosorio/heroku_face | 7d6465e71dba17a15d8edaef520adb2fcd09d91e | [
"Apache-2.0"
] | 106 | 2015-08-07T04:23:50.000Z | 2020-12-27T18:25:15.000Z | 3rdparty/boost_1_73_0/libs/assert/test/source_location_test2.cpp | qingkouwei/mediaones | cec475e1bfd5807b5351cc7e38d244ac5298ca16 | [
"MIT"
] | 130 | 2016-06-22T22:11:25.000Z | 2020-11-29T20:24:09.000Z | Libs/boost_1_76_0/libs/assert/test/source_location_test2.cpp | Antd23rus/S2DE | 47cc7151c2934cd8f0399a9856c1e54894571553 | [
"MIT"
] | 58 | 2015-01-28T15:55:31.000Z | 2021-04-26T08:12:28.000Z | // Copyright 2019 Peter Dimov
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
#define BOOST_DISABLE_CURRENT_LOCATION
#include <boost/assert/source_location.hpp>
#include <boost/core/lightweight_test.hpp>
int main()
{
{
boost::source_location loc;
BOOST_TEST_CSTR_EQ( loc.file_name(), "(unknown)" );
BOOST_TEST_CSTR_EQ( loc.function_name(), "(unknown)" );
BOOST_TEST_EQ( loc.line(), 0 );
BOOST_TEST_EQ( loc.column(), 0 );
}
{
boost::source_location loc = BOOST_CURRENT_LOCATION;
BOOST_TEST_CSTR_EQ( loc.file_name(), "(unknown)" );
BOOST_TEST_CSTR_EQ( loc.function_name(), "(unknown)" );
BOOST_TEST_EQ( loc.line(), 0 );
BOOST_TEST_EQ( loc.column(), 0 );
}
return boost::report_errors();
}
| 25.727273 | 63 | 0.647821 | uosorio |
e21fc60bc3e5611ff5b9d7606c686b5601eeb85e | 2,877 | cc | C++ | lib/asm.cc | kibergus/photon_charmer | 13d35da8de6a8a8739aea9a400265ba74e7d279a | [
"Apache-2.0"
] | null | null | null | lib/asm.cc | kibergus/photon_charmer | 13d35da8de6a8a8739aea9a400265ba74e7d279a | [
"Apache-2.0"
] | null | null | null | lib/asm.cc | kibergus/photon_charmer | 13d35da8de6a8a8739aea9a400265ba74e7d279a | [
"Apache-2.0"
] | null | null | null | #include "asm.h"
#include "hal/pwm.h"
#include "hal/ws2812/ws2812.h"
namespace {
constexpr int COMMAND_SIZE = 9;
constexpr int BUFFER_SIZE = 250;
uint8_t buffer[BUFFER_SIZE][COMMAND_SIZE];
// Instruction pointer.
volatile int ip = 0;
int read_pointer = 0;
THD_WORKING_AREA(asmThreadArea, 256);
__attribute__((noreturn)) THD_FUNCTION(asmThread, arg) {
(void)arg;
chRegSetThreadName("asm");
// Timer has a 16 bit resolution and we need more.
int elapsed = 0;
systime_t last_timer_value = chVTGetSystemTimeX();
for (;;) {
uint8_t* command = buffer[ip];
uint8_t opcode = command[0];
if (opcode == 0) {
chThdExit(0);
}
if (opcode == 1) {
int delay = (int(command[1]) << 24) |
(int(command[2]) << 16) |
(int(command[3]) << 8) |
int(command[4]);
systime_t next_timer_value = chVTGetSystemTimeX();
elapsed += chTimeDiffX(last_timer_value, next_timer_value);
last_timer_value = next_timer_value;
// 2 is a magic constant. For some reason it is just 2 times faster than should.
if (delay > int(TIME_I2MS(elapsed)) * 2) {
chThdSleepMilliseconds(delay - elapsed);
}
}
if (opcode == 2 || opcode == 3) {
// PWM command.
for (int offset = 0; offset < 4; ++offset) {
int channel = offset + (opcode == 2 ? 0 : 4);
int duty_cycle = int(command[offset * 2 + 1]) << 8 | command[offset * 2 + 2];
setPwm(channel, duty_cycle);
}
}
if (opcode >= 4 || opcode <= 8) {
// RGB command.
for (int offset = 0; offset < 1; ++offset) {
int channel = offset + (opcode - 4) * 2;
ws2812_write_led(channel, command[offset * 3 + 1], command[offset * 3 + 2], command[offset * 3 + 3]);
}
}
ip = (ip + 1) % BUFFER_SIZE;
}
}
uint8_t decode_hex(uint8_t c) {
if (c <= '9') {
return c - '0';
} else {
return c - 'a' + 10;
}
}
void read_command(BaseSequentialStream *chp) {
uint8_t hex_buffer[COMMAND_SIZE * 2];
for (int i = 0; i < COMMAND_SIZE * 2; ++i) {
hex_buffer[i] = streamGet(chp);
}
for (int i = 0; i < COMMAND_SIZE; ++i) {
buffer[read_pointer][i] = decode_hex(hex_buffer[i * 2]) << 4 | decode_hex(hex_buffer[i * 2 + 1]);
}
}
} // namespace
void execute_lamp_asm(BaseSequentialStream* chp) {
ip = 0;
read_pointer = 0;
for (;;) {
read_command(chp);
if (buffer[read_pointer][0] == 0 || buffer[read_pointer][0] == 1) {
break;
}
read_pointer = (read_pointer + 1) % BUFFER_SIZE;
}
chThdCreateStatic(asmThreadArea, sizeof(asmThreadArea), NORMALPRIO, asmThread, NULL);
for (;;) {
while (read_pointer == ip) {
chThdSleepMilliseconds(1);
}
read_command(chp);
if (buffer[read_pointer][0] == 0) {
return;
}
read_pointer = (read_pointer + 1) % BUFFER_SIZE;
}
}
| 25.6875 | 109 | 0.587417 | kibergus |
e220a9eb6309ade06701242c5d9db5b2f37a1921 | 11,421 | cpp | C++ | CaWE/MapEditor/ToolNewBrush.cpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | CaWE/MapEditor/ToolNewBrush.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | CaWE/MapEditor/ToolNewBrush.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#include "ToolNewBrush.hpp"
#include "CompMapEntity.hpp"
#include "ChildFrame.hpp"
#include "ChildFrameViewWin2D.hpp"
#include "ChildFrameViewWin3D.hpp"
#include "Group.hpp"
#include "MapBrush.hpp"
#include "MapDocument.hpp"
#include "Renderer2D.hpp"
#include "ToolManager.hpp"
#include "ToolOptionsBars.hpp"
#include "DialogCreateArch.hpp"
#include "../CursorMan.hpp"
#include "../CommandHistory.hpp"
#include "../GameConfig.hpp"
#include "Commands/AddPrim.hpp"
#include "Commands/Group_Assign.hpp"
#include "Commands/Group_New.hpp"
#include "wx/wx.h"
/*** Begin of TypeSys related definitions for this class. ***/
void* ToolNewBrushT::CreateInstance(const cf::TypeSys::CreateParamsT& Params)
{
const ToolCreateParamsT* TCPs=static_cast<const ToolCreateParamsT*>(&Params);
return new ToolNewBrushT(TCPs->MapDoc, TCPs->ToolMan, TCPs->ParentOptionsBar);
}
const cf::TypeSys::TypeInfoT ToolNewBrushT::TypeInfo(GetToolTIM(), "ToolNewBrushT", "ToolT", ToolNewBrushT::CreateInstance, NULL);
/*** End of TypeSys related definitions for this class. ***/
ToolNewBrushT::ToolNewBrushT(MapDocumentT& MapDoc, ToolManagerT& ToolMan, wxWindow* ParentOptionsBar)
: ToolT(MapDoc, ToolMan),
m_NewBrush(NULL),
m_NewBrushType(0),
m_DragBegin(),
m_DragCurrent(),
m_OptionsBar(new OptionsBar_NewBrushToolT(ParentOptionsBar))
{
// TODO: OnActivate: Set Status bar: Click and drag in a 2D view in order to create a new brush.
}
ToolNewBrushT::~ToolNewBrushT()
{
delete m_NewBrush;
m_NewBrush=NULL;
}
wxWindow* ToolNewBrushT::GetOptionsBar()
{
// Cannot define this method inline in the header file, because there the compiler
// does not yet know that the type of m_OptionsBar is in fact related to wxWindow.
return m_OptionsBar;
}
bool ToolNewBrushT::OnKeyDown2D(ViewWindow2DT& ViewWindow, wxKeyEvent& KE)
{
return OnKeyDown(ViewWindow, KE);
}
bool ToolNewBrushT::OnLMouseDown2D(ViewWindow2DT& ViewWindow, wxMouseEvent& ME)
{
const int ThirdAxis=ViewWindow.GetAxesInfo().ThirdAxis;
const Vector3fT WorldPos =m_MapDoc.SnapToGrid(ViewWindow.WindowToWorld(ME.GetPosition(), 0.0f), ME.AltDown(), -1 /*Snap all axes.*/);
// ViewWindow.SetCursor(CursorMan->GetCursor(CursorManT::NEW_BRUSH_TOOL)); // Not really neeeded - cursor is already set in OnMouseMove2D().
ViewWindow.CaptureMouse();
// (Try to) determine good initial points for the drag rectangle.
// Especially the initial heights are problematic - can we further improve the current strategy?
m_DragBegin =WorldPos;
m_DragCurrent=WorldPos;
m_DragBegin [ThirdAxis]=m_MapDoc.GetMostRecentSelBB().Min[ThirdAxis];
m_DragCurrent[ThirdAxis]=m_MapDoc.GetMostRecentSelBB().Max[ThirdAxis];
if (fabs(m_DragBegin[ThirdAxis]-m_DragCurrent[ThirdAxis])<8.0f)
m_DragCurrent[ThirdAxis]=m_DragBegin[ThirdAxis]+8.0f;
// Update the new brush instance according to the current drag rectangle.
UpdateNewBrush(ViewWindow);
m_ToolMan.UpdateAllObservers(this, UPDATE_NOW);
return true;
}
bool ToolNewBrushT::OnLMouseUp2D(ViewWindow2DT& ViewWindow, wxMouseEvent& ME)
{
if (!ViewWindow.HasCapture()) return false; // Drag started outside of ViewWindow.
ViewWindow.ReleaseMouse();
if (!m_NewBrush) return true; // Something went wrong - user has to try again.
if (m_NewBrushType!=5)
{
// It's a normal brush, not an arch.
const char* CmdDescr=""; // Describes the command that is submitted to the command history for actually adding m_NewBrush to the world.
switch (m_NewBrushType)
{
case 0: CmdDescr="new block brush"; break;
case 1: CmdDescr="new wedge brush"; break;
case 2: CmdDescr="new cylinder brush"; break;
case 3: CmdDescr="new pyramid brush"; break;
case 4: CmdDescr="new sphere brush"; break;
}
m_MapDoc.CompatSubmitCommand(new CommandAddPrimT(m_MapDoc, m_NewBrush, m_MapDoc.GetRootMapEntity(), CmdDescr));
m_NewBrush=NULL; // Instance is now "owned" by the command.
}
else
{
// It's an arch.
ArchDialogT ArchDlg(m_NewBrush->GetBB(), ViewWindow.GetAxesInfo());
// We *must* delete the brush before ArchDlg is shown - event processing continues (e.g. incoming mouse move events)!
delete m_NewBrush;
m_NewBrush = NULL;
if (ArchDlg.ShowModal() == wxID_OK)
{
const ArrayT<MapPrimitiveT*> ArchSegments = ArchDlg.GetArch(m_MapDoc.GetGameConfig()->GetMatMan().GetDefaultMaterial());
ArrayT<CommandT*> SubCommands;
// 1. Add the arch segments to the world.
CommandAddPrimT* CmdAddSegments = new CommandAddPrimT(m_MapDoc, ArchSegments, m_MapDoc.GetRootMapEntity(), "new arch segments");
CmdAddSegments->Do();
SubCommands.PushBack(CmdAddSegments);
// 2. Create a new group.
CommandNewGroupT* CmdNewGroup = new CommandNewGroupT(m_MapDoc, wxString::Format("arch (%lu side%s)", ArchSegments.Size(), ArchSegments.Size()==1 ? "" : "s"));
GroupT* NewGroup = CmdNewGroup->GetGroup();
NewGroup->SelectAsGroup = true;
CmdNewGroup->Do();
SubCommands.PushBack(CmdNewGroup);
// 3. Put the ArchSegments into the new group.
ArrayT<MapElementT*> ArchSegmentsAsElems;
for (unsigned long SegNr = 0; SegNr < ArchSegments.Size(); SegNr++)
ArchSegmentsAsElems.PushBack(ArchSegments[SegNr]);
CommandAssignGroupT* CmdAssign = new CommandAssignGroupT(m_MapDoc, ArchSegmentsAsElems, NewGroup);
CmdAssign->Do();
SubCommands.PushBack(CmdAssign);
// 4. Submit the composite macro command.
m_MapDoc.CompatSubmitCommand(new CommandMacroT(SubCommands, "new arch"));
}
}
m_ToolMan.UpdateAllObservers(this, UPDATE_SOON);
return true;
}
bool ToolNewBrushT::OnMouseMove2D(ViewWindow2DT& ViewWindow, wxMouseEvent& ME)
{
const int HorzAxis=ViewWindow.GetAxesInfo().HorzAxis;
const int VertAxis=ViewWindow.GetAxesInfo().VertAxis;
ViewWindow.SetCursor(CursorMan->GetCursor(CursorManT::NEW_BRUSH_TOOL));
if (!m_NewBrush) return true;
const Vector3fT WorldPos=m_MapDoc.SnapToGrid(ViewWindow.WindowToWorld(ME.GetPosition(), 0.0f), ME.AltDown(), -1 /*Snap all axes.*/);
const Vector3fT OldPos =m_DragCurrent;
// Update the drag rectangle.
m_DragCurrent[HorzAxis]=WorldPos[HorzAxis];
m_DragCurrent[VertAxis]=WorldPos[VertAxis];
if (m_DragCurrent==OldPos) return true;
// Update the new brush instance according to the current drag rectangle.
UpdateNewBrush(ViewWindow);
m_ToolMan.UpdateAllObservers(this, UPDATE_NOW);
return true;
}
bool ToolNewBrushT::OnKeyDown3D(ViewWindow3DT& ViewWindow, wxKeyEvent& KE)
{
return OnKeyDown(ViewWindow, KE);
}
bool ToolNewBrushT::OnRMouseClick3D(ViewWindow3DT& ViewWindow, wxMouseEvent& ME)
{
if (ME.ShiftDown() && ME.ControlDown())
{
// Create a brush in the shape of the current view frustum.
// This has little practical relevance for the user, it is just a tool for debugging the view frustum computations.
// It is in the RMB *up* instead of the RMB *down* handler in order to not have the context menu shown.
ArrayT<Plane3fT> Planes;
Planes.PushBackEmpty(6);
ViewWindow.GetViewFrustum(&Planes[0]);
MapBrushT* NewBrush=new MapBrushT(Planes, m_MapDoc.GetGameConfig()->GetMatMan().GetDefaultMaterial(), true);
m_MapDoc.CompatSubmitCommand(new CommandAddPrimT(m_MapDoc, NewBrush, m_MapDoc.GetRootMapEntity(), "new view frustum brush"));
return true;
}
return false;
}
bool ToolNewBrushT::OnMouseMove3D(ViewWindow3DT& ViewWindow, wxMouseEvent& ME)
{
ViewWindow.SetCursor(CursorMan->GetCursor(CursorManT::NEW_BRUSH_TOOL));
return true;
}
void ToolNewBrushT::RenderTool2D(Renderer2DT& Renderer) const
{
if (!IsActiveTool()) return;
if (!m_NewBrush) return;
const BoundingBox3fT BB =m_NewBrush->GetBB();
const ViewWindow2DT& ViewWin=Renderer.GetViewWin2D();
Renderer.SetLineColor(wxColor(128, 128, 0)); // I want "dirty yellow".
Renderer.Rectangle(wxRect(ViewWin.WorldToTool(BB.Min), ViewWin.WorldToTool(BB.Max)), false);
const bool WasSelected=m_NewBrush->IsSelected();
m_NewBrush->SetSelected(true);
m_NewBrush->Render2D(Renderer);
m_NewBrush->SetSelected(WasSelected);
Renderer.DrawBoxDims(BB, wxRIGHT | wxTOP);
}
void ToolNewBrushT::RenderTool3D(Renderer3DT& Renderer) const
{
if (!IsActiveTool()) return;
if (!m_NewBrush) return;
for (unsigned long FaceNr=0; FaceNr<m_NewBrush->GetFaces().Size(); FaceNr++)
m_NewBrush->GetFaces()[FaceNr].Render3DBasic(Renderer.GetRMatWireframe_OffsetZ(), *wxRED, 255);
}
bool ToolNewBrushT::OnKeyDown(ViewWindowT& ViewWindow, wxKeyEvent& KE)
{
switch (KE.GetKeyCode())
{
case WXK_ESCAPE:
if (m_NewBrush)
{
// Abort the dragging (while the mouse button is still down).
delete m_NewBrush;
m_NewBrush=NULL;
}
else
{
m_ToolMan.SetActiveTool(GetToolTIM().FindTypeInfoByName("ToolSelectionT"));
}
m_ToolMan.UpdateAllObservers(this, UPDATE_SOON);
return true;
}
return false;
}
void ToolNewBrushT::UpdateNewBrush(ViewWindow2DT& ViewWindow)
{
const int HorzAxis=ViewWindow.GetAxesInfo().HorzAxis;
const int VertAxis=ViewWindow.GetAxesInfo().VertAxis;
Vector3fT Drag=m_DragCurrent-m_DragBegin;
// If they have not yet made a choice, make one for them now.
if (Drag[HorzAxis]==0.0f) Drag[HorzAxis]=ViewWindow.GetAxesInfo().MirrorHorz ? -1.0f : 1.0f;
if (Drag[VertAxis]==0.0f) Drag[VertAxis]=ViewWindow.GetAxesInfo().MirrorVert ? -1.0f : 1.0f;
// Make sure that the drag is large enough in the chosen direction.
if (fabs(Drag.x)<8.0f) Drag.x=(Drag.x<0.0f) ? -8.0f : 8.0f;
if (fabs(Drag.y)<8.0f) Drag.y=(Drag.y<0.0f) ? -8.0f : 8.0f;
if (fabs(Drag.z)<8.0f) Drag.z=(Drag.z<0.0f) ? -8.0f : 8.0f;
EditorMaterialI* Material =m_MapDoc.GetGameConfig()->GetMatMan().GetDefaultMaterial();
const BoundingBox3fT BrushBB =BoundingBox3fT(m_DragBegin, m_DragBegin+Drag);
const unsigned long NrOfFaces=m_OptionsBar->GetNrOfFaces();
delete m_NewBrush;
m_NewBrush=NULL;
m_NewBrushType=m_OptionsBar->GetBrushIndex();
switch (m_NewBrushType)
{
case 0: m_NewBrush=MapBrushT::CreateBlock (BrushBB, Material); break;
case 1: m_NewBrush=MapBrushT::CreateWedge (BrushBB, Material); break;
case 2: m_NewBrush=MapBrushT::CreateCylinder(BrushBB, NrOfFaces, Material); break;
case 3: m_NewBrush=MapBrushT::CreatePyramid (BrushBB, NrOfFaces, Material); break;
case 4: m_NewBrush=MapBrushT::CreateSphere (BrushBB, NrOfFaces, Material); break;
default: m_NewBrush=MapBrushT::CreateBlock (BrushBB, Material); break;
}
}
| 34.820122 | 170 | 0.686105 | dns |
e22516e826f334f0788e00b1520ed9cfe96376e7 | 6,923 | cpp | C++ | modules/ti.Desktop/win32/win32_desktop.cpp | mital/titanium | 5e02a4406686d627f6828fd5cc18dc1a75d0714f | [
"Apache-2.0"
] | 4 | 2016-01-02T17:14:06.000Z | 2016-05-09T08:57:33.000Z | modules/ti.Desktop/win32/win32_desktop.cpp | mital/titanium | 5e02a4406686d627f6828fd5cc18dc1a75d0714f | [
"Apache-2.0"
] | null | null | null | modules/ti.Desktop/win32/win32_desktop.cpp | mital/titanium | 5e02a4406686d627f6828fd5cc18dc1a75d0714f | [
"Apache-2.0"
] | null | null | null | /**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "win32_desktop.h"
#include <windows.h>
#include <commdlg.h>
#include <shellapi.h>
#include <shlobj.h>
#include <string>
namespace ti
{
Win32Desktop::Win32Desktop()
{
}
Win32Desktop::~Win32Desktop()
{
}
bool Win32Desktop::OpenApplication(std::string &name)
{
// this can actually open applications or documents (wordpad, notepad, file-test.txt, etc.)
char *dir = NULL;
if (FileUtils::IsFile(name))
{
// start with the current working directory as the directory of the program
dir = (char*)FileUtils::GetDirectory(name).c_str();
}
long response = (long)ShellExecuteA(NULL, "open", name.c_str(), NULL, dir, SW_SHOWNORMAL);
return (response > 32);
}
bool Win32Desktop::OpenURL(std::string &url)
{
long response = (long)ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL);
return (response > 32);
}
void Win32Desktop::TakeScreenshot(std::string &screenshotFile)
{
//ensure filename ends in bmp
screenshotFile.append(".bmp");
HWND desktop = GetDesktopWindow();
RECT desktopRect;
GetWindowRect(desktop, &desktopRect);
int x = 0;
int y = 0;
int width = desktopRect.right;
int height = desktopRect.bottom;
// get a DC compat. w/ the screen
HDC hDc = CreateCompatibleDC(0);
// make a bmp in memory to store the capture in
HBITMAP hBmp = CreateCompatibleBitmap(GetDC(0), width, height);
// join em up
SelectObject(hDc, hBmp);
// copy from the screen to my bitmap
BitBlt(hDc, 0, 0, width, height, GetDC(0), x, y, SRCCOPY);
char tmpDir[MAX_PATH];
char tmpFile[MAX_PATH];
GetTempPathA(sizeof(tmpDir), tmpDir);
GetTempFileNameA(tmpDir, "ti_", 0, tmpFile);
bool saved = SaveBMPFile(tmpFile, hBmp, hDc, width, height);
std::cout << "SCREEN SHOT file " << tmpFile << std::endl;
if(saved)
{
CopyFileA(tmpFile, screenshotFile.c_str(), FALSE);
}
// free the bitmap memory
DeleteObject(hBmp);
}
bool Win32Desktop::SaveBMPFile(const char *filename, HBITMAP bitmap, HDC bitmapDC, int width, int height) {
bool Success = false;
HDC SurfDC = NULL; // GDI-compatible device context for the surface
HBITMAP OffscrBmp = NULL; // bitmap that is converted to a DIB
HDC OffscrDC = NULL; // offscreen DC that we can select OffscrBmp into
LPBITMAPINFO lpbi = NULL; // bitmap format info; used by GetDIBits
LPVOID lpvBits = NULL; // pointer to bitmap bits array
HANDLE BmpFile = INVALID_HANDLE_VALUE; // destination .bmp file
BITMAPFILEHEADER bmfh; // .bmp file header
// We need an HBITMAP to convert it to a DIB:
if ((OffscrBmp = CreateCompatibleBitmap(bitmapDC, width, height)) == NULL)
{
return false;
}
// The bitmap is empty, so let's copy the contents of the surface to it.
// For that we need to select it into a device context. We create one.
if ((OffscrDC = CreateCompatibleDC(bitmapDC)) == NULL)
{
return false;
}
// Select OffscrBmp into OffscrDC:
HBITMAP OldBmp = (HBITMAP)SelectObject(OffscrDC, OffscrBmp);
// Now we can copy the contents of the surface to the offscreen bitmap:
BitBlt(OffscrDC, 0, 0, width, height, bitmapDC, 0, 0, SRCCOPY);
// GetDIBits requires format info about the bitmap. We can have GetDIBits
// fill a structure with that info if we pass a NULL pointer for lpvBits:
// Reserve memory for bitmap info (BITMAPINFOHEADER + largest possible
// palette):
if ((lpbi = (LPBITMAPINFO)(new char[sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)])) == NULL)
{
return false;
}
ZeroMemory(&lpbi->bmiHeader, sizeof(BITMAPINFOHEADER));
lpbi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
// Get info but first de-select OffscrBmp because GetDIBits requires it:
SelectObject(OffscrDC, OldBmp);
if (!GetDIBits(OffscrDC, OffscrBmp, 0, height, NULL, lpbi, DIB_RGB_COLORS))
{
return false;
}
// Reserve memory for bitmap bits:
if ((lpvBits = new char[lpbi->bmiHeader.biSizeImage]) == NULL)
{
return false;
}
// Have GetDIBits convert OffscrBmp to a DIB (device-independent bitmap):
if (!GetDIBits(OffscrDC, OffscrBmp, 0, height, lpvBits, lpbi, DIB_RGB_COLORS))
{
return false;
}
// Create a file to save the DIB to:
if ((BmpFile = ::CreateFileA(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,NULL)) == INVALID_HANDLE_VALUE)
{
return false;
}
DWORD Written; // number of bytes written by WriteFile
// Write a file header to the file:
bmfh.bfType = 19778; // 'BM'
// bmfh.bfSize = ??? // we'll write that later
bmfh.bfReserved1 = bmfh.bfReserved2 = 0;
// bmfh.bfOffBits = ??? // we'll write that later
if (!WriteFile(BmpFile, &bmfh, sizeof(bmfh), &Written, NULL))
{
return false;
}
if (Written < sizeof(bmfh))
{
return false;
}
// Write BITMAPINFOHEADER to the file:
if (!WriteFile(BmpFile, &lpbi->bmiHeader, sizeof(BITMAPINFOHEADER), &Written, NULL))
{
return false;
}
if (Written < sizeof(BITMAPINFOHEADER))
{
return false;
}
// Calculate size of palette:
int PalEntries;
// 16-bit or 32-bit bitmaps require bit masks:
if (lpbi->bmiHeader.biCompression == BI_BITFIELDS)
{
PalEntries = 3;
}
else
{
// bitmap is palettized?
PalEntries = (lpbi->bmiHeader.biBitCount <= 8) ?
// 2^biBitCount palette entries max.:
(int)(1 << lpbi->bmiHeader.biBitCount)
// bitmap is TrueColor -> no palette:
: 0;
}
// If biClrUsed use only biClrUsed palette entries:
if(lpbi->bmiHeader.biClrUsed)
{
PalEntries = lpbi->bmiHeader.biClrUsed;
}
// Write palette to the file:
if(PalEntries){
if (!WriteFile(BmpFile, &lpbi->bmiColors, PalEntries * sizeof(RGBQUAD), &Written, NULL))
{
return false;
}
if (Written < PalEntries * sizeof(RGBQUAD))
{
return false;
}
}
// The current position in the file (at the beginning of the bitmap bits)
// will be saved to the BITMAPFILEHEADER:
//bmfh.bfOffBits = GetFilePointer(BmpFile);
bmfh.bfOffBits = SetFilePointer(BmpFile, 0, 0, FILE_CURRENT);
// Write bitmap bits to the file:
if (!WriteFile(BmpFile, lpvBits, lpbi->bmiHeader.biSizeImage, &Written, NULL))
{
return false;
}
if (Written < lpbi->bmiHeader.biSizeImage)
{
return false;
}
// The current pos. in the file is the final file size and will be saved:
//bmfh.bfSize = GetFilePointer(BmpFile);
bmfh.bfSize = SetFilePointer(BmpFile, 0, 0, FILE_CURRENT);
// We have all the info for the file header. Save the updated version:
SetFilePointer(BmpFile, 0, 0, FILE_BEGIN);
if (!WriteFile(BmpFile, &bmfh, sizeof(bmfh), &Written, NULL))
{
return false;
}
if (Written < sizeof(bmfh))
{
return false;
}
return true;
}
}
| 27.363636 | 147 | 0.680774 | mital |
e22648c2a081ee5ea6061aec95b27d1790acc03e | 1,107 | cpp | C++ | euler/tasks/51/main.cpp | pg83/zm | ef9027bd9ee260118fdf80e8b53361da1b7892f3 | [
"MIT"
] | null | null | null | euler/tasks/51/main.cpp | pg83/zm | ef9027bd9ee260118fdf80e8b53361da1b7892f3 | [
"MIT"
] | null | null | null | euler/tasks/51/main.cpp | pg83/zm | ef9027bd9ee260118fdf80e8b53361da1b7892f3 | [
"MIT"
] | null | null | null | #include <euler/lib/euler.h>
static std::string replace(std::string s, char f, char t) {
for (auto& ch : s) {
if (ch == f) {
ch = t;
}
}
return s;
}
static std::string keyf(uint n, int d) {
return replace(std::to_string(n), '0' + d, '*');
}
static uint unkeyf(const std::string& k, uint d) {
auto res = replace(k, '*', '0' + d);
if (res[0] == '0') {
return 0;
}
return from_string<uint>(res);
}
int main() {
std::unordered_set<std::string> keys;
std::unordered_map<std::string, std::set<uint>> res;
for (uint i = 1; i <= 200000; ++i) {
for (uint d = 0; d <= 9; ++d) {
keys.insert(keyf(i, d));
}
}
for (const auto& k : keys) {
for (uint d = 0; d <= 9; ++d) {
auto kk = unkeyf(k, d);
if (is_prime_stupid(kk)) {
res[k].insert(kk);
}
}
}
for (auto& it : res) {
auto& v = it.second;
if (v.size() == 8) {
std::cout << *v.begin() << std::endl;
break;
}
}
}
| 19.421053 | 59 | 0.439024 | pg83 |
e22826f308519fa30ed3979808c19e6562740ff4 | 6,511 | cpp | C++ | tests/benchmarks.cpp | jll63/yomm11 | 4d434ae548886faab5c16c98e1973dc8b6e368d4 | [
"BSL-1.0"
] | 108 | 2015-01-25T16:58:11.000Z | 2021-09-23T06:47:07.000Z | tests/benchmarks.cpp | jll63/yomm11 | 4d434ae548886faab5c16c98e1973dc8b6e368d4 | [
"BSL-1.0"
] | 3 | 2015-06-07T17:40:27.000Z | 2017-11-01T19:33:01.000Z | tests/benchmarks.cpp | jll63/yomm11 | 4d434ae548886faab5c16c98e1973dc8b6e368d4 | [
"BSL-1.0"
] | 19 | 2015-04-23T17:34:03.000Z | 2019-06-28T09:18:45.000Z | // benchmarks.cpp
// Copyright (c) 2013 Jean-Louis Leroy
// 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)
// chrt -f 99 ./benchmarks
// 10000000 iterations, time in millisecs
// virtual function, do_nothing : 75.50
// open method, intrusive, do_nothing : 100.56
// open method, foreign, do_nothing : 1397.75
// virtual function, do_something : 1541.11
// open method, intrusive, do_something : 1608.20
// open method, foreign, do_something : 2607.76
// virtual function, 2-dispatch, do_nothing : 250.75
// open method with 2 args, intrusive, do_nothing : 150.77
// open method with 2 args, foreign, do_nothing : 2832.26
// results obtained on my computer (ThinkPad x200s):
// processor : 0 & 1
// vendor_id : GenuineIntel
// cpu family : 6
// model : 23
// model name : Intel(R) Core(TM)2 Duo CPU L9400 @ 1.86GHz
// stepping : 10
// microcode : 0xa0c
// cpu MHz : 800.000
// cache size : 6144 KB
// cpu cores : 2
// fpu : yes
// fpu_exception: yes
// cpuid level : 13
// wp : yes
// bogomips : 3724.05
// clflush size : 64
#include <iostream>
#include <iomanip>
#include <chrono>
#include "benchmarks.hpp"
using namespace std;
using namespace std::chrono;
using yorel::multi_methods::virtual_;
namespace intrusive {
MULTI_METHOD(do_nothing, void, virtual_<object>&);
BEGIN_SPECIALIZATION(do_nothing, void, object&) {
} END_SPECIALIZATION;
MULTI_METHOD(do_something, double, virtual_<object>&, double x, double a, double b, double c);
BEGIN_SPECIALIZATION(do_something, double, object&, double x, double a, double b, double c) {
return log(a * x * x + b * x + c);
} END_SPECIALIZATION;
MULTI_METHOD(do_nothing_2, void, virtual_<object>&, virtual_<object>&);
BEGIN_SPECIALIZATION(do_nothing_2, void, object&, object&) {
} END_SPECIALIZATION;
}
namespace vbase {
MULTI_METHOD(do_nothing, void, virtual_<object>&);
BEGIN_SPECIALIZATION(do_nothing, void, object&) {
} END_SPECIALIZATION;
MULTI_METHOD(do_something, double, virtual_<object>&, double x, double a, double b, double c);
BEGIN_SPECIALIZATION(do_something, double, derived&, double x, double a, double b, double c) {
return log(a * x * x + b * x + c);
} END_SPECIALIZATION;
MULTI_METHOD(do_nothing_2, void, virtual_<object>&, virtual_<object>&);
BEGIN_SPECIALIZATION(do_nothing_2, void, object&, object&) {
} END_SPECIALIZATION;
}
namespace foreign {
struct object {
virtual ~object() { }
};
MM_FOREIGN_CLASS(object);
MULTI_METHOD(do_nothing, void, virtual_<object>&);
BEGIN_SPECIALIZATION(do_nothing, void, object&) {
} END_SPECIALIZATION;
MULTI_METHOD(do_nothing_2, void, virtual_<object>&, virtual_<object>&);
BEGIN_SPECIALIZATION(do_nothing_2, void, object&, object&) {
} END_SPECIALIZATION;
MULTI_METHOD(do_something, double, virtual_<object>&, double x, double a, double b, double c);
BEGIN_SPECIALIZATION(do_something, double, object&, double x, double a, double b, double c) {
return log(a * x * x + b * x + c);
} END_SPECIALIZATION;
}
using time_type = decltype(high_resolution_clock::now());
void post(const string& description, time_type start, time_type end) {
cout << setw(50) << left << description << ": " << setw(8) << fixed << right << setprecision(2) << duration<double, milli>(end - start).count() << endl;
}
struct benchmark {
benchmark(const string& label) : label(label), start(high_resolution_clock::now()) {
}
~benchmark() {
auto end = high_resolution_clock::now();
cout << setw(50) << left << label << ": "
<< setw(8) << fixed << right << setprecision(2)
<< duration<double, milli>(end - start).count() << endl;
}
const string label;
decltype(high_resolution_clock::now()) start;
};
int main() {
yorel::multi_methods::initialize();
const int repeats = 10 * 1000 * 1000;
{
auto pf = new foreign::object;
auto pi = intrusive::object::make();
cout << repeats << " iterations, time in millisecs\n";
{
benchmark b("virtual function, do_nothing");
for (int i = 0; i < repeats; i++)
pi->do_nothing();
}
{
benchmark b("open method, intrusive, do_nothing");
for (int i = 0; i < repeats; i++)
intrusive::do_nothing(*pi);
}
{
benchmark b("open method, foreign, do_nothing");
for (int i = 0; i < repeats; i++)
foreign::do_nothing(*pf);
}
{
benchmark b("virtual function, do_something");
for (int i = 0; i < repeats; i++)
pi->do_something(1, 2, 3, 4);
}
{
benchmark b("open method, intrusive, do_something");
for (int i = 0; i < repeats; i++)
intrusive::do_something(*pi, 1, 2, 3, 4);
}
{
benchmark b("open method, foreign, do_something");
for (int i = 0; i < repeats; i++)
foreign::do_something(*pf, 1, 2, 3, 4);
}
// double dispatch
{
benchmark b("virtual function, 2-dispatch, do_nothing");
for (int i = 0; i < repeats; i++)
pi->dd1_do_nothing(pi);
}
{
benchmark b("open method with 2 args, intrusive, do_nothing");
for (int i = 0; i < repeats; i++)
intrusive::do_nothing_2(*pi, *pi);
}
{
benchmark b("open method with 2 args, foreign, do_nothing");
for (int i = 0; i < repeats; i++)
foreign::do_nothing_2(*pf, *pf);
}
}
// virtual inheritance
{
auto pi = vbase::object::make();
{
benchmark b("virtual function, vbase, do_nothing");
for (int i = 0; i < repeats; i++)
pi->do_nothing();
}
{
benchmark b("open method, vbase, do_nothing");
for (int i = 0; i < repeats; i++)
vbase::do_nothing(*pi);
}
{
benchmark b("virtual function, vbase, do_something");
for (int i = 0; i < repeats; i++)
pi->do_something(1, 2, 3, 4);
}
{
benchmark b("open method, vbase, do_something");
for (int i = 0; i < repeats; i++)
vbase::do_something(*pi, 1, 2, 3, 4);
}
// double dispatch
{
benchmark b("virtual function, 2-dispatch, vbase, do_nothing");
for (int i = 0; i < repeats; i++)
pi->dd1_do_nothing(pi);
}
{
benchmark b("open method with 2 args, vbase, do_nothing");
for (int i = 0; i < repeats; i++)
vbase::do_nothing_2(*pi, *pi);
}
}
return 0;
}
| 26.57551 | 154 | 0.620028 | jll63 |
e22d3e98b006dad29d25a1241bf1c687a69d8eed | 1,981 | cpp | C++ | libs/GameInput/RawController.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | 3 | 2019-10-27T22:32:44.000Z | 2020-05-21T04:00:46.000Z | libs/GameInput/RawController.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | null | null | null | libs/GameInput/RawController.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | null | null | null | #include "stdafx.h"
#include "RawController.h"
#include "rftl/limits"
namespace RF::input {
///////////////////////////////////////////////////////////////////////////////
void RawController::GetRawCommandStream( rftl::virtual_iterator<RawCommand>& parser ) const
{
return GetRawCommandStream( parser, rftl::numeric_limits<size_t>::max() );
}
void RawController::GetRawCommandStream( rftl::virtual_iterator<RawCommand>& parser, time::CommonClock::time_point earliestTime, time::CommonClock::time_point latestTime ) const
{
auto const onElement = [&parser, &earliestTime, &latestTime]( RawCommand const& element ) -> void {
if( element.mTime >= earliestTime && element.mTime <= latestTime )
{
parser( element );
}
};
rftl::virtual_callable_iterator<RawCommand, decltype( onElement )> filter( onElement );
GetRawCommandStream( filter );
}
void RawController::GetKnownSignals( rftl::virtual_iterator<RawSignalType>& iter ) const
{
return GetKnownSignals( iter, rftl::numeric_limits<size_t>::max() );
}
void RawController::GetRawSignalStream( rftl::virtual_iterator<RawSignal>& sampler, RawSignalType type ) const
{
return GetRawSignalStream( sampler, rftl::numeric_limits<size_t>::max(), type );
}
void RawController::GetRawSignalStream( rftl::virtual_iterator<RawSignal>& sampler, time::CommonClock::time_point earliestTime, time::CommonClock::time_point latestTime, RawSignalType type ) const
{
auto const onElement = [&sampler, &earliestTime, &latestTime]( RawSignal const& element ) -> void {
if( element.mTime >= earliestTime && element.mTime <= latestTime )
{
sampler( element );
}
};
rftl::virtual_callable_iterator<RawSignal, decltype( onElement )> filter( onElement );
GetRawSignalStream( filter, type );
}
void RawController::GetTextStream( rftl::u16string& text ) const
{
return GetTextStream( text, rftl::numeric_limits<size_t>::max() );
}
///////////////////////////////////////////////////////////////////////////////
}
| 30.015152 | 196 | 0.687027 | max-delta |
e22d685fc12753cf2dd50dc5be118f36572b8bb6 | 2,479 | cpp | C++ | tests/test-3bit-shift-register.cpp | AnandSaminathan/verification-algorithms | 5ba499b6147dc6002b6e7a1b67ffc1da6a2e1549 | [
"BSL-1.0"
] | null | null | null | tests/test-3bit-shift-register.cpp | AnandSaminathan/verification-algorithms | 5ba499b6147dc6002b6e7a1b67ffc1da6a2e1549 | [
"BSL-1.0"
] | null | null | null | tests/test-3bit-shift-register.cpp | AnandSaminathan/verification-algorithms | 5ba499b6147dc6002b6e7a1b67ffc1da6a2e1549 | [
"BSL-1.0"
] | null | null | null | #include "verification-algorithms/k-induction/k-induction.hpp"
#include "verification-algorithms/ltl-bmc/ltl-bmc.hpp"
#include "verification-algorithms/ic3/ic3.hpp"
#include "catch2/catch.hpp"
using namespace verifier;
SCENARIO("three bit shift register", "[3bit-shift-register]") {
std::vector<Symbol> symbols;
for(int i = 0; i <= 2; ++i) {
std::string name = "x" + std::to_string(i);
symbols.emplace_back(Symbol(bool_const, name));
}
std::string I = "(x0 == false && x1 == false && x2 == false)";
std::string T = "(next_x0 == x1 && next_x1 == x2 && next_x2 == true)";
GIVEN("safety properties") {
kInduction k(symbols, I, T);
IC3 i(symbols, I, T);
std::string P;
WHEN("property is allFalse") {
P = "!x0 && !x1 && !x2";
THEN("property does not hold"){
REQUIRE(k.check(P) == false);
REQUIRE(i.check(P) == false);
}
}
}
GIVEN("ltl properties") {
ltlBmc l(symbols, I, T);
l.setBound(3);
std::string P;
WHEN("property is always allFalse") {
P = "G(x0 == false && x1 == false && x2 == false)";
THEN("property does not hold") {
REQUIRE(l.check(P) == false);
}
}
WHEN("property is eventuallyAllTrue") {
P = "F(x0 == true && x1 == true && x2 == true)";
THEN("property holds") {
REQUIRE(l.check(P) == true);
}
}
WHEN("property is correctNextStep") {
P = "X(x0 == false && x1 == false && x2 == true)";
THEN("property holds") {
REQUIRE(l.check(P) == true);
}
}
WHEN("property is wrongNextStep") {
P = "X!(x0 == false && x1 == false && x2 == true)";
THEN("property does not hold") {
REQUIRE(l.check(P) == false);
}
}
WHEN("property is untilAllTrueAtleastOneFalse") {
P = "!(x0 && x1 && x2) U (x0 && x1 && x2)";
THEN("property holds") {
REQUIRE(l.check(P) == true);
}
}
WHEN("property is releaseAtleastOneFalseAllTrue") {
P = "(x0 && x1 && x2) R !(x0 && x1 && x2)";
THEN("property does not hold") {
REQUIRE(l.check(P) == false);
}
}
WHEN("property is releaseX2TrueX1false") {
P = "(x2 R !x1)";
THEN("property holds") {
REQUIRE(l.check(P) == true);
}
}
WHEN("property has undeclared variable") {
P = "G(x1 || dummy)";
THEN("throws exception") {
REQUIRE_THROWS_AS(l.check(P), std::invalid_argument);
}
}
}
}
| 25.556701 | 72 | 0.534086 | AnandSaminathan |