hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
3e99deb7e1a1c4a1303da44032e58882da6a4509
4,993
cpp
C++
core/vcf/VCFWriter.cpp
srynobio/graphite
e37aa8803ea15f0473ab368b4bae3e3347451229
[ "MIT" ]
null
null
null
core/vcf/VCFWriter.cpp
srynobio/graphite
e37aa8803ea15f0473ab368b4bae3e3347451229
[ "MIT" ]
null
null
null
core/vcf/VCFWriter.cpp
srynobio/graphite
e37aa8803ea15f0473ab368b4bae3e3347451229
[ "MIT" ]
null
null
null
#include "VCFWriter.h" #include "core/util/Utility.h" #include "core/util/Types.h" #include <algorithm> namespace graphite { VCFWriter::VCFWriter(const std::string& filename, std::vector< graphite::Sample::SharedPtr >& bamSamplePtrs, const std::string& outputDirectory) : m_bam_sample_ptrs(bamSamplePtrs), m_black_format_string(nullptr) { for (auto samplePtr : m_bam_sample_ptrs) { m_bam_sample_ptrs_map.emplace(samplePtr->getName(), samplePtr); } std::string base_filename = filename.substr(filename.find_last_of("/\\") + 1); std::string path(outputDirectory + "/" + base_filename); this->m_out_file.open(path); } VCFWriter::~VCFWriter() { this->m_out_file.close(); } void VCFWriter::writeLine(const std::string& line) { this->m_out_file << line.c_str() << std::endl; } void VCFWriter::writeHeader(const std::vector< std::string >& headerLines) { m_vcf_column_names.clear(); m_sample_names.clear(); // we need to add the graphite format rows in the header. // The code below ensures that we only write the format columns once and in the write place. std::vector< std::string > lines; bool formatWritten = false; for (auto line : headerLines) { bool isHeaderCols = false; if (line.find("#CHROM") != std::string::npos) { split(line, '\t', this->m_vcf_column_names); isHeaderCols = true; } if ((line.find("##FORMAT") != std::string::npos && !formatWritten) || (line.find("#CHROM") != std::string::npos && !formatWritten)) { for (auto formatTuple : this->m_format) { lines.emplace_back(std::get< 1 >(formatTuple)); } formatWritten = true; } if (!isHeaderCols) { lines.emplace_back(line); } } std::unordered_set< std::string > writtenLines; for (auto line : lines) { if (writtenLines.find(line) == writtenLines.end()) { writeLine(line); writtenLines.emplace(line); } } std::string headerLine = ""; bool first = true; for (auto headerName : this->m_vcf_column_names) { if (!first) { headerLine += "\t"; } headerLine += headerName; first = false; if (STANDARD_VCF_COLUMN_NAMES_SET.find(headerName) == STANDARD_VCF_COLUMN_NAMES_SET.end()) { this->m_sample_names.emplace(this->m_sample_names.end(), headerName); } } first = true; for (auto bamSamplePtr : this->m_bam_sample_ptrs) { auto sampleName = bamSamplePtr->getName(); auto iter = std::find_if(this->m_vcf_column_names.begin(), this->m_vcf_column_names.end(), [&sampleName](const std::string& columnName) { return columnName.compare(sampleName) == 0; }); if (iter == this->m_vcf_column_names.end()) // if sample not in vcf { if (!first) { headerLine += "\t"; } headerLine += sampleName; this->m_vcf_column_names.emplace(this->m_vcf_column_names.end(), sampleName); this->m_sample_names.emplace(this->m_sample_names.end(), sampleName); } else { this->m_sample_name_in_vcf.emplace(sampleName, true); } first = false; } writeLine(headerLine); } /* void VCFWriter::setSamples(const std::string& columnHeaderLine, std::unordered_map< std::string, Sample::SharedPtr >& samplePtrsMap) { this->m_sample_ptrs.clear(); this->m_sample_ptrs_map.clear(); std::vector< std::string > columns; split(columnHeaderLine, '\t', columns); for (auto column : columns) { std::string upperColumn; std::transform(column.begin(), column.end(), std::back_inserter(upperColumn), ::toupper); if (std::find(STANDARD_VCF_COLUMN_NAMES.begin(), STANDARD_VCF_COLUMN_NAMES.end(), upperColumn) == STANDARD_VCF_COLUMN_NAMES.end()) { auto iter = samplePtrsMap.find(column); if (iter == samplePtrsMap.end()) { std::cout << "error in VCFWriter::setSamples sample: " << column << " not found" << std::endl; } else { this->m_sample_ptrs.emplace_back(iter->second); this->m_sample_ptrs_map.emplace(iter->first, iter->second); } } } } */ Sample::SharedPtr VCFWriter::getSamplePtr(const std::string& sampleName) { return this->m_bam_sample_ptrs_map.find(sampleName)->second; } std::vector< std::string > VCFWriter::getSampleNames() { return m_sample_names; } bool VCFWriter::isSampleNameInOriginalVCF(const std::string& sampleName) { return (m_sample_name_in_vcf.find(sampleName) != m_sample_name_in_vcf.end()); } bool VCFWriter::isSampleNameInBam(const std::string& sampleName) { return (m_bam_sample_ptrs_map.find(sampleName) != m_bam_sample_ptrs_map.end()); } std::vector< std::string > VCFWriter::getColumnNames() { return this->m_vcf_column_names; } void VCFWriter::setBlankFormatString(const std::string& blankFormatString) { if (this->m_black_format_string == nullptr) { this->m_black_format_string = std::make_shared< std::string >(blankFormatString); } } std::shared_ptr< std::string > VCFWriter::getBlankFormatStringPtr() { return this->m_black_format_string; } }
28.050562
147
0.679551
srynobio
3e9a2a011d4e5faf3b4e2d156f665c115ecfdc68
4,667
hpp
C++
pulsar/modulemanager/ModuleCreationFuncs.hpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
pulsar/modulemanager/ModuleCreationFuncs.hpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
pulsar/modulemanager/ModuleCreationFuncs.hpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
/*! \file * * \brief Storage of module creation functions (header) * \author Benjamin Pritchard (ben@bennyp.org) */ #ifndef PULSAR_GUARD_MODULEMANAGER__MODULECREATIONFUNCS_HPP_ #define PULSAR_GUARD_MODULEMANAGER__MODULECREATIONFUNCS_HPP_ #include <functional> #include <map> #include "pulsar/types.h" #include "pulsar/modulemanager/ModuleIMPLHolder.hpp" #include "pulsar/util/PythonHelper.hpp" namespace pulsar{ /*! \brief Stores creation functions for modules within a supermodule * * This object contains a map of module names to functions that create * an object by that name. When a module is loaded, a * ModuleCreationFuncs object gets returned from the insert_supermodule * function. The ModuleManager then uses the information stored within * to populate its module creation map. */ class ModuleCreationFuncs { public: //! Creation function for a single module typedef std::function<detail::ModuleIMPLHolder * (ID_t)> Func; ///////////////////////////////////////////////////////////// // All compiler-generated constructors and operator= are ok ///////////////////////////////////////////////////////////// /*! \brief Add a creator for a C++ module * * \tparam T The module to add. This is the full type, not the type * of the base class. * * \param [in] modulename The name of the module */ template<typename T> void add_cpp_creator(const std::string & modulename) { Func cc = std::bind(&ModuleCreationFuncs::cpp_constructor_wrapper_<T>, std::placeholders::_1); creators_.emplace(modulename, cc); } /*! \brief Add a creator for a python module * * \param [in] modulename The name of the module * \param [in] cls The module to add. This should be a python class. */ void add_py_creator(const std::string & modulename, const pybind11::object & cls) { //! \todo check if it is a class? Func m = std::bind(&ModuleCreationFuncs::py_constructor_wrapper_, cls, std::placeholders::_1); creators_.emplace(modulename, m); } /*! \brief Check to see if this object can create a module of the given name * * \param [in] modulename The name of the module to query * \return True if this object can create a module with name \p modulename */ bool has_creator(const std::string & modulename) const { return creators_.count(modulename); } /*! \brief Get the creator function for a module * * \throw pulsar::PulsarException if there isn't a * creator for that module name. * * \param [in] modulename The name of the module * \return A function that can create a module with the name \p modulename */ const Func & get_creator(const std::string & modulename) const { if(!has_creator(modulename)) throw PulsarException("I don't have a creator for this module", "modulename", modulename); return creators_.at(modulename); } /*! \brief Delete all the stored creators */ void clear(void) { creators_.clear(); } private: //! Storage of all the creation functions std::map<std::string, Func> creators_; /*! \brief Wrap construction of a C++ object * * \tparam T Full type of the module (not the base type) * \param [in] id The ID of the newly-created module */ template<typename T> static detail::ModuleIMPLHolder * cpp_constructor_wrapper_(ID_t id) { // T::BaseType is the module base type (ie, TwoElectronIntegral, etc) // defined in the base type class. std::unique_ptr<typename T::BaseType> p(new T(id)); return new detail::CppModuleIMPLHolder<typename T::BaseType>(std::move(p)); } /*! \brief Wrap construction of a python object (class) * * \param [in] cls Python class * \param [in] id The ID of the newly-created module */ static detail::ModuleIMPLHolder * py_constructor_wrapper_(const pybind11::object & cls, ID_t id) { pybind11::object o = call_py_func<pybind11::object>(cls, id); return new detail::PyModuleIMPLHolder(std::move(o)); } }; } // close namespace pulsar #endif
31.748299
106
0.587315
pulsar-chem
3e9a80a4bb500e602a2a9703340d1738d101f9da
23,735
cpp
C++
openr/ctrl-server/OpenrCtrlHandler.cpp
butjar/openr
b42d1d2ba30e2e14f6b4e8e592aa88cff16b87c5
[ "MIT" ]
null
null
null
openr/ctrl-server/OpenrCtrlHandler.cpp
butjar/openr
b42d1d2ba30e2e14f6b4e8e592aa88cff16b87c5
[ "MIT" ]
null
null
null
openr/ctrl-server/OpenrCtrlHandler.cpp
butjar/openr
b42d1d2ba30e2e14f6b4e8e592aa88cff16b87c5
[ "MIT" ]
null
null
null
/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <openr/ctrl-server/OpenrCtrlHandler.h> #include <re2/re2.h> #include <folly/ExceptionString.h> #include <folly/io/async/SSLContext.h> #include <folly/io/async/ssl/OpenSSLUtils.h> #include <thrift/lib/cpp2/server/ThriftServer.h> #include <openr/common/Constants.h> #include <openr/common/Util.h> #include <openr/config-store/PersistentStore.h> #include <openr/decision/Decision.h> #include <openr/fib/Fib.h> #include <openr/if/gen-cpp2/PersistentStore_types.h> #include <openr/kvstore/KvStore.h> #include <openr/link-monitor/LinkMonitor.h> #include <openr/prefix-manager/PrefixManager.h> namespace openr { OpenrCtrlHandler::OpenrCtrlHandler( const std::string& nodeName, const std::unordered_set<std::string>& acceptablePeerCommonNames, OpenrEventBase* ctrlEvb, Decision* decision, Fib* fib, KvStore* kvStore, LinkMonitor* linkMonitor, PersistentStore* configStore, PrefixManager* prefixManager, std::shared_ptr<const Config> config, MonitorSubmitUrl const& monitorSubmitUrl, fbzmq::Context& context) : facebook::fb303::BaseService("openr"), nodeName_(nodeName), acceptablePeerCommonNames_(acceptablePeerCommonNames), decision_(decision), fib_(fib), kvStore_(kvStore), linkMonitor_(linkMonitor), configStore_(configStore), prefixManager_(prefixManager), config_(config) { // Create monitor client zmqMonitorClient_ = std::make_unique<fbzmq::ZmqMonitorClient>(context, monitorSubmitUrl); // Add fiber task to receive publication from KvStore if (kvStore_) { taskFuture_ = ctrlEvb->addFiberTaskFuture([ q = std::move(kvStore_->getKvStoreUpdatesReader()), this ]() mutable noexcept { LOG(INFO) << "Starting KvStore updates processing fiber"; while (true) { auto maybePublication = q.get(); // perform read VLOG(2) << "Received publication from KvStore"; if (maybePublication.hasError()) { LOG(INFO) << "Terminating KvStore publications processing fiber"; break; } SYNCHRONIZED(kvStorePublishers_) { for (auto& kv : kvStorePublishers_) { kv.second.next(maybePublication.value()); } } bool isAdjChanged = false; // check if any of KeyVal has 'adj' update for (auto& kv : maybePublication.value().keyVals) { auto& key = kv.first; auto& val = kv.second; // check if we have any value update. // Ttl refreshing won't update any value. if (!val.value_ref().has_value()) { continue; } // "adj:*" key has changed. Update local collection if (key.find(Constants::kAdjDbMarker.toString()) == 0) { VLOG(3) << "Adj key: " << key << " change received"; isAdjChanged = true; break; } } if (isAdjChanged) { // thrift::Publication contains "adj:*" key change. // Clean ALL pending promises longPollReqs_.withWLock([&](auto& longPollReqs) { for (auto& kv : longPollReqs) { auto& p = kv.second.first; p.setValue(true); } longPollReqs.clear(); }); } else { longPollReqs_.withWLock([&](auto& longPollReqs) { auto now = getUnixTimeStampMs(); std::vector<int64_t> reqsToClean; for (auto& kv : longPollReqs) { auto& clientId = kv.first; auto& req = kv.second; auto& p = req.first; auto& timeStamp = req.second; if (now - timeStamp >= Constants::kLongPollReqHoldTime.count()) { LOG(INFO) << "Elapsed time: " << now - timeStamp << " is over hold limit: " << Constants::kLongPollReqHoldTime.count(); reqsToClean.emplace_back(clientId); p.setValue(false); } } // cleanup expired requests since no ADJ change observed for (auto& clientId : reqsToClean) { longPollReqs.erase(clientId); } }); } } }); } } OpenrCtrlHandler::~OpenrCtrlHandler() { std::vector<apache::thrift::ServerStreamPublisher<thrift::Publication>> publishers; // NOTE: We're intentionally creating list of publishers to and then invoke // `complete()` on them. // Reason => `complete()` returns only when callback `onComplete` associated // with publisher returns. Since we acquire lock within `onComplete` callback, // we will run into the deadlock if `complete()` is invoked within // SYNCHRONIZED block SYNCHRONIZED(kvStorePublishers_) { for (auto& kv : kvStorePublishers_) { publishers.emplace_back(std::move(kv.second)); } } LOG(INFO) << "Terminating " << publishers.size() << " active KvStore snoop stream(s)."; for (auto& publisher : publishers) { std::move(publisher).complete(); } LOG(INFO) << "Cleanup all pending request(s)."; longPollReqs_.withWLock([&](auto& longPollReqs) { longPollReqs.clear(); }); LOG(INFO) << "Waiting for termination of kvStoreUpdatesQueue."; taskFuture_.wait(); } void OpenrCtrlHandler::authorizeConnection() { auto connContext = getConnectionContext()->getConnectionContext(); auto peerCommonName = connContext->getPeerCommonName(); auto peerAddr = connContext->getPeerAddress(); // We legitely accepts all connections (secure/non-secure) from localhost if (peerAddr->isLoopbackAddress()) { return; } if (peerCommonName.empty() || acceptablePeerCommonNames_.empty()) { // for now, we will allow non-secure connections, but lets log the event so // we know how often this is happening. fbzmq::LogSample sample{}; sample.addString( "event", peerCommonName.empty() ? "UNENCRYPTED_CTRL_CONNECTION" : "UNRESTRICTED_AUTHORIZATION"); sample.addString("node_name", nodeName_); sample.addString( "peer_address", connContext->getPeerAddress()->getAddressStr()); sample.addString("peer_common_name", peerCommonName); zmqMonitorClient_->addEventLog(fbzmq::thrift::EventLog( apache::thrift::FRAGILE, Constants::kEventLogCategory.toString(), {sample.toJson()})); LOG(INFO) << "Authorizing request with issues: " << sample.toJson(); return; } if (!acceptablePeerCommonNames_.count(peerCommonName)) { throw thrift::OpenrError( folly::sformat("Peer name {} is unacceptable", peerCommonName)); } } facebook::fb303::cpp2::fb303_status OpenrCtrlHandler::getStatus() { return facebook::fb303::cpp2::fb303_status::ALIVE; } folly::SemiFuture<std::unique_ptr<std::vector<fbzmq::thrift::EventLog>>> OpenrCtrlHandler::semifuture_getEventLogs() { folly::Promise<std::unique_ptr<std::vector<fbzmq::thrift::EventLog>>> p; auto eventLogs = zmqMonitorClient_->getLastEventLogs(); if (eventLogs.has_value()) { p.setValue(std::make_unique<std::vector<fbzmq::thrift::EventLog>>( eventLogs.value())); } else { p.setException( thrift::OpenrError(std::string("Fail to retrieve eventlogs"))); } return p.getSemiFuture(); } void OpenrCtrlHandler::getCounters(std::map<std::string, int64_t>& _return) { BaseService::getCounters(_return); for (auto const& kv : zmqMonitorClient_->dumpCounters()) { _return.emplace(kv.first, static_cast<int64_t>(kv.second.value)); } } void OpenrCtrlHandler::getRegexCounters( std::map<std::string, int64_t>& _return, std::unique_ptr<std::string> regex) { // Compile regex re2::RE2 compiledRegex(*regex); if (not compiledRegex.ok()) { return; } // Get all counters std::map<std::string, int64_t> counters; getCounters(counters); // Filter counters for (auto const& kv : counters) { if (RE2::PartialMatch(kv.first, compiledRegex)) { _return.emplace(kv); } } } void OpenrCtrlHandler::getSelectedCounters( std::map<std::string, int64_t>& _return, std::unique_ptr<std::vector<std::string>> keys) { // Get all counters std::map<std::string, int64_t> counters; getCounters(counters); // Filter counters for (auto const& key : *keys) { auto it = counters.find(key); if (it != counters.end()) { _return.emplace(*it); } } } int64_t OpenrCtrlHandler::getCounter(std::unique_ptr<std::string> key) { auto counter = zmqMonitorClient_->getCounter(*key); if (counter.has_value()) { return static_cast<int64_t>(counter->value); } return 0; } void OpenrCtrlHandler::getMyNodeName(std::string& _return) { _return = std::string(nodeName_); } void OpenrCtrlHandler::getOpenrVersion(thrift::OpenrVersions& _openrVersion) { _openrVersion.version = Constants::kOpenrVersion; _openrVersion.lowestSupportedVersion = Constants::kOpenrSupportedVersion; } void OpenrCtrlHandler::getBuildInfo(thrift::BuildInfo& _buildInfo) { _buildInfo = getBuildInfoThrift(); } // validate config void OpenrCtrlHandler::dryrunConfig( std::string& _return, std::unique_ptr<std::string> file) { try { // Create policy manager using new config file auto config = Config(*file); _return = config.getRunningConfig(); } catch (const std::exception& ex) { throw thrift::OpenrError(ex.what()); } } void OpenrCtrlHandler::getRunningConfig(std::string& _return) { _return = config_->getRunningConfig(); } void OpenrCtrlHandler::getRunningConfigThrift(thrift::OpenrConfig& _config) { _config = config_->getConfig(); } // // PrefixManager APIs // folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_advertisePrefixes( std::unique_ptr<std::vector<thrift::PrefixEntry>> prefixes) { CHECK(prefixManager_); return prefixManager_->advertisePrefixes(std::move(*prefixes)) .defer([](folly::Try<bool>&&) { return folly::Unit(); }); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_withdrawPrefixes( std::unique_ptr<std::vector<thrift::PrefixEntry>> prefixes) { CHECK(prefixManager_); return prefixManager_->withdrawPrefixes(std::move(*prefixes)) .defer([](folly::Try<bool>&&) { return folly::Unit(); }); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_withdrawPrefixesByType( thrift::PrefixType prefixType) { CHECK(prefixManager_); return prefixManager_->withdrawPrefixesByType(prefixType) .defer([](folly::Try<bool>&&) { return folly::Unit(); }); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_syncPrefixesByType( thrift::PrefixType prefixType, std::unique_ptr<std::vector<thrift::PrefixEntry>> prefixes) { CHECK(prefixManager_); return prefixManager_->syncPrefixesByType(prefixType, std::move(*prefixes)) .defer([](folly::Try<bool>&&) { return folly::Unit(); }); } folly::SemiFuture<std::unique_ptr<std::vector<thrift::PrefixEntry>>> OpenrCtrlHandler::semifuture_getPrefixes() { CHECK(prefixManager_); return prefixManager_->getPrefixes(); } folly::SemiFuture<std::unique_ptr<std::vector<thrift::PrefixEntry>>> OpenrCtrlHandler::semifuture_getPrefixesByType(thrift::PrefixType prefixType) { CHECK(prefixManager_); return prefixManager_->getPrefixesByType(prefixType); } // // Fib APIs // folly::SemiFuture<std::unique_ptr<thrift::RouteDatabase>> OpenrCtrlHandler::semifuture_getRouteDb() { CHECK(fib_); return fib_->getRouteDb(); } folly::SemiFuture<std::unique_ptr<std::vector<thrift::UnicastRoute>>> OpenrCtrlHandler::semifuture_getUnicastRoutesFiltered( std::unique_ptr<std::vector<std::string>> prefixes) { CHECK(fib_); return fib_->getUnicastRoutes(std::move(*prefixes)); } folly::SemiFuture<std::unique_ptr<std::vector<thrift::UnicastRoute>>> OpenrCtrlHandler::semifuture_getUnicastRoutes() { folly::Promise<std::unique_ptr<std::vector<thrift::UnicastRoute>>> p; CHECK(fib_); return fib_->getUnicastRoutes({}); } folly::SemiFuture<std::unique_ptr<std::vector<thrift::MplsRoute>>> OpenrCtrlHandler::semifuture_getMplsRoutes() { CHECK(fib_); return fib_->getMplsRoutes({}); } folly::SemiFuture<std::unique_ptr<std::vector<thrift::MplsRoute>>> OpenrCtrlHandler::semifuture_getMplsRoutesFiltered( std::unique_ptr<std::vector<int32_t>> labels) { CHECK(fib_); return fib_->getMplsRoutes(std::move(*labels)); } folly::SemiFuture<std::unique_ptr<thrift::PerfDatabase>> OpenrCtrlHandler::semifuture_getPerfDb() { CHECK(fib_); return fib_->getPerfDb(); } // // Decision APIs // folly::SemiFuture<std::unique_ptr<thrift::RouteDatabase>> OpenrCtrlHandler::semifuture_getRouteDbComputed( std::unique_ptr<std::string> nodeName) { CHECK(decision_); return decision_->getDecisionRouteDb(*nodeName); } folly::SemiFuture<std::unique_ptr<thrift::AdjDbs>> OpenrCtrlHandler::semifuture_getDecisionAdjacencyDbs() { CHECK(decision_); return decision_->getDecisionAdjacencyDbs(); } folly::SemiFuture<std::unique_ptr<thrift::PrefixDbs>> OpenrCtrlHandler::semifuture_getDecisionPrefixDbs() { CHECK(decision_); return decision_->getDecisionPrefixDbs(); } // // KvStore APIs // folly::SemiFuture<std::unique_ptr<thrift::AreasConfig>> OpenrCtrlHandler::semifuture_getAreasConfig() { CHECK(kvStore_); return kvStore_->getAreasConfig(); } folly::SemiFuture<std::unique_ptr<thrift::Publication>> OpenrCtrlHandler::semifuture_getKvStoreKeyVals( std::unique_ptr<std::vector<std::string>> filterKeys) { thrift::KeyGetParams params; params.keys = std::move(*filterKeys); CHECK(kvStore_); return kvStore_->getKvStoreKeyVals(std::move(params)); } folly::SemiFuture<std::unique_ptr<thrift::Publication>> OpenrCtrlHandler::semifuture_getKvStoreKeyValsArea( std::unique_ptr<std::vector<std::string>> filterKeys, std::unique_ptr<std::string> area) { thrift::KeyGetParams params; params.keys = std::move(*filterKeys); CHECK(kvStore_); return kvStore_->getKvStoreKeyVals(std::move(params), std::move(*area)); } folly::SemiFuture<std::unique_ptr<thrift::Publication>> OpenrCtrlHandler::semifuture_getKvStoreKeyValsFiltered( std::unique_ptr<thrift::KeyDumpParams> filter) { CHECK(kvStore_); return kvStore_->dumpKvStoreKeys(std::move(*filter)); } folly::SemiFuture<std::unique_ptr<thrift::Publication>> OpenrCtrlHandler::semifuture_getKvStoreKeyValsFilteredArea( std::unique_ptr<thrift::KeyDumpParams> filter, std::unique_ptr<std::string> area) { CHECK(kvStore_); return kvStore_->dumpKvStoreKeys(std::move(*filter), std::move(*area)); } folly::SemiFuture<std::unique_ptr<thrift::Publication>> OpenrCtrlHandler::semifuture_getKvStoreHashFiltered( std::unique_ptr<thrift::KeyDumpParams> filter) { CHECK(kvStore_); return kvStore_->dumpKvStoreHashes(std::move(*filter)); } folly::SemiFuture<std::unique_ptr<thrift::Publication>> OpenrCtrlHandler::semifuture_getKvStoreHashFilteredArea( std::unique_ptr<thrift::KeyDumpParams> filter, std::unique_ptr<std::string> area) { CHECK(kvStore_); return kvStore_->dumpKvStoreHashes(std::move(*filter), std::move(*area)); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_setKvStoreKeyVals( std::unique_ptr<thrift::KeySetParams> setParams, std::unique_ptr<std::string> area) { CHECK(kvStore_); return kvStore_->setKvStoreKeyVals(std::move(*setParams), std::move(*area)); } folly::SemiFuture<bool> OpenrCtrlHandler::semifuture_longPollKvStoreAdj( std::unique_ptr<thrift::KeyVals> snapshot) { folly::Promise<bool> p; auto sf = p.getSemiFuture(); auto timeStamp = getUnixTimeStampMs(); auto requestId = pendingRequestId_++; thrift::KeyDumpParams params; // build thrift::KeyVals with "adj:" key ONLY // to ensure KvStore ONLY compare "adj:" key thrift::KeyVals adjKeyVals; for (auto& kv : *snapshot) { if (kv.first.find(Constants::kAdjDbMarker.toString()) == 0) { adjKeyVals.emplace(kv.first, kv.second); } } // Only care about "adj:" key params.prefix = Constants::kAdjDbMarker; // Only dump difference between KvStore and client snapshot params.keyValHashes_ref() = std::move(adjKeyVals); // Explicitly do SYNC call to KvStore std::unique_ptr<thrift::Publication> thriftPub{nullptr}; try { thriftPub = semifuture_getKvStoreKeyValsFiltered( std::make_unique<thrift::KeyDumpParams>(params)) .get(); } catch (std::exception const& ex) { p.setException(thrift::OpenrError(ex.what())); return sf; } if (thriftPub->keyVals.size() > 0) { VLOG(3) << "AdjKey has been added/modified. Notify immediately"; p.setValue(true); } else if ( thriftPub->tobeUpdatedKeys_ref().has_value() && thriftPub->tobeUpdatedKeys_ref().value().size() > 0) { VLOG(3) << "AdjKey has been deleted/expired. Notify immediately"; p.setValue(true); } else { // Client provided data is consistent with KvStore. // Store req for future processing when there is publication // from KvStore. VLOG(3) << "No adj change detected. Store req as pending request"; longPollReqs_.withWLock([&](auto& longPollReq) { longPollReq.emplace(requestId, std::make_pair(std::move(p), timeStamp)); }); } return sf; } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_processKvStoreDualMessage( std::unique_ptr<thrift::DualMessages> messages, std::unique_ptr<std::string> area) { CHECK(kvStore_); return kvStore_->processKvStoreDualMessage( std::move(*messages), std::move(*area)); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_updateFloodTopologyChild( std::unique_ptr<thrift::FloodTopoSetParams> params, std::unique_ptr<std::string> area) { CHECK(kvStore_); return kvStore_->updateFloodTopologyChild( std::move(*params), std::move(*area)); } folly::SemiFuture<std::unique_ptr<thrift::SptInfos>> OpenrCtrlHandler::semifuture_getSpanningTreeInfos( std::unique_ptr<std::string> area) { CHECK(kvStore_); return kvStore_->getSpanningTreeInfos(std::move(*area)); } folly::SemiFuture<std::unique_ptr<thrift::PeersMap>> OpenrCtrlHandler::semifuture_getKvStorePeers() { CHECK(kvStore_); return kvStore_->getKvStorePeers(); } folly::SemiFuture<std::unique_ptr<thrift::PeersMap>> OpenrCtrlHandler::semifuture_getKvStorePeersArea( std::unique_ptr<std::string> area) { CHECK(kvStore_); return kvStore_->getKvStorePeers(std::move(*area)); } apache::thrift::ServerStream<thrift::Publication> OpenrCtrlHandler::subscribeKvStore() { // Get new client-ID (monotonically increasing) auto clientToken = publisherToken_++; auto streamAndPublisher = apache::thrift::ServerStream<thrift::Publication>::createPublisher( [this, clientToken]() { SYNCHRONIZED(kvStorePublishers_) { if (kvStorePublishers_.erase(clientToken)) { LOG(INFO) << "KvStore snoop stream-" << clientToken << " ended."; } else { LOG(ERROR) << "Can't remove unknown KvStore snoop stream-" << clientToken; } } }); SYNCHRONIZED(kvStorePublishers_) { assert(kvStorePublishers_.count(clientToken) == 0); LOG(INFO) << "KvStore snoop stream-" << clientToken << " started."; kvStorePublishers_.emplace( clientToken, std::move(streamAndPublisher.second)); } return std::move(streamAndPublisher.first); } folly::SemiFuture<apache::thrift::ResponseAndServerStream< thrift::Publication, thrift::Publication>> OpenrCtrlHandler::semifuture_subscribeAndGetKvStore() { return semifuture_getKvStoreKeyValsFiltered( std::make_unique<thrift::KeyDumpParams>()) .defer( [stream = subscribeKvStore()]( folly::Try<std::unique_ptr<thrift::Publication>>&& pub) mutable { pub.throwIfFailed(); return apache::thrift::ResponseAndServerStream< thrift::Publication, thrift::Publication>{std::move(*pub.value()), std::move(stream)}; }); } // // LinkMonitor APIs // folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_setNodeOverload() { CHECK(linkMonitor_); return linkMonitor_->setNodeOverload(true); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_unsetNodeOverload() { CHECK(linkMonitor_); return linkMonitor_->setNodeOverload(false); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_setInterfaceOverload( std::unique_ptr<std::string> interfaceName) { CHECK(linkMonitor_); return linkMonitor_->setInterfaceOverload(std::move(*interfaceName), true); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_unsetInterfaceOverload( std::unique_ptr<std::string> interfaceName) { CHECK(linkMonitor_); return linkMonitor_->setInterfaceOverload(std::move(*interfaceName), false); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_setInterfaceMetric( std::unique_ptr<std::string> interfaceName, int32_t overrideMetric) { CHECK(linkMonitor_); return linkMonitor_->setLinkMetric(std::move(*interfaceName), overrideMetric); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_unsetInterfaceMetric( std::unique_ptr<std::string> interfaceName) { CHECK(linkMonitor_); return linkMonitor_->setLinkMetric(std::move(*interfaceName), std::nullopt); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_setAdjacencyMetric( std::unique_ptr<std::string> interfaceName, std::unique_ptr<std::string> adjNodeName, int32_t overrideMetric) { CHECK(linkMonitor_); return linkMonitor_->setAdjacencyMetric( std::move(*interfaceName), std::move(*adjNodeName), overrideMetric); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_unsetAdjacencyMetric( std::unique_ptr<std::string> interfaceName, std::unique_ptr<std::string> adjNodeName) { CHECK(linkMonitor_); return linkMonitor_->setAdjacencyMetric( std::move(*interfaceName), std::move(*adjNodeName), std::nullopt); } folly::SemiFuture<std::unique_ptr<thrift::DumpLinksReply>> OpenrCtrlHandler::semifuture_getInterfaces() { CHECK(linkMonitor_); return linkMonitor_->getInterfaces(); } folly::SemiFuture<std::unique_ptr<thrift::AdjacencyDatabase>> OpenrCtrlHandler::semifuture_getLinkMonitorAdjacencies() { CHECK(linkMonitor_); return linkMonitor_->getLinkMonitorAdjacencies(); } // // ConfigStore API // folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_setConfigKey( std::unique_ptr<std::string> key, std::unique_ptr<std::string> value) { CHECK(configStore_); return configStore_->store(std::move(*key), std::move(*value)); } folly::SemiFuture<folly::Unit> OpenrCtrlHandler::semifuture_eraseConfigKey(std::unique_ptr<std::string> key) { CHECK(configStore_); auto sf = configStore_->erase(std::move(*key)); return std::move(sf).defer([](folly::Try<bool>&&) { return folly::Unit(); }); } folly::SemiFuture<std::unique_ptr<std::string>> OpenrCtrlHandler::semifuture_getConfigKey(std::unique_ptr<std::string> key) { CHECK(configStore_); auto sf = configStore_->load(std::move(*key)); return std::move(sf).defer( [](folly::Try<std::optional<std::string>>&& val) mutable { if (val.hasException() or not val->has_value()) { throw thrift::OpenrError("key doesn't exists"); } return std::make_unique<std::string>(std::move(val).value().value()); }); } } // namespace openr
31.944818
80
0.693111
butjar
3e9e39a205baf4b5faf2fc2283874d3dc7e30256
3,598
cpp
C++
source/directsound/ResultCodeDS.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
85
2015-04-06T05:37:10.000Z
2022-03-22T19:53:03.000Z
source/directsound/ResultCodeDS.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
10
2016-03-17T11:18:24.000Z
2021-05-11T09:21:43.000Z
source/directsound/ResultCodeDS.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
45
2015-09-14T03:54:01.000Z
2022-03-22T19:53:09.000Z
#include "stdafx.h" /* * Copyright (c) 2007-2012 SlimDX Group * * 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 <dsound.h> #include "../Result.h" #include "ResultCodeDS.h" namespace SlimDX { namespace DirectSound { ResultCode::ResultCode() { } Result ResultCode::Success::get() { return Result( DS_OK ); } Result ResultCode::Failure::get() { return Result( E_FAIL ); } Result ResultCode::NoVirtualization::get() { return Result( DS_NO_VIRTUALIZATION ); } Result ResultCode::AccessDenied::get() { return Result( DSERR_ACCESSDENIED ); } Result ResultCode::Allocated::get() { return Result( DSERR_ALLOCATED ); } Result ResultCode::AlreadyInitialized::get() { return Result( DSERR_ALREADYINITIALIZED ); } Result ResultCode::BadFormat::get() { return Result( DSERR_BADFORMAT ); } Result ResultCode::BadSendBufferGuid::get() { return Result( DSERR_BADSENDBUFFERGUID ); } Result ResultCode::BufferLost::get() { return Result( DSERR_BUFFERLOST ); } Result ResultCode::BufferTooSmall::get() { return Result( DSERR_BUFFERTOOSMALL ); } Result ResultCode::ControlUnavailable::get() { return Result( DSERR_CONTROLUNAVAIL ); } Result ResultCode::DirectSound8Required::get() { return Result( DSERR_DS8_REQUIRED ); } Result ResultCode::EffectsUnavailable::get() { return Result( DSERR_FXUNAVAILABLE ); } Result ResultCode::Generic::get() { return Result( DSERR_GENERIC ); } Result ResultCode::InvalidCall::get() { return Result( DSERR_INVALIDCALL ); } Result ResultCode::InvalidParameter::get() { return Result( DSERR_INVALIDPARAM ); } Result ResultCode::NoAggregation::get() { return Result( DSERR_NOAGGREGATION ); } Result ResultCode::NoDriver::get() { return Result( DSERR_NODRIVER ); } Result ResultCode::NoInterface::get() { return Result( DSERR_NOINTERFACE ); } Result ResultCode::ObjectNotFound::get() { return Result( DSERR_OBJECTNOTFOUND ); } Result ResultCode::OtherApplicationHasPriority::get() { return Result( DSERR_OTHERAPPHASPRIO ); } Result ResultCode::PriorityLevelNeeded::get() { return Result( DSERR_PRIOLEVELNEEDED ); } Result ResultCode::SendLoop::get() { return Result( DSERR_SENDLOOP ); } Result ResultCode::Uninitialized::get() { return Result( DSERR_UNINITIALIZED ); } Result ResultCode::Unsupported::get() { return Result( DSERR_UNSUPPORTED ); } } }
22.209877
80
0.697332
HeavenWu
3ea06032c6b839ed37c92bac252531157a01e331
227
cpp
C++
AtCoder/arc110/A.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
AtCoder/arc110/A.cpp
iamsuryakant/competitive-programming
413000f5bc4a627407e1335c35dcdbee516e8cc1
[ "MIT" ]
null
null
null
AtCoder/arc110/A.cpp
iamsuryakant/competitive-programming
413000f5bc4a627407e1335c35dcdbee516e8cc1
[ "MIT" ]
2
2021-01-23T14:35:48.000Z
2021-03-15T05:04:24.000Z
#include<bits/stdc++.h> using namespace std; #define int long long signed main() { int N; cin >> N; int ans = 1; for (int i = 2; i <= N; i++) ans = lcm(ans, i); cout << ans + 1; return 0; }
17.461538
52
0.488987
Code-With-Aagam
3ea0aada20fa0af2c42f1d81a9414e33a2e15f04
4,115
cpp
C++
cpp/libs/opendnp3/src/opendnp3/link/SecLinkLayerStates.cpp
SensusDA/opendnp3
c9aab97279fa7461155fd583d3955853b3ad99a0
[ "Apache-2.0" ]
null
null
null
cpp/libs/opendnp3/src/opendnp3/link/SecLinkLayerStates.cpp
SensusDA/opendnp3
c9aab97279fa7461155fd583d3955853b3ad99a0
[ "Apache-2.0" ]
null
null
null
cpp/libs/opendnp3/src/opendnp3/link/SecLinkLayerStates.cpp
SensusDA/opendnp3
c9aab97279fa7461155fd583d3955853b3ad99a0
[ "Apache-2.0" ]
null
null
null
/** * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp 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. * * This project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #include "SecLinkLayerStates.h" #include <openpal/logging/LogMacros.h> #include "opendnp3/ErrorCodes.h" #include "opendnp3/link/LinkLayer.h" #include "opendnp3/LogLevels.h" using namespace openpal; namespace opendnp3 { //////////////////////////////////////// // SecStateBase //////////////////////////////////////// void SecStateBase::OnTransmitResult(LinkLayer* apLL, bool success) { FORMAT_LOG_BLOCK(apLL->GetLogger(), flags::ERR, "Invalid event for state: %s", this->Name()); } //////////////////////////////////////////////////////// // Class SLLS_NotReset //////////////////////////////////////////////////////// SLLS_NotReset SLLS_NotReset::instance; void SLLS_NotReset::TestLinkStatus(LinkLayer* apLL, bool aFcb) { SIMPLE_LOG_BLOCK_WITH_CODE(apLL->GetLogger(), flags::WARN, DLERR_UNEXPECTED_LPDU, "TestLinkStatus ignored"); } void SLLS_NotReset::ConfirmedUserData(LinkLayer* apLL, bool aFcb, const openpal::ReadBufferView&) { SIMPLE_LOG_BLOCK_WITH_CODE(apLL->GetLogger(), flags::WARN, DLERR_UNEXPECTED_LPDU, "ConfirmedUserData ignored"); } void SLLS_NotReset::ResetLinkStates(LinkLayer* apLL) { apLL->QueueAck(); apLL->ResetReadFCB(); apLL->ChangeState(SLLS_TransmitWaitReset::Inst()); } void SLLS_NotReset::RequestLinkStatus(LinkLayer* apLL) { apLL->QueueLinkStatus(); apLL->ChangeState(SLLS_TransmitWaitNotReset::Inst()); } //////////////////////////////////////////////////////// // Class SLLS_Reset //////////////////////////////////////////////////////// SLLS_Reset SLLS_Reset::instance; void SLLS_Reset::TestLinkStatus(LinkLayer* apLL, bool aFcb) { if(apLL->NextReadFCB() == aFcb) { apLL->QueueAck(); apLL->ToggleReadFCB(); apLL->ChangeState(SLLS_TransmitWaitReset::Inst()); } else { // "Re-transmit most recent response that contained function code 0 (ACK) or 1 (NACK)." // This is a PITA implement // TODO - see if this function is deprecated or not SIMPLE_LOG_BLOCK(apLL->GetLogger(), flags::WARN, "Received TestLinkStatus with invalid FCB"); } } void SLLS_Reset::ConfirmedUserData(LinkLayer* apLL, bool aFcb, const openpal::ReadBufferView& arBuffer) { apLL->QueueAck(); if (apLL->NextReadFCB() == aFcb) { apLL->ToggleReadFCB(); apLL->DoDataUp(arBuffer); } else { SIMPLE_LOG_BLOCK(apLL->GetLogger(), flags::WARN, "Confirmed data w/ wrong FCB"); } apLL->ChangeState(SLLS_TransmitWaitReset::Inst()); } void SLLS_Reset::ResetLinkStates(LinkLayer* apLL) { apLL->QueueAck(); apLL->ResetReadFCB(); apLL->ChangeState(SLLS_TransmitWaitReset::Inst()); } void SLLS_Reset::RequestLinkStatus(LinkLayer* apLL) { apLL->QueueLinkStatus(); apLL->ChangeState(SLLS_TransmitWaitReset::Inst()); } //////////////////////////////////////////////////////// // Class SLLS_TransmitWaitReset //////////////////////////////////////////////////////// SLLS_TransmitWaitReset SLLS_TransmitWaitReset::instance; //////////////////////////////////////////////////////// // Class SLLS_TransmitWaitNotReset //////////////////////////////////////////////////////// SLLS_TransmitWaitNotReset SLLS_TransmitWaitNotReset::instance; } //end namepsace
30.036496
112
0.659538
SensusDA
3ea87a0fd7acdfda840408072d0b37830315e238
38
cc
C++
chapter-09/9.40.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
1
2017-04-01T06:57:30.000Z
2017-04-01T06:57:30.000Z
chapter-09/9.40.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
chapter-09/9.40.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
q2.substr(0, 13) + q1.substr(18, 15);
19
37
0.605263
hongmi
3ea944ff0a8d3b41810e752dc9aff778847630b6
1,482
cpp
C++
wxdraw/object/Object.cpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
wxdraw/object/Object.cpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
wxdraw/object/Object.cpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
#include <uuid/uuid.h> #include "wxdraw/object/Object.hpp" #include "wxdraw/property/Property.hpp" namespace wxdraw::object { std::map<std::type_index, std::map<wxString, int>> Object::Serials; /** コンストラクタ @param type 型名 */ Object::Object(const wxString& type) : type_(type) { } /** コピーコンストラクタ @param src コピー元 */ Object::Object(const Object& src) : type_(src.type_) { onCreate(typeid(src)); } /** */ PropertyPtr Object::generateProperty() { auto property = std::make_shared<Property>(shared_from_this()); property->appendMember("Id", id_).setShow(false); return property; } /** */ void Object::onUpdateProperty() { wxRegEx match("^([A-Za-z]+)_(\\d+)"); if(match.Matches(name_)) { std::type_index type(typeid(*this)); auto name = match.GetMatch(name_, 1); auto index = wxAtoi(match.GetMatch(name_, 2)); if(index > Serials[type][name]) { Serials[type][name] = index; } } } /** 新規IDを生成する @return 新規ID */ wxString Object::CreateId() { uuid_t id; uuid_generate(id); uuid_string_t strId; uuid_unparse_upper(id, strId); return wxString(strId); } /** 新規に生成されたときの処理 */ void Object::onCreate() { onCreate(typeid(*this)); } /** */ wxDataObject* Object::toDataObject() { return new wxTextDataObject(getId()); } /** 新規に生成されたときの処理 */ void Object::onCreate(const std::type_index& type) { id_ = CreateId(); if(name_.IsEmpty()) { name_ = wxString::Format("%s_%d", type_, ++Serials[type][type_]); } } }
19.5
69
0.649798
yasuikentarow
3eaadd4e70d02bdf4fa75abc46863373b6e19c16
8,778
cpp
C++
ofxHammingCodeExample/src/main.cpp
2bbb/ofxHammingCode
0434eec8db7c4f50206ad0c34f90e9b0c5c7c386
[ "MIT" ]
4
2015-04-01T08:57:35.000Z
2021-12-28T15:22:35.000Z
ofxHammingCodeExample/src/main.cpp
2bbb/ofxHammingCode
0434eec8db7c4f50206ad0c34f90e9b0c5c7c386
[ "MIT" ]
1
2017-05-30T10:12:51.000Z
2017-06-01T15:07:52.000Z
ofxHammingCodeExample/src/main.cpp
2bbb/ofxHammingCode
0434eec8db7c4f50206ad0c34f90e9b0c5c7c386
[ "MIT" ]
3
2020-11-26T00:46:14.000Z
2021-12-28T15:22:37.000Z
#include "ofMain.h" #include "ofxHammingCode.h" class ofApp : public ofBaseApp { public: void setup() { testH74(); std::cout << std::endl; testH74SECDED(); std::cout << std::endl; test3126(ofRandom(0, 1 << 25)); std::cout << std::endl; testH3126SECDED(ofRandom(0, 1 << 25)); std::cout << std::endl; ofExit(); } void testH74() { ofLogNotice() << "==== H74 ====" << std::endl; std::uint8_t d; d = 175; ofLogNotice() << "raw data: " << (int)d; std::uint16_t h = ofxHammingCode::H74::encode(d); ofLogNotice() << "encoded data: " << h; if(ofxHammingCode::H74::isCorrect(h)) { ofLogNotice() << "decoded: " << (int)ofxHammingCode::H74::decode(h); } else { ofLogNotice() << "incorrect data"; } std::cout << std::endl; h = ofxHammingCode::H74::encode(d); h ^= 4; ofLogNotice() << "add 1bit noise: " << h; if(ofxHammingCode::H74::isCorrect(h)) { ofLogNotice() << "decoded: " << (int)ofxHammingCode::H74::decode(h); } else { ofLogNotice() << "incorrect data"; } ofxHammingCode::H74::correct(h); ofLogNotice() << "corrected data: " << h; if(ofxHammingCode::H74::isCorrect(h)) { ofLogNotice() << "decoded: " << (int)ofxHammingCode::H74::decode(h); } else { ofLogNotice() << "incorrect data"; } std::cout << std::endl; h = ofxHammingCode::H74::encode(d); h ^= 5; ofLogNotice() << "add 2bit noise (this will be judged incorrect and can't correct): " << h; if(ofxHammingCode::H74::isCorrect(h)) { ofLogNotice() << "decoded: (but, incorrect) " << (int)ofxHammingCode::H74::decode(h); } else { ofLogNotice() << "incorrect data"; ofxHammingCode::H74::correct(h); ofLogNotice() << "corrected data (but, incorrect) : " << h; if(ofxHammingCode::H74::isCorrect(h)) { ofLogNotice() << "decoded (but, incorrect) : " << (int)ofxHammingCode::H74::decode(h); } else { ofLogNotice() << "incorrect data"; } } } void testH74SECDED() { ofLogNotice() << "==== H74::SECDED ===="; ofLogNotice() << "[single error correction, double error detection]" << std::endl; std::uint8_t d; d = 175; ofLogNotice() << "raw data: " << (int)d; std::uint16_t h = ofxHammingCode::H74::SECDED::encode(d); ofLogNotice() << "encoded data: " << h; if(ofxHammingCode::H74::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << (int)ofxHammingCode::H74::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; } std::cout << std::endl; h = ofxHammingCode::H74::SECDED::encode(d); h ^= 4; ofLogNotice() << "add 1bit noise: " << h; if(ofxHammingCode::H74::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << (int)ofxHammingCode::H74::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; } ofxHammingCode::H74::SECDED::correct(h); ofLogNotice() << "corrected data: " << h; if(ofxHammingCode::H74::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << (int)ofxHammingCode::H74::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; } std::cout << std::endl; h = ofxHammingCode::H74::SECDED::encode(d); h ^= 5; ofLogNotice() << "add 2bit noise: " << h; if(ofxHammingCode::H74::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << (int)ofxHammingCode::H74::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; if(ofxHammingCode::H74::SECDED::isCorrectable(h)) { ofLogNotice() << "this data is correctable"; ofxHammingCode::H74::SECDED::correct(h); ofLogNotice() << "corrected data: " << h; if(ofxHammingCode::H74::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << (int)ofxHammingCode::H74::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; } } else { ofLogNotice() << "this data can't correctable"; } } } void test3126(const std::uint32_t d) { ofLogNotice() << "==== H3126 ====" << std::endl; ofLogNotice() << "raw data: " << d; uint32_t h = ofxHammingCode::H3126::encode(d); ofLogNotice() << "encoded data: " << h; if(ofxHammingCode::H3126::isCorrect(h)) { ofLogNotice() << "decoded: " << ofxHammingCode::H3126::decode(h); } else { ofLogNotice() << "incorrect data"; } std::cout << std::endl; h = ofxHammingCode::H3126::encode(d); h ^= 8192; ofLogNotice() << "add 1bit noise: " << h << ", " << ofxHammingCode::H3126::decode(h); if(ofxHammingCode::H3126::isCorrect(h)) { ofLogNotice() << "decoded: " << ofxHammingCode::H3126::decode(h); } else { ofLogNotice() << "incorrect data"; } ofLogNotice() << "do correct"; ofxHammingCode::H3126::correct(h); ofLogNotice() << "corrected data: " << h << ", " << ofxHammingCode::H3126::decode(h); if(ofxHammingCode::H3126::isCorrect(h)) { ofLogNotice() << "decoded: " << ofxHammingCode::H3126::decode(h); } else { ofLogNotice() << "incorrect data"; } } void testH3126SECDED(const std::uint32_t d) { ofLogNotice() << "==== H3126::SECDED ===="; ofLogNotice() << "[single error correction, double error detection]" << std::endl; ofLogNotice() << "raw data: " << d; std::uint32_t h = ofxHammingCode::H3126::SECDED::encode(d); ofLogNotice() << "encoded data: " << h; if(ofxHammingCode::H3126::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << ofxHammingCode::H3126::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; } std::cout << std::endl; h = ofxHammingCode::H3126::SECDED::encode(d); h ^= 1024; ofLogNotice() << "add 1bit noise: " << h << ", " << ofxHammingCode::H3126::SECDED::decode(h); if(ofxHammingCode::H3126::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << ofxHammingCode::H3126::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; } ofLogNotice() << "do correct"; ofxHammingCode::H3126::SECDED::correct(h); ofLogNotice() << "corrected data: " << h << ", " << ofxHammingCode::H3126::SECDED::decode(h); if(ofxHammingCode::H3126::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << ofxHammingCode::H3126::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; } std::cout << std::endl; h = ofxHammingCode::H3126::SECDED::encode(d); h ^= 5; ofLogNotice() << "add 2bit noise: " << h; if(ofxHammingCode::H3126::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << ofxHammingCode::H3126::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; if(ofxHammingCode::H3126::SECDED::isCorrectable(h)) { ofLogNotice() << "this data is correctable"; ofxHammingCode::H3126::SECDED::correct(h); ofLogNotice() << "corrected data: " << h; if(ofxHammingCode::H74::SECDED::isCorrect(h)) { ofLogNotice() << "decoded: " << ofxHammingCode::H3126::SECDED::decode(h); } else { ofLogNotice() << "incorrect data"; } } else { ofLogNotice() << "this data can't correctable"; } } } }; //======================================================================== int main( ){ ofSetupOpenGL(480, 480, OF_WINDOW); ofRunApp(new ofApp()); }
35.395161
102
0.478241
2bbb
3eab688c5ba8ab15b39541e2c0ad87cbefd6c3f3
758
cpp
C++
misc/SAP Labs Online Contest - 3rd Edition/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
misc/SAP Labs Online Contest - 3rd Edition/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
misc/SAP Labs Online Contest - 3rd Edition/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
/** * author: MaGnsi0 * created: 11.12.2021 19:39:28 **/ #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string s; cin >> s; vector<int> ones; for (int i = 0; i < (int)s.size(); ++i) { if (s[i] == '0' || (i && s[i - 1] == '1')) { continue; } int cnt = 0; for (int j = i; j < (int)s.size(); ++j) { if (s[j] == '1') { cnt++; } else { break; } } ones.push_back(cnt); } sort(ones.begin(), ones.end()); int res = 0; for (int i = 0; i < (int)ones.size() - 1; ++i) { res += ones[i]; } cout << res << "\n"; }
21.657143
58
0.390501
MaGnsio
3ead6eb60a456bc5a1322d18a7655b504b963b05
5,178
cpp
C++
src/editor/log_ui.cpp
OndraVoves/LumixEngine
b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f
[ "MIT" ]
null
null
null
src/editor/log_ui.cpp
OndraVoves/LumixEngine
b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f
[ "MIT" ]
null
null
null
src/editor/log_ui.cpp
OndraVoves/LumixEngine
b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f
[ "MIT" ]
null
null
null
#include "log_ui.h" #include "editor/platform_interface.h" #include "engine/log.h" #include "imgui/imgui.h" namespace Lumix { LogUI::LogUI(IAllocator& allocator) : m_allocator(allocator) , m_messages(allocator) , m_current_tab(Error) , m_notifications(allocator) , m_last_uid(1) , m_guard(false) , m_is_opened(false) , m_are_notifications_hovered(false) , m_move_notifications_to_front(false) { g_log_info.getCallback().bind<LogUI, &LogUI::onInfo>(this); g_log_error.getCallback().bind<LogUI, &LogUI::onError>(this); g_log_warning.getCallback().bind<LogUI, &LogUI::onWarning>(this); for (int i = 0; i < Count; ++i) { m_new_message_count[i] = 0; m_messages.emplace(allocator); } } LogUI::~LogUI() { g_log_info.getCallback().unbind<LogUI, &LogUI::onInfo>(this); g_log_error.getCallback().unbind<LogUI, &LogUI::onError>(this); g_log_warning.getCallback().unbind<LogUI, &LogUI::onWarning>(this); } void LogUI::setNotificationTime(int uid, float time) { for (auto& notif : m_notifications) { if (notif.uid == uid) { notif.time = time; break; } } } int LogUI::addNotification(const char* text) { m_move_notifications_to_front = true; if (!m_notifications.empty() && m_notifications.back().message == text) return -1; auto& notif = m_notifications.emplace(m_allocator); notif.time = 10.0f; notif.message = text; notif.uid = ++m_last_uid; return notif.uid; } void LogUI::push(Type type, const char* message) { MT::SpinLock lock(m_guard); ++m_new_message_count[type]; m_messages[type].push(string(message, m_allocator)); if (type == Error) { addNotification(message); } } void LogUI::onInfo(const char* system, const char* message) { push(Info, message); } void LogUI::onWarning(const char* system, const char* message) { push(Warning, message); } void LogUI::onError(const char* system, const char* message) { push(Error, message); } void fillLabel(char* output, int max_size, const char* label, int count) { copyString(output, max_size, label); catString(output, max_size, "("); int len = stringLength(output); toCString(count, output + len, max_size - len); catString(output, max_size, ")###"); catString(output, max_size, label); } void LogUI::showNotifications() { m_are_notifications_hovered = false; if (m_notifications.empty()) return; ImGui::SetNextWindowPos(ImVec2(10, 30)); bool opened; if (!ImGui::Begin("Notifications", &opened, ImVec2(200, 0), 1.0f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ShowBorders)) { ImGui::End(); return; } m_are_notifications_hovered = ImGui::IsWindowHovered(); if (ImGui::Button("Close")) m_notifications.clear(); if (m_move_notifications_to_front) ImGui::BringToFront(); m_move_notifications_to_front = false; for (int i = 0; i < m_notifications.size(); ++i) { if (i > 0) ImGui::Separator(); ImGui::Text("%s", m_notifications[i].message.c_str()); } ImGui::End(); } void LogUI::update(float time_delta) { if (m_are_notifications_hovered) return; for (int i = 0; i < m_notifications.size(); ++i) { m_notifications[i].time -= time_delta; if (m_notifications[i].time < 0) { m_notifications.erase(i); --i; } } } int LogUI::getUnreadErrorCount() const { return m_new_message_count[Error]; } void LogUI::onGUI() { MT::SpinLock lock(m_guard); showNotifications(); if (ImGui::BeginDock("Log", &m_is_opened)) { const char* labels[] = { "Info", "Warning", "Error" }; for (int i = 0; i < lengthOf(labels); ++i) { char label[40]; fillLabel(label, sizeof(label), labels[i], m_new_message_count[i]); if(i > 0) ImGui::SameLine(); if (ImGui::Button(label)) { m_current_tab = i; m_new_message_count[i] = 0; } } auto* messages = &m_messages[m_current_tab]; if (ImGui::Button("Clear")) { for (int i = 0; i < m_messages.size(); ++i) { m_messages[m_current_tab].clear(); m_new_message_count[m_current_tab] = 0; } } ImGui::SameLine(); char filter[128] = ""; ImGui::FilterInput("Filter", filter, sizeof(filter)); int len = 0; if (ImGui::Button("Copy to clipboard")) { for (int i = 0; i < messages->size(); ++i) { const char* msg = (*messages)[i].c_str(); if (filter[0] == '\0' || strstr(msg, filter) != nullptr) { len += stringLength(msg); } } if (len > 0) { char* mem = (char*)m_allocator.allocate(len); mem[0] = '\0'; for (int i = 0; i < messages->size(); ++i) { const char* msg = (*messages)[i].c_str(); if (filter[0] == '\0' || strstr(msg, filter) != nullptr) { catString(mem, len, msg); catString(mem, len, "\n"); } } PlatformInterface::copyToClipboard(mem); m_allocator.deallocate(mem); } } if (ImGui::BeginChild("log_messages")) { for (int i = 0; i < messages->size(); ++i) { const char* msg = (*messages)[i].c_str(); if (filter[0] == '\0' || strstr(msg, filter) != nullptr) { ImGui::TextUnformatted(msg); } } } ImGui::EndChild(); } ImGui::EndDock(); } } // namespace Lumix
20.795181
83
0.653534
OndraVoves
3eae1d8f730602093de5ae38dac9ece861131e15
442
hxx
C++
include/WonderRabbitProject/key/detail.include_symbols.hxx
usagi/libWRP-key
28d3969da339f9df97981552fd5980269f8b96a4
[ "MIT" ]
2
2017-12-27T18:38:07.000Z
2021-04-07T11:24:06.000Z
include/WonderRabbitProject/key/detail.include_symbols.hxx
usagi/libWRP-key
28d3969da339f9df97981552fd5980269f8b96a4
[ "MIT" ]
null
null
null
include/WonderRabbitProject/key/detail.include_symbols.hxx
usagi/libWRP-key
28d3969da339f9df97981552fd5980269f8b96a4
[ "MIT" ]
1
2015-05-16T08:44:42.000Z
2015-05-16T08:44:42.000Z
#pragma once #if defined(_WIN64) || defined(_WIN32) #ifndef NOMINMAX #define NOMINMAX #endif #ifndef WRP_NO_KEY_WRITER #include <rtccore.h> #endif #include <windef.h> #include <winbase.h> #include <winuser.h> #elif defined(__APPLE__) #include "/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h" #elif defined(__linux) #include <linux/uinput.h> #endif
24.555556
126
0.735294
usagi
3ebda98f396ff33efaae6cb3465b19c24b226c51
2,320
cpp
C++
APIO17_rainbow.cpp
puyuliao/APIO
504570c950d7d824653a466642ed7284453d48eb
[ "MIT" ]
null
null
null
APIO17_rainbow.cpp
puyuliao/APIO
504570c950d7d824653a466642ed7284453d48eb
[ "MIT" ]
null
null
null
APIO17_rainbow.cpp
puyuliao/APIO
504570c950d7d824653a466642ed7284453d48eb
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include<stdint.h> using namespace std; #define IOS {cin.tie(0);ios_base::sync_with_stdio(false);} #define N 200005 #define lowbit(x) (x&-x) #include"rainbow.h" struct dbit{ vector<int> v[N]; int n,m; void init(int _n,int _m){ n = _n,m = _m; for(int i=1;i<=n;i++) v[i].clear(); } void ins(int x,int y){ for(;x<=n;x+=lowbit(x)) v[x].push_back(y); } void preprocess(){ for(int i=1;i<=n;i++){ sort(v[i].begin(),v[i].end()); } } int qur(int x,int y,int xx,int yy){ if(x > xx || y > yy) return 0; int r = 0; for(;x;x-=lowbit(x)) r -= (int)(upper_bound(v[x].begin(),v[x].end(),yy) - lower_bound(v[x].begin(),v[x].end(),y)); for(;xx;xx-=lowbit(xx)) r += (int)(upper_bound(v[xx].begin(),v[xx].end(),yy) - lower_bound(v[xx].begin(),v[xx].end(),y)); return r; } }bv,be1,be2,bf; vector<pair<int,int> > v; set<pair<int,int> > sv,se1,se2,sf; int xmn,xmx,ymn,ymx; void put(int sr,int sc){ sv.insert({sr,sc}); sv.insert({sr+1,sc}); sv.insert({sr,sc+1}); sv.insert({sr+1,sc+1}); se1.insert({sr,sc}); se1.insert({sr,sc+1}); se2.insert({sr,sc}); se2.insert({sr+1,sc}); sf.insert({sr,sc}); } void init(int R,int C,int sr,int sc,int M,char* S){ bv.init(R+2,C+2); be1.init(R+2,C+2); //vert be2.init(R+2,C+2); //hori bf.init(R+2,C+2); sv.clear(); se1.clear(); se2.clear(); sf.clear(); put(sr,sc); xmn = xmx = sr, ymn = ymx = sc; for(int j=0;j<M;j++){ char &i = S[j]; if(i == 'N') sr--; else if(i == 'E') sc++; else if(i == 'W') sc--; else if(i == 'S') sr++; v.push_back({sr,sc}); xmx = max(xmx,sr); xmn = min(xmn,sr); ymx = max(ymx,sc); ymn = min(ymn,sc); put(sr,sc); } for(auto i : sv) bv.ins(i.first,i.second); for(auto i : se1) be1.ins(i.first,i.second); for(auto i : se2) be2.ins(i.first,i.second); for(auto i : sf) bf.ins(i.first,i.second); bv.preprocess(); be1.preprocess(); be2.preprocess(); bf.preprocess(); } int colour(int ar,int ac,int br,int bc){ int v = (br-ar+bc-ac+2)*2 + bv.qur(ar,ac+1,br,bc); int e = (br-ar+bc-ac+2)*2 + be1.qur(ar-1,ac+1,br,bc) + be2.qur(ar,ac,br,bc); int f = bf.qur(ar-1,ac,br,bc); //cout << v << ' ' << e << ' ' << f << '\n'; return e-v-f + 1 + (ar < xmn && ac < ymn && br > xmx && bc > ymx); }
26.363636
124
0.539224
puyuliao
3ec3296f39a1dbce3f40bc6034574220bea61a77
8,544
cxx
C++
Applications/ConvertTransformToRIREFormat/niftkConvertTransformToRIREFormat.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
Applications/ConvertTransformToRIREFormat/niftkConvertTransformToRIREFormat.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
Applications/ConvertTransformToRIREFormat/niftkConvertTransformToRIREFormat.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include <niftkConversionUtils.h> #include <itkImage.h> #include <itkImageFileReader.h> #include <itkNifTKImageIOFactory.h> #include <itkImageRegistrationFactory.h> #include <itkPoint.h> #include <itkEulerAffineTransform.h> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/format.hpp> #include <iostream> #include <fstream> #include <niftkLogHelper.h> /*! * \file niftkConvertTransformToRIREFormat.cxx * \page niftkConvertTransformToRIREFormat * \section niftkConvertTransformToRIREFormatSummary Converts an ITK transformation file to that required by Vanderbilt's Retrospective Image Registration Evaluation project. * \section niftkConvertTransformToRIREFormatCaveat Caveats */ void Usage(char *exec) { niftk::LogHelper::PrintCommandLineHeader(std::cout); std::cout << " " << std::endl; std::cout << " Converts an ITK transformation file to that required by Vanderbilt's Retrospective Image Registration Evaluation project." << std::endl; std::cout << " " << std::endl; std::cout << " " << exec << " -i inputImage -t inputTransformationFile -o outputFileName [options]" << std::endl; std::cout << " " << std::endl; std::cout << "*** [mandatory] ***" << std::endl << std::endl; std::cout << " -i <filename> Input Source/Moving image " << std::endl; std::cout << " -t <filename> ITK transformation file " << std::endl; std::cout << " -o <filename> Output Vanderbilt transformation file " << std::endl << std::endl; std::cout << "*** [options] ***" << std::endl << std::endl; std::cout << " -p <string> [001] Patient identifier (eg. 001) " << std::endl; std::cout << " -f <string> [mr_PD] Fixed image identifier " << std::endl; std::cout << " -m <string> [CT] Moving image identifier " << std::endl; } std::string padString(std::string input, int desiredLength) { std::string result = input; while (result.length() < 11) { result = std::string(" ") + result; } return result; } int main(int argc, char** argv) { itk::NifTKImageIOFactory::Initialize(); const unsigned int Dimension = 3; typedef short PixelType; // Define command line params std::string imageFile; std::string itkTransform; std::string vanderbiltTransform; std::string patientIdentifier = "001"; std::string fixedImageIdentifier = "mr_PD"; std::string movingImageIdentifier = "CT"; // Parse command line args for(int i=1; i < argc; i++){ if(strcmp(argv[i], "-help")==0 || strcmp(argv[i], "-Help")==0 || strcmp(argv[i], "-HELP")==0 || strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--h")==0){ Usage(argv[0]); return -1; } else if(strcmp(argv[i], "-i") == 0){ imageFile=argv[++i]; std::cout << "Set -i=" << imageFile<< std::endl; } else if(strcmp(argv[i], "-t") == 0){ itkTransform=argv[++i]; std::cout << "Set -t=" << itkTransform<< std::endl; } else if(strcmp(argv[i], "-o") == 0){ vanderbiltTransform=argv[++i]; std::cout << "Set -o=" << vanderbiltTransform<< std::endl; } else if(strcmp(argv[i], "-p") == 0){ patientIdentifier=argv[++i]; std::cout << "Set -p=" << patientIdentifier<< std::endl; } else if(strcmp(argv[i], "-f") == 0){ fixedImageIdentifier=argv[++i]; std::cout << "Set -f=" << fixedImageIdentifier<< std::endl; } else if(strcmp(argv[i], "-m") == 0){ movingImageIdentifier=argv[++i]; std::cout << "Set -m=" << movingImageIdentifier<< std::endl; } else { std::cerr << argv[0] << ":\tParameter " << argv[i] << " unknown." << std::endl; return -1; } } // Validate command line args if (imageFile.length() == 0 || itkTransform.length() == 0 || vanderbiltTransform.length() == 0) { Usage(argv[0]); return EXIT_FAILURE; } if (patientIdentifier.length() == 0 || fixedImageIdentifier.length() == 0 || movingImageIdentifier.length() == 0) { Usage(argv[0]); return EXIT_FAILURE; } typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileReader< ImageType > ImageReaderType; ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName( imageFile ); // Load image. try { std::cout << "Reading image:" << imageFile<< std::endl; imageReader->Update(); std::cout << "Done"<< std::endl; } catch( itk::ExceptionObject & err ) { std::cerr << "Failed to load input images: " << err << std::endl; return EXIT_FAILURE; } // Setup objects to load transformation typedef itk::ImageRegistrationFactory<ImageType, Dimension, double> FactoryType; FactoryType::Pointer factory = FactoryType::New(); FactoryType::TransformType::Pointer globalTransform; try { std::cout << "Loading transformation from:" << itkTransform<< std::endl; globalTransform = factory->CreateTransform(itkTransform); itk::EulerAffineTransform<double, Dimension, Dimension>* affineTransform = dynamic_cast<itk::EulerAffineTransform<double, Dimension, Dimension>*>(globalTransform.GetPointer()); affineTransform->InvertTransformationMatrix(); std::cout << "Done"<< std::endl; } catch (itk::ExceptionObject& exceptionObject) { std::cerr << "Failed to load ITK tranform:" << exceptionObject << std::endl; return EXIT_FAILURE; } using namespace boost::gregorian; date today = day_clock::local_day(); std::ofstream myfile; myfile.open (vanderbiltTransform.c_str()); myfile << "-------------------------------------------------------------------------" << std::endl; myfile << "Transformation Parameters" << std::endl; myfile << std::endl; myfile << "Investigator(s): M. J. Clarkson, K. K. Leung and S. Ourselin" << std::endl; myfile << std::endl; myfile << "Dementia Research Centre, Institute Of Neurology, University College London, London, UK" << std::endl; myfile << std::endl; myfile << "Method: NifTK" << std::endl; myfile << "Date: " << to_iso_extended_string(today) << std::endl; myfile << "Patient number: " << patientIdentifier << std::endl; myfile << "From: " << movingImageIdentifier << std::endl; myfile << "To: " << fixedImageIdentifier << std::endl; myfile << std::endl; myfile << "Point x y z new_x new_y new_z" << std::endl; myfile << std::endl; typedef itk::Point<double, 3> PointType; ImageType::Pointer image = imageReader->GetOutput(); ImageType::SizeType size = image->GetLargestPossibleRegion().GetSize(); ImageType::SpacingType spacing = image->GetSpacing(); ImageType::IndexType index; PointType point; PointType transformedPoint; unsigned int counter = 1; for (unsigned int z = 0; z <= size[2]; z+= (size[2]-1)) { for (unsigned int y = 0; y <= size[1]; y+= (size[1]-1)) { for (unsigned int x = 0; x <= size[0]; x+= (size[0]-1)) { index[0] = x; index[1] = y; index[2] = z; image->TransformIndexToPhysicalPoint( index, point ); transformedPoint = globalTransform->TransformPoint(point); double mx = point[0]; double my = point[1]; double mz = point[2]; double fx = transformedPoint[0]; double fy = transformedPoint[1]; double fz = transformedPoint[2]; myfile << boost::format(" %s %10.4f %10.4f %10.4f%10.4f %10.4f %10.4f ") % counter % mx % my %mz % fx %fy %fz << std::endl; counter++; } } } myfile << std::endl; myfile << "(All distances are in millimeters.)" << std::endl; myfile << "-------------------------------------------------------------------------" << std::endl; myfile.close(); return 0; }
35.89916
180
0.584504
NifTK
3ec6ac96bf6b8fcce060ab2c8f5c5e4e3ef81afa
2,670
hpp
C++
sdk/packages/laikago/components/LaikagoDriver.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
sdk/packages/laikago/components/LaikagoDriver.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
sdk/packages/laikago/components/LaikagoDriver.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2022-01-28T16:37:51.000Z
2022-01-28T16:37:51.000Z
/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <memory> #include "engine/alice/alice_codelet.hpp" #include "include/laikago_sdk/laikago_sdk.hpp" #include "messages/imu.capnp.h" #include "messages/state.capnp.h" namespace isaac { namespace laikago { // A driver for Laikago, a quadruped robot designed by Unitree Roboitcs. The driver receives // holonomic control commands and translates them to laikago sdk high level velocity command // which it outputs. On the other side it receives laikago states (base velocity), translates // them into holonomic base state and publishes them. class LaikagoDriver : public alice::Codelet { public: void start() override; void tick() override; void stop() override; // The desired motion of Laikago of type messages::HolonomicBaseControls ISAAC_PROTO_RX(StateProto, base_command); // The state of Laikago of type messages::HolonomicBaseDynamics ISAAC_PROTO_TX(StateProto, base_state); // The imu proto has linear and angular acceleration data ISAAC_PROTO_TX(ImuProto, imu); // Maximum linear speed robot is allowed to travel with ISAAC_PARAM(double, speed_limit_linear, 0.6); // Maximum angular speed robot is allowed to rotate with ISAAC_PARAM(double, speed_limit_angular, 0.8); // Minimum command speed to switch to walking mode ISAAC_PARAM(double, min_command_speed, 0.01); // Scale backward speed. // The laikago walks backward slower than forward given the same command value. // To approximately compensate the bias, we scale up the command speed ISAAC_PARAM(double, scale_back_speed, 2.0); // Scale side walk speed. // The laikago side walk speed is about three times slower than command. // To approximately compensate the tracking error, we scale up the command speed ISAAC_PARAM(double, scale_side_speed, 3.0); private: // Failsafe for safety alice::Failsafe* failsafe_; // Laikago direction command ::laikago::HighCmd cmd_; // Laikago odometry states ::laikago::HighState state_; // Class to define Laikago control level std::unique_ptr<::laikago::Control> control_; // UDP for robot communication std::unique_ptr<::laikago::UDP> udp_; }; } // namespace laikago } // namespace isaac ISAAC_ALICE_REGISTER_CODELET(isaac::laikago::LaikagoDriver);
34.675325
93
0.768539
ddr95070
3ecb6d7001fba712c1c9caa2cf77e3a71f381c83
1,638
cpp
C++
src/limitless/pipeline/scene_data.cpp
Tehsapper/graphics-engine
5b7cd93c750ccce7b254c6bb4a13948b2b4ec975
[ "MIT" ]
9
2020-07-23T13:00:12.000Z
2021-01-07T10:44:24.000Z
src/limitless/pipeline/scene_data.cpp
Tehsapper/graphics-engine
5b7cd93c750ccce7b254c6bb4a13948b2b4ec975
[ "MIT" ]
7
2020-09-11T18:23:45.000Z
2020-11-01T19:05:47.000Z
src/limitless/pipeline/scene_data.cpp
Tehsapper/graphics-engine
5b7cd93c750ccce7b254c6bb4a13948b2b4ec975
[ "MIT" ]
3
2020-08-24T01:59:48.000Z
2021-02-18T16:41:27.000Z
#include <limitless/pipeline/scene_data.hpp> #include <limitless/core/context.hpp> #include <limitless/core/buffer_builder.hpp> #include <limitless/camera.hpp> using namespace Limitless; namespace { constexpr auto SCENE_DATA_BUFFER_NAME = "scene_data"; } SceneDataStorage::SceneDataStorage(Context& ctx) { BufferBuilder builder; buffer = builder.setTarget(Buffer::Type::Uniform) .setUsage(Buffer::Usage::DynamicDraw) .setAccess(Buffer::MutableAccess::WriteOrphaning) .setDataSize(sizeof(SceneData)) .build(SCENE_DATA_BUFFER_NAME, ctx); } SceneDataStorage::~SceneDataStorage() { if (auto* ctx = ContextState::getState(glfwGetCurrentContext()); ctx) { ctx->getIndexedBuffers().remove(SCENE_DATA_BUFFER_NAME, buffer); } } void SceneDataStorage::update(Context& context, const Camera& camera) { scene_data.projection = camera.getProjection(); scene_data.projection_inverse = glm::inverse(camera.getProjection()); scene_data.view = camera.getView(); scene_data.view_inverse = glm::inverse(camera.getView()); scene_data.VP = camera.getProjection() * camera.getView(); scene_data.VP_inverse = glm::inverse(scene_data.VP); scene_data.camera_position = { camera.getPosition(), 1.0f }; scene_data.resolution = context.getSize(); scene_data.far_plane = camera.getFar(); scene_data.near_plane = camera.getNear(); buffer->mapData(&scene_data, sizeof(SceneData)); buffer->bindBase(context.getIndexedBuffers().getBindingPoint(IndexedBuffer::Type::UniformBuffer, SCENE_DATA_BUFFER_NAME)); }
38.093023
126
0.714896
Tehsapper
3ece945fc559f14d7602b9ed64737789028e6964
2,774
hpp
C++
dev/restinio/utils/from_string.hpp
binarytrails/restinio
3a3d6ed6c2185166e30679ab5cae8a51aea1a2f0
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
dev/restinio/utils/from_string.hpp
binarytrails/restinio
3a3d6ed6c2185166e30679ab5cae8a51aea1a2f0
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
dev/restinio/utils/from_string.hpp
binarytrails/restinio
3a3d6ed6c2185166e30679ab5cae8a51aea1a2f0
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* restinio */ /*! Convert strings to numeric types. */ #pragma once #include <cctype> #include <string> #include <limits> #include <stdexcept> #include <algorithm> #include <fmt/format.h> #include <restinio/string_view.hpp> #include <restinio/exception.hpp> #include "from_string_details.ipp" namespace restinio { namespace utils { //! Read int values. //! \{ inline void read_value( std::int64_t & v, const char * data, std::size_t size ) { v = details::parse_integer< details::int64_parse_traits_t >( data, data + size ); } inline void read_value( std::uint64_t & v, const char * data, std::size_t size ) { v = details::parse_integer< details::uint64_parse_traits_t >( data, data + size ); } inline void read_value( std::int32_t & v, const char * data, std::size_t size ) { v = details::parse_integer< details::int32_parse_traits_t >( data, data + size ); } inline void read_value( std::uint32_t & v, const char * data, std::size_t size ) { v = details::parse_integer< details::uint32_parse_traits_t >( data, data + size ); } inline void read_value( std::int16_t & v, const char * data, std::size_t size ) { v = details::parse_integer< details::int16_parse_traits_t >( data, data + size ); } inline void read_value( std::uint16_t & v, const char * data, std::size_t size ) { v = details::parse_integer< details::uint16_parse_traits_t >( data, data + size ); } inline void read_value( std::int8_t & v, const char * data, std::size_t size ) { v = details::parse_integer< details::int8_parse_traits_t >( data, data + size ); } inline void read_value( std::uint8_t & v, const char * data, std::size_t size ) { v = details::parse_integer< details::uint8_parse_traits_t >( data, data + size ); } //! \} //! Read float values. //! \{ inline void read_value( float & v, const char * data, std::size_t size ) { std::string buf{ data, size }; v = std::stof( buf ); } inline void read_value( double & v, const char * data, std::size_t size ) { std::string buf{ data, size }; v = std::stod( buf ); } //! \} //! Get a value from string. template < typename Value_Type > Value_Type from_string( string_view_t s ) { Value_Type result; read_value( result, s.data(), s.length() ); return result; } //! Get a value from string. template <> inline std::string from_string< std::string >( string_view_t s ) { return std::string{ s.data(), s.size() }; } //! Get a value from string_view. template <> inline string_view_t from_string< string_view_t >( string_view_t s ) { return s; } // //! Get a value from string. // template < typename Value_Type > // Value_Type // from_string( const std::string & s ) // { // return from_string< Value_Type >( string_view_t{ s.data(), s.size() } ); // } } /* namespace utils */ } /* namespace restinio */
19.673759
83
0.677722
binarytrails
3ecf38ab00949781a3c49d2c721b9209255d539b
39,677
cpp
C++
Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Inc/AdvancedSessions/AdvancedFriendsGameInstance.gen.cpp
Maskside/DriftGame
a518574f3ba4256da0cc948b9f147b4d3aaa3b5c
[ "MIT" ]
1
2019-08-05T23:14:02.000Z
2019-08-05T23:14:02.000Z
Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Inc/AdvancedSessions/AdvancedFriendsGameInstance.gen.cpp
Maskside/DriftGame
a518574f3ba4256da0cc948b9f147b4d3aaa3b5c
[ "MIT" ]
12
2019-08-05T22:30:45.000Z
2019-08-07T21:45:39.000Z
EvilCube/Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Inc/AdvancedSessions/AdvancedFriendsGameInstance.gen.cpp
0Bennyman/ProjectLDR
517ef2cdd1115cd73e74d383d80637b17945c248
[ "Linux-OpenIB" ]
null
null
null
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "AdvancedSessions/Classes/AdvancedFriendsGameInstance.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeAdvancedFriendsGameInstance() {} // Cross Module References ADVANCEDSESSIONS_API UClass* Z_Construct_UClass_UAdvancedFriendsGameInstance_NoRegister(); ADVANCEDSESSIONS_API UClass* Z_Construct_UClass_UAdvancedFriendsGameInstance(); ENGINE_API UClass* Z_Construct_UClass_UGameInstance(); UPackage* Z_Construct_UPackage__Script_AdvancedSessions(); ADVANCEDSESSIONS_API UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged(); ADVANCEDSESSIONS_API UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged(); ADVANCEDSESSIONS_API UScriptStruct* Z_Construct_UScriptStruct_FBPUniqueNetId(); ADVANCEDSESSIONS_API UEnum* Z_Construct_UEnum_AdvancedSessions_EBPLoginStatus(); ADVANCEDSESSIONS_API UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged(); ADVANCEDSESSIONS_API UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted(); ONLINESUBSYSTEMUTILS_API UScriptStruct* Z_Construct_UScriptStruct_FBlueprintSessionResult(); ADVANCEDSESSIONS_API UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived(); // End Cross Module References static FName NAME_UAdvancedFriendsGameInstance_OnPlayerLoginChanged = FName(TEXT("OnPlayerLoginChanged")); void UAdvancedFriendsGameInstance::OnPlayerLoginChanged(int32 PlayerNum) { AdvancedFriendsGameInstance_eventOnPlayerLoginChanged_Parms Parms; Parms.PlayerNum=PlayerNum; ProcessEvent(FindFunctionChecked(NAME_UAdvancedFriendsGameInstance_OnPlayerLoginChanged),&Parms); } static FName NAME_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged = FName(TEXT("OnPlayerLoginStatusChanged")); void UAdvancedFriendsGameInstance::OnPlayerLoginStatusChanged(int32 PlayerNum, EBPLoginStatus PreviousStatus, EBPLoginStatus NewStatus, FBPUniqueNetId NewPlayerUniqueNetID) { AdvancedFriendsGameInstance_eventOnPlayerLoginStatusChanged_Parms Parms; Parms.PlayerNum=PlayerNum; Parms.PreviousStatus=PreviousStatus; Parms.NewStatus=NewStatus; Parms.NewPlayerUniqueNetID=NewPlayerUniqueNetID; ProcessEvent(FindFunctionChecked(NAME_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged),&Parms); } static FName NAME_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged = FName(TEXT("OnPlayerTalkingStateChanged")); void UAdvancedFriendsGameInstance::OnPlayerTalkingStateChanged(FBPUniqueNetId PlayerId, bool bIsTalking) { AdvancedFriendsGameInstance_eventOnPlayerTalkingStateChanged_Parms Parms; Parms.PlayerId=PlayerId; Parms.bIsTalking=bIsTalking ? true : false; ProcessEvent(FindFunctionChecked(NAME_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged),&Parms); } static FName NAME_UAdvancedFriendsGameInstance_OnSessionInviteAccepted = FName(TEXT("OnSessionInviteAccepted")); void UAdvancedFriendsGameInstance::OnSessionInviteAccepted(int32 LocalPlayerNum, FBPUniqueNetId PersonInvited, FBlueprintSessionResult const& SessionToJoin) { AdvancedFriendsGameInstance_eventOnSessionInviteAccepted_Parms Parms; Parms.LocalPlayerNum=LocalPlayerNum; Parms.PersonInvited=PersonInvited; Parms.SessionToJoin=SessionToJoin; ProcessEvent(FindFunctionChecked(NAME_UAdvancedFriendsGameInstance_OnSessionInviteAccepted),&Parms); } static FName NAME_UAdvancedFriendsGameInstance_OnSessionInviteReceived = FName(TEXT("OnSessionInviteReceived")); void UAdvancedFriendsGameInstance::OnSessionInviteReceived(int32 LocalPlayerNum, FBPUniqueNetId PersonInviting, const FString& AppId, FBlueprintSessionResult const& SessionToJoin) { AdvancedFriendsGameInstance_eventOnSessionInviteReceived_Parms Parms; Parms.LocalPlayerNum=LocalPlayerNum; Parms.PersonInviting=PersonInviting; Parms.AppId=AppId; Parms.SessionToJoin=SessionToJoin; ProcessEvent(FindFunctionChecked(NAME_UAdvancedFriendsGameInstance_OnSessionInviteReceived),&Parms); } void UAdvancedFriendsGameInstance::StaticRegisterNativesUAdvancedFriendsGameInstance() { } struct Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics { static const UE4CodeGen_Private::FIntPropertyParams NewProp_PlayerNum; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::NewProp_PlayerNum = { "PlayerNum", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnPlayerLoginChanged_Parms, PlayerNum), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::NewProp_PlayerNum, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::Function_MetaDataParams[] = { { "Category", "AdvancedIdentity" }, { "DisplayName", "OnPlayerLoginChanged" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, { "ToolTip", "Called when the designated LocalUser has changed login state" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsGameInstance, nullptr, "OnPlayerLoginChanged", sizeof(AdvancedFriendsGameInstance_eventOnPlayerLoginChanged_Parms), Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics { static const UE4CodeGen_Private::FStructPropertyParams NewProp_NewPlayerUniqueNetID; static const UE4CodeGen_Private::FEnumPropertyParams NewProp_NewStatus; static const UE4CodeGen_Private::FBytePropertyParams NewProp_NewStatus_Underlying; static const UE4CodeGen_Private::FEnumPropertyParams NewProp_PreviousStatus; static const UE4CodeGen_Private::FBytePropertyParams NewProp_PreviousStatus_Underlying; static const UE4CodeGen_Private::FIntPropertyParams NewProp_PlayerNum; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_NewPlayerUniqueNetID = { "NewPlayerUniqueNetID", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnPlayerLoginStatusChanged_Parms, NewPlayerUniqueNetID), Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_NewStatus = { "NewStatus", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnPlayerLoginStatusChanged_Parms, NewStatus), Z_Construct_UEnum_AdvancedSessions_EBPLoginStatus, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_NewStatus_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_PreviousStatus = { "PreviousStatus", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnPlayerLoginStatusChanged_Parms, PreviousStatus), Z_Construct_UEnum_AdvancedSessions_EBPLoginStatus, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_PreviousStatus_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_PlayerNum = { "PlayerNum", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnPlayerLoginStatusChanged_Parms, PlayerNum), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_NewPlayerUniqueNetID, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_NewStatus, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_NewStatus_Underlying, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_PreviousStatus, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_PreviousStatus_Underlying, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::NewProp_PlayerNum, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::Function_MetaDataParams[] = { { "Category", "AdvancedIdentity" }, { "DisplayName", "OnPlayerLoginStatusChanged" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, { "ToolTip", "Called when the designated LocalUser has changed login status" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsGameInstance, nullptr, "OnPlayerLoginStatusChanged", sizeof(AdvancedFriendsGameInstance_eventOnPlayerLoginStatusChanged_Parms), Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics { static void NewProp_bIsTalking_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsTalking; static const UE4CodeGen_Private::FStructPropertyParams NewProp_PlayerId; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::NewProp_bIsTalking_SetBit(void* Obj) { ((AdvancedFriendsGameInstance_eventOnPlayerTalkingStateChanged_Parms*)Obj)->bIsTalking = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::NewProp_bIsTalking = { "bIsTalking", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(AdvancedFriendsGameInstance_eventOnPlayerTalkingStateChanged_Parms), &Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::NewProp_bIsTalking_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::NewProp_PlayerId = { "PlayerId", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnPlayerTalkingStateChanged_Parms, PlayerId), Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::NewProp_bIsTalking, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::NewProp_PlayerId, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::Function_MetaDataParams[] = { { "Category", "AdvancedVoice" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, { "ToolTip", "After a voice status has changed this event is triggered if the bEnableTalkingStatusDelegate property is true" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsGameInstance, nullptr, "OnPlayerTalkingStateChanged", sizeof(AdvancedFriendsGameInstance_eventOnPlayerTalkingStateChanged_Parms), Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SessionToJoin_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_SessionToJoin; static const UE4CodeGen_Private::FStructPropertyParams NewProp_PersonInvited; static const UE4CodeGen_Private::FIntPropertyParams NewProp_LocalPlayerNum; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_SessionToJoin_MetaData[] = { { "NativeConst", "" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_SessionToJoin = { "SessionToJoin", nullptr, (EPropertyFlags)0x0010000008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnSessionInviteAccepted_Parms, SessionToJoin), Z_Construct_UScriptStruct_FBlueprintSessionResult, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_SessionToJoin_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_SessionToJoin_MetaData)) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_PersonInvited = { "PersonInvited", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnSessionInviteAccepted_Parms, PersonInvited), Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_LocalPlayerNum = { "LocalPlayerNum", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnSessionInviteAccepted_Parms, LocalPlayerNum), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_SessionToJoin, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_PersonInvited, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::NewProp_LocalPlayerNum, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::Function_MetaDataParams[] = { { "Category", "AdvancedFriends" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, { "ToolTip", "After a session invite has been accepted by the local player this event is triggered, call JoinSession on the session result to join it\nThis function is currently not hooked up in any of Epics default subsystems, it is here for custom subsystems" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsGameInstance, nullptr, "OnSessionInviteAccepted", sizeof(AdvancedFriendsGameInstance_eventOnSessionInviteAccepted_Parms), Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SessionToJoin_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_SessionToJoin; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_AppId_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_AppId; static const UE4CodeGen_Private::FStructPropertyParams NewProp_PersonInviting; static const UE4CodeGen_Private::FIntPropertyParams NewProp_LocalPlayerNum; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_SessionToJoin_MetaData[] = { { "NativeConst", "" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_SessionToJoin = { "SessionToJoin", nullptr, (EPropertyFlags)0x0010000008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnSessionInviteReceived_Parms, SessionToJoin), Z_Construct_UScriptStruct_FBlueprintSessionResult, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_SessionToJoin_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_SessionToJoin_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_AppId_MetaData[] = { { "NativeConst", "" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_AppId = { "AppId", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Str, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnSessionInviteReceived_Parms, AppId), METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_AppId_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_AppId_MetaData)) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_PersonInviting = { "PersonInviting", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnSessionInviteReceived_Parms, PersonInviting), Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_LocalPlayerNum = { "LocalPlayerNum", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsGameInstance_eventOnSessionInviteReceived_Parms, LocalPlayerNum), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_SessionToJoin, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_AppId, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_PersonInviting, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::NewProp_LocalPlayerNum, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::Function_MetaDataParams[] = { { "Category", "AdvancedFriends" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, { "ToolTip", "After a session invite has been accepted by the local player this event is triggered, call JoinSession on the session result to join it" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsGameInstance, nullptr, "OnSessionInviteReceived", sizeof(AdvancedFriendsGameInstance_eventOnSessionInviteReceived_Parms), Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_UAdvancedFriendsGameInstance_NoRegister() { return UAdvancedFriendsGameInstance::StaticClass(); } struct Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bEnableTalkingStatusDelegate_MetaData[]; #endif static void NewProp_bEnableTalkingStatusDelegate_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bEnableTalkingStatusDelegate; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bCallVoiceInterfaceEventsOnPlayerControllers_MetaData[]; #endif static void NewProp_bCallVoiceInterfaceEventsOnPlayerControllers_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bCallVoiceInterfaceEventsOnPlayerControllers; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bCallIdentityInterfaceEventsOnPlayerControllers_MetaData[]; #endif static void NewProp_bCallIdentityInterfaceEventsOnPlayerControllers_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bCallIdentityInterfaceEventsOnPlayerControllers; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bCallFriendInterfaceEventsOnPlayerControllers_MetaData[]; #endif static void NewProp_bCallFriendInterfaceEventsOnPlayerControllers_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bCallFriendInterfaceEventsOnPlayerControllers; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UGameInstance, (UObject* (*)())Z_Construct_UPackage__Script_AdvancedSessions, }; const FClassFunctionLinkInfo Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::FuncInfo[] = { { &Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginChanged, "OnPlayerLoginChanged" }, // 2119024663 { &Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerLoginStatusChanged, "OnPlayerLoginStatusChanged" }, // 3142842418 { &Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnPlayerTalkingStateChanged, "OnPlayerTalkingStateChanged" }, // 3754370357 { &Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteAccepted, "OnSessionInviteAccepted" }, // 2888372703 { &Z_Construct_UFunction_UAdvancedFriendsGameInstance_OnSessionInviteReceived, "OnSessionInviteReceived" }, // 3380053279 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::Class_MetaDataParams[] = { { "IncludePath", "AdvancedFriendsGameInstance.h" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, { "ObjectInitializerConstructorDeclared", "" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bEnableTalkingStatusDelegate_MetaData[] = { { "Category", "AdvancedVoiceInterface" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, }; #endif void Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bEnableTalkingStatusDelegate_SetBit(void* Obj) { ((UAdvancedFriendsGameInstance*)Obj)->bEnableTalkingStatusDelegate = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bEnableTalkingStatusDelegate = { "bEnableTalkingStatusDelegate", nullptr, (EPropertyFlags)0x0010000000000005, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UAdvancedFriendsGameInstance), &Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bEnableTalkingStatusDelegate_SetBit, METADATA_PARAMS(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bEnableTalkingStatusDelegate_MetaData, ARRAY_COUNT(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bEnableTalkingStatusDelegate_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallVoiceInterfaceEventsOnPlayerControllers_MetaData[] = { { "Category", "AdvancedFriendsInterface" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, }; #endif void Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallVoiceInterfaceEventsOnPlayerControllers_SetBit(void* Obj) { ((UAdvancedFriendsGameInstance*)Obj)->bCallVoiceInterfaceEventsOnPlayerControllers = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallVoiceInterfaceEventsOnPlayerControllers = { "bCallVoiceInterfaceEventsOnPlayerControllers", nullptr, (EPropertyFlags)0x0010000000000005, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UAdvancedFriendsGameInstance), &Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallVoiceInterfaceEventsOnPlayerControllers_SetBit, METADATA_PARAMS(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallVoiceInterfaceEventsOnPlayerControllers_MetaData, ARRAY_COUNT(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallVoiceInterfaceEventsOnPlayerControllers_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallIdentityInterfaceEventsOnPlayerControllers_MetaData[] = { { "Category", "AdvancedFriendsInterface" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, }; #endif void Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallIdentityInterfaceEventsOnPlayerControllers_SetBit(void* Obj) { ((UAdvancedFriendsGameInstance*)Obj)->bCallIdentityInterfaceEventsOnPlayerControllers = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallIdentityInterfaceEventsOnPlayerControllers = { "bCallIdentityInterfaceEventsOnPlayerControllers", nullptr, (EPropertyFlags)0x0010000000000005, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UAdvancedFriendsGameInstance), &Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallIdentityInterfaceEventsOnPlayerControllers_SetBit, METADATA_PARAMS(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallIdentityInterfaceEventsOnPlayerControllers_MetaData, ARRAY_COUNT(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallIdentityInterfaceEventsOnPlayerControllers_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallFriendInterfaceEventsOnPlayerControllers_MetaData[] = { { "Category", "AdvancedFriendsInterface" }, { "ModuleRelativePath", "Classes/AdvancedFriendsGameInstance.h" }, }; #endif void Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallFriendInterfaceEventsOnPlayerControllers_SetBit(void* Obj) { ((UAdvancedFriendsGameInstance*)Obj)->bCallFriendInterfaceEventsOnPlayerControllers = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallFriendInterfaceEventsOnPlayerControllers = { "bCallFriendInterfaceEventsOnPlayerControllers", nullptr, (EPropertyFlags)0x0010000000000005, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UAdvancedFriendsGameInstance), &Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallFriendInterfaceEventsOnPlayerControllers_SetBit, METADATA_PARAMS(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallFriendInterfaceEventsOnPlayerControllers_MetaData, ARRAY_COUNT(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallFriendInterfaceEventsOnPlayerControllers_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bEnableTalkingStatusDelegate, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallVoiceInterfaceEventsOnPlayerControllers, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallIdentityInterfaceEventsOnPlayerControllers, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::NewProp_bCallFriendInterfaceEventsOnPlayerControllers, }; const FCppClassTypeInfoStatic Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UAdvancedFriendsGameInstance>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::ClassParams = { &UAdvancedFriendsGameInstance::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::PropPointers, nullptr, ARRAY_COUNT(DependentSingletons), ARRAY_COUNT(FuncInfo), ARRAY_COUNT(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::PropPointers), 0, 0x001000A8u, METADATA_PARAMS(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UAdvancedFriendsGameInstance() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UAdvancedFriendsGameInstance_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UAdvancedFriendsGameInstance, 52736387); template<> ADVANCEDSESSIONS_API UClass* StaticClass<UAdvancedFriendsGameInstance>() { return UAdvancedFriendsGameInstance::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UAdvancedFriendsGameInstance(Z_Construct_UClass_UAdvancedFriendsGameInstance, &UAdvancedFriendsGameInstance::StaticClass, TEXT("/Script/AdvancedSessions"), TEXT("UAdvancedFriendsGameInstance"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UAdvancedFriendsGameInstance); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
92.058005
874
0.877587
Maskside
a7931c1ff13b09f0846a37116e038ced826b351e
333
cpp
C++
OnlineJudgeUVa/C++/11xxx/11683 - Laser Sculpture/main.cpp
DVRodri8/Competitive-programs
db90c63aea8fa4403ae7ec735c7f7ce73c842be4
[ "MIT" ]
null
null
null
OnlineJudgeUVa/C++/11xxx/11683 - Laser Sculpture/main.cpp
DVRodri8/Competitive-programs
db90c63aea8fa4403ae7ec735c7f7ce73c842be4
[ "MIT" ]
null
null
null
OnlineJudgeUVa/C++/11xxx/11683 - Laser Sculpture/main.cpp
DVRodri8/Competitive-programs
db90c63aea8fa4403ae7ec735c7f7ce73c842be4
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int hight, weight, n, next_n, res; while(cin >> hight >> weight && hight != 0){ cin >> n; res = hight - n; for(;weight > 1; weight--){ cin >> next_n; if(n > next_n) res += n - next_n; n = next_n; } cout << res << endl; } return 0; }
16.65
46
0.510511
DVRodri8
a7948639a90f294fd23bddf2a0c1c604f622769d
8,957
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/numeric/ublas/tensor/expression_evaluation.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
ReactNativeFrontend/ios/Pods/boost/boost/numeric/ublas/tensor/expression_evaluation.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ReactNativeFrontend/ios/Pods/boost/boost/numeric/ublas/tensor/expression_evaluation.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// // Copyright (c) 2018-2019, Cem Bassoy, cem.bassoy@gmail.com // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // The authors gratefully acknowledge the support of // Fraunhofer IOSB, Ettlingen, Germany // #ifndef _BOOST_UBLAS_TENSOR_EXPRESSIONS_EVALUATION_HPP_ #define _BOOST_UBLAS_TENSOR_EXPRESSIONS_EVALUATION_HPP_ #include <type_traits> #include <stdexcept> namespace boost::numeric::ublas { template<class element_type, class storage_format, class storage_type> class tensor; template<class size_type> class basic_extents; } namespace boost::numeric::ublas::detail { template<class T, class D> struct tensor_expression; template<class T, class EL, class ER, class OP> struct binary_tensor_expression; template<class T, class E, class OP> struct unary_tensor_expression; } namespace boost::numeric::ublas::detail { template<class T, class E> struct has_tensor_types { static constexpr bool value = false; }; template<class T> struct has_tensor_types<T,T> { static constexpr bool value = true; }; template<class T, class D> struct has_tensor_types<T, tensor_expression<T,D>> { static constexpr bool value = std::is_same<T,D>::value || has_tensor_types<T,D>::value; }; template<class T, class EL, class ER, class OP> struct has_tensor_types<T, binary_tensor_expression<T,EL,ER,OP>> { static constexpr bool value = std::is_same<T,EL>::value || std::is_same<T,ER>::value || has_tensor_types<T,EL>::value || has_tensor_types<T,ER>::value; }; template<class T, class E, class OP> struct has_tensor_types<T, unary_tensor_expression<T,E,OP>> { static constexpr bool value = std::is_same<T,E>::value || has_tensor_types<T,E>::value; }; } // namespace boost::numeric::ublas::detail namespace boost::numeric::ublas::detail { /** @brief Retrieves extents of the tensor * */ template<class T, class F, class A> auto retrieve_extents(tensor<T,F,A> const& t) { return t.extents(); } /** @brief Retrieves extents of the tensor expression * * @note tensor expression must be a binary tree with at least one tensor type * * @returns extents of the child expression if it is a tensor or extents of one child of its child. */ template<class T, class D> auto retrieve_extents(tensor_expression<T,D> const& expr) { static_assert(detail::has_tensor_types<T,tensor_expression<T,D>>::value, "Error in boost::numeric::ublas::detail::retrieve_extents: Expression to evaluate should contain tensors."); auto const& cast_expr = static_cast<D const&>(expr); if constexpr ( std::is_same<T,D>::value ) return cast_expr.extents(); else return retrieve_extents(cast_expr); } /** @brief Retrieves extents of the binary tensor expression * * @note tensor expression must be a binary tree with at least one tensor type * * @returns extents of the (left and if necessary then right) child expression if it is a tensor or extents of a child of its (left and if necessary then right) child. */ template<class T, class EL, class ER, class OP> auto retrieve_extents(binary_tensor_expression<T,EL,ER,OP> const& expr) { static_assert(detail::has_tensor_types<T,binary_tensor_expression<T,EL,ER,OP>>::value, "Error in boost::numeric::ublas::detail::retrieve_extents: Expression to evaluate should contain tensors."); if constexpr ( std::is_same<T,EL>::value ) return expr.el.extents(); if constexpr ( std::is_same<T,ER>::value ) return expr.er.extents(); else if constexpr ( detail::has_tensor_types<T,EL>::value ) return retrieve_extents(expr.el); else if constexpr ( detail::has_tensor_types<T,ER>::value ) return retrieve_extents(expr.er); } /** @brief Retrieves extents of the binary tensor expression * * @note tensor expression must be a binary tree with at least one tensor type * * @returns extents of the child expression if it is a tensor or extents of a child of its child. */ template<class T, class E, class OP> auto retrieve_extents(unary_tensor_expression<T,E,OP> const& expr) { static_assert(detail::has_tensor_types<T,unary_tensor_expression<T,E,OP>>::value, "Error in boost::numeric::ublas::detail::retrieve_extents: Expression to evaluate should contain tensors."); if constexpr ( std::is_same<T,E>::value ) return expr.e.extents(); else if constexpr ( detail::has_tensor_types<T,E>::value ) return retrieve_extents(expr.e); } } // namespace boost::numeric::ublas::detail /////////////// namespace boost::numeric::ublas::detail { template<class T, class F, class A, class S> auto all_extents_equal(tensor<T,F,A> const& t, basic_extents<S> const& extents) { return extents == t.extents(); } template<class T, class D, class S> auto all_extents_equal(tensor_expression<T,D> const& expr, basic_extents<S> const& extents) { static_assert(detail::has_tensor_types<T,tensor_expression<T,D>>::value, "Error in boost::numeric::ublas::detail::all_extents_equal: Expression to evaluate should contain tensors."); auto const& cast_expr = static_cast<D const&>(expr); if constexpr ( std::is_same<T,D>::value ) if( extents != cast_expr.extents() ) return false; if constexpr ( detail::has_tensor_types<T,D>::value ) if ( !all_extents_equal(cast_expr, extents)) return false; return true; } template<class T, class EL, class ER, class OP, class S> auto all_extents_equal(binary_tensor_expression<T,EL,ER,OP> const& expr, basic_extents<S> const& extents) { static_assert(detail::has_tensor_types<T,binary_tensor_expression<T,EL,ER,OP>>::value, "Error in boost::numeric::ublas::detail::all_extents_equal: Expression to evaluate should contain tensors."); if constexpr ( std::is_same<T,EL>::value ) if(extents != expr.el.extents()) return false; if constexpr ( std::is_same<T,ER>::value ) if(extents != expr.er.extents()) return false; if constexpr ( detail::has_tensor_types<T,EL>::value ) if(!all_extents_equal(expr.el, extents)) return false; if constexpr ( detail::has_tensor_types<T,ER>::value ) if(!all_extents_equal(expr.er, extents)) return false; return true; } template<class T, class E, class OP, class S> auto all_extents_equal(unary_tensor_expression<T,E,OP> const& expr, basic_extents<S> const& extents) { static_assert(detail::has_tensor_types<T,unary_tensor_expression<T,E,OP>>::value, "Error in boost::numeric::ublas::detail::all_extents_equal: Expression to evaluate should contain tensors."); if constexpr ( std::is_same<T,E>::value ) if(extents != expr.e.extents()) return false; if constexpr ( detail::has_tensor_types<T,E>::value ) if(!all_extents_equal(expr.e, extents)) return false; return true; } } // namespace boost::numeric::ublas::detail namespace boost::numeric::ublas::detail { /** @brief Evaluates expression for a tensor * * Assigns the results of the expression to the tensor. * * \note Checks if shape of the tensor matches those of all tensors within the expression. */ template<class tensor_type, class derived_type> void eval(tensor_type& lhs, tensor_expression<tensor_type, derived_type> const& expr) { if constexpr (detail::has_tensor_types<tensor_type, tensor_expression<tensor_type,derived_type> >::value ) if(!detail::all_extents_equal(expr, lhs.extents() )) throw std::runtime_error("Error in boost::numeric::ublas::tensor: expression contains tensors with different shapes."); #pragma omp parallel for for(auto i = 0u; i < lhs.size(); ++i) lhs(i) = expr()(i); } /** @brief Evaluates expression for a tensor * * Applies a unary function to the results of the expressions before the assignment. * Usually applied needed for unary operators such as A += C; * * \note Checks if shape of the tensor matches those of all tensors within the expression. */ template<class tensor_type, class derived_type, class unary_fn> void eval(tensor_type& lhs, tensor_expression<tensor_type, derived_type> const& expr, unary_fn const fn) { if constexpr (detail::has_tensor_types< tensor_type, tensor_expression<tensor_type,derived_type> >::value ) if(!detail::all_extents_equal( expr, lhs.extents() )) throw std::runtime_error("Error in boost::numeric::ublas::tensor: expression contains tensors with different shapes."); #pragma omp parallel for for(auto i = 0u; i < lhs.size(); ++i) fn(lhs(i), expr()(i)); } /** @brief Evaluates expression for a tensor * * Applies a unary function to the results of the expressions before the assignment. * Usually applied needed for unary operators such as A += C; * * \note Checks if shape of the tensor matches those of all tensors within the expression. */ template<class tensor_type, class unary_fn> void eval(tensor_type& lhs, unary_fn const fn) { #pragma omp parallel for for(auto i = 0u; i < lhs.size(); ++i) fn(lhs(i)); } } #endif
30.99308
167
0.726248
Harshitha91
a794e9c3b2b7b4021dd9bc5360e76d720f00477f
2,383
cpp
C++
src/presentation/enrollevent.cpp
vieiramanoel/TP1-2019-1
4d68de98efcb0b77d921b3b0dc4c922a41ac7db3
[ "MIT" ]
null
null
null
src/presentation/enrollevent.cpp
vieiramanoel/TP1-2019-1
4d68de98efcb0b77d921b3b0dc4c922a41ac7db3
[ "MIT" ]
null
null
null
src/presentation/enrollevent.cpp
vieiramanoel/TP1-2019-1
4d68de98efcb0b77d921b3b0dc4c922a41ac7db3
[ "MIT" ]
null
null
null
#include <presentation/enrollevent.h> #include "ui_enrollevent.h" #include <iostream> #include <sstream> EnrollEvent::EnrollEvent(QWidget *parent, std::shared_ptr<EventContainer> ec, std::shared_ptr<PresentationsContainer> pc) : QWidget (parent), ui(new Ui::EnrollEvent) { ui->setupUi(this); events_container = ec; presentations_container = pc; } EnrollEvent::~EnrollEvent(){ delete ui; } template<typename Out> void split(const std::string &s, char delim, Out result) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } void EnrollEvent::on_eventCodeInput_textChanged(const QString &eventCode) { this->eventCode = eventCode.toUtf8().data(); } void EnrollEvent::on_eventNameInput_textChanged(const QString &eventName) { this->eventName = eventName.toUtf8().data(); } void EnrollEvent::on_eventCity_textChanged(const QString &eventCity) { this->eventCity = eventCity.toUtf8().data(); } void EnrollEvent::on_buttonBox_accepted() { std::list<std::shared_ptr<Presentation>> matchPresentations; for (auto code : presentation_codes) { auto presentation = presentations_container->GetPresentation(code); if (presentation != nullptr) { matchPresentations.push_back(presentation); } } if(events_container->CreateEvent(eventCode, ageGroup, eventName, eventType, eventCity, eventState, matchPresentations)) { this->deleteLater(); } else { ui->errMsg->setText("Wrong entries"); }; } void EnrollEvent::on_buttonBox_rejected() { this->deleteLater(); } void EnrollEvent::on_comboBox_3_currentTextChanged(const QString &state) { this->eventState = state.toUtf8().data(); } void EnrollEvent::on_ageGroupCombo_activated(const QString &ageGroup) { this->ageGroup = ageGroup.toUtf8().data(); } void EnrollEvent::on_eventTypeCombo_currentTextChanged(const QString &eventType) { this->eventType = eventType.toUtf8().data(); } void EnrollEvent::on_presCodesInput_textChanged(const QString &presCodes) { auto presentations = presCodes.toUtf8().data(); presentation_codes = split(presentations, ','); }
25.623656
141
0.706253
vieiramanoel
a795393e249d531a2d390700d23cda9d267ac487
6,807
cpp
C++
kernel/runtime/dmzRuntimeContextMessaging.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
2
2015-11-05T03:03:43.000Z
2017-05-15T12:55:39.000Z
kernel/runtime/dmzRuntimeContextMessaging.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
kernel/runtime/dmzRuntimeContextMessaging.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
#include "dmzRuntimeContextDefinitions.h" #include "dmzRuntimeContextMessaging.h" #include "dmzRuntimeMessageContext.h" dmz::Message dmz::RuntimeContextDefinitions::create_message ( const String &Name, const String &ParentName, RuntimeContext *context, RuntimeContextMessaging *messagingContext) { Message result; Message *type (messageNameTable.lookup (Name)); if (!type && context) { MessageContext *parentContext (0); if (ParentName) { Message *parent (messageNameTable.lookup (ParentName)); if (parent) { parentContext = parent->get_message_context (); } } MessageContext *mtc = new MessageContext (Name, context, messagingContext, parentContext); if (mtc) { type = new Message (mtc); if (type) { if (messageNameTable.store (type->get_name (), type)) { define_message(*type); messageHandleTable.store (type->get_handle (), type); } else { delete type; type = 0; type = messageNameTable.lookup (Name); } } mtc->unref (); mtc = 0; } } if (type) { result = *type; } return result; } //! Constructor. dmz::RuntimeContextMessaging::RuntimeContextMessaging ( RuntimeContextThreadKey &theKey, RuntimeContextDefinitions &defs, RuntimeContext *context) : log (context ? context->get_log_context () : 0), head (0), tail (0), messageCount (0), key (theKey), obsHandleTable (&obsHandleLock), obsNameTable (&obsNameLock), monostateErrorTable (&monostateErrorLock) { globalType = defs.create_message ("Global_Message", "", context, this); key.ref (); if (log) { log->ref (); } } //! Destructor. dmz::RuntimeContextMessaging::~RuntimeContextMessaging () { obsHandleTable.clear (); obsNameTable.clear (); key.unref (); if (log) { log->unref (); } listLock.lock (); if (head) { delete head; head = tail = 0; } listLock.unlock (); } inline void local_send ( const dmz::UInt32 Count, const dmz::Handle ObsHandle, const dmz::Data *InData, dmz::MessageContext &context, dmz::MessageContext &realContext) { if (!context.inSend) { context.inSend = dmz::True; dmz::HashTableHandleIterator it; const dmz::Message Type (&realContext); for ( dmz::MessageObserver *obs = context.obsTable.get_first (it); obs != 0; obs = context.obsTable.get_next (it)) { obs->receive_message (Type, Count, ObsHandle, InData, 0); } context.inSend = dmz::False; } } void dmz::RuntimeContextMessaging::send_monostate_warning (const Message &Msg) { if (log) { MessageContext *context = Msg.get_message_context (); if (context && !monostateErrorTable.lookup (context->Handle.get_runtime_handle ())) { String out ("Attempting to send Monostate Message: "); out << context->Name << " to target. Target ignored."; log->write_kernel_message (LogLevelWarn, out); monostateErrorTable.store (context->Handle.get_runtime_handle (), context); } } } dmz::UInt32 dmz::RuntimeContextMessaging::send ( const Boolean IncrementCount, const Message &Type, const Handle ObserverHandle, const Data *InData, Data *outData) const { RuntimeContextMessaging *self ((RuntimeContextMessaging *)this); UInt32 result (0); if (self->key.is_main_thread ()) { MessageContext *type (Type.get_message_context ()); MessageContext *startType (type); if (type) { if (Type != globalType) { if (IncrementCount) { self->messageCount++; if (messageCount <= 1) { self->messageCount = 2; } } result = messageCount; if (ObserverHandle) { MessageObserver *obs (0); while (!obs && type) { obs = type->obsTable.lookup (ObserverHandle); if (!obs) { type = type->parent; } } if (obs && type) { obs->receive_message (Type, result, ObserverHandle, InData, outData); } } else { while (type) { local_send (result, ObserverHandle, InData, *type, *startType); type = type->parent; } } } MessageContext *gcontext (globalType.get_message_context ()); if (gcontext) { local_send (result, ObserverHandle, InData, *gcontext, *startType); } } } else { send_delayed (Type, ObserverHandle, InData); result = 1; } return result; } void dmz::RuntimeContextMessaging::send_delayed ( const Message &Type, const Handle ObserverHandle, const Data *InData) const { if (Type.get_message_context ()) { RuntimeContextMessaging *self ((RuntimeContextMessaging *)this); MessageStruct *ms (new MessageStruct (Type, ObserverHandle, InData)); if (ms) { self->listLock.lock (); if (tail) { self->tail->next = ms; self->tail = ms; } else { self->head = self->tail = ms; } self->listLock.unlock (); } } } //! Sends messages from other threads. void dmz::RuntimeContextMessaging::update_time_slice () { if (head) { listLock.lock (); MessageStruct *ms = head; head = tail = 0; listLock.unlock (); while (ms) { ms->Type.send (ms->ObserverHandle, ms->DataPtr, 0); ms = ms->next; } delete ms; ms = 0; } } //! Adds message observer. dmz::Boolean dmz::RuntimeContextMessaging::add_observer (MessageObserver &obs) { const Handle ObsHandle (obs.get_message_observer_handle ()); const Boolean Result1 (ObsHandle ? obsHandleTable.store (ObsHandle, &obs) : False); const String Name (obs.get_message_observer_name ()); const Boolean Result2 (Name && ObsHandle ? obsNameTable.store (Name, &obs) : False); return Result1 && Result2; } //! Removes message observer. dmz::Boolean dmz::RuntimeContextMessaging::remove_observer (MessageObserver &obs) { const Handle ObsHandle (obs.get_message_observer_handle ()); const Boolean Result1 (ObsHandle ? (&obs == obsHandleTable.remove (ObsHandle)) : False); // Prevent the remove of a different obs with same name const String Name (obs.get_message_observer_name ()); const Boolean Result2 (Name && ObsHandle ? (&obs == obsNameTable.lookup (Name)) : False); if (Result2) { obsNameTable.remove (Name); } return Result1 && Result2; }
23.391753
87
0.595563
dmzgroup
a795a6b641042be7518f02828585a77f3defbc63
9,206
cpp
C++
Text/orientationHandler.cpp
ntclark/Graphic
86acc119d172bb53c1666432538836b461d8a3f2
[ "BSD-3-Clause" ]
12
2018-03-15T00:20:55.000Z
2021-08-11T10:02:15.000Z
Text/orientationHandler.cpp
ntclark/Graphic
86acc119d172bb53c1666432538836b461d8a3f2
[ "BSD-3-Clause" ]
null
null
null
Text/orientationHandler.cpp
ntclark/Graphic
86acc119d172bb53c1666432538836b461d8a3f2
[ "BSD-3-Clause" ]
2
2019-04-09T17:15:31.000Z
2020-12-05T19:52:59.000Z
// Copyright 2018 InnoVisioNate Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "text.h" #include <stdio.h> #include <commctrl.h> #include "Graphic_resource.h" LRESULT CALLBACK Text::orientationHandler(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) { Text *p = (Text *)GetWindowLongPtr(hwnd,GWLP_USERDATA); switch ( msg ) { case WM_INITDIALOG: { PROPSHEETPAGE *pPage = reinterpret_cast<PROPSHEETPAGE *>(lParam); p = (Text *)pPage -> lParam; SetWindowLongPtr(hwnd,GWLP_USERDATA,(ULONG_PTR)p); p -> hwndOrientation = hwnd; SendDlgItemMessage(hwnd,IDDI_TEXT_PLANEHEIGHT,TBM_SETSEL,(WPARAM)FALSE,MAKELPARAM(0,100)); if ( ! p -> showPositionSettings ) { RECT rcBox,rcParent; GetWindowRect(hwnd,&rcParent); GetClientRect(GetDlgItem(hwnd,IDDI_TEXT_POSITION_GROUP),&rcBox); for ( long id = IDDI_TEXT_POSITION_GROUP; id <= IDDI_TEXT_ZCOORDINATE; id++ ) ShowWindow(GetDlgItem(hwnd,id),SW_HIDE); for ( long id = IDDI_TEXT_FORMATTING_GROUP; id <= IDDI_TEXT_FORMAT_RIGHT; id++ ) { RECT rcItem; GetWindowRect(GetDlgItem(hwnd,id),&rcItem); SetWindowPos(GetDlgItem(hwnd,id),HWND_TOP,rcItem.left - rcParent.left,rcItem.top - rcParent.top - rcBox.bottom,0,0,SWP_NOSIZE); } } } return LRESULT(TRUE); case WM_SHOWWINDOW: { if ( ! (BOOL)wParam ) break; SendDlgItemMessage(hwnd,IDDI_TEXT_XYPLANE,BM_SETCHECK,(WPARAM)BST_UNCHECKED,0L); SendDlgItemMessage(hwnd,IDDI_TEXT_YXPLANE,BM_SETCHECK,(WPARAM)BST_UNCHECKED,0L); SendDlgItemMessage(hwnd,IDDI_TEXT_YZPLANE,BM_SETCHECK,(WPARAM)BST_UNCHECKED,0L); SendDlgItemMessage(hwnd,IDDI_TEXT_ZXPLANE,BM_SETCHECK,(WPARAM)BST_UNCHECKED,0L); SendDlgItemMessage(hwnd,IDDI_TEXT_ZYPLANE,BM_SETCHECK,(WPARAM)BST_UNCHECKED,0L); SendDlgItemMessage(hwnd,IDDI_TEXT_SCREENPLANE,BM_SETCHECK,(WPARAM)BST_UNCHECKED,0L); long buttonId; switch ( p -> coordinatePlane ) { case CoordinatePlane_XY: buttonId = IDDI_TEXT_XYPLANE; break; case CoordinatePlane_XZ: buttonId = IDDI_TEXT_XZPLANE; break; case CoordinatePlane_YX: buttonId = IDDI_TEXT_YXPLANE; break; case CoordinatePlane_YZ: buttonId = IDDI_TEXT_YZPLANE; break; case CoordinatePlane_ZX: buttonId = IDDI_TEXT_ZXPLANE; break; case CoordinatePlane_ZY: buttonId = IDDI_TEXT_ZYPLANE; break; case CoordinatePlane_screen: buttonId = IDDI_TEXT_SCREENPLANE; break; } SendDlgItemMessage(hwnd,buttonId,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); if ( p -> flipVertical ) SendDlgItemMessage(hwnd,IDDI_TEXT_FLIP_TB,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); if ( p -> flipHorizontal ) SendDlgItemMessage(hwnd,IDDI_TEXT_FLIP_LR,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); SendDlgItemMessage(hwnd,IDDI_TEXT_PLANEHEIGHT,TBM_SETPOS,(WPARAM)TRUE,(LPARAM)static_cast<long>(100.0 * (1.0 - p -> planeHeight))); char szTemp[32]; sprintf(szTemp,"%g",p -> dpStart.x); SetDlgItemText(hwnd,IDDI_TEXT_XCOORDINATE,szTemp); sprintf(szTemp,"%g",p -> dpStart.y); SetDlgItemText(hwnd,IDDI_TEXT_YCOORDINATE,szTemp); sprintf(szTemp,"%g",p -> dpStart.z); SetDlgItemText(hwnd,IDDI_TEXT_ZCOORDINATE,szTemp); EnableWindow(GetDlgItem(hwnd,IDDI_TEXT_XCOORDINATE),p -> enablePositionSettings); EnableWindow(GetDlgItem(hwnd,IDDI_TEXT_YCOORDINATE),p -> enablePositionSettings); EnableWindow(GetDlgItem(hwnd,IDDI_TEXT_ZCOORDINATE),p -> enablePositionSettings); TextFormat format; p -> propertyFormat -> get_longValue(reinterpret_cast<long*>(&format)); if ( format & TEXT_COORDINATES_FROM_TOP ) SendDlgItemMessage(hwnd,IDDI_TEXT_FORMAT_FROM_TOP,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); else { if ( format & TEXT_COORDINATES_FROM_CENTER ) SendDlgItemMessage(hwnd,IDDI_TEXT_FORMAT_FROM_CENTER,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); else SendDlgItemMessage(hwnd,IDDI_TEXT_FORMAT_FROM_BOTTOM,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); } if ( format & TEXT_FORMAT_CENTER ) SendDlgItemMessage(hwnd,IDDI_TEXT_FORMAT_CENTER,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); else { if ( format & TEXT_FORMAT_RIGHT ) SendDlgItemMessage(hwnd,IDDI_TEXT_FORMAT_RIGHT,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); else SendDlgItemMessage(hwnd,IDDI_TEXT_FORMAT_LEFT,BM_SETCHECK,(WPARAM)BST_CHECKED,0L); } } break; case WM_COMMAND: { if ( ! p ) break; int id = LOWORD(wParam); int notificationCode = HIWORD(wParam); switch ( notificationCode ) { case EN_CHANGE: { char szTemp[32]; switch ( id) { case IDDI_TEXT_XCOORDINATE: GetDlgItemText(hwnd,IDDI_TEXT_XCOORDINATE,szTemp,32); p -> propertyPositionX -> put_szValue(szTemp); break; case IDDI_TEXT_YCOORDINATE: GetDlgItemText(hwnd,IDDI_TEXT_YCOORDINATE,szTemp,32); p -> propertyPositionY -> put_szValue(szTemp); break; case IDDI_TEXT_ZCOORDINATE: GetDlgItemText(hwnd,IDDI_TEXT_ZCOORDINATE,szTemp,32); p -> propertyPositionZ -> put_szValue(szTemp); break; } } break; case BN_CLICKED: { switch ( id ) { case IDDI_TEXT_XYPLANE: if ( BST_CHECKED == SendDlgItemMessage(hwnd,id,BM_GETCHECK,0L,0L) ) p -> coordinatePlane = CoordinatePlane_XY; break; case IDDI_TEXT_XZPLANE: if ( BST_CHECKED == SendDlgItemMessage(hwnd,id,BM_GETCHECK,0L,0L) ) p -> coordinatePlane = CoordinatePlane_XZ; break; case IDDI_TEXT_YXPLANE: if ( BST_CHECKED == SendDlgItemMessage(hwnd,id,BM_GETCHECK,0L,0L) ) p -> coordinatePlane = CoordinatePlane_YX; break; case IDDI_TEXT_YZPLANE: if ( BST_CHECKED == SendDlgItemMessage(hwnd,id,BM_GETCHECK,0L,0L) ) p -> coordinatePlane = CoordinatePlane_YZ; break; case IDDI_TEXT_ZXPLANE: if ( BST_CHECKED == SendDlgItemMessage(hwnd,id,BM_GETCHECK,0L,0L) ) p -> coordinatePlane = CoordinatePlane_ZX; break; case IDDI_TEXT_ZYPLANE: if ( BST_CHECKED == SendDlgItemMessage(hwnd,id,BM_GETCHECK,0L,0L) ) p -> coordinatePlane = CoordinatePlane_ZY; break; case IDDI_TEXT_FLIP_LR: { long isChecked = (long)SendDlgItemMessage(hwnd,IDDI_TEXT_FLIP_LR,BM_GETCHECK,0L,0L); p -> flipHorizontal = isChecked == BST_CHECKED ? TRUE : FALSE; } break; case IDDI_TEXT_FLIP_TB: { long isChecked = (long)SendDlgItemMessage(hwnd,IDDI_TEXT_FLIP_TB,BM_GETCHECK,0L,0L); p -> flipVertical = isChecked == BST_CHECKED ? TRUE : FALSE; } break; case IDDI_TEXT_SCREENPLANE: if ( BST_CHECKED == SendDlgItemMessage(hwnd,id,BM_GETCHECK,0L,0L) ) p -> coordinatePlane = CoordinatePlane_screen; break; case IDDI_TEXT_FORMAT_FROM_BOTTOM: case IDDI_TEXT_FORMAT_FROM_CENTER: case IDDI_TEXT_FORMAT_FROM_TOP: { long format; p -> propertyFormat -> get_longValue(&format); format = format & 0x000F; if ( IDDI_TEXT_FORMAT_FROM_BOTTOM == id ) { format |= TEXT_COORDINATES_FROM_BOTTOM; } else { if ( IDDI_TEXT_FORMAT_FROM_CENTER == id ) format |= TEXT_COORDINATES_FROM_CENTER; else format |= TEXT_COORDINATES_FROM_TOP; } p -> propertyFormat -> put_longValue(format); } break; case IDDI_TEXT_FORMAT_LEFT: case IDDI_TEXT_FORMAT_RIGHT: case IDDI_TEXT_FORMAT_CENTER: { long format; p -> propertyFormat -> get_longValue(&format); format = format & 0x00F0; if ( IDDI_TEXT_FORMAT_LEFT == id ) { format |= TEXT_FORMAT_LEFT; } else { if ( IDDI_TEXT_FORMAT_CENTER == id ) format |= TEXT_FORMAT_CENTER; else format |= TEXT_FORMAT_RIGHT; } p -> propertyFormat -> put_longValue(format); } break; } } break; } } break; case WM_NOTIFY: { if ( ! p ) break; int idControl = (int)wParam; if ( idControl == IDDI_TEXT_PLANEHEIGHT ) { p -> propertyPlaneHeight -> put_doubleValue(static_cast<double>(100 - SendDlgItemMessage(hwnd,IDDI_TEXT_PLANEHEIGHT,TBM_GETPOS,0L,0L))/100.0); } } break; default: break; } return LRESULT(FALSE); }
35.682171
151
0.623941
ntclark
a7962e72628836bbaf732ecc20253b7b84be3e94
1,596
hpp
C++
include/uvpp/handle.hpp
leoxiaofei/uvpp
e4fd4ccdbd29a456c7c36d95d5e56a0b7c999080
[ "MIT" ]
1
2022-03-23T08:01:28.000Z
2022-03-23T08:01:28.000Z
include/uvpp/handle.hpp
leoxiaofei/uvpp
e4fd4ccdbd29a456c7c36d95d5e56a0b7c999080
[ "MIT" ]
null
null
null
include/uvpp/handle.hpp
leoxiaofei/uvpp
e4fd4ccdbd29a456c7c36d95d5e56a0b7c999080
[ "MIT" ]
null
null
null
#pragma once #include "error.hpp" #include "callback.hpp" namespace uvpp { /** * Wraps a libuv's uv_handle_t, or derived such as uv_stream_t, uv_tcp_t etc. * * Resources are released on the close call as mandated by libuv and NOT on the dtor */ template<typename HANDLE_O, typename HANDLE_T> class Handle { HANDLE_T* m_uv_handle; Callback m_cb_close; public: typedef HANDLE_T Hwnd; typedef Handle<HANDLE_O, HANDLE_T> Self; protected: Handle() : m_uv_handle(new HANDLE_T) { m_uv_handle->data = this; } virtual ~Handle() { Destory(); } Handle(const Handle&) = delete; Handle& operator=(const Handle&) = delete; public: template<typename T = HANDLE_T> T* get() { return reinterpret_cast<T*>(m_uv_handle); } template<typename T = HANDLE_T> const T* get() const { return reinterpret_cast<const T*>(m_uv_handle); } template<typename SUB_REQUEST_T> static HANDLE_O* self(SUB_REQUEST_T* handle) { return reinterpret_cast<HANDLE_O*>(handle->data); } bool is_active() const { return uv_is_active(get<uv_handle_t>()) != 0; } bool is_closing() const { return !!uv_is_closing(get<uv_handle_t>()); } void close(const Callback& cb_close) { if (!is_closing()) { m_cb_close = cb_close; uv_close(this->get<uv_handle_t>(), INVOKE_CLOSE_CB(m_cb_close)); } } protected: virtual void Destory() { if (!is_closing()) { uv_close(this->get<uv_handle_t>(), [](uv_handle_t* handle) { delete (HANDLE_T*)(handle); }); m_uv_handle = nullptr; } } }; }
17.538462
85
0.654762
leoxiaofei
a79a5e364fc17e882ff36c65673d68b9cc638b54
269
hpp
C++
include/philchess/uci/cli.hpp
philipplenk/paulchen332
a0796a1b506854a0a91b14b66fc383c6f120bc9f
[ "BSD-2-Clause" ]
4
2020-12-12T16:55:23.000Z
2021-12-17T17:19:11.000Z
include/philchess/uci/cli.hpp
philipplenk/paulchen332
a0796a1b506854a0a91b14b66fc383c6f120bc9f
[ "BSD-2-Clause" ]
4
2020-11-25T11:20:01.000Z
2022-02-05T09:38:31.000Z
include/philchess/uci/cli.hpp
philipplenk/paulchen332
a0796a1b506854a0a91b14b66fc383c6f120bc9f
[ "BSD-2-Clause" ]
null
null
null
#ifndef PHILCHESS_UCI_CLI_H #define PHILCHESS_UCI_CLI_H namespace philchess { namespace uci { template <typename ENGINE_T, typename IO_T, typename ...ARGS_T> void run_cli(IO_T io, ARGS_T&&... args); }} //end namespace philchess:uci #include "cli_impl.hpp" #endif
19.214286
64
0.758364
philipplenk
a79b730fc6dffc2d26ef865b38379f8532b52a52
5,459
hpp
C++
src/q/mpmc_flexible_lock_queue.hpp
KjellKod/QMPSC
1cb20d22a6d6c14e14fad3612bd1532fdffbabde
[ "Unlicense" ]
1
2018-09-21T09:39:15.000Z
2018-09-21T09:39:15.000Z
src/q/mpmc_flexible_lock_queue.hpp
KjellKod/QMPSC
1cb20d22a6d6c14e14fad3612bd1532fdffbabde
[ "Unlicense" ]
null
null
null
src/q/mpmc_flexible_lock_queue.hpp
KjellKod/QMPSC
1cb20d22a6d6c14e14fad3612bd1532fdffbabde
[ "Unlicense" ]
null
null
null
/** ========================================================================== * Not any company's property but Public-Domain * Do with source-code as you will. No requirement to keep this * header if need to use it/change it/ or do whatever with it * * Note that there is No guarantee that this code will work * and I take no responsibility for this code and any problems you * might get if using it. * * ========================================================================== * 2010 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================ * * Example of a normal std::queue protected by a mutex for operations, * making it safe for thread communication, using std::mutex from C++0x with * the help from the std::thread library from JustSoftwareSolutions * ref: http://www.stdthread.co.uk/doc/headers/mutex.html * * This exampel was totally inspired by Anthony Williams lock-based data structures in * Ref: "C++ Concurrency In Action" http://www.manning.com/williams */ #pragma once #include <queue> #include <mutex> #include <exception> #include <condition_variable> #include <chrono> /** Multiple producer, multiple consumer (mpmc) thread safe queue * protected by mutex. Since 'return by reference' is used this queue won't throw */ namespace mpmc { template<typename T> class flexible_lock_queue { static const int kUnlimited = -1; static const int kSmallDefault = 100; const int kMaxSize; std::queue<T> queue_; mutable std::mutex m_; std::condition_variable data_cond_; flexible_lock_queue& operator=(const flexible_lock_queue&) = delete; flexible_lock_queue(const flexible_lock_queue& other) = delete; bool internal_full() const; size_t internal_capacity() const; public: // -1 : unbounded // 0 ... N : bounded (0 is silly) flexible_lock_queue(const int maxSize = kSmallDefault); bool lock_free() const; bool push(T& item); bool pop(T& popped_item); bool wait_and_pop(T& popped_item, std::chrono::milliseconds max_wait); bool full(); bool empty() const; size_t size() const; size_t capacity() const; size_t capacity_free() const; size_t usage() const; }; // maxSize of -1 equals unlimited size template<typename T> flexible_lock_queue<T>::flexible_lock_queue(int maxSize) : kMaxSize (maxSize){} template<typename T> bool flexible_lock_queue<T>::lock_free() const { return false; } template<typename T> bool flexible_lock_queue<T>::push(T& item) { { std::lock_guard<std::mutex> lock(m_); if (internal_full()) { return false; } queue_.push(std::move(item)); } // lock_guard off data_cond_.notify_one(); return true; } template<typename T> bool flexible_lock_queue<T>::pop(T& popped_item) { std::lock_guard<std::mutex> lock(m_); if (queue_.empty()) { return false; } popped_item = std::move(queue_.front()); queue_.pop(); return true; } template<typename T> bool flexible_lock_queue<T>::wait_and_pop(T& popped_item, std::chrono::milliseconds max_wait) { std::unique_lock<std::mutex> lock(m_); auto const timeout = std::chrono::steady_clock::now() + max_wait; while (queue_.empty()) { if (data_cond_.wait_until(lock, timeout) == std::cv_status::timeout) { break; } // This 'while' loop is equal to // data_cond_.wait(lock, [](bool result){return !queue_.empty();}); } if (queue_.empty()) { return false; } popped_item = std::move(queue_.front()); queue_.pop(); return true; } template<typename T> bool flexible_lock_queue<T>::full() { std::lock_guard<std::mutex> lock(m_); return internal_full(); } template<typename T> bool flexible_lock_queue<T>::empty() const { std::lock_guard<std::mutex> lock(m_); return queue_.empty(); } template<typename T> size_t flexible_lock_queue<T>::size() const { std::lock_guard<std::mutex> lock(m_); return queue_.size(); } template<typename T> size_t flexible_lock_queue<T>::capacity() const { std::lock_guard<std::mutex> lock(m_); return internal_capacity(); } template<typename T> size_t flexible_lock_queue<T>::capacity_free() const { std::lock_guard<std::mutex> lock(m_); return internal_capacity() - queue_.size(); } template<typename T> size_t flexible_lock_queue<T>::usage() const { std::lock_guard<std::mutex> lock(m_); return (100 * queue_.size() / internal_capacity()); } // private template<typename T> size_t flexible_lock_queue<T>::internal_capacity() const { if (kMaxSize == kUnlimited) { return std::numeric_limits<unsigned int>::max(); } return kMaxSize; } template<typename T> bool flexible_lock_queue<T>::internal_full() const { if (kMaxSize == kUnlimited) { return false; } return (queue_.size() >= kMaxSize); } } // mpmc
29.668478
98
0.621909
KjellKod
a79e9cf3d018a84485c909f5306a7f4defd3a08a
5,019
cpp
C++
Samples/LuckyDraw/Source/CViewInit.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
310
2019-11-25T04:14:11.000Z
2022-03-31T23:39:19.000Z
Samples/LuckyDraw/Source/CViewInit.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
79
2019-11-17T07:51:02.000Z
2022-03-22T08:49:41.000Z
Samples/LuckyDraw/Source/CViewInit.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
24
2020-05-10T09:37:55.000Z
2022-03-05T13:19:31.000Z
#include "pch.h" #include "CViewInit.h" #include "CViewDemo.h" #include "CLocalize.h" #include "ViewManager/CViewManager.h" #include "Context/CContext.h" #include "GridPlane/CGridPlane.h" #include "SkyDome/CSkyDome.h" CViewInit::CViewInit() : m_initState(CViewInit::DownloadBundles), m_getFile(NULL), m_downloaded(0), m_largeFont(NULL), m_canvasObject(NULL), m_guiText(NULL), m_blinkTime(0.0f) { } CViewInit::~CViewInit() { m_canvasObject->remove(); delete m_largeFont; // handle click event CEventManager::getInstance()->unRegisterEvent(this); } io::path CViewInit::getBuiltInPath(const char* name) { return getApplication()->getBuiltInPath(name); } void CViewInit::onInit() { CBaseApp* app = getApplication(); app->getFileSystem()->addFileArchive(getBuiltInPath("BuiltIn.zip"), false, false); CShaderManager* shaderMgr = CShaderManager::getInstance(); shaderMgr->initBasicShader(); CGlyphFreetype* freetypeFont = CGlyphFreetype::getInstance(); freetypeFont->initFont("Segoe UI Light", "BuiltIn/Fonts/segoeui/segoeuil.ttf"); // handle click event CEventManager::getInstance()->registerEvent("ViewInit", this); } void CViewInit::initScene() { CBaseApp* app = getApplication(); // init segoeuil.ttf inside BuiltIn.zip CGlyphFreetype* freetypeFont = CGlyphFreetype::getInstance(); freetypeFont->initFont("Segoe UI Light", "BuiltIn/Fonts/segoeui/segoeuil.ttf"); freetypeFont->initFont("LasVegas", "LuckyDraw/LasVegasJackpotRegular.otf"); freetypeFont->initFont("Sans", "LuckyDraw/droidsans.ttf"); // create a scene CContext* context = CContext::getInstance(); CScene* scene = context->initScene(); CZone* zone = scene->createZone(); // create 2d camera CGameObject* guiCameraObject = zone->createEmptyObject(); CCamera* guiCamera = guiCameraObject->addComponent<CCamera>(); guiCamera->setProjectionType(CCamera::OrthoUI); // 2d gui m_largeFont = new CGlyphFont(); m_largeFont->setFont("Segoe UI Light", 30); // create 2D Canvas m_canvasObject = zone->createEmptyObject(); CCanvas* canvas = m_canvasObject->addComponent<CCanvas>(); // create UI Text in Canvas m_guiText = canvas->createText(m_largeFont); m_guiText->setPosition(core::vector3df(0.0f, -40.0f, 0.0f)); m_guiText->setText(CLocalize::get("TXT_CLICK_TO_CONTINUE")); m_guiText->setTextAlign(CGUIElement::Center, CGUIElement::Bottom); // set gui camera context->setGUICamera(guiCamera); } void CViewInit::loadConfig() { CXMLSpreadsheet xlsText; if (xlsText.open("Luckydraw/text.xml") == true) { CLocalize::createGetInstance()->init(&xlsText); CLocalize::getInstance()->setLanguage(ELanguage::EN); } } void CViewInit::onDestroy() { } void CViewInit::onUpdate() { CContext* context = CContext::getInstance(); switch (m_initState) { case CViewInit::DownloadBundles: { io::IFileSystem* fileSystem = getApplication()->getFileSystem(); std::vector<std::string> listBundles; listBundles.push_back("LuckyDraw.zip"); #ifdef __EMSCRIPTEN__ const char* filename = listBundles[m_downloaded].c_str(); if (m_getFile == NULL) { m_getFile = new CGetFileURL(filename, filename); m_getFile->download(CGetFileURL::Get); char log[512]; sprintf(log, "Download asset: %s", filename); os::Printer::log(log); } else { if (m_getFile->getState() == CGetFileURL::Finish) { // [bundles].zip fileSystem->addFileArchive(filename, false, false); if (++m_downloaded >= listBundles.size()) m_initState = CViewInit::InitScene; else { delete m_getFile; m_getFile = NULL; } } else if (m_getFile->getState() == CGetFileURL::Error) { // retry download delete m_getFile; m_getFile = NULL; } } #else for (std::string& bundle : listBundles) { const char* r = bundle.c_str(); #if defined(WINDOWS_STORE) fileSystem->addFileArchive(getBuiltInPath(r), false, false); #elif defined(MACOS) fileSystem->addFileArchive(getBuiltInPath(r), false, false); #else fileSystem->addFileArchive(r, false, false); #endif } m_initState = CViewInit::InitScene; #endif } break; case CViewInit::InitScene: { loadConfig(); initScene(); m_initState = CViewInit::Finished; } break; case CViewInit::Error: { // todo nothing with black screen } break; default: { CScene* scene = context->getScene(); if (scene != NULL) scene->update(); } break; } } void CViewInit::onRender() { if (m_initState == CViewInit::Finished) { float blink = 400.0f; m_blinkTime = m_blinkTime + getTimeStep(); if (m_blinkTime < blink) m_guiText->setVisible(false); else m_guiText->setVisible(true); if (m_blinkTime > blink * 2.0f) m_blinkTime = 0.0f; CGraphics2D::getInstance()->render(CContext::getInstance()->getGUICamera()); } } bool CViewInit::OnEvent(const SEvent& event) { if (event.EventType == EET_MOUSE_INPUT_EVENT) { if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { CViewManager::getInstance()->getLayer(0)->changeView<CViewDemo>(); } } return false; }
22.40625
83
0.708109
tsukoyumi
a7a9873d1b73ac3d2568f56a5099ef89f68c7288
1,548
cpp
C++
ewk/unittest/utc_blink_ewk_settings_loads_images_automatically_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
null
null
null
ewk/unittest/utc_blink_ewk_settings_loads_images_automatically_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
null
null
null
ewk/unittest/utc_blink_ewk_settings_loads_images_automatically_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 Samsung Electronics. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utc_blink_ewk_base.h" class utc_blink_ewk_settings_load_images_automatically_set : public utc_blink_ewk_base { }; /** * @brief Tests if returns TRUE when initiated with a correct webview and set to TRUE. */ TEST_F(utc_blink_ewk_settings_load_images_automatically_set, POS_TEST1) { Ewk_Settings* settings = ewk_view_settings_get(GetEwkWebView()); if (!settings) { FAIL(); } Eina_Bool result = ewk_settings_loads_images_automatically_set(settings, EINA_TRUE); if (!result) { FAIL(); } result = ewk_settings_loads_images_automatically_get(settings); EXPECT_EQ(result, EINA_TRUE); } /** * @brief Tests if returns FALSE when initiated with a correct webview and set to FALSE. */ TEST_F(utc_blink_ewk_settings_load_images_automatically_set, POS_TEST2) { Ewk_Settings* settings = ewk_view_settings_get(GetEwkWebView()); if (!settings) { FAIL(); } Eina_Bool result = ewk_settings_loads_images_automatically_set(settings, EINA_FALSE); if (!result) { FAIL(); } result = ewk_settings_loads_images_automatically_get(settings); EXPECT_EQ(result, EINA_FALSE); } /** * @brief Tests if returns FALSE when initiated with NULL webview. */ TEST_F(utc_blink_ewk_settings_load_images_automatically_set, NEG_TEST) { Eina_Bool result = ewk_settings_loads_images_automatically_set(NULL, EINA_TRUE); EXPECT_EQ(result, EINA_FALSE); }
28.145455
88
0.768734
Jabawack
a7ae7f1bebd880fe5048a3818db152d226f6478e
4,735
cc
C++
wcd/src/DetectorConstruction.cc
lagoproject/sims
bc34510b803136c770ecd9c789dc7cfade2ccbbd
[ "BSD-3-Clause" ]
null
null
null
wcd/src/DetectorConstruction.cc
lagoproject/sims
bc34510b803136c770ecd9c789dc7cfade2ccbbd
[ "BSD-3-Clause" ]
null
null
null
wcd/src/DetectorConstruction.cc
lagoproject/sims
bc34510b803136c770ecd9c789dc7cfade2ccbbd
[ "BSD-3-Clause" ]
null
null
null
// Geant4 Libraries // #include "G4Material.hh" #include "G4Element.hh" #include "G4LogicalBorderSurface.hh" #include "G4LogicalSkinSurface.hh" #include "G4OpticalSurface.hh" #include "G4MultiFunctionalDetector.hh" #include "G4VPrimitiveScorer.hh" #include "G4PSEnergyDeposit.hh" #include "G4VPhysicalVolume.hh" #include "G4Box.hh" #include "G4Sphere.hh" #include "G4LogicalVolume.hh" #include "G4ThreeVector.hh" #include "G4PVPlacement.hh" #include "G4SystemOfUnits.hh" #include "G4NistManager.hh" #include "G4UnitsTable.hh" #include "G4PhysicalConstants.hh" #include "G4GeometryManager.hh" #include "G4PhysicalVolumeStore.hh" #include "G4LogicalVolumeStore.hh" #include "G4SolidStore.hh" #include "G4LogicalSkinSurface.hh" #include "G4LogicalBorderSurface.hh" #include "G4RunManager.hh" // Local Libraries // //#include "PMTSD.hh" #include "DetectorConstruction.hh" #include "DetectorMessenger.hh" #include "PMTSD.hh" #include "world.hh" #include "wcdCont.hh" #include "wcdCalo.hh" #include "wcdpmt.hh" #include "worldGround.hh" #include "grdFloor.hh" // C++ Libraries // DetectorConstruction::DetectorConstruction() : G4VUserDetectorConstruction() { G4cout << "...DetectorConstruction..." << G4endl; expHall = new world(); groundBase = new worldGround(); grd = new grdFloor(); wcdCont = new wcdCont(); wcdCalo = new wcdCalo(); pmt_det = new wcdpmt(); wcdRadius = 93.*cm; wcdHight = 142.*cm; checkOverlaps = true; detecMess = new DetectorMessenger(this); } DetectorConstruction::~DetectorConstruction() {} // ************************* // Doing Mechanical Detector // ************************* G4VPhysicalVolume* DetectorConstruction::Construct() { G4GeometryManager::GetInstance()->OpenGeometry(); G4PhysicalVolumeStore::GetInstance()->Clean(); G4LogicalVolumeStore::GetInstance()->Clean(); G4SolidStore::GetInstance()->Clean(); G4LogicalSkinSurface::CleanSurfaceTable(); G4LogicalBorderSurface::CleanSurfaceTable(); return ConstructDetector(); } G4VPhysicalVolume* DetectorConstruction::ConstructDetector() { expHall->DefineMaterials(); expHall->buildDetector(&checkOverlaps); groundBase->DefineMaterials(); groundBase->buildDetector(expHall->getLogVolume(), &checkOverlaps); wcdCont->DefineMaterials(); wcdCont->buildDetector(groundBase->getLogVolume(), &checkOverlaps, wcdRadius, wcdHight); wcdCalo->DefineMaterials(); wcdCalo->buildDetector(wcdCont->getLogVolume(), wcdCont->getPhysVolume(), &checkOverlaps, wcdRadius, wcdHight); pmt_det->DefineMaterials(); pmt_det->buildDetector(wcdCalo->getLogVolume(), wcdHight, &checkOverlaps); fwaterVolume = wcdCalo->getPhysVolume(); grd->DefineMaterials(); grd->buildDetector(wcdHight, groundBase->getLogVolume(), &checkOverlaps); return expHall->getPhysVolume(); } void DetectorConstruction::setWcdRadius( G4double wcdR ) { this->wcdRadius = wcdR; wcdCont->getLogVolume()->RemoveDaughter(wcdCont->getPhysVolume()); delete wcdCont->getPhysVolume(); wcdCont->buildDetector(groundBase->getLogVolume(), &checkOverlaps, wcdRadius, wcdHight); wcdCalo->getLogVolume()->RemoveDaughter(wcdCalo->getPhysVolume()); delete wcdCalo->getPhysVolume(); wcdCalo->buildDetector(wcdCont->getLogVolume(), wcdCont->getPhysVolume(), &checkOverlaps, wcdRadius, wcdHight); pmt_det->getLogVolume()->RemoveDaughter(pmt_det->getPhysVolume()); delete pmt_det->getPhysVolume(); pmt_det->buildDetector(wcdCalo->getLogVolume(), wcdHight, &checkOverlaps); fwaterVolume = wcdCalo->getPhysVolume(); grd->getLogVolume()->RemoveDaughter(grd->getPhysVolume()); delete grd->getPhysVolume(); grd->buildDetector(wcdHight, groundBase->getLogVolume(), &checkOverlaps); G4RunManager::GetRunManager()->GeometryHasBeenModified(); } void DetectorConstruction::setWcdHight( G4double wcdH ) { this->wcdHight = wcdH; wcdCont->getLogVolume()->RemoveDaughter(wcdCont->getPhysVolume()); delete wcdCont->getPhysVolume(); wcdCont->buildDetector(groundBase->getLogVolume(), &checkOverlaps, wcdRadius, wcdHight); wcdCalo->getLogVolume()->RemoveDaughter(wcdCalo->getPhysVolume()); delete wcdCalo->getPhysVolume(); wcdCalo->buildDetector(wcdCont->getLogVolume(), wcdCont->getPhysVolume(), &checkOverlaps, wcdRadius, wcdHight); pmt_det->getLogVolume()->RemoveDaughter(pmt_det->getPhysVolume()); delete pmt_det->getPhysVolume(); pmt_det->buildDetector(wcdCalo->getLogVolume(), wcdHight, &checkOverlaps); fwaterVolume = wcdCalo->getPhysVolume(); grd->getLogVolume()->RemoveDaughter(grd->getPhysVolume()); delete grd->getPhysVolume(); grd->buildDetector(wcdHight, groundBase->getLogVolume(), &checkOverlaps); G4RunManager::GetRunManager()->GeometryHasBeenModified(); }
27.852941
113
0.745512
lagoproject
a7b0240148a4f75a7c44199a0b79e18db1909cd8
7,135
cpp
C++
test/interconnection/steiner_tree_test.cpp
sheiny/ophidian
037ae44357e0093d60b379513615b467c1f841cf
[ "Apache-2.0" ]
40
2016-04-22T14:42:42.000Z
2021-05-25T23:14:23.000Z
test/interconnection/steiner_tree_test.cpp
sheiny/ophidian
037ae44357e0093d60b379513615b467c1f841cf
[ "Apache-2.0" ]
64
2016-04-28T21:10:47.000Z
2017-11-07T11:33:17.000Z
test/interconnection/steiner_tree_test.cpp
eclufsc/openeda
037ae44357e0093d60b379513615b467c1f841cf
[ "Apache-2.0" ]
25
2016-04-18T19:31:48.000Z
2021-05-05T15:50:41.000Z
#include <catch.hpp> #include <ophidian/interconnection/SteinerTree.h> #include <ophidian/geometry/Distance.h> #include <memory> #include <algorithm> using namespace ophidian::interconnection; using namespace ophidian::geometry; TEST_CASE("Steiner Tree/empty steiner tree", "[interconnection]") { auto tree = SteinerTree::create(); CHECK( tree->size(SteinerTree::Segment{}) == 0 ); CHECK( tree->size(SteinerTree::Point{}) == 0 ); } TEST_CASE("Steiner Tree/add point", "[interconnection]") { const auto kPosition = SteinerTree::DbuPoint{SteinerTree::dbu_t{1.0}, SteinerTree::dbu_t{2.0}}; auto tree = SteinerTree::create(); auto point = tree->add(kPosition); CHECK( tree->size(SteinerTree::Point{}) == 1 ); CHECK( Approx(tree->position(point).x()) == kPosition.x() ); CHECK( Approx(tree->position(point).y()) == kPosition.y() ); } TEST_CASE("Steiner Tree/add segment", "[interconnection]") { const auto kPositionP1 = SteinerTree::DbuPoint{SteinerTree::dbu_t{1.0}, SteinerTree::dbu_t{2.0}}; const auto kPositionP2 = SteinerTree::DbuPoint{SteinerTree::dbu_t{100.0}, SteinerTree::dbu_t{200.0}}; auto tree = SteinerTree::create(); auto p1 = tree->add(kPositionP1); auto p2 = tree->add(kPositionP2); auto seg = tree->add(p1, p2); CHECK( tree->size(SteinerTree::Point{}) == 2 ); CHECK( tree->size(SteinerTree::Segment{}) == 1 ); auto checkUV = [](const SteinerTree & tree, const SteinerTree::Segment & seg, const SteinerTree::Point & point) -> bool{ return tree.u(seg) == point ^ tree.v(seg) == point; }; CHECK( checkUV(*tree, seg, p1) ); CHECK( checkUV(*tree, seg, p2) ); CHECK( Approx(tree->length(seg)) == ManhattanDistance(kPositionP1, kPositionP2) ); } TEST_CASE("Steiner Tree/add same point twice", "[interconnection]") { const auto kPosition = SteinerTree::DbuPoint{SteinerTree::dbu_t{1.0}, SteinerTree::dbu_t{2.0}}; auto tree = SteinerTree::create(); auto p1 = tree->add(kPosition); auto p2 = tree->add(kPosition); CHECK( p1 == p2 ); CHECK( tree->size(SteinerTree::Point{}) == 1 ); } TEST_CASE("Steiner Tree/geometry helper", "[interconnection]") { const auto kPositionP1 = SteinerTree::DbuPoint{SteinerTree::dbu_t{1.0}, SteinerTree::dbu_t{2.0}}; const auto kPositionP2 = SteinerTree::DbuPoint{SteinerTree::dbu_t{100.0}, SteinerTree::dbu_t{200.0}}; const auto kSegment = make<ophidian::geometry::Segment, ophidian::geometry::Point, SteinerTree::dbu_t>({kPositionP1, kPositionP2}); auto tree = SteinerTree::create(); auto segment = tree->add(tree->add(kPositionP1), tree->add(kPositionP2)); const auto geometrySegment = make_segment(*tree, segment); CHECK( Approx(geometrySegment.first.x()) == kSegment.first.x() ); CHECK( Approx(geometrySegment.first.y()) == kSegment.first.y() ); CHECK( Approx(geometrySegment.second.x()) == kSegment.second.x() ); CHECK( Approx(geometrySegment.second.y()) == kSegment.second.y() ); } TEST_CASE("Steiner Tree/steiner point iteration", "[interconnection]") { const auto kPositionP1 = SteinerTree::DbuPoint{SteinerTree::dbu_t{1.0}, SteinerTree::dbu_t{2.0}}; const auto kPositionP2 = SteinerTree::DbuPoint{SteinerTree::dbu_t{100.0}, SteinerTree::dbu_t{200.0}}; auto tree = SteinerTree::create(); auto p1 = SteinerTree::Point{}; auto p2 = SteinerTree::Point{}; auto segment = tree->add(p1 = tree->add(kPositionP1), p2 = tree->add(kPositionP2)); CHECK( std::count(tree->points().first, tree->points().second, p1 ) == 1 ); CHECK( std::count(tree->points().first, tree->points().second, p2 ) == 1 ); } TEST_CASE("Steiner Tree/steiner point segments iteration", "[interconnection]") { const auto kPositionP1 = SteinerTree::DbuPoint{SteinerTree::dbu_t{1.0}, SteinerTree::dbu_t{2.0}}; const auto kPositionP2 = SteinerTree::DbuPoint{SteinerTree::dbu_t{100.0}, SteinerTree::dbu_t{200.0}}; auto tree = SteinerTree::create(); auto p1 = SteinerTree::Point{}; auto p2 = SteinerTree::Point{}; auto segment = tree->add(p1 = tree->add(kPositionP1), p2 = tree->add(kPositionP2)); CHECK( std::count(tree->segments(p1).first, tree->segments(p1).second, segment) == 1 ); } namespace { class TreeWith4PointsFixture { public: static const SteinerTree::DbuPoint kPositionP1; static const SteinerTree::DbuPoint kPositionP2; static const SteinerTree::DbuPoint kPositionP3; static const SteinerTree::DbuPoint kPositionP4; TreeWith4PointsFixture() : tree_(SteinerTree::create()) { points_[0] = tree_->add(kPositionP1); points_[1] = tree_->add(kPositionP2); points_[2] = tree_->add(kPositionP3); points_[3] = tree_->add(kPositionP4); segments_[0] = tree_->add(points_[0], points_[1]); segments_[1] = tree_->add(points_[0], points_[2]); segments_[2] = tree_->add(points_[2], points_[3]); } virtual ~TreeWith4PointsFixture() { } protected: std::unique_ptr<SteinerTree> tree_; std::array<SteinerTree::Point, 4> points_; std::array<SteinerTree::Segment, 3> segments_; }; } const SteinerTree::DbuPoint TreeWith4PointsFixture::kPositionP1{SteinerTree::dbu_t{1.0}, SteinerTree::dbu_t{2.0}}; const SteinerTree::DbuPoint TreeWith4PointsFixture::kPositionP2{SteinerTree::dbu_t{100.0}, SteinerTree::dbu_t{200.0}}; const SteinerTree::DbuPoint TreeWith4PointsFixture::kPositionP3{SteinerTree::dbu_t{500.0}, SteinerTree::dbu_t{200.0}}; const SteinerTree::DbuPoint TreeWith4PointsFixture::kPositionP4{SteinerTree::dbu_t{200.0}, SteinerTree::dbu_t{200.0}}; TEST_CASE_METHOD(TreeWith4PointsFixture, "Steiner Tree/steiner point segments iteration2", "[interconnection]") { auto p1Segs = tree_->segments(points_[0]); auto p2Segs = tree_->segments(points_[1]); auto p3Segs = tree_->segments(points_[2]); auto p4Segs = tree_->segments(points_[3]); CHECK( std::count(p1Segs.first, p1Segs.second, segments_[0]) == 1 ); CHECK( std::count(p1Segs.first, p1Segs.second, segments_[1]) == 1 ); CHECK( std::count(p2Segs.first, p2Segs.second, segments_[0]) == 1 ); CHECK( std::count(p3Segs.first, p3Segs.second, segments_[1]) == 1 ); CHECK( std::count(p3Segs.first, p3Segs.second, segments_[2]) == 1 ); CHECK( std::count(p4Segs.first, p4Segs.second, segments_[2]) == 1 ); } TEST_CASE_METHOD(TreeWith4PointsFixture, "Steiner Tree/steiner segments iteration", "[interconnection]") { auto segments = tree_->segments(); CHECK( std::distance(segments.first, segments.second) == tree_->size(SteinerTree::Segment{}) ); CHECK( std::count(segments.first, segments.second, segments_[0]) == 1 ); CHECK( std::count(segments.first, segments.second, segments_[1]) == 1 ); CHECK( std::count(segments.first, segments.second, segments_[2]) == 1 ); } TEST_CASE_METHOD(TreeWith4PointsFixture, "Steiner Tree/iterator general", "[interconnection]") { SteinerTree::PointIterator it = tree_->points().first; const SteinerTree::PointIterator theEnd = tree_->points().second; for(;it != theEnd; ++it) { } auto it2 = std::next(it); CHECK(true); }
44.04321
135
0.685074
sheiny
a7b6a94f6dc93d5b65087423379d3e9f9d28e2bf
373
cpp
C++
package/test_vcpkg/example.cpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
284
2017-11-20T08:23:54.000Z
2022-03-30T12:52:00.000Z
package/conan/test_package/example.cpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
9
2018-02-14T08:21:41.000Z
2021-07-27T19:52:12.000Z
package/test_vcpkg/example.cpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
17
2018-03-10T00:01:36.000Z
2021-06-29T10:44:27.000Z
#include "selene/img/typed/Image.hpp" #include "selene/img/typed/ImageTypeAliases.hpp" #include "selene/img_ops/ImageConversions.hpp" #include <iostream> int main() { using namespace sln::literals; sln::Image_8u3 img0({20_px, 20_px}); const auto img1 = sln::convert_image<sln::PixelFormat::RGB, sln::PixelFormat::Y>(img0); std::cout << "Done.\n"; return 0; }
23.3125
89
0.710456
kmhofmann
a7b832630215f0c09ca62c3291a61f31e1897841
626
cpp
C++
result.cpp
Chiburu/ncl
4dcc061efaf623e21af4bb9eda309bd982ec2967
[ "MIT" ]
null
null
null
result.cpp
Chiburu/ncl
4dcc061efaf623e21af4bb9eda309bd982ec2967
[ "MIT" ]
null
null
null
result.cpp
Chiburu/ncl
4dcc061efaf623e21af4bb9eda309bd982ec2967
[ "MIT" ]
null
null
null
#include "result.h" Result::Result(STATUS status) : status_(status) , values_() {} STATUS Result::status() const { return status_; } STATUS Result::error() const { return ERR(status_); } bool Result::hasError() const { return error() != NOERROR; } bool Result::noError() const { return !hasError(); } bool Result::contains(const QString &key) const { return values_.contains(key); } QVariant Result::value(const QString &key) const { return values_.value(key); } void Result::insert(const QString &key, const QVariant &value) { values_.insert(key, value); }
14.904762
63
0.640575
Chiburu
a7b9d07fb7f2a3f1a17791b35f7ea88602dd4ff2
8,559
hpp
C++
cpp-projects/base/geometry/point3.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
null
null
null
cpp-projects/base/geometry/point3.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
null
null
null
cpp-projects/base/geometry/point3.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
1
2021-07-06T14:47:41.000Z
2021-07-06T14:47:41.000Z
/******************************************************************************* ** Toolbox-base ** ** MIT License ** ** Copyright (c) [2018] [Florian Lance] ** ** ** ** 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. ** ** ** ********************************************************************************/ #pragma once // local #include "geometry/point.hpp" namespace tool::geo { template<typename acc> struct Point3; template<typename acc> using Pt3 = Point3<acc>; using Pt3f = Pt3<float>; using Pt3d = Pt3<double>; template<typename acc> using Vec3 = Pt3<acc>; using Vec3f = Pt3<float>; using Vec3d = Pt3<double>; using Col3 = Pt3<std::uint8_t>; using Col3f= Pt3f; template<typename acc> using Normal3 = Vec3<acc>; template<typename acc> struct Point3 : public Point<acc,3>{ using Point<acc,3>::v; Point3() = default; Point3(const Point3& other) = default; Point3& operator=(const Point3& other) = default; Point3(Point3&& other) = default; Point3& operator=(Point3&& other) = default; constexpr explicit Point3(const Point<acc,3>& other){ v = other.v; } constexpr explicit Point3(Point<acc,3>&& other){ v = std::move(other.v); } constexpr explicit Point3(acc v) noexcept { this->v = {v,v,v}; } constexpr explicit Point3(acc x, acc y, acc z) noexcept { v = {x,y,z}; } constexpr Point3(std::initializer_list<acc> l) noexcept{ std::move(l.begin(), l.end(), std::begin(v)); } inline acc& x() noexcept {return v[0];} constexpr acc x() const noexcept {return v[0];} inline acc& y() noexcept {return v[1];} constexpr acc y() const noexcept {return v[1];} inline acc& z() noexcept {return v[2];} constexpr acc z() const noexcept {return v[2];} template <typename acc2> constexpr Point3<acc2> conv() const noexcept{ return {static_cast<acc2>(x()),static_cast<acc2>(y()),static_cast<acc2>(z())}; } constexpr Point3 operator-() const noexcept{ return invert(*this); } inline Point3 &operator+=(const Point3 &pt) noexcept{ (*this) = *this + pt; return *this; } inline Point3 &operator+=(acc v) noexcept{ (*this) = *this + v; return *this; } inline Point3 &operator-=(const Point3 &pt) noexcept{ (*this) = *this - pt; return *this; } inline Point3 &operator-=(acc v) noexcept{ (*this) = *this - v; return *this; } inline Point3 &operator*=(const Point3 &ptl) noexcept{ (*this) = *this * ptl; return *this; } inline Point3 &operator*=(acc v) noexcept{ (*this) = *this * v; return *this; } inline Point3 &operator/=(const Point3 &ptl){ (*this) = *this / ptl; return *this; } inline Point3 &operator/=(acc v) { (*this) = *this / v; return *this; } }; // functions template <typename acc> constexpr Pt3<acc> add(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ return {l.x()+r.x(), l.y()+r.y(),l.z()+r.z()}; } template <typename acc> constexpr Pt3<acc> add(const Pt3<acc> &p, acc value) noexcept{ return {p.x() + value, p.y() + value, p.z() + value}; } template <typename acc> constexpr Pt3<acc> add(acc value, const Pt3<acc> &p) noexcept{ return add(p,value); } template <typename acc> constexpr Pt3<acc> substract(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ return {l.x()-r.x(), l.y()-r.y(), l.z()-r.z()}; } template <typename acc> constexpr Pt3<acc> substract(const Pt3<acc> &p, acc value) noexcept{ return {p.x() - value, p.y() - value, p.z() - value}; } template <typename acc> constexpr Pt3<acc> multiply(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ return {l.x()*r.x(), l.y()*r.y(), l.z()*r.z()}; } template <typename acc> constexpr Pt3<acc> multiply(const Pt3<acc> &p, acc value) noexcept{ return {p.x() * value, p.y() * value, p.z() * value}; } template <typename acc> constexpr Pt3<acc> divide(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ const acc zero{0}; if(r.x() > zero && r.y() > zero && r.z() > zero){ return {l.x()/r.x(), l.y()/r.y(), l.z()/r.z()}; } return l; // do nothing } template <typename acc> constexpr Pt3<acc> divide(const Pt3<acc> &p, acc value) noexcept{ if(value > acc{0}){ return {p.x() / value, p.y() / value, p.z() / value}; } return p; // do nothing } template <typename acc> constexpr acc sum(const Vec3<acc> &vec) noexcept{ return vec.x() + vec.y() + vec.z(); } template <typename acc> constexpr acc dot(const Vec3<acc> &l, const Vec3<acc> &r) noexcept { return sum(multiply(l,r)); } template<typename acc> constexpr Pt3<acc> cross(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ return { l.y() * r.z() - l.z() * r.y(), l.z() * r.x() - l.x() * r.z(), l.x() * r.y() - l.y() * r.x() }; // __m128 const set0 = _mm_set_ps(0.0f, a.z, a.y, a.x); // __m128 const set1 = _mm_set_ps(0.0f, b.z, b.y, b.x); // __m128 const xpd0 = glm_vec4_cross(set0, set1); // vec<4, float, Q> Result; // Result.data = xpd0; // return vec<3, float, Q>(Result); } template<typename acc> constexpr Pt3<acc> invert(const Vec3<acc> &vec){ return multiply(vec,acc{-1}); } template <typename acc> inline Vec3<acc> normalize(const Vec3<acc> &vec){ return divide(vec, norm(vec)); } template <typename acc> constexpr acc square_norm(const Vec3<acc> &vec) noexcept { return dot(vec,vec); } template <typename acc> inline acc norm(const Pt3<acc> &p) noexcept { return sqrt(square_norm(p)); } // operators template <typename acc> constexpr Pt3<acc> operator+(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ return add(l,r); } template <typename acc> constexpr Pt3<acc> operator-(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ return substract(l,r); } template <typename acc> constexpr Pt3<acc> operator*(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ return multiply(l,r); } template <typename acc> constexpr Pt3<acc> operator/(const Pt3<acc> &l, const Pt3<acc> &r) noexcept{ return divide(l,r); } template <typename acc> constexpr Pt3<acc> operator+(const Pt3<acc> &p, acc value) noexcept{ return add(p, value); } template <typename acc> constexpr Pt3<acc> operator+(acc value, const Pt3<acc> &p) noexcept{ return add(p, value); } template <typename acc> constexpr Pt3<acc> operator-(const Pt3<acc> &p, acc value) noexcept{ return substract(p, value); } template <typename acc> constexpr Pt3<acc> operator*(const Pt3<acc> &p, acc value) noexcept{ return multiply(p, value); } template <typename acc> constexpr Pt3<acc> operator*(acc value, const Pt3<acc> &p) noexcept{ return multiply(p, value); } template <typename acc> constexpr Pt3<acc> operator/(const Pt3<acc> &p, acc value) noexcept{ return divide(p, value); } };
28.915541
86
0.577053
FlorianLance
a7c1ac8a2cdfb1dc66af9cdb4b14b51fdcd1b638
958
cpp
C++
src/fsm-editor/nodes/condnode.cpp
AsuMagic/centauri-fsm-editor
0830969dd0c1548870ab71efa8b36a77fc40dbd4
[ "MIT" ]
null
null
null
src/fsm-editor/nodes/condnode.cpp
AsuMagic/centauri-fsm-editor
0830969dd0c1548870ab71efa8b36a77fc40dbd4
[ "MIT" ]
null
null
null
src/fsm-editor/nodes/condnode.cpp
AsuMagic/centauri-fsm-editor
0830969dd0c1548870ab71efa8b36a77fc40dbd4
[ "MIT" ]
null
null
null
#include "condnode.hpp" #include "../editor.hpp" #include "../visitors/predvisitor.hpp" #include "../visitors/noderenderer.hpp" namespace fsme { namespace nodes { CondNode::CondNode(FsmEditor& editor, ax::NodeEditor::NodeId id) : Node(editor, id) { resize_pins(m_inputs, 1); set_output_count(1); } void CondNode::set_output_count(std::size_t i) { resize_pins(m_outputs, std::max(i, std::size_t(1))); } void CondNode::erase_output_pin(std::size_t i) { erase_pin(m_outputs, m_outputs.begin() + i); set_output_count(m_outputs.size()); // force to 1 minimum } void CondNode::reset_output_pins() { resize_pins(m_outputs, 0); set_output_count(0); } widgets::BoolExpressionInput& CondNode::get_expression(ed::PinId output) { const auto it = m_conditions.find(output); if (it == m_conditions.end()) { const auto p = m_conditions.emplace(std::make_pair(output, editor().new_unique_id())); return p.first->second; } return it->second; } } }
18.784314
88
0.718163
AsuMagic
a7c387469c9c704406af01f88dafef2b4b710ac2
2,265
cpp
C++
OmegaUp/riceHub.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
OmegaUp/riceHub.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
OmegaUp/riceHub.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
//hacemos busqueda binaria sobre la cantidad maxima de camiones // para probar si puedes hacer que k camiones te mande, solo hay que hacer un reccorido sobre el arreglo // sobre cada posible k-tupla de campos consecutivos // debes demostrar que el mejor lugar para tomar una k tupla es entre los dos campos centrales o en el campo //central esto lo puedes hacer con una desigualdad, viendo lo que aporta por parejas los más lejanos de cada //lado si tienes dos, cualquier lugar entre ellos conviene // si tienes 4, lo que te aportan el mas a la izq y el mas a la der es minimo la distancia entre ellos // y si estas fuera de ellos la distancia entre ellos mas otra cosa // entonces lo pones entre ellos, y luego te fijas en cuanto aportan el segundo mas a la derecha // y el segundo mas a la izquierda en conjunto, igual es minimo la distancia entre ellos // con esos dos datos ya tenemos una solucion O(r log(r)) y es suficiente #include <iostream> #include <algorithm> using namespace std; typedef int64_t ll; const int maxR = (int)1e5; int campos[maxR], r; ll b; //funcion que calcula si se puede que k campos te manden arroz bool sePuede(int k){ int pt, izq, der; ll costoDer = 0, costoIzq = 0, mini; pt = (k-1)/2; izq = pt; der = (k-1) - pt; for(int i = 0; i < pt; ++i) costoIzq += campos[pt] - campos[i]; for(int i = pt+1; i < k; ++i) costoDer += campos[i] - campos[pt]; mini = costoDer + costoIzq; for(; pt + der < r-1; ++pt){ costoIzq += (izq+1)*(campos[pt+1]-campos[pt]); costoIzq -= campos[pt+1] - campos[pt-izq]; costoDer -= der*(campos[pt+1]-campos[pt]); costoDer += campos[pt+der+1] - campos[pt+1]; if(costoDer + costoIzq < mini) mini = costoDer + costoIzq; } return mini <= b; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int aux; cin>>r>>aux>>b; for(int i = 0; i < r; ++i) cin>>campos[i]; int inf = 1, sup = r, mitad; //busqueda binaria sobre el max de camiones que t epueden mandar while(inf != sup){ mitad = (inf + sup)/2 +1; if(sePuede(mitad)) inf = mitad; else sup = mitad - 1; } cout<<inf<<'\n'; }
31.458333
109
0.624283
CaDe27
a7c3f6afeca5cf32eda70608ea52da0e13de643f
16,488
cpp
C++
test/unit/alphabet/composite/composite_integration_test.cpp
SGSSGene/seqan3
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/alphabet/composite/composite_integration_test.cpp
SGSSGene/seqan3
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/alphabet/composite/composite_integration_test.cpp
SGSSGene/seqan3
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <gtest/gtest.h> #include <seqan3/alphabet/all.hpp> using namespace seqan3; // Some haessllihckeiten-tests TEST(composite, custom_constructors) { qualified<dna4, phred42> t11{'C'_dna4}; qualified<dna4, phred42> t12{'C'_rna4}; qualified<dna4, phred42> t13{phred42{3}}; qualified<dna4, phred42> t14{phred63{3}}; qualified<aa27, phred63> t20{'K'_aa27, phred63{}}; qualified<aa27, phred63> t21{'K'_aa27}; qualified<aa27, phred63> t22{phred63{3}}; qualified<aa27, phred63> t23{phred42{3}}; qualified<gapped<dna4>, phred42> t31{'C'_dna4}; qualified<gapped<dna4>, phred42> t32{'C'_rna4}; qualified<gapped<dna4>, phred42> t33{phred42{3}}; qualified<gapped<dna4>, phred42> t34{gap{}}; qualified<gapped<dna4>, phred42> t35{gapped<dna4>('C'_dna4)}; qualified<gapped<dna4>, phred42> t36{gapped<dna4>(gap{})}; qualified<gapped<dna4>, phred42> t37{gap{}, phred42{3}}; gapped<qualified<dna4, phred42>> t41{'C'_dna4}; gapped<qualified<dna4, phred42>> t42{'C'_rna4}; gapped<qualified<dna4, phred42>> t43{phred42{3}}; gapped<qualified<dna4, phred42>> t44{gap{}}; gapped<qualified<dna4, phred42>> t45{qualified<dna4, phred42>{'C'_dna4, phred42{0}}}; qualified<qualified<gapped<dna4>, phred42>, phred42> t51{'C'_dna4}; qualified<qualified<gapped<dna4>, phred42>, phred42> t52{'C'_rna4}; qualified<qualified<gapped<dna4>, phred42>, phred42> t53{phred42{3}}; qualified<qualified<gapped<dna4>, phred42>, phred42> t54{gap{}}; qualified<qualified<gapped<dna4>, phred42>, phred42> t55{gapped<dna4>('C'_dna4)}; qualified<qualified<gapped<dna4>, phred42>, phred42> t56{gapped<dna4>(gap{})}; gapped<alphabet_variant<dna4, phred42>> t61{'C'_dna4}; gapped<alphabet_variant<dna4, phred42>> t62{'C'_rna4}; gapped<alphabet_variant<dna4, phred42>> t63{phred42{3}}; gapped<alphabet_variant<dna4, phred42>> t64{gap{}}; gapped<alphabet_variant<dna4, phred42>> t65{qualified<dna4, phred42>{'C'_dna4, phred42{0}}}; EXPECT_EQ(t11, t12); EXPECT_EQ(t13, t14); EXPECT_EQ(t20, t21); EXPECT_EQ(t22, t23); EXPECT_EQ(t31, t32); EXPECT_NE(t31, t33); EXPECT_NE(t31, t34); EXPECT_EQ(t31, t35); EXPECT_EQ(t34, t36); EXPECT_EQ(t41, t42); EXPECT_NE(t41, t43); EXPECT_NE(t41, t44); EXPECT_EQ(t41, t45); EXPECT_EQ(t51, t52); EXPECT_NE(t51, t53); EXPECT_NE(t51, t54); EXPECT_EQ(t51, t55); EXPECT_EQ(t54, t56); EXPECT_EQ(t61, t62); EXPECT_NE(t61, t63); EXPECT_NE(t61, t64); EXPECT_EQ(t61, t65); } TEST(composite_constexpr, custom_constructor) { constexpr qualified<dna4, phred42> t11{'C'_dna4}; constexpr qualified<dna4, phred42> t12{'C'_rna4}; constexpr qualified<dna4, phred42> t13{phred42{3}}; constexpr qualified<dna4, phred42> t14{phred63{3}}; constexpr qualified<aa27, phred63> t21{'K'_aa27}; constexpr qualified<aa27, phred63> t22{phred63{3}}; constexpr qualified<aa27, phred63> t23{phred42{3}}; constexpr qualified<gapped<dna4>, phred42> t31{'C'_dna4}; constexpr qualified<gapped<dna4>, phred42> t32{'C'_rna4}; constexpr qualified<gapped<dna4>, phred42> t33{phred42{3}}; constexpr qualified<gapped<dna4>, phred42> t34{gap{}}; constexpr qualified<gapped<dna4>, phred42> t35{gapped<dna4>('C'_dna4)}; constexpr qualified<gapped<dna4>, phred42> t36{gapped<dna4>(gap{})}; constexpr qualified<gapped<dna4>, phred42> t37{gap{}, phred42{3}}; constexpr gapped<qualified<dna4, phred42>> t41{'C'_dna4}; constexpr gapped<qualified<dna4, phred42>> t42{'C'_rna4}; constexpr gapped<qualified<dna4, phred42>> t43{phred42{3}}; constexpr gapped<qualified<dna4, phred42>> t44{gap{}}; constexpr gapped<qualified<dna4, phred42>> t45{qualified<dna4, phred42>{'C'_dna4, phred42{0}}}; constexpr qualified<qualified<gapped<dna4>, phred42>, phred42> t51{'C'_dna4}; constexpr qualified<qualified<gapped<dna4>, phred42>, phred42> t52{'C'_rna4}; constexpr qualified<qualified<gapped<dna4>, phred42>, phred42> t53{phred42{3}}; constexpr qualified<qualified<gapped<dna4>, phred42>, phred42> t54{gap{}}; constexpr qualified<qualified<gapped<dna4>, phred42>, phred42> t55{gapped<dna4>('C'_dna4)}; constexpr qualified<qualified<gapped<dna4>, phred42>, phred42> t56{gapped<dna4>(gap{})}; constexpr gapped<alphabet_variant<dna4, phred42>> t61{'C'_dna4}; constexpr gapped<alphabet_variant<dna4, phred42>> t62{'C'_rna4}; constexpr gapped<alphabet_variant<dna4, phred42>> t63{phred42{3}}; constexpr gapped<alphabet_variant<dna4, phred42>> t64{gap{}}; constexpr gapped<alphabet_variant<dna4, phred42>> t65{qualified<dna4, phred42>{'C'_dna4, phred42{0}}}; } TEST(composite, custom_assignment) { qualified<dna4, phred42> t11{}; qualified<dna4, phred42> t12{'C'_dna4}; qualified<dna4, phred42> t13{'C'_dna4, phred42{3}}; t11 = 'C'_dna4; EXPECT_EQ(t11, t12); t11 = 'C'_rna4; EXPECT_EQ(t11, t12); t11 = phred42{3}; EXPECT_EQ(t11, t13); // t11 = phred63{3}; // does not work because of explicit conversion qualified<aa27, phred63> t20{'K'_aa27, phred63{}}; qualified<aa27, phred63> t21{}; qualified<aa27, phred63> t22{'K'_aa27, phred63{3}}; t21 = 'K'_aa27; EXPECT_EQ(t20, t21); t21 = phred63{3}; EXPECT_EQ(t21, t22); qualified<gapped<dna4>, phred42> t31{}; qualified<gapped<dna4>, phred42> t32{'C'_dna4}; qualified<gapped<dna4>, phred42> t33{'C'_dna4, phred42{3}}; qualified<gapped<dna4>, phred42> t34{gap{}, phred42{3}}; t31 = 'C'_dna4; EXPECT_EQ(t31, t32); t31 = 'C'_rna4; EXPECT_EQ(t31, t32); t31 = phred42{3}; EXPECT_EQ(t31, t33); t31 = gap{}; EXPECT_EQ(t31, t34); t31 = gapped<dna4>('C'_dna4); EXPECT_EQ(t31, t33); t31 = gapped<dna4>(gap{}); EXPECT_EQ(t31, t34); gapped<qualified<dna4, phred42>> t41{}; gapped<qualified<dna4, phred42>> t42{'C'_dna4}; gapped<qualified<dna4, phred42>> t43{qualified<dna4, phred42>{'C'_dna4, phred42{3}}}; gapped<qualified<dna4, phred42>> t44{gap{}}; gapped<qualified<dna4, phred42>> t45{qualified<dna4, phred42>{'C'_dna4, phred42{0}}}; t41 = 'C'_dna4; EXPECT_EQ(t41, t42); t41 = 'C'_rna4; EXPECT_EQ(t41, t42); t41 = phred42{3}; // EXPECT_EQ(t41, t43); should work intuitively but does not because on assignment the qualified object is defaulted t41 = gap{}; EXPECT_EQ(t41, t44); t41 = qualified<dna4, phred42>{'C'_dna4, phred42{0}}; EXPECT_EQ(t41, t45); qualified<qualified<gapped<dna4>, phred42>, phred42> t51{}; qualified<qualified<gapped<dna4>, phred42>, phred42> t52{'C'_dna4}; qualified<qualified<gapped<dna4>, phred42>, phred42> t53{qualified<gapped<dna4>, phred42>{'C'_dna4, phred42{0}}, phred42{3}}; qualified<qualified<gapped<dna4>, phred42>, phred42> t54{qualified<gapped<dna4>, phred42>{gap{}, phred42{0}}, phred42{3}}; t51 = 'C'_dna4; EXPECT_EQ(t51, t52); t51 = 'C'_rna4; EXPECT_EQ(t51, t52); t51 = phred42{3}; EXPECT_EQ(t51, t53); t51 = gap{}; EXPECT_EQ(t51, t54); t51 = gapped<dna4>('C'_dna4); EXPECT_EQ(t51, t53); t51 = gapped<dna4>(gap{}); EXPECT_EQ(t51, t54); gapped<alphabet_variant<dna4, phred42>> t61{}; gapped<alphabet_variant<dna4, phred42>> t62{'C'_dna4}; gapped<alphabet_variant<dna4, phred42>> t63{phred42{3}}; gapped<alphabet_variant<dna4, phred42>> t64{gap{}}; gapped<alphabet_variant<dna4, phred42>> t65{qualified<dna4, phred42>{'C'_dna4, phred42{0}}}; t61 = 'C'_dna4; EXPECT_EQ(t61, t62); t61 = 'C'_rna4; EXPECT_EQ(t61, t62); t61 = phred42{3}; EXPECT_EQ(t61, t63); t61 = gap{}; EXPECT_EQ(t61, t64); t61 = qualified<dna4, phred42>{'C'_dna4, phred42{0}}; EXPECT_EQ(t61, t65); } constexpr bool do_assignment() { qualified<dna4, phred42> t11{}; t11 = 'C'_dna4; t11 = 'C'_rna4; t11 = phred42{3}; // t11 = phred63{3}; // does not work because of explicit conversion qualified<aa27, phred63> t21{}; t21 = 'K'_aa27; t21 = phred63{3}; qualified<gapped<dna4>, phred42> t31{}; t31 = 'C'_dna4; t31 = 'C'_rna4; t31 = phred42{3}; t31 = gap{}; t31 = gapped<dna4>('C'_dna4); t31 = gapped<dna4>(gap{}); gapped<qualified<dna4, phred42>> t41{}; t41 = 'C'_dna4; t41 = 'C'_rna4; t41 = phred42{3}; t41 = gap{}; t41 = qualified<dna4, phred42>{'C'_dna4, phred42{0}}; qualified<qualified<gapped<dna4>, phred42>, phred42> t51{}; t51 = 'C'_dna4; t51 = 'C'_rna4; t51 = phred42{3}; t51 = gap{}; t51 = gapped<dna4>('C'_dna4); t51 = gapped<dna4>(gap{}); gapped<alphabet_variant<dna4, phred42>> t61{}; t61 = 'C'_rna4; t61 = phred42{3}; t61 = gap{}; t61 = qualified<dna4, phred42>{'C'_dna4, phred42{0}}; return true; } TEST(composite_constexpr, custom_assignment) { [[maybe_unused]] constexpr bool foo = do_assignment(); } TEST(composite, custom_comparison) { /* Tests marked with "// *" would not be possible if all single argument constructors of alphabet_variant * are made explicit */ qualified<dna4, phred42> t11{'C'_dna4, phred42{3}}; EXPECT_EQ(t11, 'C'_dna4); EXPECT_EQ(t11, 'C'_rna4); EXPECT_EQ(t11, phred42{3}); EXPECT_LT(t11, 'G'_dna4); EXPECT_LT(t11, 'G'_rna4); EXPECT_LT(t11, phred42{4}); EXPECT_EQ('C'_dna4, t11); EXPECT_EQ('C'_rna4, t11); EXPECT_EQ(phred42{3}, t11); EXPECT_LT('A'_dna4, t11); EXPECT_LT('A'_rna4, t11); EXPECT_LT(phred42{2}, t11); qualified<aa27, phred63> t21{'K'_aa27, phred63{3}}; EXPECT_EQ(t21, 'K'_aa27); EXPECT_EQ(t21, phred63{3}); EXPECT_LT(t21, 'L'_aa27); EXPECT_LT(t21, phred63{4}); EXPECT_EQ('K'_aa27, t21); EXPECT_EQ(phred63{3}, t21); EXPECT_LT('C'_aa27, t21); EXPECT_LT(phred63{2}, t21); qualified<gapped<dna4>, phred42> t31{'C'_dna4, phred42{3}}; EXPECT_EQ(t31, 'C'_dna4); EXPECT_EQ(t31, 'C'_rna4); EXPECT_EQ(t31, phred42{3}); EXPECT_NE(t31, gap{}); EXPECT_EQ(t31, gapped<dna4>('C'_dna4)); EXPECT_LT(t31, 'G'_dna4); // * EXPECT_LT(t31, 'G'_rna4); // * EXPECT_LT(t31, phred42{4}); EXPECT_LT(t31, gap{}); // * EXPECT_LT(t31, gapped<dna4>('G'_dna4)); EXPECT_EQ('C'_dna4, t31); EXPECT_EQ('C'_rna4, t31); EXPECT_EQ(phred42{3}, t31); EXPECT_NE(gap{}, t31); EXPECT_EQ(gapped<dna4>('C'_dna4), t31); EXPECT_LT('A'_dna4, t31); // * EXPECT_LT('A'_rna4, t31); // * EXPECT_LT(phred42{2}, t31); EXPECT_GT(gap{}, t31); // * EXPECT_LT(gapped<dna4>('A'_dna4), t31); gapped<qualified<dna4, phred42>> t41{qualified<dna4, phred42>{'C'_dna4, phred42{3}}}; EXPECT_EQ(t41, 'C'_dna4); EXPECT_EQ(t41, 'C'_rna4); EXPECT_EQ(t41, phred42{3}); EXPECT_NE(t41, gap{}); EXPECT_EQ(t41, (qualified<dna4, phred42>{'C'_dna4, phred42{3}})); EXPECT_EQ(t41, (gapped<qualified<dna4, phred42>>{qualified<dna4, phred42>{'C'_dna4, phred42{3}}})); // EXPECT_LT(t41, 'G'_dna4); // not supposed to work // EXPECT_LT(t41, 'G'_rna4); // not supposed to work // EXPECT_LT(t41, phred42{4}); // would never be LT, because dna4 part of tuple defaulted to 'A' on RHS EXPECT_LT(t41, gap{}); // * EXPECT_LT(t41, (qualified<dna4, phred42>{'G'_dna4, phred42{2}})); // * EXPECT_LT(t41, (gapped<qualified<dna4, phred42>>{qualified<dna4, phred42>{'G'_dna4, phred42{2}}})); EXPECT_EQ('C'_dna4, t41); EXPECT_EQ('C'_rna4, t41); EXPECT_EQ(phred42{3}, t41); EXPECT_EQ((qualified<dna4, phred42>{'C'_dna4, phred42{3}}), t41); EXPECT_NE(gap{}, t41); // EXPECT_LT('A'_dna4, t41); // not supposed to work // EXPECT_LT('A'_rna4, t41); // not supposed to work // EXPECT_LT(phred42{2}, t41); // not supposed to work EXPECT_LT((qualified<dna4, phred42>{'A'_dna4, phred42{2}}), t41); // * EXPECT_GT(gap{}, t41); // * qualified<qualified<gapped<dna4>, phred42>, phred42> t51{qualified<gapped<dna4>, phred42>{'C'_dna4, phred42{3}}}; EXPECT_EQ(t51, 'C'_dna4); EXPECT_EQ(t51, 'C'_rna4); EXPECT_NE(t51, gap{}); EXPECT_EQ(t51, gapped<dna4>('C'_dna4)); EXPECT_EQ(t51, phred42{0}); // "outer" phred element EXPECT_EQ(t51, (qualified<gapped<dna4>, phred42>{'C'_dna4, phred42{3}})); // EXPECT_LT(t51, 'G'_dna4); // not supposed to work // EXPECT_LT(t51, 'G'_rna4); // not supposed to work // EXPECT_LT(t51, gap{}); // not supposed to work // EXPECT_LT(t51, gapped<dna4>('G'_dna4)); // not supposed to work EXPECT_LT(t51, phred42{1}); EXPECT_LT(t51, (qualified<gapped<dna4>, phred42>{'C'_dna4, phred42{4}})); EXPECT_EQ('C'_dna4, t51); EXPECT_EQ('C'_rna4, t51); EXPECT_NE(gap{}, t51); EXPECT_EQ(gapped<dna4>('C'_dna4), t51); EXPECT_EQ(phred42{0}, t51); EXPECT_EQ((qualified<gapped<dna4>, phred42>{'C'_dna4, phred42{3}}), t51); // EXPECT_LT('A'_dna4, t51); // not supposed to work // EXPECT_LT('A'_rna4, t51); // not supposed to work // EXPECT_GT(gap{}, t51); // not supposed to work // EXPECT_LT(gapped<dna4>('A'_dna4), t51); // not supposed to work EXPECT_GT(phred42{1}, t51); EXPECT_GT((qualified<gapped<dna4>, phred42>{'C'_dna4, phred42{4}}), t51); gapped<alphabet_variant<dna4, phred42>> t61{'C'_rna4}; EXPECT_EQ(t61, 'C'_rna4); EXPECT_EQ(t61, 'C'_dna4); EXPECT_NE(t61, gap{}); EXPECT_NE(t61, phred42{0}); EXPECT_LT(t61, 'G'_rna4); // * EXPECT_LT(t61, 'G'_dna4); // * EXPECT_LT(t61, gap{}); // * EXPECT_LT(t61, phred42{1}); // * EXPECT_EQ('C'_rna4, t61); EXPECT_EQ('C'_dna4, t61); EXPECT_NE(gap{}, t61); EXPECT_NE(phred42{0}, t61); EXPECT_LT('A'_rna4, t61); // * EXPECT_LT('A'_dna4, t61); // * EXPECT_GT(gap{}, t61); // * EXPECT_GT(phred42{0}, t61); // * } TEST(composite, get_) { qualified<qualified<gapped<dna4>, phred42>, phred42> t51{qualified<gapped<dna4>, phred42>{'C'_dna4, phred42{3}}}; EXPECT_EQ(get<0>(t51), 'C'_dna4); EXPECT_EQ(get<0>(get<0>(t51)), 'C'_dna4); EXPECT_EQ(get<0>(t51), 'C'_rna4); EXPECT_EQ(get<0>(get<0>(t51)), 'C'_rna4); EXPECT_NE(get<0>(t51), gap{}); EXPECT_NE(get<0>(get<0>(t51)), gap{}); EXPECT_EQ(get<0>(t51), gapped<dna4>('C'_dna4)); EXPECT_EQ(get<0>(get<0>(t51)), gapped<dna4>('C'_dna4)); EXPECT_NE(get<0>(t51), phred42{0}); }
40.811881
129
0.576237
SGSSGene
a7c433984ede093460d064b29f7f8246ecc5e21d
623
cpp
C++
src/components/animatedtextureddrawable.cpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
src/components/animatedtextureddrawable.cpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
src/components/animatedtextureddrawable.cpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
#include "drawingcomponents.hpp" namespace Sys { AnimatedTexturedDrawable::AnimatedTexturedDrawable(entityid_t myEntity, double argx, double argy, double argxoffset, double argyoffset, int arglength, double argwidth, double argheight) : TexturedDrawable(myEntity, argx, argy, argxoffset, argyoffset, 1), length(arglength), index(0), width(argwidth), height(argheight) { AnimatedTexturedDrawables.add(this); } AnimatedTexturedDrawable::~AnimatedTexturedDrawable() { if(position->entityID == entityID) delete position; AnimatedTexturedDrawables.remove(this); } }
36.647059
189
0.730337
wareya
a7c5f2732105dc69e1c2f5f19f7c6b8b4439f0a1
1,404
cpp
C++
Implementations/12 - Graphs Hard (4)/12.4 - Tarjan BCC.cpp
Senpat/USACO
7f65e083e70c10b43224c6e1acbab79af249b942
[ "MIT" ]
null
null
null
Implementations/12 - Graphs Hard (4)/12.4 - Tarjan BCC.cpp
Senpat/USACO
7f65e083e70c10b43224c6e1acbab79af249b942
[ "MIT" ]
null
null
null
Implementations/12 - Graphs Hard (4)/12.4 - Tarjan BCC.cpp
Senpat/USACO
7f65e083e70c10b43224c6e1acbab79af249b942
[ "MIT" ]
null
null
null
/** * Description: * Source: GeeksForGeeks (corrected) * Verification: USACO December 2017, Push a Box * https://pastebin.com/yUWuzTH8 */ template<int SZ> struct BCC { int N; vi adj[SZ]; vector<vpi> fin; void addEdge(int u, int v) { adj[u].pb(v), adj[v].pb(u); } int ti = 0, disc[SZ], low[SZ], comp[SZ], par[SZ]; vpi st; void BCCutil(int u, bool root = 0) { disc[u] = low[u] = ti++; int child = 0; for (int i: adj[u]) if (i != par[u]) if (disc[i] == -1) { child ++; par[i] = u; st.pb({u,i}); BCCutil(i); low[u] = min(low[u],low[i]); if ((root && child > 1) || (!root && disc[u] <= low[i])) { // articulation point! vpi tmp; while (st.back() != mp(u,i)) tmp.pb(st.back()), st.pop_back(); tmp.pb(st.back()), st.pop_back(); fin.pb(tmp); } } else if (disc[i] < disc[u]) { low[u] = min(low[u],disc[i]); st.pb({u,i}); } } void bcc(int _N) { N = _N; FOR(i,1,N+1) par[i] = disc[i] = low[i] = -1; FOR(i,1,N+1) if (disc[i] == -1) { BCCutil(i,1); if (sz(st)) fin.pb(st); st.clear(); } } };
27.529412
97
0.39245
Senpat
a7c8de8d3bb76bf649204a5b379d39a7f971de2b
9,479
hpp
C++
include/boost/simd/arch/common/simd/function/ldexp.hpp
nickporubsky/boost-simd-clone
b81dfcd9d6524a131ea714f1eebb5bb75adddcc7
[ "BSL-1.0" ]
5
2018-02-20T11:21:12.000Z
2019-11-12T13:45:09.000Z
include/boost/simd/arch/common/simd/function/ldexp.hpp
nickporubsky/boost-simd-clone
b81dfcd9d6524a131ea714f1eebb5bb75adddcc7
[ "BSL-1.0" ]
null
null
null
include/boost/simd/arch/common/simd/function/ldexp.hpp
nickporubsky/boost-simd-clone
b81dfcd9d6524a131ea714f1eebb5bb75adddcc7
[ "BSL-1.0" ]
2
2017-11-17T15:30:36.000Z
2018-03-01T02:06:25.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LDEXP_HPP_INCLUDED #define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LDEXP_HPP_INCLUDED #include <boost/simd/detail/overload.hpp> #include <boost/simd/meta/hierarchy/simd.hpp> #include <boost/simd/meta/as_logical.hpp> #include <boost/simd/config.hpp> #include <boost/simd/detail/constant/limitexponent.hpp> #include <boost/simd/detail/constant/maxexponent.hpp> #include <boost/simd/constant/nbmantissabits.hpp> #include <boost/simd/constant/one.hpp> #include <boost/simd/function/bitwise_cast.hpp> #include <boost/simd/function/is_equal.hpp> #include <boost/simd/function/rshl.hpp> #include <boost/simd/function/expocvt.hpp> #include <boost/simd/function/if_plus.hpp> #include <boost/simd/function/if_minus.hpp> #include <boost/simd/function/is_flint.hpp> #include <boost/simd/function/shift_left.hpp> #include <boost/simd/function/toint.hpp> #include <boost/simd/detail/dispatch/meta/as_integer.hpp> #ifndef BOOST_SIMD_NO_DENORMALS #include <boost/simd/detail/constant/minexponent.hpp> #include <boost/simd/constant/smallestposval.hpp> #include <boost/simd/function/if_else.hpp> #include <boost/simd/function/is_less.hpp> #include <boost/simd/function/if_minus.hpp> #endif namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; // a0 a1 integers BOOST_DISPATCH_OVERLOAD(ldexp_ , (typename A0, typename A1, typename X) , bd::cpu_ , bs::pack_<bd::integer_<A0>, X> , bs::pack_<bd::integer_<A1>, X> ) { BOOST_FORCEINLINE A0 operator()( const A0& a0, const A1& a1) const BOOST_NOEXCEPT { return rshl(a0, a1); } }; BOOST_DISPATCH_OVERLOAD(ldexp_ , (typename A0, typename A1, typename X) , bd::cpu_ , bs::pack_<bd::integer_<A0>, X> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator()( const A0& a0, A1 a1) const BOOST_NOEXCEPT { using sA0 = bd::scalar_of_t<A0>; using iA0 = bd::as_integer_t<sA0>; return rshl(a0, iA0(a1)); } }; // a0 floating BOOST_DISPATCH_OVERLOAD(ldexp_ , (typename A0, typename A1, typename X, typename Y) , bd::cpu_ , bs::pedantic_tag , bs::pack_<bd::floating_<A0>, X> , bs::pack_<bd::integer_<A1>, Y> ) { BOOST_FORCEINLINE A0 operator()(const pedantic_tag & , const A0& a0, const A1& a1) const BOOST_NOEXCEPT { using iA0 = bd::as_integer_t<A0>; using sA0 = bd::scalar_of_t<A0>; iA0 e = a1; A0 f = One<A0>(); #ifndef BOOST_SIMD_NO_DENORMALS auto denormal = is_less(e, Minexponent<A0>()); e = if_minus(denormal, e, Minexponent<A0>()); f = if_else(denormal, Smallestposval<A0>(), One<A0>()); #endif auto test = is_equal(e, Limitexponent<A0>()); f = if_plus(test, f, One<A0>()); e = if_minus(test, e, One<iA0>()); e += Maxexponent<A0>(); e = shift_left(e, Nbmantissabits<sA0>()); return a0*bitwise_cast<A0>(e)*f; } }; BOOST_DISPATCH_OVERLOAD(ldexp_ , (typename A0, typename A1, typename X) , bd::cpu_ , bs::pedantic_tag , bs::pack_<bd::floating_<A0>, X> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator()(const pedantic_tag & , const A0& a0, const A1& a1) const BOOST_NOEXCEPT { using iA0 = bd::as_integer_t<A0>; using sA0 = bd::scalar_of_t<A0>; using siA0 = bd::scalar_of_t<iA0>; siA0 e = a1; A0 f = One<A0>(); #ifndef BOOST_SIMD_NO_DENORMALS auto denormal = is_less(e, Minexponent<siA0>()); e = if_minus(denormal, e, Minexponent<siA0>()); f = if_else(denormal, Smallestposval<A0>(), One<A0>()); #endif if (is_equal(e, Limitexponent<siA0>())) { f+= One<sA0>(); e-= One<siA0>(); } e += Maxexponent<sA0>(); e = shift_left(e, Nbmantissabits<sA0>()); return a0*(bitwise_cast<sA0>(e)*f); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename A1, typename X, typename Y) , bd::cpu_ , bs::pack_<bd::floating_<A0>, X> , bs::pack_<bd::integer_<A1>, Y> ) { BOOST_FORCEINLINE A0 operator() (const A0& a0, const A1& a1) const BOOST_NOEXCEPT { using i_t = bd::as_integer_t<A0>; using sA0 = bd::scalar_of_t<A0>; i_t ik = a1+Maxexponent<A0>(); ik = shift_left(ik, Nbmantissabits<sA0>()); return a0*bitwise_cast<A0>(ik); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename A1, typename X) , bd::cpu_ , bs::pack_<bd::floating_<A0>, X> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator() (const A0& a0, A1 a1) const BOOST_NOEXCEPT { using iA0 = bd::as_integer_t<A0>; using sA0 = bd::scalar_of_t<A0>; using siA0 = bd::scalar_of_t<iA0>; siA0 ik = a1+Maxexponent<sA0>(); ik = shift_left(ik, Nbmantissabits<sA0>()); return a0*A0(bitwise_cast<sA0>(ik)); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename X) , bd::cpu_ , bs::pack_<bd::floating_<A0>, X> , bs::pack_<bd::floating_<A0>, X> ) { BOOST_FORCEINLINE A0 operator() ( const A0& a0, const A0& a1) const BOOST_NOEXCEPT { return ldexp(a0, toint(a1)); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename X) , bd::cpu_ , boost::simd::pedantic_tag , bs::pack_<bd::floating_<A0>, X> , bs::pack_<bd::floating_<A0>, X> ) { BOOST_FORCEINLINE A0 operator() ( const pedantic_tag & , const A0& a0, const A0& a1) const BOOST_NOEXCEPT { return pedantic_(ldexp)(a0, toint(a1)); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename X) , bd::cpu_ , bs::pack_<bd::double_<A0>, X> , bs::pack_<bd::double_<A0>, X> ) { BOOST_FORCEINLINE A0 operator() (const A0& a0, const A0& a1) const BOOST_NOEXCEPT { return a0*expocvt(a1); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename A1, typename X) , bd::cpu_ , bs::pedantic_tag , bs::pack_<bd::single_<A0>, X> , bd::scalar_<bd::single_<A1>> ) { BOOST_FORCEINLINE A0 operator() ( const pedantic_tag & , const A0& a0, const A1& a1) const BOOST_NOEXCEPT { return pedantic_(ldexp)(a0, toint(a1)); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename A1, typename X) , bd::cpu_ , bs::pedantic_tag , bs::pack_<bd::double_<A0>, X> , bd::scalar_<bd::double_<A1>> ) { BOOST_FORCEINLINE A0 operator() ( const pedantic_tag & , const A0& a0, const A1& a1) const BOOST_NOEXCEPT { return pedantic_(ldexp)(a0, toint(a1)); // return a0*expocvt(a1); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename A1, typename X) , bd::cpu_ , bs::pack_<bd::single_<A0>, X> , bd::scalar_<bd::single_<A1>> ) { BOOST_FORCEINLINE A0 operator() (const A0& a0, const A1& a1) const BOOST_NOEXCEPT { return ldexp(a0, toint(a1)); } }; BOOST_DISPATCH_OVERLOAD ( ldexp_ , (typename A0, typename A1, typename X) , bd::cpu_ , bs::pack_<bd::double_<A0>, X> , bd::scalar_<bd::double_<A1>> ) { BOOST_FORCEINLINE A0 operator() ( const A0& a0, const A1& a1) const BOOST_NOEXCEPT { return a0*expocvt(a1); } }; } } } #endif
34.721612
100
0.503218
nickporubsky
a7c9f82b6f9f33e9e4028f3fcfb0afa2078e1898
558
cpp
C++
LeetCode/sqrtx.cpp
SusmoySenGupta/online-judge-solutions
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
[ "MIT" ]
null
null
null
LeetCode/sqrtx.cpp
SusmoySenGupta/online-judge-solutions
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
[ "MIT" ]
null
null
null
LeetCode/sqrtx.cpp
SusmoySenGupta/online-judge-solutions
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
[ "MIT" ]
null
null
null
/* author: Susmoy Sen Gupta problem link: https://leetcode.com/problems/sqrtx/ Runtime: 0ms */ class Solution { public: int mySqrt(int x) { if(x == 0 || x == 1) return x; int left = 1, right = x; while(left < right) { int mid = left + (right - left) / 2 ; if (x / mid == mid) return mid; else if(x / mid < mid) right = mid; else left = mid + 1; } return right - 1; } };
21.461538
51
0.405018
SusmoySenGupta
a7cbd9540ad1ff7a2714e40711f3852cbef0bff7
3,039
cpp
C++
cpp/src/runtime/cifar10.cpp
fragata-ai/arhat
e22e6655ee83140be30b9657e63af1593e3054ed
[ "Apache-2.0" ]
23
2019-11-28T13:52:04.000Z
2021-12-20T03:00:07.000Z
cpp/src/runtime/cifar10.cpp
fragata-ai/arhat
e22e6655ee83140be30b9657e63af1593e3054ed
[ "Apache-2.0" ]
1
2019-12-05T09:17:39.000Z
2019-12-05T10:57:30.000Z
cpp/src/runtime/cifar10.cpp
fragata-ai/arhat
e22e6655ee83140be30b9657e63af1593e3054ed
[ "Apache-2.0" ]
2
2019-12-03T00:02:26.000Z
2019-12-04T17:01:00.000Z
// // Copyright 2019-2020 FRAGATA COMPUTER SYSTEMS AG // Copyright 2017-2018 Intel 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. // // // Based on neon, Intel(R) Nervana(tm) reference deep learning framework. // Ported from Python to C++ and partly modified by FRAGATA COMPUTER SYSTEMS AG. // #include <cstdio> #include <cstdint> #include <string> #include "runtime/arhat.h" namespace arhat { // // Cifar10 // // construction/destruction Cifar10::Cifar10() { numTrain = 0; numTest = 0; imgSize = 0; xTrain = nullptr; yTrain = nullptr; xTest = nullptr; yTest = nullptr; } Cifar10::~Cifar10() { delete[] xTrain; delete[] yTrain; delete[] xTest; delete[] yTest; } // iterface void Cifar10::Load( const char *path, bool normalize, bool contrastNormalize, bool whiten, bool padClasses) { // Whitening is not yet implemented; prefabricated data sets are used instead // File naming conventions: cifar10[_suffix].dat where suffix contains // n = normalize, c = contrastNormalize, w = whiten std::string fn = std::string(path) + "/cifar10"; std::string suffix("_"); if (normalize) { suffix += 'n'; } if (contrastNormalize) { suffix += 'c'; } if (whiten) { suffix += 'w'; } if (suffix.length() > 1) { fn += suffix; } fn += ".dat"; FILE *fp = fopen(fn.c_str(), "rb"); if (fp == nullptr) { char buf[256]; sprintf(buf, "Cannot open file [%s]\n", fn.c_str()); Error(buf, __FILE__, __LINE__); } numTrain = 50000; numTest = 10000; imgSize = 32; int xTrainSize = numTrain * 3 * imgSize * imgSize; int yTrainSize = numTrain; int xTestSize = numTest * 3 * imgSize * imgSize; int yTestSize = numTest; xTrain = new float[xTrainSize]; yTrain = new float[yTrainSize]; xTest = new float[xTestSize]; yTest = new float[yTestSize]; ReadData(fp, "xTrain", xTrain, xTrainSize); ReadData(fp, "yTrain", yTrain, yTrainSize); ReadData(fp, "xTest", xTest, xTestSize); ReadData(fp, "yTest", yTest, yTestSize); } // implementation void Cifar10::ReadData(FILE *fp, const char *tag, float *data, int count) { int nread = int(fread(data, sizeof(float), count, fp)); if (nread != count) { char buf[256]; sprintf(buf, "Data set %s too short: want %d, got %d\n", tag, count, nread); Error(buf, __FILE__, __LINE__); } } } // arhat
25.115702
84
0.62718
fragata-ai
a7cca33ad4ca6b1c5b649674d112cc20be866805
870
cpp
C++
src/ui/starred-files-list-model.cpp
Kashif-Nadeem/seafile-client
999b3d0775d91aa7da51a66326134aabd5009a0e
[ "Apache-2.0" ]
387
2015-01-01T14:20:30.000Z
2022-03-29T04:30:36.000Z
src/ui/starred-files-list-model.cpp
Kashif-Nadeem/seafile-client
999b3d0775d91aa7da51a66326134aabd5009a0e
[ "Apache-2.0" ]
755
2015-01-03T17:00:46.000Z
2022-03-31T07:10:45.000Z
src/ui/starred-files-list-model.cpp
Kashif-Nadeem/seafile-client
999b3d0775d91aa7da51a66326134aabd5009a0e
[ "Apache-2.0" ]
310
2015-01-09T00:45:56.000Z
2022-03-18T12:17:51.000Z
#include <QTimer> #include <QHash> #include <QDebug> #include <algorithm> // std::sort #include "utils/utils.h" #include "seafile-applet.h" #include "main-window.h" #include "rpc/rpc-client.h" #include "starred-file-item.h" #include "starred-files-list-model.h" namespace { bool compareFileByTimestamp(const StarredItem& a, const StarredItem& b) { return a.mtime > b.mtime; } } // namespace StarredFilesListModel::StarredFilesListModel(QObject *parent) : QStandardItemModel(parent) { } void StarredFilesListModel::setFiles(const std::vector<StarredItem>& files) { int i, n = files.size(); clear(); std::vector<StarredItem> list = files; std::sort(list.begin(), list.end(), compareFileByTimestamp); for (i = 0; i < n; i++) { StarredFileItem *item = new StarredFileItem(files[i]); appendRow(item); } }
20.232558
75
0.672414
Kashif-Nadeem
a7d10b7c07c7d14b192486f8ca487383eeb9ef1b
604
cpp
C++
Timus/1086-2.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Timus/1086-2.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Timus/1086-2.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
# include <iostream> using namespace std; int prost[16000]; int i,j,k,x,n; bool flag; void look(int x) { int i; i=prost[k]; while( k!=x ) { i=i+2; flag=true; for ( int j=1 ; j<=k ; j++ ) { if( i%prost[j]==0 ) { flag=false; break; } if( prost[j]*prost[j]>i ) break; // This is very important } if( flag ) { k=k+1; prost[k]=i; } } cout<<prost[k]<<endl; } int main() { prost[1]=2; prost[2]=3; prost[3]=5; k=3; cin>>n; for ( int i=1 ; i<=n ; i++ ) { cin>>x; if(x>k) look(x); else cout<<prost[x]<<endl; } }
9.4375
35
0.466887
s9v
a7d2d6665ccbacaa63493253ffbe66dadf3f8f4a
17,560
cc
C++
RedBlackTree.cc
JanX2/red-black-and-interval-trees
4b78646b63ac95dfaac5c3756cfd1ebf4d165a32
[ "BSD-3-Clause" ]
null
null
null
RedBlackTree.cc
JanX2/red-black-and-interval-trees
4b78646b63ac95dfaac5c3756cfd1ebf4d165a32
[ "BSD-3-Clause" ]
1
2018-10-30T21:19:23.000Z
2018-10-30T21:19:23.000Z
RedBlackTree.cc
JanX2/red-black-and-interval-trees
4b78646b63ac95dfaac5c3756cfd1ebf4d165a32
[ "BSD-3-Clause" ]
null
null
null
#include "RedBlackTree.h" #include <stdio.h> #include <math.h> // If the symbol CHECK_RB_TREE_ASSUMPTIONS is defined then the // code does a lot of extra checking to make sure certain assumptions // are satisfied. This only needs to be done if you suspect bugs are // present or if you make significant changes and want to make sure // your changes didn't mess anything up. // #define CHECK_RB_TREE_ASSUMPTIONS 1 const int MIN_INT=-MAX_INT; RedBlackTreeNode::RedBlackTreeNode(){ }; RedBlackTreeNode::RedBlackTreeNode(RedBlackEntry * newEntry) : storedEntry (newEntry) , key(newEntry->GetKey()) { }; RedBlackTreeNode::~RedBlackTreeNode(){ }; RedBlackEntry * RedBlackTreeNode::GetEntry() const {return storedEntry;} RedBlackEntry::RedBlackEntry(){ }; RedBlackEntry::~RedBlackEntry(){ }; void RedBlackEntry::Print() const { cout << "No Print Method defined. Using Default: " << GetKey() << endl; } RedBlackTree::RedBlackTree() { nil = new RedBlackTreeNode; nil->left = nil->right = nil->parent = nil; nil->red = 0; nil->key = MIN_INT; nil->storedEntry = NULL; root = new RedBlackTreeNode; root->parent = root->left = root->right = nil; root->key = MAX_INT; root->red=0; root->storedEntry = NULL; } /***********************************************************************/ /* FUNCTION: LeftRotate */ /**/ /* INPUTS: the node to rotate on */ /**/ /* OUTPUT: None */ /**/ /* Modifies Input: this, x */ /**/ /* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */ /* Cormen, Leiserson, Rivest (Chapter 14). Basically this */ /* makes the parent of x be to the left of x, x the parent of */ /* its parent before the rotation and fixes other pointers */ /* accordingly. */ /***********************************************************************/ void RedBlackTree::LeftRotate(RedBlackTreeNode* x) { RedBlackTreeNode* y; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ /* very subtle bug because sometimes this function modifies */ /* the parent pointer of nil. This can be a problem if a */ /* function which calls LeftRotate also uses the nil sentinel */ /* and expects the nil sentinel's parent pointer to be unchanged */ /* after calling this function. For example, when DeleteFixUP */ /* calls LeftRotate it expects the parent pointer of nil to be */ /* unchanged. */ y=x->right; x->right=y->left; if (y->left != nil) y->left->parent=x; /* used to use sentinel here */ /* and do an unconditional assignment instead of testing for nil */ y->parent=x->parent; /* instead of checking if x->parent is the root as in the book, we */ /* count on the root sentinel to implicitly take care of this case */ if( x == x->parent->left) { x->parent->left=y; } else { x->parent->right=y; } y->left=x; x->parent=y; #ifdef CHECK_RB_TREE_ASSUMPTIONS CheckAssumptions(); #elif defined(DEBUG_ASSERT) Assert(!nil->red,C_TEXT("nil not red in RedBlackTree::LeftRotate")); #endif } /***********************************************************************/ /* FUNCTION: RighttRotate */ /**/ /* INPUTS: node to rotate on */ /**/ /* OUTPUT: None */ /**/ /* Modifies Input?: this, y */ /**/ /* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */ /* Cormen, Leiserson, Rivest (Chapter 14). Basically this */ /* makes the parent of x be to the left of x, x the parent of */ /* its parent before the rotation and fixes other pointers */ /* accordingly. */ /***********************************************************************/ void RedBlackTree::RightRotate(RedBlackTreeNode* y) { RedBlackTreeNode* x; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ /* very subtle bug because sometimes this function modifies */ /* the parent pointer of nil. This can be a problem if a */ /* function which calls LeftRotate also uses the nil sentinel */ /* and expects the nil sentinel's parent pointer to be unchanged */ /* after calling this function. For example, when DeleteFixUP */ /* calls LeftRotate it expects the parent pointer of nil to be */ /* unchanged. */ x=y->left; y->left=x->right; if (nil != x->right) x->right->parent=y; /*used to use sentinel here */ /* and do an unconditional assignment instead of testing for nil */ /* instead of checking if x->parent is the root as in the book, we */ /* count on the root sentinel to implicitly take care of this case */ x->parent=y->parent; if( y == y->parent->left) { y->parent->left=x; } else { y->parent->right=x; } x->right=y; y->parent=x; #ifdef CHECK_RB_TREE_ASSUMPTIONS CheckAssumptions(); #elif defined(DEBUG_ASSERT) Assert(!nil->red,C_TEXT("nil not red in RedBlackTree::RightRotate")); #endif } /***********************************************************************/ /* FUNCTION: TreeInsertHelp */ /**/ /* INPUTS: z is the node to insert */ /**/ /* OUTPUT: none */ /**/ /* Modifies Input: this, z */ /**/ /* EFFECTS: Inserts z into the tree as if it were a regular binary tree */ /* using the algorithm described in _Introduction_To_Algorithms_ */ /* by Cormen et al. This funciton is only intended to be called */ /* by the Insert function and not by the user */ /***********************************************************************/ void RedBlackTree::TreeInsertHelp(RedBlackTreeNode* z) { /* This function should only be called by RedBlackTree::Insert */ RedBlackTreeNode* x; RedBlackTreeNode* y; z->left=z->right=nil; y=root; x=root->left; while( x != nil) { y=x; if ( x->key > z->key) { x=x->left; } else { /* x->key <= z->key */ x=x->right; } } z->parent=y; if ( (y == root) || (y->key > z->key) ) { y->left=z; } else { y->right=z; } #if defined(DEBUG_ASSERT) Assert(!nil->red,C_TEXT("nil not red in RedBlackTree::TreeInsertHelp")); #endif } /* Before calling InsertNode the node x should have its key set */ /***********************************************************************/ /* FUNCTION: InsertNode */ /**/ /* INPUTS: newEntry is the entry to insert*/ /**/ /* OUTPUT: This function returns a pointer to the newly inserted node */ /* which is guarunteed to be valid until this node is deleted. */ /* What this means is if another data structure stores this */ /* pointer then the tree does not need to be searched when this */ /* is to be deleted. */ /**/ /* Modifies Input: tree */ /**/ /* EFFECTS: Creates a node node which contains the appropriate key and */ /* info pointers and inserts it into the tree. */ /***********************************************************************/ RedBlackTreeNode * RedBlackTree::Insert(RedBlackEntry * newEntry) { RedBlackTreeNode * y; RedBlackTreeNode * x; RedBlackTreeNode * newNode; x = new RedBlackTreeNode(newEntry); TreeInsertHelp(x); newNode = x; x->red=1; while(x->parent->red) { /* use sentinel instead of checking for root */ if (x->parent == x->parent->parent->left) { y=x->parent->parent->right; if (y->red) { x->parent->red=0; y->red=0; x->parent->parent->red=1; x=x->parent->parent; } else { if (x == x->parent->right) { x=x->parent; LeftRotate(x); } x->parent->red=0; x->parent->parent->red=1; RightRotate(x->parent->parent); } } else { /* case for x->parent == x->parent->parent->right */ /* this part is just like the section above with */ /* left and right interchanged */ y=x->parent->parent->left; if (y->red) { x->parent->red=0; y->red=0; x->parent->parent->red=1; x=x->parent->parent; } else { if (x == x->parent->left) { x=x->parent; RightRotate(x); } x->parent->red=0; x->parent->parent->red=1; LeftRotate(x->parent->parent); } } } root->left->red=0; return(newNode); #ifdef CHECK_RB_TREE_ASSUMPTIONS CheckAssumptions(); #elif defined(DEBUG_ASSERT) Assert(!nil->red,C_TEXT("nil not red in RedBlackTree::Insert")); Assert(!root->red,C_TEXT("root not red in RedBlackTree::Insert")); #endif } /***********************************************************************/ /* FUNCTION: GetSuccessorOf */ /**/ /* INPUTS: x is the node we want the succesor of */ /**/ /* OUTPUT: This function returns the successor of x or NULL if no */ /* successor exists. */ /**/ /* Modifies Input: none */ /**/ /* Note: uses the algorithm in _Introduction_To_Algorithms_ */ /***********************************************************************/ RedBlackTreeNode * RedBlackTree::GetSuccessorOf(RedBlackTreeNode * x) const { RedBlackTreeNode* y; if (nil != (y = x->right)) { /* assignment to y is intentional */ while(y->left != nil) { /* returns the minium of the right subtree of x */ y=y->left; } return(y); } else { y=x->parent; while(x == y->right) { /* sentinel used instead of checking for nil */ x=y; y=y->parent; } if (y == root) return(nil); return(y); } } /***********************************************************************/ /* FUNCTION: GetPredecessorOf */ /**/ /* INPUTS: x is the node to get predecessor of */ /**/ /* OUTPUT: This function returns the predecessor of x or NULL if no */ /* predecessor exists. */ /**/ /* Modifies Input: none */ /**/ /* Note: uses the algorithm in _Introduction_To_Algorithms_ */ /***********************************************************************/ RedBlackTreeNode * RedBlackTree::GetPredecessorOf(RedBlackTreeNode * x) const { RedBlackTreeNode* y; if (nil != (y = x->left)) { /* assignment to y is intentional */ while(y->right != nil) { /* returns the maximum of the left subtree of x */ y=y->right; } return(y); } else { y=x->parent; while(x == y->left) { if (y == root) return(nil); x=y; y=y->parent; } return(y); } } /***********************************************************************/ /* FUNCTION: Print */ /**/ /* INPUTS: none */ /**/ /* OUTPUT: none */ /**/ /* EFFECTS: This function recursively prints the nodes of the tree */ /* inorder. */ /**/ /* Modifies Input: none */ /**/ /* Note: This function should only be called from ITTreePrint */ /***********************************************************************/ void RedBlackTreeNode::Print(RedBlackTreeNode * nil, RedBlackTreeNode * root) const { storedEntry->Print(); printf(", key=%i ",key); printf(" l->key="); if( left == nil) printf("NULL"); else printf("%i",left->key); printf(" r->key="); if( right == nil) printf("NULL"); else printf("%i",right->key); printf(" p->key="); if( parent == root) printf("NULL"); else printf("%i",parent->key); printf(" red=%i\n",red); } void RedBlackTree::TreePrintHelper( RedBlackTreeNode* x) const { if (x != nil) { TreePrintHelper(x->left); x->Print(nil,root); TreePrintHelper(x->right); } } RedBlackTree::~RedBlackTree() { RedBlackTreeNode * x = root->left; TemplateStack<RedBlackTreeNode *> stuffToFree; if (x != nil) { if (x->left != nil) { stuffToFree.Push(x->left); } if (x->right != nil) { stuffToFree.Push(x->right); } // delete x->storedEntry; delete x; while( stuffToFree.NotEmpty() ) { x = stuffToFree.Pop(); if (x->left != nil) { stuffToFree.Push(x->left); } if (x->right != nil) { stuffToFree.Push(x->right); } // delete x->storedEntry; delete x; } } delete nil; delete root; } /***********************************************************************/ /* FUNCTION: Print */ /**/ /* INPUTS: none */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: This function recursively prints the nodes of the tree */ /* inorder. */ /**/ /* Modifies Input: none */ /**/ /***********************************************************************/ void RedBlackTree::Print() const { TreePrintHelper(root->left); } /***********************************************************************/ /* FUNCTION: DeleteFixUp */ /**/ /* INPUTS: x is the child of the spliced */ /* out node in DeleteNode. */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: Performs rotations and changes colors to restore red-black */ /* properties after a node is deleted */ /**/ /* Modifies Input: this, x */ /**/ /* The algorithm from this function is from _Introduction_To_Algorithms_ */ /***********************************************************************/ void RedBlackTree::DeleteFixUp(RedBlackTreeNode* x) { RedBlackTreeNode * w; RedBlackTreeNode * rootLeft = root->left; while( (!x->red) && (rootLeft != x)) { if (x == x->parent->left) { w=x->parent->right; if (w->red) { w->red=0; x->parent->red=1; LeftRotate(x->parent); w=x->parent->right; } if ( (!w->right->red) && (!w->left->red) ) { w->red=1; x=x->parent; } else { if (!w->right->red) { w->left->red=0; w->red=1; RightRotate(w); w=x->parent->right; } w->red=x->parent->red; x->parent->red=0; w->right->red=0; LeftRotate(x->parent); x=rootLeft; /* this is to exit while loop */ } } else { /* the code below is has left and right switched from above */ w=x->parent->left; if (w->red) { w->red=0; x->parent->red=1; RightRotate(x->parent); w=x->parent->left; } if ( (!w->right->red) && (!w->left->red) ) { w->red=1; x=x->parent; } else { if (!w->left->red) { w->right->red=0; w->red=1; LeftRotate(w); w=x->parent->left; } w->red=x->parent->red; x->parent->red=0; w->left->red=0; RightRotate(x->parent); x=rootLeft; /* this is to exit while loop */ } } } x->red=0; #ifdef CHECK_RB_TREE_ASSUMPTIONS CheckAssumptions(); #elif defined(DEBUG_ASSERT) Assert(!nil->red,C_TEXT("nil not black in RedBlackTree::DeleteFixUp")); #endif } /***********************************************************************/ /* FUNCTION: DeleteNode */ /**/ /* INPUTS: tree is the tree to delete node z from */ /**/ /* OUTPUT: returns the RedBlackEntry stored at deleted node */ /**/ /* EFFECT: Deletes z from tree and but don't call destructor */ /**/ /* Modifies Input: z */ /**/ /* The algorithm from this function is from _Introduction_To_Algorithms_ */ /***********************************************************************/ RedBlackEntry * RedBlackTree::DeleteNode(RedBlackTreeNode * z){ RedBlackTreeNode* y; RedBlackTreeNode* x; RedBlackEntry * returnValue = z->storedEntry; y= ((z->left == nil) || (z->right == nil)) ? z : GetSuccessorOf(z); x= (y->left == nil) ? y->right : y->left; if (root == (x->parent = y->parent)) { /* assignment of y->p to x->p is intentional */ root->left=x; } else { if (y == y->parent->left) { y->parent->left=x; } else { y->parent->right=x; } } if (y != z) { /* y should not be nil in this case */ #ifdef DEBUG_ASSERT Assert( (y!=nil),C_TEXT("y is nil in DeleteNode \n")); #endif /* y is the node to splice out and x is its child */ y->left=z->left; y->right=z->right; y->parent=z->parent; z->left->parent=z->right->parent=y; if (z == z->parent->left) { z->parent->left=y; } else { z->parent->right=y; } if (!(y->red)) { y->red = z->red; DeleteFixUp(x); } else y->red = z->red; delete z; #ifdef CHECK_RB_TREE_ASSUMPTIONS CheckAssumptions(); #elif defined(DEBUG_ASSERT) Assert(!nil->red,C_TEXT("nil not black in RedBlackTree::Delete")); #endif } else { if (!(y->red)) DeleteFixUp(x); delete y; #ifdef CHECK_RB_TREE_ASSUMPTIONS CheckAssumptions(); #elif defined(DEBUG_ASSERT) Assert(!nil->red,C_TEXT("nil not black in RedBlackTree::Delete")); #endif } return returnValue; } /***********************************************************************/ /* FUNCTION: Enumerate */ /**/ /* INPUTS: tree is the tree to look for keys between [low,high] */ /**/ /* OUTPUT: stack containing pointers to the nodes between [low,high] */ /**/ /* Modifies Input: none */ /**/ /* EFFECT: Returns a stack containing pointers to nodes containing */ /* keys which in [low,high]/ */ /**/ /***********************************************************************/ TemplateStack<RedBlackTreeNode *> * RedBlackTree::Enumerate(int low, int high) { TemplateStack<RedBlackTreeNode *> * enumResultStack = new TemplateStack<RedBlackTreeNode *>(4); RedBlackTreeNode* x=root->left; RedBlackTreeNode* lastBest=NULL; while(nil != x) { if ( x->key > high ) { x=x->left; } else { lastBest=x; x=x->right; } } while ( (lastBest) && (low <= lastBest->key) ) { enumResultStack->Push(lastBest); lastBest=GetPredecessorOf(lastBest); } return(enumResultStack); } void RedBlackTree::CheckAssumptions() const { VERIFY(nil->key == MIN_INT); VERIFY(root->key == MAX_INT); VERIFY(nil->storedEntry == NULL); VERIFY(root->storedEntry == NULL); VERIFY(nil->red == 0); VERIFY(root->red == 0); }
28.00638
88
0.552961
JanX2
a7d315693421da6a9170f0ecca63ab3e87792c54
1,488
cpp
C++
clang-tools-extra/test/clang-tidy/checkers/llvm-namespace-comment.cpp
DougGregor/llvm-project
97602a8bd045f087e02348b64ffbdd143a33e10b
[ "Apache-2.0" ]
1
2022-03-28T05:58:03.000Z
2022-03-28T05:58:03.000Z
clang-tools-extra/test/clang-tidy/checkers/llvm-namespace-comment.cpp
DougGregor/llvm-project
97602a8bd045f087e02348b64ffbdd143a33e10b
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/test/clang-tidy/checkers/llvm-namespace-comment.cpp
DougGregor/llvm-project
97602a8bd045f087e02348b64ffbdd143a33e10b
[ "Apache-2.0" ]
null
null
null
// RUN: %check_clang_tidy %s llvm-namespace-comment %t namespace n1 { namespace n2 { void f(); // CHECK-MESSAGES: :[[@LINE+2]]:1: warning: namespace 'n2' not terminated with a closing comment [llvm-namespace-comment] // CHECK-MESSAGES: :[[@LINE+1]]:2: warning: namespace 'n1' not terminated with a closing comment [llvm-namespace-comment] }} // CHECK-FIXES: } // namespace n2 // CHECK-FIXES: } // namespace n1 #define MACRO macro_expansion namespace MACRO { void f(); // CHECK-MESSAGES: :[[@LINE+1]]:1: warning: namespace 'MACRO' not terminated with a closing comment [llvm-namespace-comment] } // CHECK-FIXES: } // namespace MACRO namespace MACRO { void g(); } // namespace MACRO namespace MACRO { void h(); // CHECK-MESSAGES: :[[@LINE+1]]:2: warning: namespace 'MACRO' ends with a comment that refers to an expansion of macro [llvm-namespace-comment] } // namespace macro_expansion // CHECK-FIXES: } // namespace MACRO namespace n1 { namespace MACRO { namespace n2 { void f(); // CHECK-MESSAGES: :[[@LINE+3]]:1: warning: namespace 'n2' not terminated with a closing comment [llvm-namespace-comment] // CHECK-MESSAGES: :[[@LINE+2]]:2: warning: namespace 'MACRO' not terminated with a closing comment [llvm-namespace-comment] // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: namespace 'n1' not terminated with a closing comment [llvm-namespace-comment] }}} // CHECK-FIXES: } // namespace n2 // CHECK-FIXES: } // namespace MACRO // CHECK-FIXES: } // namespace n1
35.428571
145
0.693548
DougGregor
a7d384bf9c47725b0ffebbfba3faa312be98a32f
664
cpp
C++
CascadedShadowMaps11/WaitDlg.cpp
wjingzhe/CascadedShadowMaps11
ff6adcccfef9932ebf4c173acc30459f7389176e
[ "MIT" ]
null
null
null
CascadedShadowMaps11/WaitDlg.cpp
wjingzhe/CascadedShadowMaps11
ff6adcccfef9932ebf4c173acc30459f7389176e
[ "MIT" ]
null
null
null
CascadedShadowMaps11/WaitDlg.cpp
wjingzhe/CascadedShadowMaps11
ff6adcccfef9932ebf4c173acc30459f7389176e
[ "MIT" ]
1
2020-11-22T09:40:46.000Z
2020-11-22T09:40:46.000Z
#include "WaitDlg.h" INT_PTR WaitDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { CWaitDlg* pDialog = (CWaitDlg*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA); switch (uMsg) { case WM_INITDIALOG: return true; break; case WM_CLOSE: pDialog->DestroyDialog(); return TRUE; break; } return FALSE; } unsigned int UpdateBarDialog(void * pArg) { CWaitDlg* pDialog = (CWaitDlg*)pArg; // We create the dialog in this thread,so we can call SendMessage without blocking on the // main thread's message pump pDialog->GetDialogControls(); while (pDialog->IsRunning()) { pDialog->UpdateProcessBar(); Sleep(100); } return 0; }
17.025641
90
0.715361
wjingzhe
a7d9dd86299cbdcef75a4e208831de4ea440c379
844
cpp
C++
FtsUtilityAI/Source/FtsUtilityAI/Private/FtsUtilityAiObject.cpp
FreetimeStudio/FtsUtilityAI
cf1f214d685fcc3c24f426881bdad6c8257e36e3
[ "MIT" ]
1
2021-03-02T02:45:00.000Z
2021-03-02T02:45:00.000Z
FtsUtilityAI/Source/FtsUtilityAI/Private/FtsUtilityAiObject.cpp
FreetimeStudio/FtsUtilityAI
cf1f214d685fcc3c24f426881bdad6c8257e36e3
[ "MIT" ]
null
null
null
FtsUtilityAI/Source/FtsUtilityAI/Private/FtsUtilityAiObject.cpp
FreetimeStudio/FtsUtilityAI
cf1f214d685fcc3c24f426881bdad6c8257e36e3
[ "MIT" ]
null
null
null
// (c) MIT 2020 by FreetimeStudio #include "FtsUtilityAiObject.h" UFtsUtilityAiObject::UFtsUtilityAiObject() : Super() { UtilityId = NAME_None; } void UFtsUtilityAiObject::SetUtilityId(const FName& NewId) { UtilityId = NewId; } FName UFtsUtilityAiObject::GetUtilityId() const { return UtilityId; } UFtsUtilityAIComponent* UFtsUtilityAiObject::GetUtilityComponent() const { return AiComponent; } void UFtsUtilityAiObject::Initialize_Implementation(UFtsUtilityAIComponent* InAiComponent) { AiComponent = InAiComponent; } void UFtsUtilityAiObject::Uninitialize_Implementation() { } #if WITH_EDITOR FText UFtsUtilityAiObject::GetNodeTitle() const { return FText::FromName(UtilityId); } void UFtsUtilityAiObject::ClearInputs() { } void UFtsUtilityAiObject::AddInput(UFtsUtilityAiObject* NewInput) { } #endif
16.230769
90
0.768957
FreetimeStudio
a7daa5db671caeb7f4d8cda0d4afeae778645cdf
1,004
hpp
C++
include/cynodelic/mulinum/detail/enable_if.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
include/cynodelic/mulinum/detail/enable_if.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
include/cynodelic/mulinum/detail/enable_if.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt /** * @file enable_if.hpp * * @brief Defines the `enable_if` template alias. */ #ifndef CYNODELIC_MULINUM_DETAIL_ENABLE_IF_HPP #define CYNODELIC_MULINUM_DETAIL_ENABLE_IF_HPP #include <cynodelic/mulinum/config.hpp> namespace cynodelic { namespace mulinum { namespace detail { /** * @brief Helper for @ref enable_if. */ template <bool X, typename = void> struct enable_if_impl; /** * @brief Helper for @ref enable_if. */ template <typename T> struct enable_if_impl<true, T> { using type = T; }; /** * @brief Helper metafunction for overloading and SFINAE. */ template <bool Cond, typename T = void> using enable_if = typename enable_if_impl<Cond, T>::type; } // end of "detail" namespace }} // end of "cynodelic::mulinum" namespace #endif // CYNODELIC_MULINUM_DETAIL_ENABLE_IF_HPP
19.686275
80
0.72012
cynodelic
a7db28f1c395e3cab6ac3f19f675f30df5026599
700
cpp
C++
comprecttransform.cpp
dibu13/Qt-2D-Painter
9e8e0416e5e8424d1dfbf91d5c5c3a47e481ae6a
[ "MIT" ]
null
null
null
comprecttransform.cpp
dibu13/Qt-2D-Painter
9e8e0416e5e8424d1dfbf91d5c5c3a47e481ae6a
[ "MIT" ]
2
2019-02-22T13:42:09.000Z
2019-04-02T19:09:45.000Z
comprecttransform.cpp
dibu13/Qt-2D-Painter
9e8e0416e5e8424d1dfbf91d5c5c3a47e481ae6a
[ "MIT" ]
1
2019-10-10T12:19:55.000Z
2019-10-10T12:19:55.000Z
#include "comprecttransform.h" #include "gameobject.h" #include <iostream> CompRectTransform::CompRectTransform(GameObject* gameobject, float p_x, float p_y, float s_x, float s_y) : Component (gameobject, RECT_TRANSFORM), pos_x(p_x), pos_y(p_y), scale_x(s_x), scale_y(s_y) { } void CompRectTransform::Save(QDataStream& out) { out << pos_x; out << pos_y; out << scale_x; out << scale_y; } void CompRectTransform::Load(QDataStream& in) { in >> pos_x; in >> pos_y; in >> scale_x; in >> scale_y; std::cout << "Rect(" << pos_x << "," << pos_y << "," << scale_x << "," << scale_y << ")"; }
20
106
0.561429
dibu13
a7e313f28cdfb1a7c249e8e69786ffc54ee92f62
4,159
cc
C++
src/core/sibyl/util/Config.cc
arjun-k-r/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
34
2017-03-01T05:49:17.000Z
2022-01-01T15:30:06.000Z
src/core/sibyl/util/Config.cc
arjun-k-r/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
1
2018-12-19T17:02:52.000Z
2018-12-19T17:02:52.000Z
src/core/sibyl/util/Config.cc
junosan/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
24
2017-09-19T01:51:50.000Z
2022-02-04T19:53:16.000Z
/* Copyright 2017 Hosang Yoon 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 "Config.h" #include <iostream> #include <fstream> #include <algorithm> namespace sibyl { #include "toggle_win32_min_max.h" bool Config::SetFile(CSTR &filename_, Config::Mode mode_) { filename = filename_; mode = mode_; lines.clear(); map_key_idx.clear(); bool success = true; std::ifstream ifs(filename); if (ifs.is_open() == true) { for (STR line; std::getline(ifs, line);) { if (line.back() == '\r') line.pop_back(); auto posEq = line.find_first_of('='); if (posEq != std::string::npos) { auto keylen = std::min(posEq, line.find_first_of(' ')); STR key(line, 0, keylen); auto it_success = map_key_idx.insert(std::make_pair(key, lines.size())); if (it_success.second == false) { std::cerr << "Config::SetFile: Overlapping key " << key << " found" << std::endl; success = false; break; } } lines.push_back(line); } } else { if (mode == read_write) { std::ofstream ofs(filename, std::ios::app); if (ofs.is_open() == false) { std::cerr << "Config::SetFile: Cannot write " << filename << std::endl; success = false; } // else: writing a new file (success = true) } else { std::cerr << "Config::SetFile: Cannot read " << filename << std::endl; success = false; } } if (success == false) filename.clear(); return success; } #include "toggle_win32_min_max.h" Config::SS& Config::Get(CSTR &key) { bool success = false; if (filename.empty() == true) std::cerr << "Config::Get: Valid SetFile call must precede this" << std::endl; else if (SetFile(filename, mode) == true) { auto it = map_key_idx.find(key); if (it != std::end(map_key_idx)) { STR line = lines.at(it->second); auto posEq = line.find_first_of('='); STR val = line.substr(posEq + 1); ss.clear(); ss.str(val); success = true; } } if (success == false) ss.setstate(std::ios_base::failbit); return ss; } bool Config::Set(CSTR &key, CSTR &val) { bool success = false; if (mode == read_only) std::cerr << "Config::Set: Cannot set in read_only mode" << std::endl; else if (filename.empty() == true) std::cerr << "Config::Set: Valid SetFile call must precede this" << std::endl; else if (SetFile(filename, mode) == true) { std::size_t n = lines.size(); STR line; // line to be written std::size_t idx; // idx of line to be written auto it = map_key_idx.find(key); if (it != std::end(map_key_idx)) { STR prev = lines.at(it->second); auto posEq = prev.find_first_of('='); prev.resize(posEq + 1); line = prev + val; idx = it->second; } else { line = key + '=' + val; idx = n; } std::ofstream ofs(filename, std::ios::trunc); for (std::size_t i = 0; i < n + 1; i++) { if (i == idx) ofs << line << '\n'; else if (i < n) ofs << lines.at(i) << '\n'; } success = true; } return success; } }
29.496454
101
0.520077
arjun-k-r
a7e494fe7eb6b45ce4255ade3396d6e9f6fa9ef1
203
cpp
C++
traits/pli.cpp
ywen-cmd/C-Templates
3960bd4e852ed0d3b4db5203f4d125b4a725dd48
[ "FSFAP" ]
null
null
null
traits/pli.cpp
ywen-cmd/C-Templates
3960bd4e852ed0d3b4db5203f4d125b4a725dd48
[ "FSFAP" ]
null
null
null
traits/pli.cpp
ywen-cmd/C-Templates
3960bd4e852ed0d3b4db5203f4d125b4a725dd48
[ "FSFAP" ]
null
null
null
#include<iostream> typedef int Int; void g(Int); template <typename T> void f(T i){ if(i>0) g(-i); } void g(Int){ f<Int>(42); } int main(){ g(1); return 0; }
10.684211
22
0.472906
ywen-cmd
a7e4c781d3ecf6b3e9829eef4c03ef2d86a19cd1
6,204
cpp
C++
uut/video/uutGraphics.cpp
kolyden/engine
cab1881a8493b591a136a5ce3d502e704fdea7bf
[ "Unlicense" ]
null
null
null
uut/video/uutGraphics.cpp
kolyden/engine
cab1881a8493b591a136a5ce3d502e704fdea7bf
[ "Unlicense" ]
null
null
null
uut/video/uutGraphics.cpp
kolyden/engine
cab1881a8493b591a136a5ce3d502e704fdea7bf
[ "Unlicense" ]
null
null
null
#include "uutGraphics.h" #include "core/uutContext.h" #include "uutVideo.h" #include "uutImage.h" #include "uutTexture.h" #include "uutVideoBuffer.h" #include "uutVertex2.h" #include "uutVertex3.h" #include "uutFont.h" #include "uutFontFace.h" namespace uut { Graphics::Graphics(Context* context) : Module(context) , _currentCount(0) , _currentType(PRIMITIVE_TRIANGLES) , _vertexType(VertexType::None) , _vertexMax(0) , _data(0) , _currentColor(Color::WHITE) , _currentColorUint(_currentColor.ToUint()) { } void Graphics::SetColor(const Color& color) { _currentColor = color; _currentColorUint = _currentColor.ToUint(); } void Graphics::DrawLine(const Vector2f& start, const Vector2f& end) { TestBufferCount(2); ChangeBufferParam(PRIMITIVE_LINES, VertexType::V2D); SetTexture(0); auto verts = (Vertex2*)_data; verts[_currentCount++] = Vertex2(start, _currentColorUint); verts[_currentCount++] = Vertex2(end, _currentColorUint); } void Graphics::DrawLine(const Vector3f& start, const Vector3f& end) { TestBufferCount(2); ChangeBufferParam(PRIMITIVE_LINES, VertexType::V3D); SetTexture(0); auto verts = (Vertex3*)_data; verts[_currentCount++] = Vertex3(start, _currentColorUint); verts[_currentCount++] = Vertex3(end, _currentColorUint); } void Graphics::DrawTexture(Texture* texture, const Rectf& rect) { TestBufferCount(6); ChangeBufferParam(PRIMITIVE_TRIANGLES, VertexType::V2D); SetTexture(texture); const float x1 = rect.pos.x; const float y1 = rect.pos.y; const float x2 = x1 + rect.size.x; const float y2 = y1 + rect.size.y; const float tx1 = 0.0f, ty1 = 0.0f; const float tx2 = 1.0f, ty2 = 1.0f; auto verts = (Vertex2*)_data; verts[_currentCount++] = Vertex2(Vector2f(x1, y1), Vector2f(tx1, ty1), _currentColorUint); verts[_currentCount++] = Vertex2(Vector2f(x2, y1), Vector2f(tx2, ty1), _currentColorUint); verts[_currentCount++] = Vertex2(Vector2f(x1, y2), Vector2f(tx1, ty2), _currentColorUint); verts[_currentCount++] = Vertex2(Vector2f(x2, y1), Vector2f(tx2, ty1), _currentColorUint); verts[_currentCount++] = Vertex2(Vector2f(x2, y2), Vector2f(tx2, ty2), _currentColorUint); verts[_currentCount++] = Vertex2(Vector2f(x1, y2), Vector2f(tx1, ty2), _currentColorUint); } void Graphics::DrawTriangle(Texture* tex, const Vertex2& v0, const Vertex2& v1, const Vertex2& v2) { TestBufferCount(3); ChangeBufferParam(PRIMITIVE_TRIANGLES, VertexType::V2D); SetTexture(tex); auto verts = (Vertex2*)_data; verts[_currentCount++] = v0; verts[_currentCount++] = v1; verts[_currentCount++] = v2; } void Graphics::DrawTriangle(Texture* tex, const Vertex3& v0, const Vertex3& v1, const Vertex3& v2) { TestBufferCount(3); ChangeBufferParam(PRIMITIVE_TRIANGLES, VertexType::V3D); SetTexture(tex); auto verts = (Vertex3*)_data; verts[_currentCount++] = v0; verts[_currentCount++] = v1; verts[_currentCount++] = v2; } void Graphics::DrawQuad(Texture* tex, const Vertex2& v0, const Vertex2& v1, const Vertex2& v2, const Vertex2& v3) { DrawTriangle(tex, v0, v1, v2); DrawTriangle(tex, v1, v3, v2); } void Graphics::DrawQuad(Texture* tex, const Vertex3& v0, const Vertex3& v1, const Vertex3& v2, const Vertex3& v3) { DrawTriangle(tex, v0, v1, v2); DrawTriangle(tex, v1, v3, v2); } void Graphics::PrintText(Font* font, const Vector2f& pos, const String& text) { if (font == 0) return; auto face = font->GetFace(0); auto tex = face->GetTexture(0); List<Vertex2> list; face->GenerateLine(list, text); TestBufferCount(list.Count()); ChangeBufferParam(PRIMITIVE_TRIANGLES, VertexType::V2D); SetTexture(tex); auto verts = (Vertex2*)_data; for (int i = 0; i < list.Count(); i++) { list[i].pos += pos; verts[_currentCount++] = list[i]; } } void Graphics::Flush() { if (_currentCount == 0) return; _video->BindTexture(_texture); switch (_vertexType) { case uut::Graphics::VertexType::V2D: _buffer->UpdateData(0, _currentCount * Vertex2::DECLARE.size, _data); if (_video->BindBuffer(_buffer, Vertex2::DECLARE.size, Vertex2::DECLARE.types, Vertex2::DECLARE.count)) { _video->SetColor(COLOR_DRAW, _currentColor); _video->DrawPrimitives(_currentType, _currentCount, 0); _video->UnbindBuffer(_buffer, Vertex2::DECLARE.types, Vertex2::DECLARE.count); } break; case uut::Graphics::VertexType::V3D: _buffer->UpdateData(0, _currentCount * Vertex3::DECLARE.size, _data); if (_video->BindBuffer(_buffer, Vertex3::DECLARE.size, Vertex3::DECLARE.types, Vertex3::DECLARE.count)) { _video->SetColor(COLOR_DRAW, _currentColor); _video->DrawPrimitives(_currentType, _currentCount, 0); _video->UnbindBuffer(_buffer, Vertex3::DECLARE.types, Vertex3::DECLARE.count); } break; } _currentCount = 0; } void Graphics::ResetStates() { Flush(); _texture = 0; _vertexType = VertexType::None; } ////////////////////////////////////////////////////////////////////////// void Graphics::OnRegister() { _video = _context->GetModule<Video>(); } void Graphics::OnInit() { } void Graphics::ChangeBufferParam(EPrimitiveType type, VertexType vert) { if (!_buffer) { _buffer = SharedPtr<VideoBuffer>(new VideoBuffer(_context)); _buffer->Create(BUFFER_VERTEX, BUFFER_SIZE, BUFFERFLAG_DYNAMIC); _data = new uint8_t[BUFFER_SIZE]; } if (_currentType == type && _vertexType == vert) return; Flush(); _currentType = type; _vertexType = vert; switch (_vertexType) { case VertexType::V2D: _vertexMax = BUFFER_SIZE / Vertex2::DECLARE.size; break; case VertexType::V3D: _vertexMax = BUFFER_SIZE / Vertex3::DECLARE.size; break; } } void Graphics::SetTexture(Texture* texture) { if (_texture == texture) return; Flush(); _texture = texture; } void Graphics::TestBufferCount(int count) { if (_currentCount + count >= _vertexMax) Flush(); } }
26.741379
115
0.660703
kolyden
a7e695c28b1ebd82ca035cac1aaef052912d75f2
821
hpp
C++
test/test_Scatter.hpp
paulfreddy/rccl
9dfc2c183e0e0fc2ed19a5b2bdd29aa7c177dbc3
[ "FSFAP" ]
98
2017-12-29T17:34:39.000Z
2022-03-24T00:48:38.000Z
test/test_Scatter.hpp
paulfreddy/rccl
9dfc2c183e0e0fc2ed19a5b2bdd29aa7c177dbc3
[ "FSFAP" ]
136
2018-02-12T08:18:33.000Z
2022-03-31T21:16:36.000Z
test/test_Scatter.hpp
paulfreddy/rccl
9dfc2c183e0e0fc2ed19a5b2bdd29aa7c177dbc3
[ "FSFAP" ]
56
2018-06-06T14:41:21.000Z
2022-03-08T00:52:33.000Z
/************************************************************************* * Copyright (c) 2019-2020 Advanced Micro Devices, Inc. All rights reserved. * * See LICENSE.txt for license information ************************************************************************/ #ifndef TEST_SCATTER_HPP #define TEST_SCATTER_HPP #include "CorrectnessTest.hpp" namespace CorrectnessTests { class ScatterCorrectnessTest : public CorrectnessTest { public: static void ComputeExpectedResults(Dataset& dataset, int const root) { for (int i = 0; i < dataset.numDevices; i++) HIP_CALL(hipMemcpy(dataset.expected[i], (int8_t *)dataset.inputs[root]+dataset.NumBytes()*i, dataset.NumBytes(), hipMemcpyDeviceToHost)); } }; } #endif
31.576923
108
0.533496
paulfreddy
a7e72087fe5a4f12fa957e35d17290600630507c
27,055
cpp
C++
vendor/android-tools/logd/LogKlog.cpp
dylanh333/android-unmkbootimg
7c30a58b5bc3d208fbbbbc713717e2aae98df699
[ "MIT" ]
3
2018-04-01T18:35:29.000Z
2020-12-18T21:09:53.000Z
vendor/android-tools/logd/LogKlog.cpp
dylanh333/android-unmkbootimg
7c30a58b5bc3d208fbbbbc713717e2aae98df699
[ "MIT" ]
2
2017-04-24T12:29:05.000Z
2017-05-09T12:27:10.000Z
vendor/android-tools/logd/LogKlog.cpp
dylanh333/android-unmkbootimg
7c30a58b5bc3d208fbbbbc713717e2aae98df699
[ "MIT" ]
null
null
null
/* * Copyright (C) 2014 The Android Open Source Project * * 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 <ctype.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sys/prctl.h> #include <sys/uio.h> #include <syslog.h> #include <private/android_filesystem_config.h> #include <private/android_logger.h> #include "LogBuffer.h" #include "LogKlog.h" #include "LogReader.h" #define KMSG_PRIORITY(PRI) \ '<', '0' + (LOG_SYSLOG | (PRI)) / 10, '0' + (LOG_SYSLOG | (PRI)) % 10, '>' static const char priority_message[] = { KMSG_PRIORITY(LOG_INFO), '\0' }; // List of the _only_ needles we supply here to android::strnstr static const char suspendStr[] = "PM: suspend entry "; static const char resumeStr[] = "PM: suspend exit "; static const char suspendedStr[] = "Suspended for "; static const char healthdStr[] = "healthd"; static const char batteryStr[] = ": battery "; static const char auditStr[] = " audit("; static const char klogdStr[] = "logd.klogd: "; // Parsing is hard // called if we see a '<', s is the next character, returns pointer after '>' static char* is_prio(char* s, ssize_t len) { if ((len <= 0) || !isdigit(*s++)) return nullptr; --len; static const size_t max_prio_len = (len < 4) ? len : 4; size_t priolen = 0; char c; while (((c = *s++)) && (++priolen <= max_prio_len)) { if (!isdigit(c)) return ((c == '>') && (*s == '[')) ? s : nullptr; } return nullptr; } // called if we see a '[', s is the next character, returns pointer after ']' static char* is_timestamp(char* s, ssize_t len) { while ((len > 0) && (*s == ' ')) { ++s; --len; } if ((len <= 0) || !isdigit(*s++)) return nullptr; --len; bool first_period = true; char c; while ((len > 0) && ((c = *s++))) { --len; if ((c == '.') && first_period) { first_period = false; } else if (!isdigit(c)) { return ((c == ']') && !first_period && (*s == ' ')) ? s : nullptr; } } return nullptr; } // Like strtok_r with "\r\n" except that we look for log signatures (regex) // \(\(<[0-9]\{1,4\}>\)\([[] *[0-9]+[.][0-9]+[]] \)\{0,1\}\|[[] // *[0-9]+[.][0-9]+[]] \) // and split if we see a second one without a newline. // We allow nuls in content, monitoring the overall length and sub-length of // the discovered tokens. #define SIGNATURE_MASK 0xF0 // <digit> following ('0' to '9' masked with ~SIGNATURE_MASK) added to signature #define LESS_THAN_SIG SIGNATURE_MASK #define OPEN_BRACKET_SIG ((SIGNATURE_MASK << 1) & SIGNATURE_MASK) // space is one more than <digit> of 9 #define OPEN_BRACKET_SPACE ((char)(OPEN_BRACKET_SIG | 10)) char* android::log_strntok_r(char* s, ssize_t& len, char*& last, ssize_t& sublen) { sublen = 0; if (len <= 0) return nullptr; if (!s) { if (!(s = last)) return nullptr; // fixup for log signature split <, // LESS_THAN_SIG + <digit> if ((*s & SIGNATURE_MASK) == LESS_THAN_SIG) { *s = (*s & ~SIGNATURE_MASK) + '0'; *--s = '<'; ++len; } // fixup for log signature split [, // OPEN_BRACKET_SPACE is space, OPEN_BRACKET_SIG + <digit> if ((*s & SIGNATURE_MASK) == OPEN_BRACKET_SIG) { *s = (*s == OPEN_BRACKET_SPACE) ? ' ' : (*s & ~SIGNATURE_MASK) + '0'; *--s = '['; ++len; } } while ((len > 0) && ((*s == '\r') || (*s == '\n'))) { ++s; --len; } if (len <= 0) return last = nullptr; char *peek, *tok = s; for (;;) { if (len <= 0) { last = nullptr; return tok; } char c = *s++; --len; ssize_t adjust; switch (c) { case '\r': case '\n': s[-1] = '\0'; last = s; return tok; case '<': peek = is_prio(s, len); if (!peek) break; if (s != (tok + 1)) { // not first? s[-1] = '\0'; *s &= ~SIGNATURE_MASK; *s |= LESS_THAN_SIG; // signature for '<' last = s; return tok; } adjust = peek - s; if (adjust > len) { adjust = len; } sublen += adjust; len -= adjust; s = peek; if ((*s == '[') && ((peek = is_timestamp(s + 1, len - 1)))) { adjust = peek - s; if (adjust > len) { adjust = len; } sublen += adjust; len -= adjust; s = peek; } break; case '[': peek = is_timestamp(s, len); if (!peek) break; if (s != (tok + 1)) { // not first? s[-1] = '\0'; if (*s == ' ') { *s = OPEN_BRACKET_SPACE; } else { *s &= ~SIGNATURE_MASK; *s |= OPEN_BRACKET_SIG; // signature for '[' } last = s; return tok; } adjust = peek - s; if (adjust > len) { adjust = len; } sublen += adjust; len -= adjust; s = peek; break; } ++sublen; } // NOTREACHED } log_time LogKlog::correction = (log_time(CLOCK_REALTIME) < log_time(CLOCK_MONOTONIC)) ? log_time::EPOCH : (log_time(CLOCK_REALTIME) - log_time(CLOCK_MONOTONIC)); LogKlog::LogKlog(LogBuffer* buf, LogReader* reader, int fdWrite, int fdRead, bool auditd) : SocketListener(fdRead, false), logbuf(buf), reader(reader), signature(CLOCK_MONOTONIC), initialized(false), enableLogging(true), auditd(auditd) { static const char klogd_message[] = "%s%s%" PRIu64 "\n"; char buffer[strlen(priority_message) + strlen(klogdStr) + strlen(klogd_message) + 20]; snprintf(buffer, sizeof(buffer), klogd_message, priority_message, klogdStr, signature.nsec()); write(fdWrite, buffer, strlen(buffer)); } bool LogKlog::onDataAvailable(SocketClient* cli) { if (!initialized) { prctl(PR_SET_NAME, "logd.klogd"); initialized = true; enableLogging = false; } char buffer[LOGGER_ENTRY_MAX_PAYLOAD]; ssize_t len = 0; for (;;) { ssize_t retval = 0; if (len < (ssize_t)(sizeof(buffer) - 1)) { retval = read(cli->getSocket(), buffer + len, sizeof(buffer) - 1 - len); } if ((retval == 0) && (len <= 0)) { break; } if (retval < 0) { return false; } len += retval; bool full = len == (sizeof(buffer) - 1); char* ep = buffer + len; *ep = '\0'; ssize_t sublen; for (char *ptr = nullptr, *tok = buffer; !!(tok = android::log_strntok_r(tok, len, ptr, sublen)); tok = nullptr) { if (((tok + sublen) >= ep) && (retval != 0) && full) { if (sublen > 0) memmove(buffer, tok, sublen); len = sublen; break; } if ((sublen > 0) && *tok) { log(tok, sublen); } } } return true; } void LogKlog::calculateCorrection(const log_time& monotonic, const char* real_string, ssize_t len) { static const char real_format[] = "%Y-%m-%d %H:%M:%S.%09q UTC"; if (len < (ssize_t)(strlen(real_format) + 5)) return; log_time real; const char* ep = real.strptime(real_string, real_format); if (!ep || (ep > &real_string[len]) || (real > log_time(CLOCK_REALTIME))) { return; } // kernel report UTC, log_time::strptime is localtime from calendar. // Bionic and liblog strptime does not support %z or %Z to pick up // timezone so we are calculating our own correction. time_t now = real.tv_sec; struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; localtime_r(&now, &tm); if ((tm.tm_gmtoff < 0) && ((-tm.tm_gmtoff) > (long)real.tv_sec)) { real = log_time::EPOCH; } else { real.tv_sec += tm.tm_gmtoff; } if (monotonic > real) { correction = log_time::EPOCH; } else { correction = real - monotonic; } } void LogKlog::sniffTime(log_time& now, const char*& buf, ssize_t len, bool reverse) { if (len <= 0) return; const char* cp = nullptr; if ((len > 10) && (*buf == '[')) { cp = now.strptime(buf, "[ %s.%q]"); // can index beyond buffer bounds if (cp && (cp > &buf[len - 1])) cp = nullptr; } if (cp) { len -= cp - buf; if ((len > 0) && isspace(*cp)) { ++cp; --len; } buf = cp; if (isMonotonic()) return; const char* b; if (((b = android::strnstr(cp, len, suspendStr))) && (((b += strlen(suspendStr)) - cp) < len)) { len -= b - cp; calculateCorrection(now, b, len); } else if (((b = android::strnstr(cp, len, resumeStr))) && (((b += strlen(resumeStr)) - cp) < len)) { len -= b - cp; calculateCorrection(now, b, len); } else if (((b = android::strnstr(cp, len, healthdStr))) && (((b += strlen(healthdStr)) - cp) < len) && ((b = android::strnstr(b, len -= b - cp, batteryStr))) && (((b += strlen(batteryStr)) - cp) < len)) { // NB: healthd is roughly 150us late, so we use it instead to // trigger a check for ntp-induced or hardware clock drift. log_time real(CLOCK_REALTIME); log_time mono(CLOCK_MONOTONIC); correction = (real < mono) ? log_time::EPOCH : (real - mono); } else if (((b = android::strnstr(cp, len, suspendedStr))) && (((b += strlen(suspendStr)) - cp) < len)) { len -= b - cp; log_time real; char* endp; real.tv_sec = strtol(b, &endp, 10); if ((*endp == '.') && ((endp - b) < len)) { unsigned long multiplier = NS_PER_SEC; real.tv_nsec = 0; len -= endp - b; while (--len && isdigit(*++endp) && (multiplier /= 10)) { real.tv_nsec += (*endp - '0') * multiplier; } if (reverse) { if (real > correction) { correction = log_time::EPOCH; } else { correction -= real; } } else { correction += real; } } } convertMonotonicToReal(now); } else { if (isMonotonic()) { now = log_time(CLOCK_MONOTONIC); } else { now = log_time(CLOCK_REALTIME); } } } pid_t LogKlog::sniffPid(const char*& buf, ssize_t len) { if (len <= 0) return 0; const char* cp = buf; // sscanf does a strlen, let's check if the string is not nul terminated. // pseudo out-of-bounds access since we always have an extra char on buffer. if (((ssize_t)strnlen(cp, len) == len) && cp[len]) { return 0; } // HTC kernels with modified printk "c0 1648 " if ((len > 9) && (cp[0] == 'c') && isdigit(cp[1]) && (isdigit(cp[2]) || (cp[2] == ' ')) && (cp[3] == ' ')) { bool gotDigit = false; int i; for (i = 4; i < 9; ++i) { if (isdigit(cp[i])) { gotDigit = true; } else if (gotDigit || (cp[i] != ' ')) { break; } } if ((i == 9) && (cp[i] == ' ')) { int pid = 0; char dummy; if (sscanf(cp + 4, "%d%c", &pid, &dummy) == 2) { buf = cp + 10; // skip-it-all return pid; } } } while (len) { // Mediatek kernels with modified printk if (*cp == '[') { int pid = 0; char dummy; if (sscanf(cp, "[%d:%*[a-z_./0-9:A-Z]]%c", &pid, &dummy) == 2) { return pid; } break; // Only the first one } ++cp; --len; } return 0; } // kernel log prefix, convert to a kernel log priority number static int parseKernelPrio(const char*& buf, ssize_t len) { int pri = LOG_USER | LOG_INFO; const char* cp = buf; if ((len > 0) && (*cp == '<')) { pri = 0; while (--len && isdigit(*++cp)) { pri = (pri * 10) + *cp - '0'; } if ((len > 0) && (*cp == '>')) { ++cp; } else { cp = buf; pri = LOG_USER | LOG_INFO; } buf = cp; } return pri; } // Passed the entire SYSLOG_ACTION_READ_ALL buffer and interpret a // compensated start time. void LogKlog::synchronize(const char* buf, ssize_t len) { const char* cp = android::strnstr(buf, len, suspendStr); if (!cp) { cp = android::strnstr(buf, len, resumeStr); if (!cp) return; } else { const char* rp = android::strnstr(buf, len, resumeStr); if (rp && (rp < cp)) cp = rp; } do { --cp; } while ((cp > buf) && (*cp != '\n')); if (*cp == '\n') { ++cp; } parseKernelPrio(cp, len - (cp - buf)); log_time now; sniffTime(now, cp, len - (cp - buf), true); const char* suspended = android::strnstr(buf, len, suspendedStr); if (!suspended || (suspended > cp)) { return; } cp = suspended; do { --cp; } while ((cp > buf) && (*cp != '\n')); if (*cp == '\n') { ++cp; } parseKernelPrio(cp, len - (cp - buf)); sniffTime(now, cp, len - (cp - buf), true); } // Convert kernel log priority number into an Android Logger priority number static int convertKernelPrioToAndroidPrio(int pri) { switch (pri & LOG_PRIMASK) { case LOG_EMERG: // FALLTHRU case LOG_ALERT: // FALLTHRU case LOG_CRIT: return ANDROID_LOG_FATAL; case LOG_ERR: return ANDROID_LOG_ERROR; case LOG_WARNING: return ANDROID_LOG_WARN; default: // FALLTHRU case LOG_NOTICE: // FALLTHRU case LOG_INFO: break; case LOG_DEBUG: return ANDROID_LOG_DEBUG; } return ANDROID_LOG_INFO; } static const char* strnrchr(const char* s, ssize_t len, char c) { const char* save = nullptr; for (; len > 0; ++s, len--) { if (*s == c) { save = s; } } return save; } // // log a message into the kernel log buffer // // Filter rules to parse <PRI> <TIME> <tag> and <message> in order for // them to appear correct in the logcat output: // // LOG_KERN (0): // <PRI>[<TIME>] <tag> ":" <message> // <PRI>[<TIME>] <tag> <tag> ":" <message> // <PRI>[<TIME>] <tag> <tag>_work ":" <message> // <PRI>[<TIME>] <tag> '<tag>.<num>' ":" <message> // <PRI>[<TIME>] <tag> '<tag><num>' ":" <message> // <PRI>[<TIME>] <tag>_host '<tag>.<num>' ":" <message> // (unimplemented) <PRI>[<TIME>] <tag> '<num>.<tag>' ":" <message> // <PRI>[<TIME>] "[INFO]"<tag> : <message> // <PRI>[<TIME>] "------------[ cut here ]------------" (?) // <PRI>[<TIME>] "---[ end trace 3225a3070ca3e4ac ]---" (?) // LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, LOG_SYSLOG, LOG_LPR, LOG_NEWS // LOG_UUCP, LOG_CRON, LOG_AUTHPRIV, LOG_FTP: // <PRI+TAG>[<TIME>] (see sys/syslog.h) // Observe: // Minimum tag length = 3 NB: drops things like r5:c00bbadf, but allow PM: // Maximum tag words = 2 // Maximum tag length = 16 NB: we are thinking of how ugly logcat can get. // Not a Tag if there is no message content. // leading additional spaces means no tag, inherit last tag. // Not a Tag if <tag>: is "ERROR:", "WARNING:", "INFO:" or "CPU:" // Drop: // empty messages // messages with ' audit(' in them if auditd is running // logd.klogd: // return -1 if message logd.klogd: <signature> // int LogKlog::log(const char* buf, ssize_t len) { if (auditd && android::strnstr(buf, len, auditStr)) { return 0; } const char* p = buf; int pri = parseKernelPrio(p, len); log_time now; sniffTime(now, p, len - (p - buf), false); // sniff for start marker const char* start = android::strnstr(p, len - (p - buf), klogdStr); if (start) { uint64_t sig = strtoll(start + strlen(klogdStr), nullptr, 10); if (sig == signature.nsec()) { if (initialized) { enableLogging = true; } else { enableLogging = false; } return -1; } return 0; } if (!enableLogging) { return 0; } // Parse pid, tid and uid const pid_t pid = sniffPid(p, len - (p - buf)); const pid_t tid = pid; uid_t uid = AID_ROOT; if (pid) { logbuf->wrlock(); uid = logbuf->pidToUid(pid); logbuf->unlock(); } // Parse (rules at top) to pull out a tag from the incoming kernel message. // Some may view the following as an ugly heuristic, the desire is to // beautify the kernel logs into an Android Logging format; the goal is // admirable but costly. while ((p < &buf[len]) && (isspace(*p) || !*p)) { ++p; } if (p >= &buf[len]) { // timestamp, no content return 0; } start = p; const char* tag = ""; const char* etag = tag; ssize_t taglen = len - (p - buf); const char* bt = p; static const char infoBrace[] = "[INFO]"; static const ssize_t infoBraceLen = strlen(infoBrace); if ((taglen >= infoBraceLen) && !fastcmp<strncmp>(p, infoBrace, infoBraceLen)) { // <PRI>[<TIME>] "[INFO]"<tag> ":" message bt = p + infoBraceLen; taglen -= infoBraceLen; } const char* et; for (et = bt; (taglen > 0) && *et && (*et != ':') && !isspace(*et); ++et, --taglen) { // skip ':' within [ ... ] if (*et == '[') { while ((taglen > 0) && *et && *et != ']') { ++et; --taglen; } if (taglen <= 0) { break; } } } const char* cp; for (cp = et; (taglen > 0) && isspace(*cp); ++cp, --taglen) { } // Validate tag ssize_t size = et - bt; if ((taglen > 0) && (size > 0)) { if (*cp == ':') { // ToDo: handle case insensitive colon separated logging stutter: // <tag> : <tag>: ... // One Word tag = bt; etag = et; p = cp + 1; } else if ((taglen > size) && (tolower(*bt) == tolower(*cp))) { // clean up any tag stutter if (!fastcmp<strncasecmp>(bt + 1, cp + 1, size - 1)) { // no match // <PRI>[<TIME>] <tag> <tag> : message // <PRI>[<TIME>] <tag> <tag>: message // <PRI>[<TIME>] <tag> '<tag>.<num>' : message // <PRI>[<TIME>] <tag> '<tag><num>' : message // <PRI>[<TIME>] <tag> '<tag><stuff>' : message const char* b = cp; cp += size; taglen -= size; while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) { } const char* e; for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) { } if ((taglen > 0) && (*cp == ':')) { tag = b; etag = e; p = cp + 1; } } else { // what about <PRI>[<TIME>] <tag>_host '<tag><stuff>' : message static const char host[] = "_host"; static const ssize_t hostlen = strlen(host); if ((size > hostlen) && !fastcmp<strncmp>(bt + size - hostlen, host, hostlen) && !fastcmp<strncmp>(bt + 1, cp + 1, size - hostlen - 1)) { const char* b = cp; cp += size - hostlen; taglen -= size - hostlen; if (*cp == '.') { while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) { } const char* e; for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) { } if ((taglen > 0) && (*cp == ':')) { tag = b; etag = e; p = cp + 1; } } } else { goto twoWord; } } } else { // <PRI>[<TIME>] <tag> <stuff>' : message twoWord: while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) { } const char* e; for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) { } // Two words if ((taglen > 0) && (*cp == ':')) { tag = bt; etag = e; p = cp + 1; } } } // else no tag static const char cpu[] = "CPU"; static const ssize_t cpuLen = strlen(cpu); static const char warning[] = "WARNING"; static const ssize_t warningLen = strlen(warning); static const char error[] = "ERROR"; static const ssize_t errorLen = strlen(error); static const char info[] = "INFO"; static const ssize_t infoLen = strlen(info); size = etag - tag; if ((size <= 1) || // register names like x9 ((size == 2) && (isdigit(tag[0]) || isdigit(tag[1]))) || // register names like x18 but not driver names like en0 ((size == 3) && (isdigit(tag[1]) && isdigit(tag[2]))) || // blacklist ((size == cpuLen) && !fastcmp<strncmp>(tag, cpu, cpuLen)) || ((size == warningLen) && !fastcmp<strncasecmp>(tag, warning, warningLen)) || ((size == errorLen) && !fastcmp<strncasecmp>(tag, error, errorLen)) || ((size == infoLen) && !fastcmp<strncasecmp>(tag, info, infoLen))) { p = start; etag = tag = ""; } // Suppress additional stutter in tag: // eg: [143:healthd]healthd -> [143:healthd] taglen = etag - tag; // Mediatek-special printk induced stutter const char* mp = strnrchr(tag, taglen, ']'); if (mp && (++mp < etag)) { ssize_t s = etag - mp; if (((s + s) < taglen) && !fastcmp<memcmp>(mp, mp - 1 - s, s)) { taglen = mp - tag; } } // Deal with sloppy and simplistic harmless p = cp + 1 etc above. if (len < (p - buf)) { p = &buf[len]; } // skip leading space while ((p < &buf[len]) && (isspace(*p) || !*p)) { ++p; } // truncate trailing space or nuls ssize_t b = len - (p - buf); while ((b > 0) && (isspace(p[b - 1]) || !p[b - 1])) { --b; } // trick ... allow tag with empty content to be logged. log() drops empty if ((b <= 0) && (taglen > 0)) { p = " "; b = 1; } // paranoid sanity check, can not happen ... if (b > LOGGER_ENTRY_MAX_PAYLOAD) { b = LOGGER_ENTRY_MAX_PAYLOAD; } if (taglen > LOGGER_ENTRY_MAX_PAYLOAD) { taglen = LOGGER_ENTRY_MAX_PAYLOAD; } // calculate buffer copy requirements ssize_t n = 1 + taglen + 1 + b + 1; // paranoid sanity check, first two just can not happen ... if ((taglen > n) || (b > n) || (n > (ssize_t)USHRT_MAX) || (n <= 0)) { return -EINVAL; } // Careful. // We are using the stack to house the log buffer for speed reasons. // If we malloc'd this buffer, we could get away without n's USHRT_MAX // test above, but we would then required a max(n, USHRT_MAX) as // truncating length argument to logbuf->log() below. Gain is protection // of stack sanity and speedup, loss is truncated long-line content. char newstr[n]; char* np = newstr; // Convert priority into single-byte Android logger priority *np = convertKernelPrioToAndroidPrio(pri); ++np; // Copy parsed tag following priority memcpy(np, tag, taglen); np += taglen; *np = '\0'; ++np; // Copy main message to the remainder memcpy(np, p, b); np[b] = '\0'; if (!isMonotonic()) { // Watch out for singular race conditions with timezone causing near // integer quarter-hour jumps in the time and compensate accordingly. // Entries will be temporal within near_seconds * 2. b/21868540 static uint32_t vote_time[3]; vote_time[2] = vote_time[1]; vote_time[1] = vote_time[0]; vote_time[0] = now.tv_sec; if (vote_time[1] && vote_time[2]) { static const unsigned near_seconds = 10; static const unsigned timezones_seconds = 900; int diff0 = (vote_time[0] - vote_time[1]) / near_seconds; unsigned abs0 = (diff0 < 0) ? -diff0 : diff0; int diff1 = (vote_time[1] - vote_time[2]) / near_seconds; unsigned abs1 = (diff1 < 0) ? -diff1 : diff1; if ((abs1 <= 1) && // last two were in agreement on timezone ((abs0 + 1) % (timezones_seconds / near_seconds)) <= 2) { abs0 = (abs0 + 1) / (timezones_seconds / near_seconds) * timezones_seconds; now.tv_sec -= (diff0 < 0) ? -abs0 : abs0; } } } // Log message int rc = logbuf->log(LOG_ID_KERNEL, now, uid, pid, tid, newstr, (unsigned short)n); // notify readers if (!rc) { reader->notifyNewLog(); } return rc; }
32.440048
81
0.478987
dylanh333
a7e72a61d5549b381ddee10bd292ffd184542df7
437
cpp
C++
main.cpp
CryFeiFei/KTodo
cee290e69ce050810c23e23b2a24e2849251b7e4
[ "MIT" ]
3
2019-12-12T02:27:25.000Z
2021-06-21T02:48:59.000Z
main.cpp
CryFeiFei/KTodo
cee290e69ce050810c23e23b2a24e2849251b7e4
[ "MIT" ]
null
null
null
main.cpp
CryFeiFei/KTodo
cee290e69ce050810c23e23b2a24e2849251b7e4
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include <QApplication> #include <QWidget> int main(int argc, char *argv[]) { // Q_IMPORT_PLUGIN("D:\\QtVersion\\Qt5.13_Build_X64\\Qt5.13_X64\\plugins"); // QCoreApplication::setLibraryPaths() // QStringList list; // list << QString("D:\\QtVersion\\Qt5.13_Build_X64\\Qt5.13_X64\\plugins"); // QCoreApplication::setLibraryPaths(list); QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
21.85
75
0.709382
CryFeiFei
a7e8e4488ae0bf4f49022b5322e3c2c91d660cc5
146
cpp
C++
GinX/src/GinX/Scene/System.cpp
SvenWalter201/GinX
feb9a4b262815374596fe7fa1d7dadd280879424
[ "MIT" ]
null
null
null
GinX/src/GinX/Scene/System.cpp
SvenWalter201/GinX
feb9a4b262815374596fe7fa1d7dadd280879424
[ "MIT" ]
null
null
null
GinX/src/GinX/Scene/System.cpp
SvenWalter201/GinX
feb9a4b262815374596fe7fa1d7dadd280879424
[ "MIT" ]
null
null
null
#include "gxpch.h" #include "System.h" namespace GinX { System::System(const char* name, Scene* scene) : m_Name(name), m_Scene(scene) { } }
13.272727
47
0.664384
SvenWalter201
a7e90e714e449bfe2ea48319155c5449015fd2a9
1,208
cpp
C++
src/coreclr/tests/src/Interop/PInvoke/Generics/GenericsNative.Point3B.cpp
abock/runtime
b3346807be96f6089fc1538946b3611f607389e2
[ "MIT" ]
6
2020-01-04T14:02:35.000Z
2020-01-05T15:28:09.000Z
src/coreclr/tests/src/Interop/PInvoke/Generics/GenericsNative.Point3B.cpp
abock/runtime
b3346807be96f6089fc1538946b3611f607389e2
[ "MIT" ]
2
2020-06-06T09:07:48.000Z
2020-06-06T09:13:07.000Z
src/coreclr/tests/src/Interop/PInvoke/Generics/GenericsNative.Point3B.cpp
abock/runtime
b3346807be96f6089fc1538946b3611f607389e2
[ "MIT" ]
3
2021-02-10T16:20:05.000Z
2021-03-12T07:55:36.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include <stdio.h> #include <stdint.h> #include <xplatform.h> #include <platformdefines.h> struct Point3B { bool e00; bool e01; bool e02; }; static Point3B Point3BValue = { }; extern "C" DLL_EXPORT Point3B STDMETHODCALLTYPE GetPoint3B(bool e00, bool e01, bool e02) { throw "P/Invoke for Point3<bool> should be unsupported."; } extern "C" DLL_EXPORT void STDMETHODCALLTYPE GetPoint3BOut(bool e00, bool e01, bool e02, Point3B* pValue) { throw "P/Invoke for Point3<bool> should be unsupported."; } extern "C" DLL_EXPORT const Point3B* STDMETHODCALLTYPE GetPoint3BPtr(bool e00, bool e01, bool e02) { throw "P/Invoke for Point3<bool> should be unsupported."; } extern "C" DLL_EXPORT Point3B STDMETHODCALLTYPE AddPoint3B(Point3B lhs, Point3B rhs) { throw "P/Invoke for Point3<bool> should be unsupported."; } extern "C" DLL_EXPORT Point3B STDMETHODCALLTYPE AddPoint3Bs(const Point3B* pValues, uint32_t count) { throw "P/Invoke for Point3<bool> should be unsupported."; }
28.093023
105
0.740066
abock
a7e93e21f1257860f2cf0e26953dafc4857e6049
2,378
cxx
C++
src/max5487/max5487.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
src/max5487/max5487.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
src/max5487/max5487.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
/* * Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <unistd.h> #include <stdlib.h> #include <stdexcept> #include "max5487.hpp" using namespace upm; MAX5487::MAX5487 (int csn) : m_csnPinCtx(csn), m_spi(0) { mraa::Result error = mraa::SUCCESS; m_name = "MAX5487"; if (csn == -1) { throw std::invalid_argument(std::string(__FUNCTION__)); } error = m_csnPinCtx.dir (mraa::DIR_OUT); if (error != mraa::SUCCESS) { throw std::invalid_argument(std::string(__FUNCTION__) + ": mraa_gpio_dir() failed"); } CSOff (); } void MAX5487::setWiperA (uint8_t wiper) { uint8_t data[2] = { 0x00, 0x00}; CSOn (); data[0] = R_WR_WIPER_A; data[1] = wiper; uint8_t* retData = m_spi.write(data, 2); CSOff (); } void MAX5487::setWiperB (uint8_t wiper) { uint8_t data[2] = { 0x00, 0x00}; CSOn (); data[0] = R_WR_WIPER_B; data[1] = wiper; uint8_t* retData = m_spi.write(data, 2); CSOff (); } /* * ************** * private area * ************** */ mraa::Result MAX5487::CSOn () { return m_csnPinCtx.write(LOW); } mraa::Result MAX5487::CSOff () { return m_csnPinCtx.write(HIGH); }
25.297872
73
0.664844
whpenner
a7eaea2c0ac29e351f4533128da0c9b69586f047
248
cpp
C++
src/common/db_type.cpp
ybbhwxfj/block-db
2482ff6631184ecbc6329db97a2c0f8e19a6711f
[ "Apache-2.0" ]
null
null
null
src/common/db_type.cpp
ybbhwxfj/block-db
2482ff6631184ecbc6329db97a2c0f8e19a6711f
[ "Apache-2.0" ]
null
null
null
src/common/db_type.cpp
ybbhwxfj/block-db
2482ff6631184ecbc6329db97a2c0f8e19a6711f
[ "Apache-2.0" ]
1
2021-12-28T02:25:34.000Z
2021-12-28T02:25:34.000Z
#include "common/db_type.h" db_type global_db_type = DB_S; template<> enum_strings<db_type>::e2s_t enum_strings<db_type>::enum2str = { {DB_S, "db-s"}, {DB_SN, "db-sn"}, {DB_D, "db-d"}, {DB_GRO, "db-gro"}, {DB_TK, "db-tk"}, };
20.666667
75
0.596774
ybbhwxfj
a7eca038df96b999dcfcb67641fb6cb92ec82dce
21,591
cpp
C++
source/sample/transformer/T2TBatchLoader.cpp
xiaozhang521/NASToolkit
a43294f17253af92004209b9e9ada3388aa96fe4
[ "Apache-2.0" ]
2
2020-05-08T08:25:47.000Z
2020-05-18T06:45:58.000Z
source/sample/transformer/T2TBatchLoader.cpp
Daimengli/NiuTensor
3739e29b789801e82cc904c78740accdfc16b889
[ "Apache-2.0" ]
null
null
null
source/sample/transformer/T2TBatchLoader.cpp
Daimengli/NiuTensor
3739e29b789801e82cc904c78740accdfc16b889
[ "Apache-2.0" ]
1
2020-03-13T03:13:03.000Z
2020-03-13T03:13:03.000Z
/* NiuTrans.Tensor - an open-source tensor library * Copyright (C) 2019, Natural Language Processing Lab, Northestern University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Created by: XIAO Tong (xiaotong@mail.neu.edu.cn) 2018-07-31 */ #include "T2TBatchLoader.h" #include "T2TUtility.h" #include "../../tensor/XUtility.h" #include "../../tensor/core/CHeader.h" #include "../../network/XNoder.h" namespace transformer { /* constructor */ T2TBatchLoader::T2TBatchLoader() { seqLen = NULL; seqLen2 = NULL; nseqBuf = 0; nextSeq = -1; nextBatch = -1; buf = NULL; buf2 = NULL; bufBatch = NULL; bufSize = 0; bufBatchSize = 0; seqOffset = NULL; } /* de-constructor */ T2TBatchLoader::~T2TBatchLoader() { delete[] buf; delete[] buf2; delete[] bufBatch; delete[] seqLen; delete[] seqLen2; delete[] seqOffset; } /* initialization >> argc - number of arguments >> argv - list of pointers to the arguments */ void T2TBatchLoader::Init(int argc, char ** argv) { LoadParamInt(argc, argv, "bufsize", &bufSize, 50000); LoadParamBool(argc, argv, "doubledend", &isDoubledEnd, false); LoadParamBool(argc, argv, "smallbatch", &isSmallBatch, true); LoadParamBool(argc, argv, "bigbatch", &isBigBatch, false); LoadParamBool(argc, argv, "randbatch", &isRandomBatch, false); LoadParamInt(argc, argv, "bucketsize", &bucketSize, 0); buf = new int[bufSize]; buf2 = new int[bufSize]; bufBatch = new BatchNode[bufSize]; seqLen = new int[bufSize]; seqLen2 = new int[bufSize]; seqOffset = new int[bufSize]; } char line[MAX_SEQUENCE_LENGTH]; struct SampleNode { int id; int offset; int * p; int size; int value; int key; }; int CompareSampleNode(const void * a, const void * b) { return ((SampleNode*)b)->value - ((SampleNode*)a)->value; } int CompareSampleNodeV2(const void * a, const void * b) { return ((SampleNode*)b)->key - ((SampleNode*)a)->key; } /* load data to buffer >> file - where to load data >> isSorted - indicates whether the samples are sorted by length >> step - the number of sequences we go over when move to the next sample */ int T2TBatchLoader::LoadBuf(FILE * file, bool isSorted, int step) { int lineCount = 0; int seqCount = 0; int wordCount = 0; while(fgets(line, MAX_SEQUENCE_LENGTH - 1, file)){ int len = (int)strlen(line); while(line[len - 1] == '\r' || line[len - 1] == '\n'){ line[len - 1] = 0; len--; } len = (int)strlen(line); if(len == 0) continue; /* how many characters are in a word */ int wSize = 0; /* how many words are in the sentence */ int wNum = 0; int wNumLocal = 0; int i = 0; for(i = 0; i < len; i++){ /* load word (id) seperated by space or tab */ if((line[i] == ' ' || line[i] == '\t') && wSize > 0){ line[i] = 0; if(wSize == 3 && line[i - 1] == '|' && line[i - 2] == '|' && line[i - 3] == '|'){ seqLen[seqCount] = wNumLocal; seqOffset[seqCount] = wordCount + wNum - wNumLocal; seqCount++; wNumLocal = 0; } else{ buf[wordCount + wNum++] = atoi(line + i - wSize); wNumLocal++; } wSize = 0; } else wSize++; } if(wSize > 0){ buf[wordCount + wNum++] = atoi(line + i - wSize); wNumLocal++; } seqLen[seqCount] = wNumLocal; seqOffset[seqCount] = wordCount + wNum - wNumLocal; seqCount++; wordCount += wNum; lineCount++; if(wordCount >= bufSize - MAX_SEQUENCE_LENGTH) break; CheckNTErrors(seqCount % step == 0, "Wrong number of sequences!"); } nseqBuf = seqCount; nextSeq = 0; /* sort the sequences by length */ if (isSorted) { CheckNTErrors(seqCount % step == 0, "Wrong number of sequences!"); SampleNode * nodes = new SampleNode[seqCount]; int count = 0; int offset = 0; for (int i = 0; i < seqCount; i += step) { SampleNode &node = nodes[count]; node.id = count; node.offset = i; node.p = buf + offset; node.size = 0; int max = 0; for (int j = 0; j < step; j++) { node.size += seqLen[i + j]; max = MAX(max, seqLen[i + j]); } node.value = max; node.key = rand(); count++; offset += node.size; } qsort(nodes, count, sizeof(SampleNode), CompareSampleNode); /* distribute samples into buckets. In each bucket, sequences have similar a length */ if (bucketSize > 0) { int low = 0; int high = low + bucketSize; int n = count - 1; int m = n; int num = 0; while (num < count) { for (m = n; m >= 0; m--) { if (nodes[m].value > high) break; } qsort(nodes + m + 1, n - m, sizeof(SampleNode), CompareSampleNodeV2); num += (n - m); n = m; low += bucketSize; high = low + bucketSize; } } count = 0; offset = 0; for(int i = 0; i < seqCount; i += step){ SampleNode &node = nodes[count]; memcpy(buf2 + offset, node.p, sizeof(int) * node.size); for(int j = 0; j < step; j++){ seqLen2[i + j] = seqLen[node.offset + j]; seqOffset[i + j] = offset + (j > 0 ? seqLen[node.offset + j - 1] : 0); } count += 1; offset += node.size; } int * tmp = buf; buf = buf2; buf2 = tmp; tmp = seqLen; seqLen = seqLen2; seqLen2 = tmp; delete[] nodes; } return lineCount; } /* clear the data buffer */ void T2TBatchLoader::ClearBuf() { nseqBuf = 0; nextSeq = -1; } /* set the random batch flag >> flag - as it is */ void T2TBatchLoader::SetRandomBatch(bool flag) { isRandomBatch = flag; } /* load a batch of sequences >> file - the handle to the data file >> isLM - indicates whether the data is used for training lms >> batchEnc - the batch of the input sequences >> paddingEnc - padding of the input sequences >> batchDec - the batch of the output sequences >> paddingDec - padding of the output sequences >> gold - gold standard >> seqs - keep the sequences in an array >> vsEnc - size of the encoder vocabulary >> vsDec - size of the decoder vocabulary >> sBatch - batch size of sequences >> wBatch - batch size of words >> isSorted - indicates whether the sequences are sorted by length >> wCount - word count >> devID - device id >> isTraining - indicates whether we are training the model */ int T2TBatchLoader::LoadBatch(FILE * file, bool isLM, XTensor * batchEnc, XTensor * paddingEnc, XTensor * batchDec, XTensor * paddingDec, XTensor * gold, XTensor * label, int * seqs, int vsEnc, int vsDec, int sBatch, int wBatch, bool isSorted, int &ws, int &wCount, int devID, bool isTraining) { if(isLM){ return LoadBatchLM(file, batchEnc, paddingEnc, batchDec, paddingDec, gold, label, seqs, vsEnc, sBatch, wBatch, isSorted, wCount, devID, isTraining); } else{ return LoadBatchMT(file, batchEnc, paddingEnc, batchDec, paddingDec, gold, label, seqs, vsEnc, vsDec, sBatch, wBatch, isSorted, ws, wCount, devID, isTraining); } } /* load a batch of sequences (for LM) >> file - the handle to the data file >> isLM - indicates whether the data is used for training lms >> batchEnc - the batch of the input sequences >> paddingEnc - padding of the input sequences >> batchDec - the batch of the output sequences >> paddingDec - padding of the output sequences >> gold - gold standard (distribution of every position) >> label - (gold standard) label index of every position >> seqs - keep the sequences in an array >> vSize - vocabulary size >> sBatch - batch size of sequences >> wBatch - batch size of words >> isSorted - indicates whether the sequences are sorted by length >> wCount - word count >> devID - device id >> isTraining - indicates whether we are training the model */ int T2TBatchLoader::LoadBatchLM(FILE * file, XTensor * batchEnc, XTensor * paddingEnc, XTensor * batchDec, XTensor * paddingDec, XTensor * gold, XTensor * label, int * seqs, int vSize, int sBatch, int wBatch, bool isSorted, int &wCount, int devID, bool isTraining) { if(nextSeq < 0 || nextSeq >= nseqBuf) LoadBuf(file, isSorted, 1); int seq = MAX(nextSeq, 0); int wc = 0; int wn = 0; int sc = 0; int max = 0; while(seq + sc < nseqBuf){ int len = isDoubledEnd ? seqLen[seq + sc] : seqLen[seq + sc] - 1; CheckNTErrors(len > 0, "Empty sequence!"); wn = len; wc += wn; sc += 1; if(max < wn) max = wn; int tc = isBigBatch ? wc : max * sc; if(sc >= sBatch && tc >= wBatch) break; } wCount = 0; nextSeq = seq + sc; if(sc <= 0) return 0; int dims[MAX_TENSOR_DIM_NUM]; dims[0] = sc; dims[1] = max; dims[2] = vSize; InitTensor2D(batchEnc, sc, max, X_INT, devID); InitTensor2D(label, sc, max, X_INT, devID); InitTensor(gold, 3, dims, X_FLOAT, devID); InitTensor2D(paddingEnc, sc, max, X_FLOAT, devID); InitTensor2D(paddingDec, sc, max, X_FLOAT, devID); batchEnc->SetZeroAll(); label->SetZeroAll(); gold->SetZeroAll(); paddingEnc->SetZeroAll(); paddingDec->SetZeroAll(); int seqSize = 0; int * batchEncValues = new int[batchEnc->unitNum]; int * labelValues = new int[label->unitNum]; MTYPE * goldOffsets = new MTYPE[gold->unitNum]; MTYPE * paddingEncOffsets = new MTYPE[paddingEnc->unitNum]; MTYPE * paddingDecOffsets = new MTYPE[paddingDec->unitNum]; int wGold = 0; memset(batchEncValues, 0, sizeof(int) * batchEnc->unitNum); memset(labelValues, 0, sizeof(int) * label->unitNum); for(int s = seq; s < seq + sc; s++){ int len = isDoubledEnd ? seqLen[s] : seqLen[s] - 1; CheckNTErrors(len <= max, "Something is wrong!"); for(int w = 0; w < len; w++){ int num = buf[seqOffset[s] + w]; batchEncValues[(int)batchEnc->GetOffset2D(s - seq, w)] = num; paddingEncOffsets[wCount] = paddingEnc->GetOffset2D(s - seq, w); paddingDecOffsets[wCount] = paddingDec->GetOffset2D(s - seq, w); if (w > 0) { goldOffsets[wGold++] = gold->GetOffset3D(s - seq, w - 1, num); labelValues[(int)label->GetOffset2D(s - seq, w - 1)] = buf[seqOffset[s] + w]; } if (w == len - 1) { if (isDoubledEnd) { goldOffsets[wGold++] = gold->GetOffset3D(s - seq, w, num); labelValues[(int)label->GetOffset2D(s - seq, w)] = buf[seqOffset[s] + w]; } else { goldOffsets[wGold++] = gold->GetOffset3D(s - seq, w, buf[seqOffset[s] + w + 1]); labelValues[(int)label->GetOffset2D(s - seq, w)] = buf[seqOffset[s] + w + 1]; } } wCount++; if(seqs != NULL) seqs[seqSize++] = buf[seqOffset[s] + w]; } if(seqs != NULL){ for(int w = len; w < max; w++) seqs[seqSize++] = -1; } } batchEnc->SetData(batchEncValues, batchEnc->unitNum); label->SetData(labelValues, label->unitNum); gold->SetDataBatched(goldOffsets, 1.0F, wGold); paddingEnc->SetDataBatched(paddingEncOffsets, 1.0F, wCount); paddingDec->SetDataBatched(paddingDecOffsets, 1.0F, wCount); /*XTensor * tmp = NewTensorBuf(paddingEnc, devID); _ConvertDataType(batchEnc, tmp); _NotEqual(tmp, paddingEnc, 0); DelTensorBuf(tmp); XTensor * tmp2 = NewTensorBuf(paddingDec, devID); _ConvertDataType(batchEnc, tmp2); _NotEqual(tmp2, paddingDec, 0); DelTensorBuf(tmp2);*/ delete[] batchEncValues; delete[] labelValues; delete[] goldOffsets; delete[] paddingEncOffsets; delete[] paddingDecOffsets; fflush(tf); return sc; } int CompareBatchNode(const void * a, const void * b) { return ((BatchNode*)b)->key - ((BatchNode*)a)->key; } /* load a batch of sequences (for MT) >> file - the handle to the data file >> batchEnc - the batch of the input sequences >> paddingEnc - padding of the input sequences >> batchDec - the batch of the output sequences >> paddingDec - padding of the output sequences >> gold - gold standard (distribution of every position) >> label - (gold standard) label index of every position >> seqs - keep the sequences in an array >> vSizeEnc - size of the encoder vocabulary >> vSizeDec - size of the decoder vocabulary >> sBatch - batch size of sequences >> wBatch - batch size of words >> isSorted - indicates whether the sequences are sorted by length >> wCount - word count >> devID - device id >> isTraining - indicates whether we are training the model */ int T2TBatchLoader::LoadBatchMT(FILE * file, XTensor * batchEnc, XTensor * paddingEnc, XTensor * batchDec, XTensor * paddingDec, XTensor * gold, XTensor * label, int * seqs, int vSizeEnc, int vSizeDec, int sBatch, int wBatch, bool isSorted, int &ws, int &wCount, int devID, bool isTraining) { if (nextBatch < 0 || nextBatch >= bufBatchSize) { LoadBuf(file, isSorted, 2); int seq = 0; bufBatchSize = 0; nextBatch = 0; /* we segment the buffer into batches */ while (seq < nseqBuf) { int wcEnc = 0; int wcDec = 0; int wnEnc = 0; int wnDec = 0; int maxEnc = 0; int maxDec = 0; int sc = 0; while (seq + sc < nseqBuf) { /* source-side sequence */ wnEnc = seqLen[seq + sc]; /* target-side sequence */ wnDec = isDoubledEnd ? seqLen[seq + sc + 1] : seqLen[seq + sc + 1] - 1; int tcEnc = isBigBatch ? (wcEnc + wnEnc) : MAX(maxEnc, wnEnc) * (sc + 2) / 2; int tcDec = isBigBatch ? (wcDec + wnDec) : MAX(maxDec, wnDec) * (sc + 2) / 2; if (sc != 0 && sc > sBatch * 2 && (tcEnc > wBatch || tcDec > wBatch)) break; wcEnc += wnEnc; sc += 1; if (maxEnc < wnEnc) maxEnc = wnEnc; wcDec += wnDec; sc += 1; if (maxDec < wnDec) maxDec = wnDec; } BatchNode & batch = bufBatch[bufBatchSize]; batch.beg = seq; batch.end = seq + sc; batch.maxEnc = maxEnc; batch.maxDec = maxDec; batch.key = rand(); bufBatchSize++; seq = seq + sc; } if(isRandomBatch) qsort(bufBatch, bufBatchSize, sizeof(BatchNode), CompareBatchNode); } if(bufBatchSize <= 0) return 0; BatchNode & batch = bufBatch[nextBatch++]; int seq = batch.beg; int sc = batch.end - batch.beg; int maxEnc = batch.maxEnc; int maxDec = batch.maxDec; CheckNTErrors(sc % 2 == 0, "The input samples must be paired"); int sCount = sc/2; int seqSize = 0; InitTensor2D(batchEnc, sCount, maxEnc, X_INT, devID); InitTensor2D(paddingEnc, sCount, maxEnc, X_FLOAT, devID); InitTensor2D(batchDec, sCount, maxDec, X_INT, devID); InitTensor2D(paddingDec, sCount, maxDec, X_FLOAT, devID); InitTensor2D(label, sCount, maxDec, X_INT, devID); //InitTensor(gold, 3, dimsDec, X_FLOAT, devID); batchEnc->SetZeroAll(); paddingEnc->SetZeroAll(); batchDec->SetZeroAll(); paddingDec->SetZeroAll(); label->SetZeroAll(); //gold->SetZeroAll(); int wCountEnc = 0; int wCountDec = 0; int wCountPad = 0; wCount = 0; int * batchEncValues = new int[batchEnc->unitNum]; int * batchDecValues = new int[batchDec->unitNum]; int * labelValues = new int[label->unitNum]; MTYPE * paddingEncOffsets = new MTYPE[sc * maxEnc / 2]; MTYPE * paddingDecOffsets = new MTYPE[sc * maxDec / 2]; //MTYPE * goldOffsets = new MTYPE[sc * maxDec / 2]; memset(batchEncValues, 0, sizeof(int) * batchEnc->unitNum); memset(batchDecValues, 0, sizeof(int) * batchDec->unitNum); memset(labelValues, 0, sizeof(int) * batchDec->unitNum); /* batch of the source-side sequences */ for(int s = seq; s < seq + sc; s += 2){ int len = seqLen[s]; int sent = (s - seq)/2; for(int w = 0; w < len; w++){ int num = buf[seqOffset[s] + w]; batchEncValues[batchEnc->GetOffset2D(sent, w)] = num; paddingEncOffsets[wCountEnc] = paddingEnc->GetOffset2D(sent, w); wCountEnc++; } } ws = wCountEnc; batchEnc->SetData(batchEncValues, batchEnc->unitNum); paddingEnc->SetDataBatched(paddingEncOffsets, 1.0F, wCountEnc); //XTensor * tmp = NewTensorBuf(paddingEnc, devID); //_ConvertDataType(batchEnc, tmp); //tmp->Dump(stderr, "tmp:"); //_NotEqual(tmp, paddingEnc, 0); //DelTensorBuf(tmp); /* batch of the target-side sequences */ for(int s = seq + 1; s < seq + sc; s += 2){ int len = isDoubledEnd ? seqLen[s] : seqLen[s] - 1; CheckNTErrors(len <= maxDec, "Something is wrong!"); int sent = (s - seq - 1)/2; for(int w = 0; w < len; w++){ int num = buf[seqOffset[s] + w]; batchDecValues[batchDec->GetOffset2D(sent, w)] = num; //paddingDecOffsets[wCountDec] = paddingDec->GetOffset2D(sent, w); if (w < len-1){ paddingDecOffsets[wCountPad++] = paddingDec->GetOffset2D(sent, w); wCount++; } if (w > 0) { //goldOffsets[wGold++] = gold->GetOffset3D(sent, w - 1, buf[seqOffset[s] + w]); labelValues[label->GetOffset2D(sent, w - 1)] = buf[seqOffset[s] + w]; } if (w == len - 1) { if (isDoubledEnd) { //goldOffsets[wGold++] = gold->GetOffset3D(sent, w, buf[seqOffset[s] + w]); labelValues[label->GetOffset2D(sent, w)] = buf[seqOffset[s] + w]; } else { //goldOffsets[wGold++] = gold->GetOffset3D(sent, w, buf[seqOffset[s] + w + 1]); labelValues[label->GetOffset2D(sent, w)] = buf[seqOffset[s] + w + 1]; } } //wCount++; wCountDec++; if(seqs != NULL) seqs[seqSize++] = buf[seqOffset[s] + w]; } if(seqs != NULL){ for(int w = len; w < maxDec; w++) seqs[seqSize++] = -1; } } batchDec->SetData(batchDecValues, batchDec->unitNum); label->SetData(labelValues, label->unitNum); paddingDec->SetDataBatched(paddingDecOffsets, 1.0F, wCountPad); //XTensor * tmp2 = NewTensorBuf(paddingDec, devID); //_ConvertDataType(batchDec, tmp2); //_NotEqual(tmp2, paddingDec, 0); //DelTensorBuf(tmp2); //gold->SetDataBatched(goldOffsets, 1.0F, wGold); delete[] batchEncValues; delete[] batchDecValues; delete[] labelValues; delete[] paddingEncOffsets; delete[] paddingDecOffsets; //delete[] goldOffsets; return sc; } /* shuffle lines of the file >> srcFile - the source file to shuffle >> tgtFile - the resulting file */ void T2TBatchLoader::Shuffle(const char * srcFile, const char * tgtFile) { char * line = new char[MAX_LINE_LENGTH]; #ifndef WIN32 sprintf(line, "shuf %s > %s", srcFile, tgtFile); system(line); #else ShowNTErrors("Cannot shuffle the file on WINDOWS systems!"); #endif delete[] line; } }
31.110951
100
0.547913
xiaozhang521
a7f0c5f6f7868feb829def0cdb75b5f7572d4d1b
3,069
hpp
C++
Source/Debug.hpp
AhsanSarwar45/OpenGLRenderer
d0905c13df5e0a9a2d4e9336d6fc60a770b5f2a2
[ "CC0-1.0" ]
2
2022-02-23T16:54:56.000Z
2022-02-23T18:43:07.000Z
Source/Debug.hpp
AhsanSarwar45/OpenGLRenderer
d0905c13df5e0a9a2d4e9336d6fc60a770b5f2a2
[ "CC0-1.0" ]
null
null
null
Source/Debug.hpp
AhsanSarwar45/OpenGLRenderer
d0905c13df5e0a9a2d4e9336d6fc60a770b5f2a2
[ "CC0-1.0" ]
null
null
null
#pragma once #include <iostream> #include <stddef.h> #include <stdio.h> #define STRINGIZE(arg) STRINGIZE1(arg) #define STRINGIZE1(arg) STRINGIZE2(arg) #define STRINGIZE2(arg) #arg #define CONCATENATE(arg1, arg2) CONCATENATE1(arg1, arg2) #define CONCATENATE1(arg1, arg2) CONCATENATE2(arg1, arg2) #define CONCATENATE2(arg1, arg2) arg1##arg2 #define MEMBER_SIZE(type, member) sizeof(((type*)0)->member) #define PRINT_INFO(structure, field) \ printf(STRINGIZE(field) ": Size: %d bytes, Offset: %d bytes, End: %d bytes\n", MEMBER_SIZE(structure, field), \ offsetof(structure, field), MEMBER_SIZE(structure, field) + offsetof(structure, field)) /* PRN_STRUCT_OFFSETS will print offset of each of the fields within structure passed as the first argument. */ #define PRN_STRUCT_OFFSETS_1(structure, field, ...) PRINT_INFO(structure, field); #define PRN_STRUCT_OFFSETS_2(structure, field, ...) \ PRINT_INFO(structure, field); \ PRN_STRUCT_OFFSETS_1(structure, __VA_ARGS__) #define PRN_STRUCT_OFFSETS_3(structure, field, ...) \ PRINT_INFO(structure, field); \ PRN_STRUCT_OFFSETS_2(structure, __VA_ARGS__) #define PRN_STRUCT_OFFSETS_4(structure, field, ...) \ PRINT_INFO(structure, field); \ PRN_STRUCT_OFFSETS_3(structure, __VA_ARGS__) #define PRN_STRUCT_OFFSETS_5(structure, field, ...) \ PRINT_INFO(structure, field); \ PRN_STRUCT_OFFSETS_4(structure, __VA_ARGS__) #define PRN_STRUCT_OFFSETS_6(structure, field, ...) \ PRINT_INFO(structure, field); \ PRN_STRUCT_OFFSETS_5(structure, __VA_ARGS__) #define PRN_STRUCT_OFFSETS_7(structure, field, ...) \ PRINT_INFO(structure, field); \ PRN_STRUCT_OFFSETS_6(structure, __VA_ARGS__) #define PRN_STRUCT_OFFSETS_8(structure, field, ...) \ PRINT_INFO(structure, field); \ PRN_STRUCT_OFFSETS_7(structure, __VA_ARGS__) #define PRN_STRUCT_OFFSETS_NARG(...) PRN_STRUCT_OFFSETS_NARG_(__VA_ARGS__, PRN_STRUCT_OFFSETS_RSEQ_N()) #define PRN_STRUCT_OFFSETS_NARG_(...) PRN_STRUCT_OFFSETS_ARG_N(__VA_ARGS__) #define PRN_STRUCT_OFFSETS_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, N, ...) N #define PRN_STRUCT_OFFSETS_RSEQ_N() 8, 7, 6, 5, 4, 3, 2, 1, 0 #define PRN_STRUCT_OFFSETS_(N, structure, field, ...) CONCATENATE(PRN_STRUCT_OFFSETS_, N)(structure, field, __VA_ARGS__) #define PRN_STRUCT_OFFSETS(structure, field, ...) \ printf("---------------------------------------------\n"); \ printf("%s: %d\n", #structure, sizeof(structure)); \ PRN_STRUCT_OFFSETS_(PRN_STRUCT_OFFSETS_NARG(field, __VA_ARGS__), structure, field, __VA_ARGS__); \ printf("---------------------------------------------\n")
50.311475
139
0.608993
AhsanSarwar45
a7f375b97ae9ecc6b8a21599abdfc4e787c4abf6
926
hpp
C++
sprout/functional/hash/std/complex.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/functional/hash/std/complex.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/functional/hash/std/complex.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2017 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_FUNCTIONAL_HASH_STD_COMPLEX_HPP #define SPROUT_FUNCTIONAL_HASH_STD_COMPLEX_HPP #include <complex> #include <sprout/config.hpp> #include <sprout/workaround/std/cstddef.hpp> #include <sprout/functional/hash.hpp> namespace sprout { // // hash_value // template<typename T> inline SPROUT_CONSTEXPR std::size_t hash_value(std::complex<T> const& v) { return sprout::hash_values(v.real(), v.imag()); } } // namespace sprout #endif // #ifndef SPROUT_FUNCTIONAL_HASH_STD_COMPLEX_HPP
33.071429
80
0.616631
kariya-mitsuru
a7f3a1b7401ad85d2505b017a0a1e7deb274cabf
1,804
cpp
C++
Win32Sockets/Win32SocketsMain.cpp
kiewic/Projects
a4d3b34c0c552c127cbb0d5e7161352d937725fa
[ "MIT" ]
7
2018-02-26T14:55:16.000Z
2019-12-03T22:33:26.000Z
Win32Sockets/Win32SocketsMain.cpp
kiewic/Projects
a4d3b34c0c552c127cbb0d5e7161352d937725fa
[ "MIT" ]
1
2019-02-13T13:08:32.000Z
2019-02-14T09:05:40.000Z
Win32Sockets/Win32SocketsMain.cpp
kiewic/Projects
a4d3b34c0c552c127cbb0d5e7161352d937725fa
[ "MIT" ]
3
2016-01-22T09:47:17.000Z
2020-04-28T10:23:30.000Z
#include "stdafx.h" void PrintHelp(wchar_t* fileName); HRESULT InitializeWinsock(); int DoTcpServer(); int DoTcpClient(); int DoUdpReceive(); int DoUdpSend(); HRESULT DoDns(wchar_t* argument); int wmain(int argc, wchar_t* argv[]) { int result = 0; HRESULT hr = S_OK; if (FAILED(InitializeWinsock())) { return 1; } if (argc < 3) { PrintHelp(argv[0]); } else if (argc >= 2 && _wcsicmp(argv[1], L"tcp") == 0 && _wcsicmp(argv[2], L"server") == 0) { result = DoTcpServer(); } else if (_wcsicmp(argv[1], L"tcp") == 0 && _wcsicmp(argv[2], L"client") == 0) { result = DoTcpClient(); } else if (_wcsicmp(argv[1], L"udp") == 0 && _wcsicmp(argv[2], L"receive") == 0) { result = DoUdpReceive(); } else if (_wcsicmp(argv[1], L"udp") == 0 && _wcsicmp(argv[2], L"send") == 0) { result = DoUdpSend(); } else if (_wcsicmp(argv[1], L"dns") == 0) { hr = DoDns(argv[2]); } else { PrintHelp(argv[0]); } // Clean. WSACleanup(); if (FAILED(hr)) { return hr; } return result; } void PrintHelp(wchar_t* fileName) { wprintf(L"Usage: %s tcp {{ server | client }}\n", fileName); wprintf(L"Usage: %s udp {{ send | receive }}\n", fileName); wprintf(L"Usage: %s dns {{ <ipv4-address> | <ipv6-address> | <hostname> }}\n", fileName); } HRESULT InitializeWinsock() { WSADATA wsaData; int result = WSAStartup(MAKEWORD(2, 2), &wsaData); if (result != 0) { int error = WSAGetLastError(); wprintf(L"WSAStartup failed with error %d.\n", error); return HRESULT_FROM_WIN32(error); } return S_OK; }
22.271605
95
0.523282
kiewic
a7f4530cf25d6da6ac5bffa9d022cebcee4487d0
19,764
cpp
C++
tools/CMFCompiler/src/main.cpp
MayushKumar/Charcoal-Engine
d9494a5f748686a493389ccf141c80b973019d2e
[ "Apache-2.0" ]
3
2020-04-21T07:08:28.000Z
2022-03-15T17:19:19.000Z
tools/CMFCompiler/src/main.cpp
MayushKumar/Charcoal-Engine
d9494a5f748686a493389ccf141c80b973019d2e
[ "Apache-2.0" ]
1
2020-06-06T13:03:52.000Z
2020-06-06T13:03:52.000Z
tools/CMFCompiler/src/main.cpp
MayushKumar/Charcoal-Engine
d9494a5f748686a493389ccf141c80b973019d2e
[ "Apache-2.0" ]
1
2020-06-06T10:43:25.000Z
2020-06-06T10:43:25.000Z
#include <iostream> #include <string> #include <fstream> #include <cstring> #include <cmath> #include <glm/glm.hpp> #include <glm/gtc/matrix_access.hpp> #include <tiny_obj_loader.h> #include "defines.h" #define DEBUG_WITHOUT_INPUT 1 void LoadWavefrontObject(std::string& filePath); void WriteToFile(CMFFormat* format); TangentVectors CalculateTangentVectors( glm::vec3 e1, glm::vec3 e2, glm::vec2 duv1, glm::vec2 duv2 ); int main(int argc, char* argv[]) { #if DEBUG_WITHOUT_INPUT #else if (argc < 2) { std::cout << "ERROR: Provide a file as a command line argument!" << std::endl; std::cin.get(); return -1; } #endif #if DEBUG_WITHOUT_INPUT std::string filePath = "../../Sandbox/assets/models/cube/cube.gltf"; #else std::string filePath = std::string(argv[1]); #endif std::string fileExt; fileExt = filePath.substr(filePath.find_last_of('.'), filePath.length()); if (!fileExt.compare(".obj")) LoadWavefrontObject(filePath); // else if (!fileExt.compare(".glb")) // LoadBinaryGltfObject(filePath); else if (!fileExt.compare(".gltf")) LoadASCIIGLTF(filePath); else { std::cout << "ERROR: File extension not supported!" << std::endl; std::cin.get(); return -1; } } void LoadWavefrontObject(std::string& filePath) { std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> tinyobjmaterials; std::string warn, err; tinyobj::attrib_t attrib; int slashPos = filePath.find_last_of("/\\"); std::string mtlBaseDir = filePath.substr(0, slashPos == std::string::npos ? 0 : slashPos); std::string fileName = filePath.substr(filePath.find_last_of("/\\") + 1, filePath.find_last_of(".") - (filePath.find_last_of("/\\")) - 1); bool success = tinyobj::LoadObj(&attrib, &shapes, &tinyobjmaterials, &warn, &err, filePath.c_str(), mtlBaseDir.c_str()); if (!warn.empty()) { std::cout << "WARNING loading Wavefront object: " << warn << std::endl; } if (!err.empty()) { std::cout << "ERROR loading Wavefront object: " << err << std::endl; } if (!success) { std::cout << "Could not load file!" << std::endl; std::cin.get(); DEBUG_BREAK(); } //////////////// MATERIALS //////////////// std::vector<CMFFormat::Material> materials; std::vector<std::vector<CMFFormat::Material::Texture>> texturesBuffers; std::vector<uint32_t> textureIndicesMap; // Maps tinyobjloader texture indices to the original indices beingh stored in the texture buffers for (uint32_t i = 0; i < tinyobjmaterials.size(); i++) { CMFFormat::Material material; auto& tinyobjmaterial = tinyobjmaterials[i]; material.NameSize = tinyobjmaterial.name.size() + 1; material.Name = new char[material.NameSize]; strcpy(material.Name, tinyobjmaterial.name.c_str()); material.ID = i; std::vector<CMFFormat::Material::Texture> textures; if (!tinyobjmaterials[i].diffuse_texname.empty()) { CMFFormat::Material::Texture tex = CMFFormat::Material::Texture(); tex.TextureType = (uint32_t)TextureType::Albedo; tex.RelativeFilepathSize = tinyobjmaterial.diffuse_texname.size() + 1; tex.RelativeFilepath = new char[tex.RelativeFilepathSize]; strcpy(tex.RelativeFilepath, tinyobjmaterial.diffuse_texname.c_str()); textures.push_back(tex); } if (!tinyobjmaterials[i].normal_texname.empty()) { CMFFormat::Material::Texture tex; tex.TextureType = (uint32_t)TextureType::Normal; tex.RelativeFilepathSize = tinyobjmaterial.normal_texname.size() + 1; tex.RelativeFilepath = new char[tex.RelativeFilepathSize]; strcpy(tex.RelativeFilepath, tinyobjmaterial.normal_texname.c_str()); textures.push_back(tex); } if (!tinyobjmaterials[i].metallic_texname.empty()) { CMFFormat::Material::Texture tex; tex.TextureType = (uint32_t)TextureType::Metallic; tex.RelativeFilepathSize = tinyobjmaterial.metallic_texname.size() + 1; tex.RelativeFilepath = new char[tex.RelativeFilepathSize]; strcpy(tex.RelativeFilepath, tinyobjmaterial.metallic_texname.c_str()); textures.push_back(tex); } if (!tinyobjmaterials[i].roughness_texname.empty()) { CMFFormat::Material::Texture tex; tex.TextureType = (uint32_t)TextureType::Roughness; tex.RelativeFilepathSize = tinyobjmaterial.roughness_texname.size() + 1; tex.RelativeFilepath = new char[tex.RelativeFilepathSize]; strcpy(tex.RelativeFilepath, tinyobjmaterial.roughness_texname.c_str()); textures.push_back(tex); } texturesBuffers.push_back(textures); material.AmbientColour[0] = tinyobjmaterials[i].ambient[0]; material.AmbientColour[1] = tinyobjmaterials[i].ambient[1]; material.AmbientColour[2] = tinyobjmaterials[i].ambient[2]; material.DiffuseColour[0] = tinyobjmaterials[i].diffuse[0]; material.DiffuseColour[1] = tinyobjmaterials[i].diffuse[1]; material.DiffuseColour[2] = tinyobjmaterials[i].diffuse[2]; material.MetallicFactor = tinyobjmaterials[i].metallic; material.RoughnessFactor = tinyobjmaterials[i].roughness; material.TextureCount = texturesBuffers[i].size(); material.Textures = texturesBuffers[i].data(); materials.push_back(material); } //////////////// GEOMETRY //////////////// std::vector<CMFFormat::Mesh> meshes; //Attribs std::vector<std::vector<CMFFormat::VertexAttrib>> vertexAttribs; std::vector<std::vector<float>> positionsBuffers; std::vector<std::vector<float>> normalsBuffers; std::vector<std::vector<float>> tangentsBuffers; std::vector<std::vector<float>> bitangentsBuffers; std::vector<std::vector<float>> texCoordsBuffers; std::vector<std::vector<uint32_t>> indexBuffers; for (uint32_t i = 0; i < shapes.size(); i++) { auto& tinyobjIndices = shapes[i].mesh.indices; const uint32_t materialID = shapes[i].mesh.material_ids[0]; for (int ID : shapes[i].mesh.material_ids) { if (ID != materialID) { std::cout << "ERROR: Conflicting Material IDs within the same Mesh"; std::cin.get(); } } CMFFormat::Mesh mesh; mesh.NameSize = shapes[i].name.size() + 1; mesh.Name = (char*)shapes[i].name.c_str(); mesh.MaterialID = materialID; std::vector<float> positions; std::vector<float> normals; std::vector<float> tangents; std::vector<float> bitangents; std::vector<float> texCoords; std::vector<uint32_t> indices; std::vector<std::vector<uint32_t>> texCoordIndicesPerVertex; std::vector<std::vector<uint32_t>> normalIndicesPerVertex; std::vector<std::vector<uint32_t>> tangentsIndicesPerVertex; std::vector<uint32_t> offsetFromOriginalVertex; std::vector<uint32_t> cumulativeVertices; indices.resize(tinyobjIndices.size()); texCoordIndicesPerVertex.resize(attrib.vertices.size() / 3); normalIndicesPerVertex.resize(attrib.vertices.size() / 3); tangentsIndicesPerVertex.resize(attrib.vertices.size() / 3); offsetFromOriginalVertex.resize(tinyobjIndices.size()); std::vector<TangentVectors> tempTangentsBuffer; for (uint32_t j = 0; j < tinyobjIndices.size(); j++) { uint32_t vertexIndex = tinyobjIndices[j].vertex_index; uint32_t normalIndex = tinyobjIndices[j].normal_index; uint32_t tangentsIndex = j / 3; // Increments tangents index every 3 indices uint32_t texCoordIndex = tinyobjIndices[j].texcoord_index >= 0 ? tinyobjIndices[j].texcoord_index : 0; if (texCoordIndicesPerVertex[vertexIndex].size()) { bool exists = false; for (uint32_t k = 0; k < texCoordIndicesPerVertex[vertexIndex].size(); k++) { if (texCoordIndicesPerVertex[vertexIndex][k] == texCoordIndex && normalIndicesPerVertex[vertexIndex][k] == normalIndex) { //Vertex Exists offsetFromOriginalVertex[j] = k; exists = true; break; } } if (!exists) { //Duplicate Vertex offsetFromOriginalVertex[j] = texCoordIndicesPerVertex[vertexIndex].size(); texCoordIndicesPerVertex[vertexIndex].push_back(texCoordIndex); normalIndicesPerVertex[vertexIndex].push_back(normalIndex); tangentsIndicesPerVertex[vertexIndex].push_back(tangentsIndex); } } else { //New Vertex texCoordIndicesPerVertex[vertexIndex].push_back(texCoordIndex); normalIndicesPerVertex[vertexIndex].push_back(normalIndex); tangentsIndicesPerVertex[vertexIndex].push_back(tangentsIndex); offsetFromOriginalVertex[j] = 0; } // Calculate Tangent Vectors if (j % 3 == 0) { tempTangentsBuffer.push_back(CalculateTangentVectors( {attrib.vertices[tinyobjIndices[j + 1].vertex_index * 3] - attrib.vertices[tinyobjIndices[j].vertex_index * 3], attrib.vertices[tinyobjIndices[j + 1].vertex_index * 3 + 1] - attrib.vertices[tinyobjIndices[j].vertex_index * 3 + 1], attrib.vertices[tinyobjIndices[j + 1].vertex_index * 3 + 2] - attrib.vertices[tinyobjIndices[j].vertex_index * 3 + 2]}, {attrib.vertices[tinyobjIndices[j + 2].vertex_index * 3] - attrib.vertices[tinyobjIndices[j].vertex_index * 3], attrib.vertices[tinyobjIndices[j + 2].vertex_index * 3 + 1] - attrib.vertices[tinyobjIndices[j].vertex_index * 3 + 1], attrib.vertices[tinyobjIndices[j + 2].vertex_index * 3 + 2] - attrib.vertices[tinyobjIndices[j].vertex_index * 3 + 2]}, {attrib.texcoords[tinyobjIndices[j + 1].texcoord_index * 2] - attrib.texcoords[tinyobjIndices[j].texcoord_index * 2], attrib.texcoords[tinyobjIndices[j + 1].texcoord_index * 2 + 1] - attrib.texcoords[tinyobjIndices[j].texcoord_index * 2 + 1]}, {attrib.texcoords[tinyobjIndices[j + 2].texcoord_index * 2] - attrib.texcoords[tinyobjIndices[j].texcoord_index * 2], attrib.texcoords[tinyobjIndices[j + 2].texcoord_index * 2 + 1] - attrib.texcoords[tinyobjIndices[j].texcoord_index * 2 + 1]} )); } } cumulativeVertices.resize(texCoordIndicesPerVertex.size()); //Appending offsets uint32_t generatedVerticesCount = 0; for (uint32_t j = 0; j < texCoordIndicesPerVertex.size(); j++) { for (uint32_t k = 0; k < texCoordIndicesPerVertex[j].size(); k++) { uint32_t texCoordIndex = texCoordIndicesPerVertex[j][k]; uint32_t normalIndex = normalIndicesPerVertex[j][k]; uint32_t tangentsIndex = tangentsIndicesPerVertex[j][k]; positions.push_back(attrib.vertices[j * 3]); positions.push_back(attrib.vertices[j * 3 + 1]); positions.push_back(attrib.vertices[j * 3 + 2]); normals.push_back(attrib.normals[normalIndex * 3]); normals.push_back(attrib.normals[normalIndex * 3 + 1]); normals.push_back(attrib.normals[normalIndex * 3 + 2]); tangents.push_back(tempTangentsBuffer[tangentsIndex].Tangent[0]); tangents.push_back(tempTangentsBuffer[tangentsIndex].Tangent[1]); tangents.push_back(tempTangentsBuffer[tangentsIndex].Tangent[2]); bitangents.push_back(tempTangentsBuffer[tangentsIndex].Bitangent[0]); bitangents.push_back(tempTangentsBuffer[tangentsIndex].Bitangent[1]); bitangents.push_back(tempTangentsBuffer[tangentsIndex].Bitangent[2]); texCoords.push_back(attrib.texcoords[texCoordIndex * 2]); texCoords.push_back(attrib.texcoords[texCoordIndex * 2 + 1]); } if (j == 0) { cumulativeVertices[j] = 0; } else { generatedVerticesCount += texCoordIndicesPerVertex[j - 1].size(); cumulativeVertices[j] = generatedVerticesCount; } } positionsBuffers.push_back(positions); normalsBuffers.push_back(normals); tangentsBuffers.push_back(tangents); bitangentsBuffers.push_back(bitangents); texCoordsBuffers.push_back(texCoords); std::vector<CMFFormat::VertexAttrib> attribs; CMFFormat::VertexAttrib positionsAttrib; positionsAttrib.NameSize = 11; positionsAttrib.Name = "a_Position"; positionsAttrib.ShaderDataType = (uint32_t)ShaderDataType::Float3; positionsAttrib.VertexAttribType = (uint32_t)VertexAttribType::Position; positionsAttrib.BufferSize = positionsBuffers[i].size() * sizeof(float); positionsAttrib.Buffer = positionsBuffers[i].data(); CMFFormat::VertexAttrib normalsAttrib; normalsAttrib.NameSize = 9; normalsAttrib.Name = "a_Normal"; normalsAttrib.ShaderDataType = (uint32_t)ShaderDataType::Float3; normalsAttrib.VertexAttribType = (uint32_t)VertexAttribType::Normal; normalsAttrib.BufferSize = normalsBuffers[i].size() * sizeof(float); normalsAttrib.Buffer = normalsBuffers[i].data(); CMFFormat::VertexAttrib tangentsAttrib; tangentsAttrib.NameSize = 10; tangentsAttrib.Name = "a_Tangent"; tangentsAttrib.ShaderDataType = (uint32_t)ShaderDataType::Float3; tangentsAttrib.VertexAttribType = (uint32_t)VertexAttribType::Tangent; tangentsAttrib.BufferSize = tangentsBuffers[i].size() * sizeof(float); tangentsAttrib.Buffer = tangentsBuffers[i].data(); CMFFormat::VertexAttrib bitangentsAttrib; bitangentsAttrib.NameSize = 13; bitangentsAttrib.Name = "a_Bitangents"; bitangentsAttrib.ShaderDataType = (uint32_t)ShaderDataType::Float3; bitangentsAttrib.VertexAttribType = (uint32_t)VertexAttribType::Bitangent; bitangentsAttrib.BufferSize = bitangentsBuffers[i].size() * sizeof(float); bitangentsAttrib.Buffer = bitangentsBuffers[i].data(); CMFFormat::VertexAttrib texCoordsAttrib; texCoordsAttrib.NameSize = 11; texCoordsAttrib.Name = "a_TexCoord"; texCoordsAttrib.ShaderDataType = (uint32_t)ShaderDataType::Float2; texCoordsAttrib.VertexAttribType = (uint32_t)VertexAttribType::TexCoord; texCoordsAttrib.BufferSize = texCoordsBuffers[i].size() * sizeof(float); texCoordsAttrib.Buffer = texCoordsBuffers[i].data(); attribs.push_back(positionsAttrib); attribs.push_back(normalsAttrib); attribs.push_back(tangentsAttrib); attribs.push_back(bitangentsAttrib); attribs.push_back(texCoordsAttrib); vertexAttribs.push_back(attribs); mesh.VertexAttribCount = vertexAttribs[i].size(); mesh.VertexAttribs = vertexAttribs[i].data(); for (uint32_t i = 0; i < tinyobjIndices.size(); i++) { uint32_t index = cumulativeVertices[tinyobjIndices[i].vertex_index] + offsetFromOriginalVertex[i]; indices[i] = index; } indexBuffers.push_back(indices); mesh.IndexBufferSize = indexBuffers[i].size() * sizeof(uint32_t); mesh.IndexBuffer = indexBuffers[i].data(); meshes.push_back(mesh); } ////////////////// WRITING TO FORMAT STRUCT ////////////////// CMFFormat* format = new CMFFormat(); format->NameSize = fileName.size() + 1; format->Name = new char[format->NameSize]; strcpy(format->Name, fileName.c_str()); format->MaterialCount = materials.size(); format->Materials = materials.data(); format->MeshCount = meshes.size(); format->Meshes = meshes.data(); WriteToFile(format); // CLEANUP for (auto& textureBuffer : texturesBuffers) { for(auto& tex: textureBuffer) delete[] tex.RelativeFilepath; } for (auto& material : materials) delete[] material.Name; delete[] format->Name; delete format; } void WriteToFile(CMFFormat* format) { std::ofstream fileStream; char* fullFileName = new char[format->NameSize + 4]; strcpy(fullFileName, format->Name); strcat(fullFileName, ".cmf"); fileStream.open(fullFileName, std::ios::binary); fileStream.write((const char*)&format->HeaderSize, sizeof(format->HeaderSize)); fileStream.write(format->Header, format->HeaderSize); fileStream.write((const char*)&format->NameSize, sizeof(format->NameSize)); fileStream.write(format->Name, format->NameSize); fileStream.write((const char*)&format->MaterialCount, sizeof(format->MaterialCount)); for (uint32_t i = 0; i < format->MaterialCount; i++) { fileStream.write((const char*)&format->Materials[i].NameSize, sizeof(format->Materials[i].NameSize)); fileStream.write(format->Materials[i].Name, format->Materials[i].NameSize); fileStream.write((const char*)&format->Materials[i].ID, sizeof(format->Materials[i].ID)); fileStream.write((const char*)&format->Materials[i].AmbientColour, sizeof(format->Materials[i].AmbientColour)); fileStream.write((const char*)&format->Materials[i].DiffuseColour, sizeof(format->Materials[i].DiffuseColour)); fileStream.write((const char*)&format->Materials[i].MetallicFactor, sizeof(format->Materials[i].MetallicFactor)); fileStream.write((const char*)&format->Materials[i].RoughnessFactor, sizeof(format->Materials[i].RoughnessFactor)); fileStream.write((const char*)&format->Materials[i].TextureCount, sizeof(format->Materials[i].TextureCount)); for (uint32_t j = 0; j < format->Materials[i].TextureCount; j++) { fileStream.write((const char*)&format->Materials[i].Textures[j].TextureType, sizeof(format->Materials[i].Textures[j].TextureType)); fileStream.write((const char*)&format->Materials[i].Textures[j].RelativeFilepathSize, sizeof(format->Materials[i].Textures[j].RelativeFilepathSize)); fileStream.write(format->Materials[i].Textures[j].RelativeFilepath, format->Materials[i].Textures[j].RelativeFilepathSize); } } fileStream.write((const char*)&format->MeshCount, sizeof(format->MeshCount)); for (uint32_t i = 0; i < format->MeshCount; i++) { fileStream.write((const char*)&format->Meshes[i].NameSize, sizeof(format->Meshes[i].NameSize)); fileStream.write(format->Meshes[i].Name, format->Meshes[i].NameSize); fileStream.write((const char*)&format->Meshes[i].MaterialID, sizeof(format->Meshes[i].MaterialID)); fileStream.write((const char*)&format->Meshes[i].VertexAttribCount, sizeof(format->Meshes[i].VertexAttribCount)); for (uint32_t j = 0; j < format->Meshes[i].VertexAttribCount; j++) { fileStream.write((const char*)&format->Meshes[i].VertexAttribs[j].NameSize, sizeof(format->Meshes[i].VertexAttribs[j].NameSize)); fileStream.write(format->Meshes[i].VertexAttribs[j].Name, format->Meshes[i].VertexAttribs[j].NameSize); fileStream.write((const char*)&format->Meshes[i].VertexAttribs[j].ShaderDataType, sizeof(format->Meshes[i].VertexAttribs[j].ShaderDataType)); fileStream.write((const char*)&format->Meshes[i].VertexAttribs[j].VertexAttribType, sizeof(format->Meshes[i].VertexAttribs[j].VertexAttribType)); fileStream.write((const char*)&format->Meshes[i].VertexAttribs[j].BufferSize, sizeof(format->Meshes[i].VertexAttribs[j].BufferSize)); fileStream.write((const char*)format->Meshes[i].VertexAttribs[j].Buffer, format->Meshes[i].VertexAttribs[j].BufferSize); } fileStream.write((const char*)&format->Meshes[i].IndexBufferSize, sizeof(format->Meshes[i].IndexBufferSize)); fileStream.write((const char*)format->Meshes[i].IndexBuffer, format->Meshes[i].IndexBufferSize); } fileStream.write((const char*)&format->FooterSize, sizeof(format->FooterSize)); fileStream.write(format->Footer, format->FooterSize); fileStream.close(); } TangentVectors CalculateTangentVectors( glm::vec3 e1, glm::vec3 e2, glm::vec2 duv1, glm::vec2 duv2 ) { TangentVectors result; e1 = glm::normalize(e1); e2 = glm::normalize(e2); duv1 = glm::normalize(duv1); duv2 = glm::normalize(duv2); glm::mat3x2 edges = glm::transpose(glm::mat2x3(e1, e2)); glm::mat2 uv = glm::transpose(glm::mat2(duv1, duv2)); glm::mat3x2 TB = glm::inverse(uv) * edges; glm::vec3 T = glm::row(TB, 0); glm::vec3 B = glm::row(TB, 1); result.Tangent[0] = T.x; result.Tangent[1] = T.y; result.Tangent[2] = T.z; result.Bitangent[0] = B.x; result.Bitangent[1] = B.y; result.Bitangent[2] = B.z; float test = glm::dot(T, B); return result; }
37.717557
153
0.701275
MayushKumar
a7f57f3934aa458ae2da53ae78ca8b4dfba7b75d
4,705
cpp
C++
SampleMathematics/Delaunay2DInsertRemove/Delaunay2DInsertRemove.cpp
bazhenovc/WildMagic
b1a7cc2140dde23d8d9a4ece52a07bd5ff938239
[ "BSL-1.0" ]
48
2015-10-07T07:26:14.000Z
2022-03-18T14:30:07.000Z
SampleMathematics/Delaunay2DInsertRemove/Delaunay2DInsertRemove.cpp
zouxiaohang/WildMagic
b1a7cc2140dde23d8d9a4ece52a07bd5ff938239
[ "BSL-1.0" ]
null
null
null
SampleMathematics/Delaunay2DInsertRemove/Delaunay2DInsertRemove.cpp
zouxiaohang/WildMagic
b1a7cc2140dde23d8d9a4ece52a07bd5ff938239
[ "BSL-1.0" ]
21
2015-09-01T03:14:47.000Z
2022-01-04T04:07:46.000Z
// Geometric Tools, LLC // Copyright (c) 1998-2012 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.0 (2010/01/01) #include "Delaunay2DInsertRemove.h" WM5_WINDOW_APPLICATION(Delaunay2DInsertRemove); //---------------------------------------------------------------------------- Delaunay2DInsertRemove::Delaunay2DInsertRemove () : WindowApplication2("SampleMathematics/Delaunay2DInsertRemove", 0, 0, 512, 512, Float4(1.0f, 1.0f, 1.0f, 1.0f)) { mDelaunay = 0; mNumVertices = 0; mVertices = 0; mNumTriangles = 0; mIndices = 0; mAdjacencies = 0; mSize = GetWidth(); } //---------------------------------------------------------------------------- bool Delaunay2DInsertRemove::OnInitialize () { if (!WindowApplication2::OnInitialize()) { return false; } // Generate random points and triangulate. mNumVertices = 32; mVertices = new1<Vector2f>(mNumVertices); int i; for (i = 0; i < mNumVertices; ++i) { mVertices[i].X() = mSize*Mathf::IntervalRandom(0.125f, 0.875f); mVertices[i].Y() = mSize*Mathf::IntervalRandom(0.125f, 0.875f); } mDelaunay = new0 IncrementalDelaunay2f(0.0f, 0.0f, (float)mSize, (float)mSize); for (i = 0; i < mNumVertices; ++i) { mDelaunay->Insert(mVertices[i]); } GetMesh(); DoFlip(true); OnDisplay(); return true; } //---------------------------------------------------------------------------- void Delaunay2DInsertRemove::OnTerminate () { delete0(mDelaunay); delete1(mVertices); delete1(mIndices); delete1(mAdjacencies); WindowApplication2::OnTerminate(); } //---------------------------------------------------------------------------- void Delaunay2DInsertRemove::OnDisplay () { ClearScreen(); ColorRGB gray(128, 128, 128); ColorRGB blue(0, 0, 255); int i, x0, y0, x1, y1, x2, y2; Vector2f v0, v1, v2; const std::vector<Vector2f>& vertices = mDelaunay->GetVertices(); // Draw the triangle mesh. std::set<Vector2f> used; for (i = 0; i < mNumTriangles; ++i) { v0 = vertices[mIndices[3*i]]; x0 = (int)(v0.X() + 0.5f); y0 = (int)(v0.Y() + 0.5f); v1 = vertices[mIndices[3*i+1]]; x1 = (int)(v1.X() + 0.5f); y1 = (int)(v1.Y() + 0.5f); v2 = vertices[mIndices[3*i+2]]; x2 = (int)(v2.X() + 0.5f); y2 = (int)(v2.Y() + 0.5f); DrawLine(x0, y0, x1, y1, gray); DrawLine(x1, y1, x2, y2, gray); DrawLine(x2, y2, x0, y0, gray); used.insert(v0); used.insert(v1); used.insert(v2); } // Draw the vertices. std::set<Vector2f>::iterator iter = used.begin(); std::set<Vector2f>::iterator end = used.end(); for (/**/; iter != end; ++iter) { v0 = *iter; x0 = (int)(v0.X() + 0.5f); y0 = (int)(v0.Y() + 0.5f); SetThickPixel(x0, y0, 2, blue); } WindowApplication2::OnDisplay(); } //---------------------------------------------------------------------------- bool Delaunay2DInsertRemove::OnMouseClick (int button, int state, int x, int y, unsigned int modifiers) { Vector2f pos((float)x, (float)(mSize - 1 - y)); if (button == MOUSE_LEFT_BUTTON && state == MOUSE_DOWN) { if (modifiers & KEY_SHIFT) { // Remove a point from the triangulation. int i = mDelaunay->GetContainingTriangle(pos); if (i >= 0) { float bary[3]; mDelaunay->GetBarycentricSet(i, pos, bary); int indices[3]; mDelaunay->GetIndexSet(i, indices); float maxBary = bary[0]; int maxIndex = 0; if (bary[1] > maxBary) { maxBary = bary[1]; maxIndex = 1; } if (bary[2] > maxBary) { maxBary = bary[2]; maxIndex = 2; } pos = mDelaunay->GetVertices()[indices[maxIndex]]; mDelaunay->Remove(pos); GetMesh(); OnDisplay(); } } else { // Insert a point into the triangulation. mDelaunay->Insert(pos); GetMesh(); OnDisplay(); } } return true; } //---------------------------------------------------------------------------- void Delaunay2DInsertRemove::GetMesh () { mDelaunay->GenerateRepresentation(); mNumTriangles = mDelaunay->GetNumTriangles(); delete1(mIndices); mIndices = new1<int>(3*mNumTriangles); size_t numBytes = 3*mNumTriangles*sizeof(int); memcpy(mIndices, mDelaunay->GetIndices(), numBytes); delete1(mAdjacencies); mAdjacencies = new1<int>(3*mNumTriangles); memcpy(mAdjacencies, mDelaunay->GetAdjacencies(), numBytes); } //----------------------------------------------------------------------------
25.570652
79
0.538789
bazhenovc
a7f68294e53a3f81df32ff5229d72597f45951ae
52
cpp
C++
Unreal/CtaCpp/Runtime/Scripts/Core/ReferencePointType.cpp
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
3
2021-06-02T16:44:02.000Z
2022-01-24T20:20:10.000Z
Unreal/CtaCpp/Runtime/Scripts/Core/ReferencePointType.cpp
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
null
null
null
Unreal/CtaCpp/Runtime/Scripts/Core/ReferencePointType.cpp
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
null
null
null
#include "ReferencePointType.h" namespace Cta { }
8.666667
32
0.730769
areilly711
a7f88f5a7299e642c97140d226ea6960771e1114
1,389
cpp
C++
project/src/platform/emscripten/System.cpp
delahee/lime
c4bc1ff140fa27c12f580fa3b518721e2a8266f2
[ "MIT" ]
1
2020-09-16T15:18:39.000Z
2020-09-16T15:18:39.000Z
openfl_lime/src/platform/emscripten/System.cpp
wannaphong/flappy
bc4630ca9120463c57c1d756c39c60a6dc509940
[ "MIT" ]
1
2020-11-17T00:58:59.000Z
2020-11-17T00:58:59.000Z
openfl_lime/src/platform/emscripten/System.cpp
wannaphong/flappy
bc4630ca9120463c57c1d756c39c60a6dc509940
[ "MIT" ]
null
null
null
#include <string> #include <cstdlib> #include <vector> namespace lime { std::string CapabilitiesGetLanguage () { return "en-US"; //char* country = NULL; //char* language = NULL; // //locale_get(&language, &country); // //return std::string(language) + "-" + std::string(country); } //double CapabilitiesGetScreenResolutionX() { // //return 0; // //} //double CapabilitiesGetScreenResolutionY() { // //return 0; // //} double CapabilitiesGetScreenDPI() { return 170; } double CapabilitiesGetPixelAspectRatio() { return 1; } //bool GetAcceleration (double &outX, double &outY, double &outZ) { // //return false; // //} void HapticVibrate (int period, int duration) { } bool LaunchBrowser (const char *inUtf8URL) { return false; //char* err; // //int result = navigator_invoke (inUtf8URL, &err); // //bps_free (err); // //return (result == BPS_SUCCESS); } std::string FileDialogFolder( const std::string &title, const std::string &text ) { return ""; } std::string FileDialogOpen( const std::string &title, const std::string &text, const std::vector<std::string> &fileTypes ) { return ""; } std::string FileDialogSave( const std::string &title, const std::string &text, const std::vector<std::string> &fileTypes ) { return ""; } }
15.263736
126
0.610511
delahee
a7fd6b0cf67d95a07042747142e2fd5580a0d5bf
1,938
cpp
C++
tools/viewer/sk_app/Window.cpp
tmpvar/skia.cc
6e36ba7bf19cc7597837bb0416882ad4d699916b
[ "Apache-2.0" ]
3
2015-08-16T03:44:19.000Z
2015-08-16T17:31:59.000Z
tools/viewer/sk_app/Window.cpp
tmpvar/skia.cc
6e36ba7bf19cc7597837bb0416882ad4d699916b
[ "Apache-2.0" ]
null
null
null
tools/viewer/sk_app/Window.cpp
tmpvar/skia.cc
6e36ba7bf19cc7597837bb0416882ad4d699916b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Window.h" #include "SkSurface.h" #include "SkCanvas.h" #include "VulkanWindowContext.h" namespace sk_app { static bool default_char_func(SkUnichar c, uint32_t modifiers, void* userData) { return false; } static bool default_key_func(Window::Key key, Window::InputState state, uint32_t modifiers, void* userData) { return false; } static bool default_mouse_func(int x, int y, Window::InputState state, uint32_t modifiers, void* userData) { return false; } static void default_paint_func(SkCanvas*, void* userData) {} Window::Window() : fCharFunc(default_char_func) , fKeyFunc(default_key_func) , fMouseFunc(default_mouse_func) , fPaintFunc(default_paint_func) { } void Window::detach() { delete fWindowContext; fWindowContext = nullptr; } bool Window::onChar(SkUnichar c, uint32_t modifiers) { return fCharFunc(c, modifiers, fCharUserData); } bool Window::onKey(Key key, InputState state, uint32_t modifiers) { return fKeyFunc(key, state, modifiers, fKeyUserData); } bool Window::onMouse(int x, int y, InputState state, uint32_t modifiers) { return fMouseFunc(x, y, state, modifiers, fMouseUserData); } void Window::onPaint() { SkSurface* backbuffer = fWindowContext->getBackbufferSurface(); if (backbuffer) { // draw into the canvas of this surface SkCanvas* canvas = backbuffer->getCanvas(); fPaintFunc(canvas, fPaintUserData); canvas->flush(); fWindowContext->swapBuffers(); } else { // try recreating testcontext } } void Window::onResize(uint32_t w, uint32_t h) { fWidth = w; fHeight = h; fWindowContext->resize(w, h); } } // namespace sk_app
24.531646
92
0.666151
tmpvar
a7ff0a05754f96bb2438daec68ff75fadce68b15
3,069
cpp
C++
bin/Cpp/MultiAlign/src/GReader.cpp
enriqueescobar-askida/Kinito.ESTsSuite
5a63af56d686be8376c93ce038899ef323925f67
[ "MIT" ]
null
null
null
bin/Cpp/MultiAlign/src/GReader.cpp
enriqueescobar-askida/Kinito.ESTsSuite
5a63af56d686be8376c93ce038899ef323925f67
[ "MIT" ]
null
null
null
bin/Cpp/MultiAlign/src/GReader.cpp
enriqueescobar-askida/Kinito.ESTsSuite
5a63af56d686be8376c93ce038899ef323925f67
[ "MIT" ]
null
null
null
/*************************************************************************** * Copyright (C) 2007 by Enrique Escobar * * Enrique.Escobar@genome.ulaval.ca * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library 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 Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <iostream> //std io #include <cstdlib> #include <fstream> //file io #include <list> #include <map> #include <string> //#include "GStack.hpp" //#include "GStack.cpp" //#include "Sequence.hpp" #include "StrSet.hpp" using namespace std; //GStack<Sequence> mySeqStack; StrSet myStrSet; int main( int argc, char *argv[] ) { cout << "Beginning!\n"; if ( argc != 3 ) { cerr << "Wrong number of parameters!\n" << endl; return EXIT_FAILURE; } string in_FileName = argv[1]; string outFileName = argv[2]; cerr << "@param1=" << argv[1] << "\t" << "@param2=" << argv[2] << "\n" << endl; if ( in_FileName == outFileName ) { cerr << "Idem parameters!\n" << endl; return EXIT_FAILURE; } ifstream input_Stream( argv[1], ios::in ); if ( input_Stream.fail() ) { cerr << "Cannot open file" << in_FileName << endl; return EXIT_FAILURE; } string str = ""; // Sequence mySeq; while ( input_Stream.good() ) { getline( input_Stream, str ); if( ! input_Stream.eof() ) { // mySeq = Sequence( str ); // mySeqStack.push( mySeq ); myStrSet.insert( str ); cout << ">>" << myStrSet.size() << "\t" << str << "\n"; } else { break; } } ofstream outputStream( argv[2], ios::out ); if ( outputStream.fail() ) { cerr << "Cannot open file" << outFileName << endl; return EXIT_FAILURE; } input_Stream.close(); outputStream.close(); StrSet::iterator StrSetIt; for ( StrSetIt = myStrSet.begin(); StrSetIt != myStrSet.end(); StrSetIt++ ) { cout << *StrSetIt+"\n"; } cout << "\nEnding!\n"; return EXIT_SUCCESS; }
26.008475
82
0.52232
enriqueescobar-askida
c5003c34d95ac9562b1b9b1a93c5d430f6ea9370
553
cpp
C++
codeforces/1101A - Minimum Integer.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
1
2018-12-25T23:55:19.000Z
2018-12-25T23:55:19.000Z
codeforces/1101A - Minimum Integer.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
codeforces/1101A - Minimum Integer.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
//============================================================================ // Problem : 1101A - Minimum Integer // Category : Math //============================================================================ #include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(false); cin.tie(0); ll q,l,r,d,lo,hi; cin >> q; while(q--) { cin >> l >> r >> d; lo = ceil(l*1./d); hi = floor(r*1./d); cout << d*(lo <= 1? hi+1 : 1) << '\n'; } return 0; }
26.333333
78
0.352622
Dijkstraido-2
c5007caf3531b45b001784350636266134b65aff
725
cpp
C++
C++/Katis/RadioCommercials/main.cpp
Gman0064/experiments
00140128c2dcc1dcc4bb3dd9a01768dc29f54946
[ "MIT" ]
null
null
null
C++/Katis/RadioCommercials/main.cpp
Gman0064/experiments
00140128c2dcc1dcc4bb3dd9a01768dc29f54946
[ "MIT" ]
null
null
null
C++/Katis/RadioCommercials/main.cpp
Gman0064/experiments
00140128c2dcc1dcc4bb3dd9a01768dc29f54946
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <sstream> using namespace std; int main() { string n_p; string i; string np_str; string i_str; vector<int> n_p_v; vector<int> i_v; getline(cin, n_p); stringstream n_p_ss(n_p); while(getline(n_p_ss, np_str, ' ')) { n_p_v.push_back(stoi(np_str)); } getline(cin, i); stringstream i_ss(i); while(getline(i_ss, i_str, ' ')) { i_v.push_back(stoi(i_str)); } int best_profit = 0; int current_profit = 0; for (int i : i_v) { current_profit = max(0, current_profit + (i - n_p_v.at(1))); best_profit = max(best_profit, current_profit); } cout << best_profit; return 0; }
19.594595
68
0.590345
Gman0064
c500fcf034ca343a8a0144b6f80e12e1b558bf68
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/failtest/cwiseunaryview_nonconst_ctor_on_const_xpr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/failtest/cwiseunaryview_nonconst_ctor_on_const_xpr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/failtest/cwiseunaryview_nonconst_ctor_on_const_xpr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:9ae677b1c27891a861bde79ee6d32d2708a195daf25fe25d79c571aa38dca581 size 271
32
75
0.882813
initialz
c504c7942fb8b4bcdbb14f0bef2edeae85de0d4c
22,384
cpp
C++
flite/lang/indic_lang/indic_lang.cpp
Barath-Kannan/flite
236f91a9a1e60fd25f1deed6d48022567cd7100f
[ "Apache-2.0" ]
7
2017-12-10T23:02:22.000Z
2021-08-05T21:12:11.000Z
flite/lang/indic_lang/indic_lang.cpp
Barath-Kannan/flite
236f91a9a1e60fd25f1deed6d48022567cd7100f
[ "Apache-2.0" ]
null
null
null
flite/lang/indic_lang/indic_lang.cpp
Barath-Kannan/flite
236f91a9a1e60fd25f1deed6d48022567cd7100f
[ "Apache-2.0" ]
3
2018-10-28T03:47:09.000Z
2020-06-04T08:54:23.000Z
#include "./indic_lang.hpp" #include "flite/flite.hpp" #include "flite/lexicon/lexicon.hpp" #include "flite/synth/ffeatures.hpp" #include "flite/synth/voice.hpp" #include "flite/utils/tokenstream.hpp" #include "flite/utils/val.hpp" // clang-format off /* ./bin/compile_regexes cst_rx_eng_digits_only "^[0-9,]+$" */ static const unsigned char cst_rx_eng_digits_only_rxprog[] = { 156, 6, 0, 27, 1, 0, 3, 11, 0, 18, 4, 0, 0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 44, 0, 2, 0, 3, 0, 0, 0, }; static const cst_regex cst_rx_eng_digits_only_rx = { 0, 1, NULL, 0, 31, (char *)cst_rx_eng_digits_only_rxprog }; const cst_regex * const cst_rx_eng_digits_only = &cst_rx_eng_digits_only_rx; /* ./bin/compile_regexes cst_rx_not_indic "^[0-9a-zA-Z/:_'-,]+$" */ static const unsigned char cst_rx_not_indic_rxprog[] = { 156, 6, 0, 87, 1, 0, 3, 11, 0, 78, 4, 0, 0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 47, 58, 95, 39, 40, 41, 42, 43, 44, 0, 2, 0, 3, 0, 0, 0, }; static const cst_regex cst_rx_not_indic_rx = { 0, 1, NULL, 0, 91, (char *)cst_rx_not_indic_rxprog }; const cst_regex * const cst_rx_not_indic = &cst_rx_not_indic_rx; /* ./bin/compile_regexes cst_rx_indic_eng_number "^[1-9][0-9],\\([0-9][0-9],\\)*[0-9][0-9][0-9]$" */ static const unsigned char cst_rx_indic_eng_number_rxprog[] = { 156, 6, 0, 137, 1, 0, 3, 4, 0, 13, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 4, 0, 14, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8, 0, 5, 44, 0, 6, 0, 48, 21, 0, 3, 6, 0, 36, 4, 0, 14, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 4, 0, 14, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8, 0, 5, 44, 0, 31, 0, 3, 7, 0, 45, 6, 0, 3, 9, 0, 3, 4, 0, 14, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 4, 0, 14, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 4, 0, 14, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 2, 0, 3, 0, 0, 0, }; static const cst_regex cst_rx_indic_eng_number_rx = { 0, 1, NULL, 0, 141, (char *)cst_rx_indic_eng_number_rxprog }; const cst_regex * const cst_rx_indic_eng_number = &cst_rx_indic_eng_number_rx; cst_val *us_tokentowords(cst_item *token); /* Note that's an ascii | not the devangari one */ extern const cst_string * const indic_postpunctuationsymbols = "\"'`.,:;!?(){}[]|"; static cst_val *cmu_indic_tokentowords_one(cst_item *token, const char *name); cst_val *cmu_indic_tokentowords(cst_item *token) { return cmu_indic_tokentowords_one(token, item_feat_string(token, "name")); } /* Indic numbers. This deals with all (quantity) numbers found in any Indic */ /* language no matter what script they are written in. We use the Indic_Nums */ /* table to convert the strings of digits (points and commas) into lists of */ /* words for those scripts' language. Thus Telugu digits get converted to */ /* Telugu words (even if the voice is a Hindi voice). */ /* We assume use lakh and crore examples when there is commas to identify */ /* thus 10,34,123 (in English digits) will be expanded to 10 lakh, thirty */ /* four thousand one hundred (and) twenty three */ /* We do English too, so I can debug it, and so lakh and crore are right */ #include "./indic_eng_num_table.hpp" #include "./indic_hin_num_table.hpp" #include "./indic_guj_num_table.hpp" #include "./indic_kan_num_table.hpp" #include "./indic_mar_num_table.hpp" #include "./indic_san_num_table.hpp" #include "./indic_tel_num_table.hpp" #include "./indic_tam_num_table.hpp" #include "./indic_pan_num_table.hpp" int ts_utf8_sequence_length(char c0); // inline int utf8_sequence_length(char c0) // { // Get the expected length of UTF8 sequence given its most // significant byte // return (( 0xE5000000 >> (( c0 >> 3 ) & 0x1E )) & 3 ) + 1; // } int ts_utf8_sequence_length(char c0); // inline int utf8_sequence_length(char c0) // { // Get the expected length of UTF8 sequence given its most // significant byte // return (( 0xE5000000 >> (( c0 >> 3 ) & 0x1E )) & 3 ) + 1; // } int indic_digit_to_offset(const char *ind_digit) { /* This functions returns int value of a single digit in Indic/English scripts. Also, it returns -1 if the character isn't a digit */ int output=-1; int i; int offset=-1; i = cst_utf8_ord_string(ind_digit); if ((i >= 0x0030) && (i <= 0x0039)) /*ASCII*/ offset = 0x0030; if ((i >= 0x0966) && (i <= 0x096F)) /*Devanagari*/ offset = 0x0966; if ((i >= 0x09E6) && (i <= 0x09EF)) /*Bengali*/ offset = 0x09E6; if ((i >= 0x0A66) && (i <= 0x0A6F)) /*Gurmukhi*/ offset = 0x0A66; if ((i >= 0x0AE6) && (i <= 0x0AEF)) /*Gujarati*/ offset = 0x0AE6; if ((i >= 0x0B66) && (i <= 0x0B6F)) /*Oriya*/ offset = 0x0B66; if ((i >= 0x0BE6) && (i <= 0x0BEF)) /*Tamil*/ offset = 0x0BE6; if ((i >= 0x0C66) && (i <= 0x0C6F)) /*Telugu*/ offset = 0x0C66; if ((i >= 0x0CE6) && (i <= 0x0CEF)) /*Kannada*/ offset = 0x0CE6; if ((i >= 0x0D66) && (i <= 0x0D6F)) /*Malayalam*/ offset = 0x0D66; if (offset == -1) { /* Not a digit */ return -1; } output = i - offset; return output; } static cst_val *indic_number_digit(const char *digit,const indic_num_table *t) { int i; if ((digit == NULL) || (t == NULL)) return NULL; i = indic_digit_to_offset(digit); if (i == -1) { printf("Error in getting int from digit %s\n", digit); return NULL; } /* The ith array index corresponds to the exact single digit number*/ return cons_val(string_val(num_table_digit(t,i,1)),NULL); } static cst_val *indic_number_two_digit(const char *digit1, const char *digit2, const indic_num_table *t) { int i,j; cst_val *r = NULL; if ((digit1 == NULL) || (digit2 == NULL) || (t == NULL)) return NULL; i = indic_digit_to_offset(digit1); j = indic_digit_to_offset(digit2); if (i == -1) { printf("Error in getting int from digit %s\n", digit1); return NULL; } if (j == -1) { printf("Error in getting int from digit %s\n", digit2); return NULL; } if (i == 0) { printf("Single digit erroneously processed as double digit %s\n", digit2); return cons_val(string_val(num_table_digit(t,i,1)),NULL); } /*10*(i-1)+j given correct two digit index*/ if (num_table_two_digit(t,10*(i-1)+j,3) != NULL) r = cons_val(string_val(num_table_two_digit(t,10*(i-1)+j,3)),r); if (num_table_two_digit(t,10*(i-1)+j,2) != NULL) r = cons_val(string_val(num_table_two_digit(t,10*(i-1)+j,2)),r); return r; } static cst_val *indic_number_lang(const indic_num_table *num_table) { return string_val(num_table->lang); } static cst_val *indic_number_hundred(const indic_num_table *num_table) { return string_val(num_table->hundred); } static cst_val *indic_number_thousand(const indic_num_table *num_table) { return string_val(num_table->thousand); } static cst_val *indic_number_lakh(const indic_num_table *num_table) { return string_val(num_table->lakh); } static cst_val *indic_number_crore(const indic_num_table *num_table) { return string_val(num_table->crore); } cst_val *indic_number(const cst_val *number, const indic_num_table *num_table) { cst_val *r = NULL; /* so its a number in some script (we actually don't care which script) */ #if 0 printf("awb_debug enter indic num "); val_print(stdout,number); printf("\n"); #endif if (number == NULL) r = NULL; /* If zero is the penultimate digit */ else if ((indic_digit_to_offset(val_string(val_car(number))) == 0) && (val_length(number) == 2)) { /* If the last digit is non-zero */ if (indic_digit_to_offset(val_string(val_car(val_cdr(number)))) != 0) { r = indic_number_digit(val_string(val_car(val_cdr(number))),num_table); } else { /* So it doesn't say zero in the end*/ } } /* If the current digit is a 0 and there is a next digit */ else if ((indic_digit_to_offset(val_string(val_car(number))) == 0) && (val_cdr(number) != NULL)) { r = indic_number(val_cdr(number),num_table); } else if (val_length(number) == 1) { r = indic_number_digit(val_string(val_car(number)),num_table); } else if (val_length(number) == 2) { r = indic_number_two_digit(val_string(val_car(number)), val_string(val_car(val_cdr(number))), num_table); } else if (val_length(number) == 3) { if ((!cst_streq(val_string(indic_number_lang(num_table)),"mar")) || indic_digit_to_offset(val_string(val_car(val_cdr(number)))) || indic_digit_to_offset(val_string(val_car(val_cdr(val_cdr(number)))))) r = val_append(indic_number_digit(val_string(val_car(number)),num_table), cons_val(indic_number_hundred(num_table), indic_number(val_cdr(number),num_table))); else r = val_append(indic_number_digit(val_string(val_car(number)),num_table), cons_val(string_val("शंभर"), indic_number(val_cdr(number),num_table))); } else if (val_length(number) == 4) { r = val_append(indic_number_digit(val_string(val_car(number)),num_table), cons_val(indic_number_thousand(num_table), indic_number(val_cdr(number),num_table))); } else if (val_length(number) == 5) { r = val_append(indic_number_two_digit(val_string(val_car(number)), val_string(val_car(val_cdr(number))), num_table), cons_val(indic_number_thousand(num_table), indic_number(val_cdr(val_cdr(number)),num_table))); } else if (val_length(number) == 6) { r = val_append(indic_number_digit(val_string(val_car(number)),num_table), cons_val(indic_number_lakh(num_table), indic_number(val_cdr(number),num_table))); } else if (val_length(number) == 7) { r = val_append(indic_number_two_digit(val_string(val_car(number)), val_string(val_car(val_cdr(number))), num_table), cons_val(indic_number_lakh(num_table), indic_number(val_cdr(val_cdr(number)),num_table))); } else if (val_length(number) == 8) { r = val_append(indic_number_digit(val_string(val_car(number)),num_table), cons_val(indic_number_crore(num_table), indic_number(val_cdr(number),num_table))); } else if (val_length(number) == 9) { r = val_append(indic_number_two_digit(val_string(val_car(number)), val_string(val_car(val_cdr(number))), num_table), cons_val(indic_number_crore(num_table), indic_number(val_cdr(val_cdr(number)),num_table))); } #if 0 printf("awb_debug end of indic num "); val_print(stdout,r); printf("\n"); #endif return r; } cst_val *indic_number_indiv(const cst_val *number, const indic_num_table *num_table) { cst_val *r = NULL; /* Exapnd this as a string of digits (not an actual quantity) */ if (number == NULL) r = NULL; else { r = val_append(indic_number_digit(val_string(val_car(number)),num_table), indic_number_indiv(val_cdr(number),num_table)); } return r; } #if 0 static int indic_nump_old(const char *number) { /* True if all (unicode) characters are in num_table's digit table */ /* or is a comma or dot */ cst_val *p; const cst_val *q; int i; int flag = TRUE; int fflag; p = cst_utf8_explode(number); for (q=p; q && (flag==TRUE); q=val_cdr(q)) { fflag = FALSE; for (i=0; i<10; i++) { if (indic_digit_to_offset(val_string(val_car(q))) != -1) { fflag = TRUE; break; } } if ((cst_streq(val_string(val_car(q)),",")) || /* English zeros sometimes occur */ (cst_streq(val_string(val_car(q)),"0"))) fflag = TRUE; flag = fflag; } delete_val(p); p = NULL; return flag; } #endif static int indic_nump(const char *number) { /* Check if non-empty string */ if (!number[0]) return FALSE; /* Catch lone commas */ if (number[0] == ',') return indic_nump(&number[1]); /* Returns 2 if all characters are numbers or commas */ /* Returns 1 if it starts with a number */ cst_val *p; const cst_val *q; int flag = TRUE; int fflag; int ffflag = FALSE; /* Switches to TRUE at first digit found */ p = cst_utf8_explode(number); for (q=p; q && (flag==TRUE); q=val_cdr(q)) { fflag = FALSE; if (indic_digit_to_offset(val_string(val_car(q))) != -1) { fflag = TRUE; ffflag = TRUE; } else if (cst_streq(val_string(val_car(q)),",")) fflag = TRUE; flag = fflag; } delete_val(p); p = NULL; return flag+ffflag; } static int indic_hyphenated(const char *number) { /* Returns positive if first character is , - / and is followed by a */ /* number */ int flag = 0; if ((number[0] == '-') || (number[0] == '/') || (number[0] == '.')) flag = indic_nump(&number[1]); return flag; } static int indic_text_splitable(const char *s,int i,int len1) { /* Returns true only if this and next chars are not both digits */ /* or both non-digits */ char *ccc, *ddd; /* Store this character and the next character */ int len2; /* Length of next character */ int flag; ccc = cst_strdup(&s[i]); ddd = cst_strdup(&s[i+len1]); len2 = ts_utf8_sequence_length(ddd[0]); ccc[len1] = '\0'; ddd[len2] = '\0'; /* Makeshift NOR */ flag = (indic_digit_to_offset(ccc) == -1)? !(indic_digit_to_offset(ddd) == -1): (indic_digit_to_offset(ddd) == -1); cst_free(ccc); cst_free(ddd); return flag; } static cst_val *indic_num_normalize(const char *number, const indic_num_table *num_table) { /* Remove , */ cst_val *p, *np; const cst_val *q; p = cst_utf8_explode(number); np = NULL; for (q=p; q; q=val_cdr(q)) { if (!cst_streq(val_string(val_car(q)),",")) np = cons_val(string_val(val_string(val_car(q))),np); } delete_val(p); return val_reverse(np); } static cst_val *cmu_indic_tokentowords_one(cst_item *token, const char *name) { /* Return list of words that expand token/name */ cst_val *r, *p; const indic_num_table *num_table; const char *variant; cst_utterance *utt; /* printf("awb_debug token_name %s name %s\n",item_name(token),name); */ r = NULL; if (item_feat_present(token,"phones")) return cons_val(string_val(name),NULL); #if 0 if (item_feat_present(token,"nsw")) nsw = item_feat_string(token,"nsw"); utt = item_utt(token); lex = val_lexicon(feat_val(utt->features,"lexicon")); #endif utt = item_utt(token); variant = get_param_string(utt->features, "variant", "none"); if (cst_streq(variant,"hin")) num_table = &hin_num_table; else if (cst_streq(variant,"guj")) num_table = &guj_num_table; else if (cst_streq(variant,"kan")) num_table = &kan_num_table; else if (cst_streq(variant,"mar")) num_table = &mar_num_table; else if (cst_streq(variant,"nep")) num_table = &hin_num_table; else if (cst_streq(variant, "pan")) num_table = &pan_num_table; else if (cst_streq(variant, "san")) num_table = &san_num_table; else if (cst_streq(variant,"tam")) num_table = &tam_num_table; else if (cst_streq(variant,"tel")) num_table = &tel_num_table; else num_table = &eng_num_table; /* This matches *English* numbers of the form 99,99,999 that require lakh or crore expansion -- otherwise they'll be dropped back to the English front end */ if (cst_regex_match(cst_rx_indic_eng_number,name)) { /* remove commas */ p = indic_num_normalize(name,num_table); if (val_length(p) <= 9) /* Long strings of digits are read as strings of digits */ r = indic_number(p, num_table); else r = indic_number_indiv(p,num_table); delete_val(p); } else if (indic_nump(name)) { /* Its script specific digits (commas/dots) */ if (indic_nump(name) == 2) { /* All characters are digits */ // printf("nump is 2\n"); p = indic_num_normalize(name,num_table); if (val_length(p) <= 9) r = indic_number(p, num_table); else r = indic_number_indiv(p,num_table); delete_val(p); } else if (indic_nump(name) == 1) { /* Some characters are digits */ int len = 1; int i = 0; char c0; char *aaa; char *bbb; while(name[i] != '\0') { /* Iterate over UTF-8 string */ c0 = name[i]; len = ts_utf8_sequence_length(c0); /* Check if char after this is comma */ if (name[i+len] == ',') { /* Skip commas */ i += len; c0 = name[i]; len = ts_utf8_sequence_length(c0); i += len; continue; } /* Find where character type switches to or from digits */ if(indic_text_splitable(name, i, len)) break; i +=len; } aaa = cst_strdup(name); aaa[i+len] = '\0'; bbb = cst_strdup(&name[i+len]); r = val_append(cmu_indic_tokentowords_one(token, aaa), cmu_indic_tokentowords_one(token, bbb)); cst_free(aaa); cst_free(bbb); } } else if (indic_hyphenated(name)) { /* For numbers seeparated by - / , */ char *aaa; aaa = cst_strdup(&name[1]); r = cmu_indic_tokentowords_one(token, aaa); cst_free(aaa); } else if (cst_regex_match(cst_rx_not_indic,name)) /* Do English analysis on non-unicode tokens */ r = us_tokentowords(token); else if (cst_strlen(name) > 0) r = cons_val(string_val(name),0); else r = NULL; return r; } int indic_utt_break(cst_tokenstream *ts, const char *token, cst_relation *tokens) { const char *postpunct = item_feat_string(relation_tail(tokens), "punc"); const char *ltoken = item_name(relation_tail(tokens)); if (cst_strchr(ts->whitespace,'\n') != cst_strrchr(ts->whitespace,'\n')) /* contains two new lines */ return TRUE; else if ((cst_strlen(ltoken) >= 3) && (cst_streq(&ltoken[cst_strlen(ltoken)-3],"।"))) /* devanagari '|' */ return TRUE; else if (strchr(postpunct,':') || strchr(postpunct,'?') || strchr(postpunct,'|') || /* if ascii '|' gets used as dvngr '|' */ strchr(postpunct,'!')) return TRUE; else if (strchr(postpunct,'.')) return TRUE; else return FALSE; } DEF_STATIC_CONST_VAL_STRING(val_string_zero,"0"); DEF_STATIC_CONST_VAL_STRING(val_string_one,"1"); const cst_val *is_english(const cst_item *p) { if (p && cst_regex_match(cst_rx_not_indic, flite_ffeature_string(p,"name"))) return (cst_val *)&val_string_one; else return (cst_val *)&val_string_zero; } void cmu_indic_lang_init(cst_voice *v) { /* Set indic language stuff */ feat_set_string(v->features,"language","cmu_indic_lang"); /* utterance break function */ feat_set(v->features,"utt_break",breakfunc_val(&indic_utt_break)); /* Phoneset -- need to get this from voice */ feat_set(v->features,"phoneset",phoneset_val(&cmu_indic_phoneset)); feat_set_string(v->features,"silence",cmu_indic_phoneset.silence); /* Get information from voice and add to lexicon */ /* Text analyser -- whitespace defaults */ feat_set_string(v->features,"text_whitespace", cst_ts_default_whitespacesymbols); feat_set_string(v->features,"text_prepunctuation", cst_ts_default_prepunctuationsymbols); /* We can't put multi-byte characters in these classes so we can't */ /* add devanagari end of sentence '|' here, but would like to -- */ /* But we do add ascii '|' to it as it sometimes gets used the same way */ feat_set_string(v->features,"text_postpunctuation", indic_postpunctuationsymbols); feat_set_string(v->features,"text_singlecharsymbols", cst_ts_default_singlecharsymbols); /* Tokenization tokenization function */ feat_set(v->features,"tokentowords_func",itemfunc_val(&cmu_indic_tokentowords)); /* Pos tagger (gpos)/induced pos */ /* Phrasing */ feat_set(v->features,"phrasing_cart",cart_val(&cmu_indic_phrasing_cart)); /* Intonation, Duration and F0 -- part of cg */ feat_set_string(v->features,"no_intonation_accent_model","1"); /* Default ffunctions (required) */ basic_ff_register(v->ffunctions); /* Indic specific features */ ff_register(v->ffunctions, "lisp_is_english", is_english); return; } // clang-format on
32.02289
100
0.585061
Barath-Kannan
c505ff3deaa0f49949fce60afd539d555478f898
391
cpp
C++
GraphComponents/charger.cpp
drewyh999/wireless_charging_scheme_simulator
02213906f1218a59505839a1921da1c4ab8c242f
[ "MIT" ]
null
null
null
GraphComponents/charger.cpp
drewyh999/wireless_charging_scheme_simulator
02213906f1218a59505839a1921da1c4ab8c242f
[ "MIT" ]
null
null
null
GraphComponents/charger.cpp
drewyh999/wireless_charging_scheme_simulator
02213906f1218a59505839a1921da1c4ab8c242f
[ "MIT" ]
null
null
null
// // Created by Dominique Zhu on 2021/3/26. // #include "charger.h" double Charger::rechargeToDestination(Coordinate *destination) { double distance = this -> getDistance(destination); if(distance > dth){ return 0; } else{ return (tau * Ps)/pow(epsilon + distance,2); } } Charger::Charger(double x, double y, double ps) : Coordinate(x, y), Ps(ps) {}
20.578947
77
0.629156
drewyh999
c50928d1c2b83f978005fc5e37ff8872c774ded9
3,316
cpp
C++
Source/UnrealEnginePython/Private/Slate/UEPyFGeometry.cpp
SIRHAMY/UnrealEnginePython
038192d7814d1aee182766028640d238204fefa4
[ "MIT" ]
2,350
2016-08-08T17:00:16.000Z
2022-03-31T22:37:15.000Z
Source/UnrealEnginePython/Private/Slate/UEPyFGeometry.cpp
SIRHAMY/UnrealEnginePython
038192d7814d1aee182766028640d238204fefa4
[ "MIT" ]
820
2016-08-08T16:35:26.000Z
2022-03-24T05:09:51.000Z
Source/UnrealEnginePython/Private/Slate/UEPyFGeometry.cpp
SIRHAMY/UnrealEnginePython
038192d7814d1aee182766028640d238204fefa4
[ "MIT" ]
658
2016-08-10T16:26:24.000Z
2022-03-30T02:42:22.000Z
#include "UEPyFGeometry.h" static PyObject *py_ue_fgeometry_get_local_size(ue_PyFGeometry *self, PyObject * args) { FVector2D size = self->geometry.GetLocalSize(); return Py_BuildValue("(ff)", size.X, size.Y); } static PyObject *py_ue_fgeometry_get_absolute_position(ue_PyFGeometry *self, PyObject * args) { #if ENGINE_MINOR_VERSION < 17 FVector2D size = self->geometry.AbsolutePosition; #else FVector2D size = self->geometry.GetAbsolutePosition(); #endif return Py_BuildValue("(ff)", size.X, size.Y); } static PyObject *py_ue_fgeometry_absolute_to_local(ue_PyFGeometry *self, PyObject * args) { float x, y; if (!PyArg_ParseTuple(args, "(ff)", &x, &y)) return nullptr; FVector2D absolute(x, y); FVector2D local = self->geometry.AbsoluteToLocal(absolute); return Py_BuildValue((char *)"(ff)", local.X, local.Y); } static PyMethodDef ue_PyFGeometry_methods[] = { { "get_local_size", (PyCFunction)py_ue_fgeometry_get_local_size, METH_VARARGS, "" }, { "get_absolute_position", (PyCFunction)py_ue_fgeometry_get_absolute_position, METH_VARARGS, "" }, { "absolute_to_local", (PyCFunction)py_ue_fgeometry_absolute_to_local, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; static PyObject *ue_PyFGeometry_str(ue_PyFGeometry *self) { return PyUnicode_FromFormat("<unreal_engine.FGeometry '%s'>", TCHAR_TO_UTF8(*self->geometry.ToString())); } static PyTypeObject ue_PyFGeometryType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.FGeometry", /* tp_name */ sizeof(ue_PyFGeometry), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)ue_PyFGeometry_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine FGeometry", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyFGeometry_methods, /* tp_methods */ }; void ue_python_init_fgeometry(PyObject *ue_module) { ue_PyFGeometryType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyFGeometryType) < 0) return; Py_INCREF(&ue_PyFGeometryType); PyModule_AddObject(ue_module, "FGeometry", (PyObject *)&ue_PyFGeometryType); } ue_PyFGeometry *py_ue_is_fgeometry(PyObject *obj) { if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyFGeometryType)) return nullptr; return (ue_PyFGeometry *)obj; } PyObject *py_ue_new_fgeometry(FGeometry geometry) { ue_PyFGeometry *ret = (ue_PyFGeometry *)PyObject_New(ue_PyFGeometry, &ue_PyFGeometryType); ret->geometry = geometry; return (PyObject *)ret; }
34.185567
99
0.604946
SIRHAMY
c509b89363067ee600a158e0ab3e110291033914
1,902
cpp
C++
BZOJ/3513/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/3513/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/3513/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<complex> #include<cstring> #define eps 0.1 #define pi 3.1415926 #define maxn 262144 #define LL long long #define buffersize 20000000 using namespace std; struct E{ double x,y; E operator+(const E b){return E{x+b.x,y+b.y};} E operator-(const E b){return E{x-b.x,y-b.y};} E operator*(const E b){return E{x*b.x-y*b.y,x*b.y+y*b.x};} }; char buffer[buffersize],*p; int readint(){ int tmp=0; while(*p<'0'||*p>'9')++p; while(*p>='0'&&*p<='9')tmp=tmp*10+*p-'0',++p; return tmp; } int T,n,a[maxn],fn,maxval,m; E c[maxn]; int rev[maxn],L; LL ans,f[maxn],sum[maxn],cnt[maxn],scnt[maxn]; void fft(E*a,int f,int n){ for(int i=0;i<n;++i)if(i<rev[i])swap(a[i],a[rev[i]]); for(int i=1;i<n;i<<=1){ E wn=E{cos(pi/i),f*sin(pi/i)}; for(int j=0;j<n;j+=(i<<1)){ E w=E{1,0}; for(int k=0;k<i;++k,w=w*wn){ E x=a[j+k],y=w*a[j+k+i]; a[j+k]=x+y;a[j+k+i]=x-y; } } } if(f==-1)for(int i=0;i<n;++i)a[i].x/=n; } int main(){ fread(buffer,sizeof(char),sizeof(buffer),stdin);p=buffer; T=readint(); while(T--){ memset(cnt,0,sizeof(cnt));ans=0;maxval=0; n=readint(); for(int i=1;i<=n;++i)a[i]=readint(),maxval=max(maxval,a[i]); for(int i=1;i<=n;++i)++cnt[a[i]]; m=maxval*2;L=0; for(fn=1;fn<=m;fn<<=1)++L; for(int i=0;i<fn;++i)c[i].x=c[i].y=0; for(int i=1;i<=maxval;++i)c[i].x=cnt[i]; rev[0]=0; for(int i=0;i<fn;++i)rev[i]=(rev[i>>1]>>1)|((i&1)<<(L-1)); fft(c,1,fn); for(int i=0;i<fn;++i)c[i]=c[i]*c[i]; fft(c,-1,fn); for(int i=0;i<=m;++i)f[i]=c[i].x+eps; for(int i=1;i<=m;++i)f[i]=f[i]-(i%2==0)*cnt[i/2]; for(int i=1;i<=m;++i)sum[i]=sum[i-1]+f[i]; for(int i=1;i<=maxval;++i)scnt[i]=scnt[i-1]+cnt[i]; for(int i=1;i<=maxval;++i)if(cnt[i]){ ans+=cnt[i]*((scnt[i-1]-1)*(scnt[i-1])-sum[i])/2+(cnt[i]-1)*cnt[i]/2*(scnt[i-1])+cnt[i]*(cnt[i]-1)*(cnt[i]-2)/6; } printf("%.7lf\n",ans*6.0/n/(n-1)/(n-2)); } return 0; }
26.054795
115
0.54837
sjj118
c50d3308f04c752e15cbc878fbac2d6148e8dce2
2,645
cpp
C++
GameGUIMP/EditConsole.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
GameGUIMP/EditConsole.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
GameGUIMP/EditConsole.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
// EditConsole.cpp : implementation file // #include "stdafx.h" #ifdef _DEBUG #undef new #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CEditConsole CEditConsole::CEditConsole() { } CEditConsole::~CEditConsole() { } BEGIN_MESSAGE_MAP(CEditConsole, CEdit) //{{AFX_MSG_MAP(CEditConsole) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CEditConsole message handlers void CEditConsole::SetTextFromConsole(void) { INDEX ctLines = _pConsole->con_ctLines; INDEX ctChars = _pConsole->con_ctLines; // allocate new string with double line ends char *strNew = (char*)AllocMemory(ctLines*(ctChars+2)+1); const char *strString = _pConsole->GetBuffer(); char *pch = strNew; // convert '\n' to '\r''\n' while(*strString!=0) { if (*strString=='\n') { *pch++='\r'; *pch++='\n'; strString++; } *pch++ = *strString++; } *pch = 0; CDlgConsole *pdlgParent = (CDlgConsole *) GetParent(); CEdit *pwndOutput = (CEdit *) pdlgParent->GetDlgItem( IDC_CONSOLE_OUTPUT); pwndOutput->SetWindowText( strNew); pwndOutput->LineScroll(ctLines-1); FreeMemory(strNew); } BOOL CEditConsole::PreTranslateMessage(MSG* pMsg) { BOOL bCtrl = (GetKeyState( VK_CONTROL) & 128) != 0; if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN) { // obtain current line index INDEX iCurrentLine = LineFromChar(-1); INDEX ctLinesEdited = GetLineCount(); // obtain char offset of current line in whole edit string INDEX iCharOffset = LineFromChar(iCurrentLine); if( !bCtrl && (iCharOffset != -1) ) { // extract string to execute char achrToExecute[ 1024]; INDEX ctLetters = GetLine( iCurrentLine, achrToExecute, 1023); // set EOF delimiter achrToExecute[ ctLetters] = 0; CTString strToExecute = achrToExecute; CPrintF( ">%s\n", strToExecute); if( ((const char*)strToExecute)[strlen(strToExecute)-1] != ';') { strToExecute += ";"; } _pShell->Execute(strToExecute); // set new text for output window SetTextFromConsole(); // remember input text into console input buffer CString sHistory; GetWindowText(sHistory); _pGame->gam_strConsoleInputBuffer = (const char *)sHistory; } // if Ctrl is not pressed and current line is not last line, "swallow return" if( !bCtrl && (ctLinesEdited-1 != iCurrentLine) ) { return TRUE; } } return CEdit::PreTranslateMessage(pMsg); }
26.45
81
0.620416
openlastchaos
c50d67ed685db594539affadf17637ae4e970dad
35,434
cpp
C++
JuceLibraryCode/modules/juce_gui_extra/code_editor/juce_CodeEditorComponent.cpp
connerlacy/QuNeoDemo
073a81d7fa7fa462e07c7b33de3e982a03a0055c
[ "Unlicense" ]
1
2019-10-16T08:54:44.000Z
2019-10-16T08:54:44.000Z
JuceLibraryCode/modules/juce_gui_extra/code_editor/juce_CodeEditorComponent.cpp
connerlacy/quneo_demo_lab
073a81d7fa7fa462e07c7b33de3e982a03a0055c
[ "Unlicense" ]
null
null
null
JuceLibraryCode/modules/juce_gui_extra/code_editor/juce_CodeEditorComponent.cpp
connerlacy/quneo_demo_lab
073a81d7fa7fa462e07c7b33de3e982a03a0055c
[ "Unlicense" ]
null
null
null
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ class CodeEditorComponent::CodeEditorLine { public: CodeEditorLine() noexcept : highlightColumnStart (0), highlightColumnEnd (0) { } bool update (CodeDocument& document, int lineNum, CodeDocument::Iterator& source, CodeTokeniser* analyser, const int spacesPerTab, const CodeDocument::Position& selectionStart, const CodeDocument::Position& selectionEnd) { Array <SyntaxToken> newTokens; newTokens.ensureStorageAllocated (8); if (analyser == nullptr) { newTokens.add (SyntaxToken (document.getLine (lineNum), -1)); } else if (lineNum < document.getNumLines()) { const CodeDocument::Position pos (&document, lineNum, 0); createTokens (pos.getPosition(), pos.getLineText(), source, analyser, newTokens); } replaceTabsWithSpaces (newTokens, spacesPerTab); int newHighlightStart = 0; int newHighlightEnd = 0; if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum) { const String line (document.getLine (lineNum)); CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0); newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()), line, spacesPerTab); newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()), line, spacesPerTab); } if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd) { highlightColumnStart = newHighlightStart; highlightColumnEnd = newHighlightEnd; } else { if (tokens.size() == newTokens.size()) { bool allTheSame = true; for (int i = newTokens.size(); --i >= 0;) { if (tokens.getReference(i) != newTokens.getReference(i)) { allTheSame = false; break; } } if (allTheSame) return false; } } tokens.swapWithArray (newTokens); return true; } void draw (CodeEditorComponent& owner, Graphics& g, const Font& font, float x, const int y, const int baselineOffset, const int lineHeight, const Colour& highlightColour) const { if (highlightColumnStart < highlightColumnEnd) { g.setColour (highlightColour); g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y, roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight); } int lastType = std::numeric_limits<int>::min(); for (int i = 0; i < tokens.size(); ++i) { SyntaxToken& token = tokens.getReference(i); if (lastType != token.tokenType) { lastType = token.tokenType; g.setColour (owner.getColourForTokenType (lastType)); } g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset); if (i < tokens.size() - 1) { if (token.width < 0) token.width = font.getStringWidthFloat (token.text); x += token.width; } } } private: struct SyntaxToken { SyntaxToken (const String& text_, const int type) noexcept : text (text_), tokenType (type), width (-1.0f) { } bool operator!= (const SyntaxToken& other) const noexcept { return text != other.text || tokenType != other.tokenType; } String text; int tokenType; float width; }; Array <SyntaxToken> tokens; int highlightColumnStart, highlightColumnEnd; static void createTokens (int startPosition, const String& lineText, CodeDocument::Iterator& source, CodeTokeniser* analyser, Array <SyntaxToken>& newTokens) { CodeDocument::Iterator lastIterator (source); const int lineLength = lineText.length(); for (;;) { int tokenType = analyser->readNextToken (source); int tokenStart = lastIterator.getPosition(); int tokenEnd = source.getPosition(); if (tokenEnd <= tokenStart) break; tokenEnd -= startPosition; if (tokenEnd > 0) { tokenStart -= startPosition; newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd), tokenType)); if (tokenEnd >= lineLength) break; } lastIterator = source; } source = lastIterator; } static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) { int x = 0; for (int i = 0; i < tokens.size(); ++i) { SyntaxToken& t = tokens.getReference(i); for (;;) { int tabPos = t.text.indexOfChar ('\t'); if (tabPos < 0) break; const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab); t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded)); } x += t.text.length(); } } int indexToColumn (int index, const String& line, int spacesPerTab) const noexcept { jassert (index <= line.length()); String::CharPointerType t (line.getCharPointer()); int col = 0; for (int i = 0; i < index; ++i) { if (t.getAndAdvance() != '\t') ++col; else col += spacesPerTab - (col % spacesPerTab); } return col; } }; //============================================================================== CodeEditorComponent::CodeEditorComponent (CodeDocument& document_, CodeTokeniser* const codeTokeniser_) : document (document_), firstLineOnScreen (0), gutter (5), spacesPerTab (4), lineHeight (0), linesOnScreen (0), columnsOnScreen (0), scrollbarThickness (16), columnToTryToMaintain (-1), useSpacesForTabs (false), xOffset (0), verticalScrollBar (true), horizontalScrollBar (false), codeTokeniser (codeTokeniser_) { caretPos = CodeDocument::Position (&document_, 0, 0); caretPos.setPositionMaintained (true); selectionStart = CodeDocument::Position (&document_, 0, 0); selectionStart.setPositionMaintained (true); selectionEnd = CodeDocument::Position (&document_, 0, 0); selectionEnd.setPositionMaintained (true); setOpaque (true); setMouseCursor (MouseCursor (MouseCursor::IBeamCursor)); setWantsKeyboardFocus (true); addAndMakeVisible (&verticalScrollBar); verticalScrollBar.setSingleStepSize (1.0); addAndMakeVisible (&horizontalScrollBar); horizontalScrollBar.setSingleStepSize (1.0); addAndMakeVisible (caret = getLookAndFeel().createCaretComponent (this)); Font f (12.0f); f.setTypefaceName (Font::getDefaultMonospacedFontName()); setFont (f); resetToDefaultColours(); verticalScrollBar.addListener (this); horizontalScrollBar.addListener (this); document.addListener (this); } CodeEditorComponent::~CodeEditorComponent() { document.removeListener (this); } void CodeEditorComponent::loadContent (const String& newContent) { clearCachedIterators (0); document.replaceAllContent (newContent); document.clearUndoHistory(); document.setSavePoint(); caretPos.setPosition (0); selectionStart.setPosition (0); selectionEnd.setPosition (0); scrollToLine (0); } bool CodeEditorComponent::isTextInputActive() const { return true; } void CodeEditorComponent::setTemporaryUnderlining (const Array <Range<int> >&) { jassertfalse; // TODO Windows IME not yet supported for this comp.. } Rectangle<int> CodeEditorComponent::getCaretRectangle() { return getLocalArea (caret, caret->getLocalBounds()); } //============================================================================== void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart, const CodeDocument::Position& affectedTextEnd) { clearCachedIterators (affectedTextStart.getLineNumber()); triggerAsyncUpdate(); updateCaretPosition(); columnToTryToMaintain = -1; if (affectedTextEnd.getPosition() >= selectionStart.getPosition() && affectedTextStart.getPosition() <= selectionEnd.getPosition()) deselectAll(); if (caretPos.getPosition() > affectedTextEnd.getPosition() || caretPos.getPosition() < affectedTextStart.getPosition()) moveCaretTo (affectedTextStart, false); updateScrollBars(); } void CodeEditorComponent::resized() { linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight; columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth); lines.clear(); rebuildLineTokens(); updateCaretPosition(); verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness); horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness); updateScrollBars(); } void CodeEditorComponent::paint (Graphics& g) { handleUpdateNowIfNeeded(); g.fillAll (findColour (CodeEditorComponent::backgroundColourId)); g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY()); g.setFont (font); const int baselineOffset = (int) font.getAscent(); const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId)); const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId)); const Rectangle<int> clip (g.getClipBounds()); const int firstLineToDraw = jmax (0, clip.getY() / lineHeight); const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1); for (int j = firstLineToDraw; j < lastLineToDraw; ++j) { lines.getUnchecked(j)->draw (*this, g, font, (float) (gutter - xOffset * charWidth), lineHeight * j, baselineOffset, lineHeight, highlightColour); } } void CodeEditorComponent::setScrollbarThickness (const int thickness) { if (scrollbarThickness != thickness) { scrollbarThickness = thickness; resized(); } } void CodeEditorComponent::handleAsyncUpdate() { rebuildLineTokens(); } void CodeEditorComponent::rebuildLineTokens() { cancelPendingUpdate(); const int numNeeded = linesOnScreen + 1; int minLineToRepaint = numNeeded; int maxLineToRepaint = 0; if (numNeeded != lines.size()) { lines.clear(); for (int i = numNeeded; --i >= 0;) lines.add (new CodeEditorLine()); minLineToRepaint = 0; maxLineToRepaint = numNeeded; } jassert (numNeeded == lines.size()); CodeDocument::Iterator source (&document); getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source); for (int i = 0; i < numNeeded; ++i) { CodeEditorLine* const line = lines.getUnchecked(i); if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab, selectionStart, selectionEnd)) { minLineToRepaint = jmin (minLineToRepaint, i); maxLineToRepaint = jmax (maxLineToRepaint, i); } } if (minLineToRepaint <= maxLineToRepaint) { repaint (gutter, lineHeight * minLineToRepaint - 1, verticalScrollBar.getX() - gutter, lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2); } } //============================================================================== void CodeEditorComponent::updateCaretPosition() { caret->setCaretPosition (getCharacterBounds (getCaretPos())); } void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting) { caretPos = newPos; columnToTryToMaintain = -1; if (highlighting) { if (dragType == notDragging) { if (abs (caretPos.getPosition() - selectionStart.getPosition()) < abs (caretPos.getPosition() - selectionEnd.getPosition())) dragType = draggingSelectionStart; else dragType = draggingSelectionEnd; } if (dragType == draggingSelectionStart) { selectionStart = caretPos; if (selectionEnd.getPosition() < selectionStart.getPosition()) { const CodeDocument::Position temp (selectionStart); selectionStart = selectionEnd; selectionEnd = temp; dragType = draggingSelectionEnd; } } else { selectionEnd = caretPos; if (selectionEnd.getPosition() < selectionStart.getPosition()) { const CodeDocument::Position temp (selectionStart); selectionStart = selectionEnd; selectionEnd = temp; dragType = draggingSelectionStart; } } triggerAsyncUpdate(); } else { deselectAll(); } updateCaretPosition(); scrollToKeepCaretOnScreen(); updateScrollBars(); } void CodeEditorComponent::deselectAll() { if (selectionStart != selectionEnd) triggerAsyncUpdate(); selectionStart = caretPos; selectionEnd = caretPos; } void CodeEditorComponent::updateScrollBars() { verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen)); verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen); horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen)); horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen); } void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen) { newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1), newFirstLineOnScreen); if (newFirstLineOnScreen != firstLineOnScreen) { firstLineOnScreen = newFirstLineOnScreen; updateCaretPosition(); updateCachedIterators (firstLineOnScreen); triggerAsyncUpdate(); } } void CodeEditorComponent::scrollToColumnInternal (double column) { const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column); if (xOffset != newOffset) { xOffset = newOffset; updateCaretPosition(); repaint(); } } void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen) { scrollToLineInternal (newFirstLineOnScreen); updateScrollBars(); } void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen) { scrollToColumnInternal (newFirstColumnOnScreen); updateScrollBars(); } void CodeEditorComponent::scrollBy (int deltaLines) { scrollToLine (firstLineOnScreen + deltaLines); } void CodeEditorComponent::scrollToKeepCaretOnScreen() { if (caretPos.getLineNumber() < firstLineOnScreen) scrollBy (caretPos.getLineNumber() - firstLineOnScreen); else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen) scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1)); const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine()); if (column >= xOffset + columnsOnScreen - 1) scrollToColumn (column + 1 - columnsOnScreen); else if (column < xOffset) scrollToColumn (column); } Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const { return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth), (pos.getLineNumber() - firstLineOnScreen) * lineHeight, roundToInt (charWidth), lineHeight); } CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y) { const int line = y / lineHeight + firstLineOnScreen; const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth); const int index = columnToIndex (line, column); return CodeDocument::Position (&document, line, index); } //============================================================================== void CodeEditorComponent::insertTextAtCaret (const String& newText) { document.deleteSection (selectionStart, selectionEnd); if (newText.isNotEmpty()) document.insertText (caretPos, newText); scrollToKeepCaretOnScreen(); } void CodeEditorComponent::insertTabAtCaret() { if (CharacterFunctions::isWhitespace (caretPos.getCharacter()) && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber()) { moveCaretTo (document.findWordBreakAfter (caretPos), false); } if (useSpacesForTabs) { const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine()); const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab); insertTextAtCaret (String::repeatedString (" ", spacesNeeded)); } else { insertTextAtCaret ("\t"); } } void CodeEditorComponent::cut() { insertTextAtCaret (String::empty); } bool CodeEditorComponent::copyToClipboard() { newTransaction(); const String selection (document.getTextBetween (selectionStart, selectionEnd)); if (selection.isNotEmpty()) SystemClipboard::copyTextToClipboard (selection); return true; } bool CodeEditorComponent::cutToClipboard() { copyToClipboard(); cut(); newTransaction(); return true; } bool CodeEditorComponent::pasteFromClipboard() { newTransaction(); const String clip (SystemClipboard::getTextFromClipboard()); if (clip.isNotEmpty()) insertTextAtCaret (clip); newTransaction(); return true; } bool CodeEditorComponent::moveCaretLeft (const bool moveInWholeWordSteps, const bool selecting) { newTransaction(); if (moveInWholeWordSteps) moveCaretTo (document.findWordBreakBefore (caretPos), selecting); else moveCaretTo (caretPos.movedBy (-1), selecting); return true; } bool CodeEditorComponent::moveCaretRight (const bool moveInWholeWordSteps, const bool selecting) { newTransaction(); if (moveInWholeWordSteps) moveCaretTo (document.findWordBreakAfter (caretPos), selecting); else moveCaretTo (caretPos.movedBy (1), selecting); return true; } void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting) { CodeDocument::Position pos (caretPos); const int newLineNum = pos.getLineNumber() + delta; if (columnToTryToMaintain < 0) columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine()); pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain)); const int colToMaintain = columnToTryToMaintain; moveCaretTo (pos, selecting); columnToTryToMaintain = colToMaintain; } bool CodeEditorComponent::moveCaretDown (const bool selecting) { newTransaction(); if (caretPos.getLineNumber() == document.getNumLines() - 1) moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting); else moveLineDelta (1, selecting); return true; } bool CodeEditorComponent::moveCaretUp (const bool selecting) { newTransaction(); if (caretPos.getLineNumber() == 0) moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting); else moveLineDelta (-1, selecting); return true; } bool CodeEditorComponent::pageDown (const bool selecting) { newTransaction(); scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen)); moveLineDelta (linesOnScreen, selecting); return true; } bool CodeEditorComponent::pageUp (const bool selecting) { newTransaction(); scrollBy (-linesOnScreen); moveLineDelta (-linesOnScreen, selecting); return true; } bool CodeEditorComponent::scrollUp() { newTransaction(); scrollBy (1); if (caretPos.getLineNumber() < firstLineOnScreen) moveLineDelta (1, false); return true; } bool CodeEditorComponent::scrollDown() { newTransaction(); scrollBy (-1); if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen) moveLineDelta (-1, false); return true; } bool CodeEditorComponent::moveCaretToTop (const bool selecting) { newTransaction(); moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting); return true; } namespace CodeEditorHelpers { static int findFirstNonWhitespaceChar (const String& line) noexcept { String::CharPointerType t (line.getCharPointer()); int i = 0; while (! t.isEmpty()) { if (! t.isWhitespace()) return i; ++t; ++i; } return 0; } } bool CodeEditorComponent::moveCaretToStartOfLine (const bool selecting) { newTransaction(); int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText()); if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0) index = 0; moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting); return true; } bool CodeEditorComponent::moveCaretToEnd (const bool selecting) { newTransaction(); moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting); return true; } bool CodeEditorComponent::moveCaretToEndOfLine (const bool selecting) { newTransaction(); moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting); return true; } bool CodeEditorComponent::deleteBackwards (const bool moveInWholeWordSteps) { if (moveInWholeWordSteps) { cut(); // in case something is already highlighted moveCaretTo (document.findWordBreakBefore (caretPos), true); } else { if (selectionStart == selectionEnd) selectionStart.moveBy (-1); } cut(); return true; } bool CodeEditorComponent::deleteForwards (const bool moveInWholeWordSteps) { if (moveInWholeWordSteps) { cut(); // in case something is already highlighted moveCaretTo (document.findWordBreakAfter (caretPos), true); } else { if (selectionStart == selectionEnd) selectionEnd.moveBy (1); else newTransaction(); } cut(); return true; } bool CodeEditorComponent::selectAll() { newTransaction(); moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false); moveCaretTo (CodeDocument::Position (&document, 0, 0), true); return true; } //============================================================================== bool CodeEditorComponent::undo() { document.undo(); scrollToKeepCaretOnScreen(); return true; } bool CodeEditorComponent::redo() { document.redo(); scrollToKeepCaretOnScreen(); return true; } void CodeEditorComponent::newTransaction() { document.newTransaction(); startTimer (600); } void CodeEditorComponent::timerCallback() { newTransaction(); } //============================================================================== Range<int> CodeEditorComponent::getHighlightedRegion() const { return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition()); } void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange) { moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false); moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true); } String CodeEditorComponent::getTextInRange (const Range<int>& range) const { return document.getTextBetween (CodeDocument::Position (&document, range.getStart()), CodeDocument::Position (&document, range.getEnd())); } //============================================================================== bool CodeEditorComponent::keyPressed (const KeyPress& key) { if (! TextEditorKeyMapper<CodeEditorComponent>::invokeKeyFunction (*this, key)) { if (key == KeyPress::tabKey || key.getTextCharacter() == '\t') { insertTabAtCaret(); } else if (key == KeyPress::returnKey) { newTransaction(); insertTextAtCaret (document.getNewLineCharacters()); } else if (key.isKeyCode (KeyPress::escapeKey)) { newTransaction(); } else if (key.getTextCharacter() >= ' ') { insertTextAtCaret (String::charToString (key.getTextCharacter())); } else { return false; } } return true; } void CodeEditorComponent::mouseDown (const MouseEvent& e) { newTransaction(); dragType = notDragging; if (! e.mods.isPopupMenu()) { beginDragAutoRepeat (100); moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown()); } else { /*PopupMenu m; addPopupMenuItems (m, &e); const int result = m.show(); if (result != 0) performPopupMenuAction (result); */ } } void CodeEditorComponent::mouseDrag (const MouseEvent& e) { if (! e.mods.isPopupMenu()) moveCaretTo (getPositionAt (e.x, e.y), true); } void CodeEditorComponent::mouseUp (const MouseEvent&) { newTransaction(); beginDragAutoRepeat (0); dragType = notDragging; } void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e) { CodeDocument::Position tokenStart (getPositionAt (e.x, e.y)); CodeDocument::Position tokenEnd (tokenStart); if (e.getNumberOfClicks() > 2) { tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0); tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0); } else { while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter())) tokenEnd.moveBy (1); tokenStart = tokenEnd; while (tokenStart.getIndexInLine() > 0 && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter())) tokenStart.moveBy (-1); } moveCaretTo (tokenEnd, false); moveCaretTo (tokenStart, true); } void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY) { if ((verticalScrollBar.isVisible() && wheelIncrementY != 0) || (horizontalScrollBar.isVisible() && wheelIncrementX != 0)) { verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY); horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0); } else { Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY); } } void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart) { if (scrollBarThatHasMoved == &verticalScrollBar) scrollToLineInternal ((int) newRangeStart); else scrollToColumnInternal (newRangeStart); } //============================================================================== void CodeEditorComponent::focusGained (FocusChangeType) { updateCaretPosition(); } void CodeEditorComponent::focusLost (FocusChangeType) { updateCaretPosition(); } //============================================================================== void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) { useSpacesForTabs = insertSpaces; if (spacesPerTab != numSpaces) { spacesPerTab = numSpaces; triggerAsyncUpdate(); } } int CodeEditorComponent::indexToColumn (int lineNum, int index) const noexcept { String::CharPointerType t (document.getLine (lineNum).getCharPointer()); int col = 0; for (int i = 0; i < index; ++i) { if (t.isEmpty()) { jassertfalse; break; } if (t.getAndAdvance() != '\t') ++col; else col += getTabSize() - (col % getTabSize()); } return col; } int CodeEditorComponent::columnToIndex (int lineNum, int column) const noexcept { String::CharPointerType t (document.getLine (lineNum).getCharPointer()); int i = 0, col = 0; while (! t.isEmpty()) { if (t.getAndAdvance() != '\t') ++col; else col += getTabSize() - (col % getTabSize()); if (col > column) break; ++i; } return i; } //============================================================================== void CodeEditorComponent::setFont (const Font& newFont) { font = newFont; charWidth = font.getStringWidthFloat ("0"); lineHeight = roundToInt (font.getHeight()); resized(); } void CodeEditorComponent::resetToDefaultColours() { coloursForTokenCategories.clear(); if (codeTokeniser != nullptr) { for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;) setColourForTokenType (i, codeTokeniser->getDefaultColour (i)); } } void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour) { jassert (tokenType < 256); while (coloursForTokenCategories.size() < tokenType) coloursForTokenCategories.add (Colours::black); coloursForTokenCategories.set (tokenType, colour); repaint(); } Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const { if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size())) return findColour (CodeEditorComponent::defaultTextColourId); return coloursForTokenCategories.getReference (tokenType); } void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) { int i; for (i = cachedIterators.size(); --i >= 0;) if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid) break; cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size()); } void CodeEditorComponent::updateCachedIterators (int maxLineNum) { const int maxNumCachedPositions = 5000; const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions); if (cachedIterators.size() == 0) cachedIterators.add (new CodeDocument::Iterator (&document)); if (codeTokeniser == nullptr) return; for (;;) { CodeDocument::Iterator* last = cachedIterators.getLast(); if (last->getLine() >= maxLineNum) break; CodeDocument::Iterator* t = new CodeDocument::Iterator (*last); cachedIterators.add (t); const int targetLine = last->getLine() + linesBetweenCachedSources; for (;;) { codeTokeniser->readNextToken (*t); if (t->getLine() >= targetLine) break; if (t->isEOF()) return; } } } void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source) { if (codeTokeniser == nullptr) return; for (int i = cachedIterators.size(); --i >= 0;) { CodeDocument::Iterator* t = cachedIterators.getUnchecked (i); if (t->getPosition() <= position) { source = *t; break; } } while (source.getPosition() < position) { const CodeDocument::Iterator original (source); codeTokeniser->readNextToken (source); if (source.getPosition() > position || source.isEOF()) { source = original; break; } } }
29.801514
155
0.591748
connerlacy
c50f535c2fc4aa6329094dcdc63decccf5c96e4c
56,567
cpp
C++
psx/octoshock/psx/cdc.cpp
Moliman/BizHawk
7d961d85bdf588072f344f220266002dee8ebc5a
[ "MIT" ]
29
2017-10-25T15:16:23.000Z
2021-02-23T04:49:18.000Z
psx/octoshock/psx/cdc.cpp
Moliman/BizHawk
7d961d85bdf588072f344f220266002dee8ebc5a
[ "MIT" ]
7
2019-01-14T14:46:46.000Z
2019-01-25T20:57:05.000Z
psx/octoshock/psx/cdc.cpp
Moliman/BizHawk
7d961d85bdf588072f344f220266002dee8ebc5a
[ "MIT" ]
9
2017-10-29T05:28:15.000Z
2020-03-24T02:11:01.000Z
/* Mednafen - Multi-system Emulator * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Games to test after changing code affecting CD reading and buffering: Bedlam Rise 2 */ // TODO: async command counter and async command phase? /* TODO: Implement missing commands. SPU CD-DA and CD-XA streaming semantics. */ /* After eject(doesn't appear to occur when drive is in STOP state): * Does not appear to occur in STOP state. * Does not appear to occur in PAUSE state. * DOES appear to occur in STANDBY state. (TODO: retest) % Result 0: 16 % Result 1: 08 % IRQ Result: e5 % 19 e0 Command abortion tests(NOP tested): Does not appear to occur when in STOP or PAUSE states(STOP or PAUSE command just executed). DOES occur after a ReadTOC completes, if ReadTOC is not followed by a STOP or PAUSE. Odd. */ #include "psx.h" #include "cdc.h" #include "spu.h" #include "endian.h" using namespace CDUtility; namespace MDFN_IEN_PSX { PS_CDC::PS_CDC() : DMABuffer(4096) { IsPSXDisc = false; Cur_disc = NULL; Open_disc = NULL; EnableLEC = false; DriveStatus = DS_STOPPED; PendingCommandPhase = 0; } PS_CDC::~PS_CDC() { } void PS_CDC::DMForceStop(void) { PSRCounter = 0; if((DriveStatus != DS_PAUSED && DriveStatus != DS_STOPPED) || PendingCommandPhase >= 2) { PendingCommand = 0x00; PendingCommandCounter = 0; PendingCommandPhase = 0; } HeaderBufValid = false; DriveStatus = DS_STOPPED; ClearAIP(); SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; } void PS_CDC::OpenTray() { //track the tray state TrayOpen = true; //effectively a NOP at t=0 DMForceStop(); //zero 31-jan-2015 - psxtech says that what this is used for is actually a 'was open' flag which gets cleared after the status gets polled. //so lets set it here, and rename it later if we're sure. Status_TrayOpenBit = true; //since Cur_disc tracks what the CDC sees mounted, it can't see anything now that it's open, so exchange these states Open_disc = Cur_disc; Cur_disc = NULL; } void PS_CDC::CloseTray(bool poke) { //track the tray state TrayOpen = false; //switch pending (open) disc to current disc Cur_disc = Open_disc; Open_disc = NULL; //cache Open_DiscID and clear it out char disc_id[5]; strncpy(disc_id,(char*)Open_DiscID,4); memset(Open_DiscID,0,sizeof(Open_DiscID)); //prepare analysis if disc: leave in empty state IsPSXDisc = false; memset(DiscID, 0, sizeof(DiscID)); //stuff to always happen, even when poking: if(Cur_disc) { Cur_disc->ReadTOC((ShockTOC*)&toc,(ShockTOCTrack*)toc.tracks); //complete analysis. if we had a disc ID, then it's a PSX disc; copy it in if(disc_id[0]) { strncpy((char *)DiscID, disc_id, 4); IsPSXDisc = true; } } //stuff to happen when not poking (reset CDC state) if(Cur_disc && !poke) { HeaderBufValid = false; DiscStartupDelay = (int64)1000 * 33868800 / 1000; } } void PS_CDC::SetDisc(ShockDiscRef *disc, const char *disc_id, bool poke) { Open_disc = disc; strncpy((char*)Open_DiscID,disc_id,4); if(poke) CloseTray(true); } int32 PS_CDC::CalcNextEvent(void) { int32 next_event = SPUCounter; if(PSRCounter > 0 && next_event > PSRCounter) next_event = PSRCounter; if(PendingCommandCounter > 0 && next_event > PendingCommandCounter) next_event = PendingCommandCounter; if(!(IRQBuffer & 0xF)) { if(CDCReadyReceiveCounter > 0 && next_event > CDCReadyReceiveCounter) next_event = CDCReadyReceiveCounter; } if(DiscStartupDelay > 0 && next_event > DiscStartupDelay) next_event = DiscStartupDelay; //fprintf(stderr, "%d %d %d %d --- %d\n", PSRCounter, PendingCommandCounter, CDCReadyReceiveCounter, DiscStartupDelay, next_event); return(next_event); } void PS_CDC::SoftReset(void) { ClearAudioBuffers(); // Not sure about initial volume state Pending_DecodeVolume[0][0] = 0x80; Pending_DecodeVolume[0][1] = 0x00; Pending_DecodeVolume[1][0] = 0x00; Pending_DecodeVolume[1][1] = 0x80; memcpy(DecodeVolume, Pending_DecodeVolume, sizeof(DecodeVolume)); RegSelector = 0; memset(ArgsBuf, 0, sizeof(ArgsBuf)); ArgsWP = ArgsRP = 0; memset(ResultsBuffer, 0, sizeof(ResultsBuffer)); ResultsWP = 0; ResultsRP = 0; ResultsIn = 0; CDCReadyReceiveCounter = 0; IRQBuffer = 0; IRQOutTestMask = 0; RecalcIRQ(); DMABuffer.Flush(); SB_In = 0; SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; //memset(SubQBuf, 0, sizeof(SubQBuf)); memset(SubQBuf_Safe, 0, sizeof(SubQBuf_Safe)); SubQChecksumOK = false; memset(HeaderBuf, 0, sizeof(HeaderBuf)); FilterFile = 0; FilterChan = 0; PendingCommand = 0; PendingCommandPhase = 0; PendingCommandCounter = 0; Mode = 0x20; HeaderBufValid = false; DriveStatus = DS_STOPPED; ClearAIP(); StatusAfterSeek = DS_STOPPED; SeekRetryCounter = 0; Forward = false; Backward = false; Muted = false; PlayTrackMatch = 0; PSRCounter = 0; CurSector = 0; ClearAIP(); SeekTarget = 0; CommandLoc = 0; CommandLoc_Dirty = true; Status_TrayOpenBit = true; TrayOpen = false; } void PS_CDC::Power(void) { SPU->Power(); SoftReset(); DiscStartupDelay = 0; SPUCounter = SPU->UpdateFromCDC(0); lastts = 0; } SYNCFUNC(PS_CDC) { NSS(TrayOpen); NSS(Status_TrayOpenBit); NSS(DiscStartupDelay); NSS(AudioBuffer); NSS(Pending_DecodeVolume); NSS(DecodeVolume); NSS(ADPCM_ResampBuf); NSS(ADPCM_ResampCurPhase); NSS(ADPCM_ResampCurPos); NSS(RegSelector); NSS(ArgsBuf); NSS(ArgsWP); NSS(ArgsRP); NSS(ArgsReceiveLatch); NSS(ArgsReceiveBuf); NSS(ArgsReceiveIn); NSS(ResultsBuffer); NSS(ResultsIn); NSS(ResultsWP); NSS(ResultsRP); SSS(DMABuffer); NSS(SB); NSS(SB_In); NSS(SectorPipe); NSS(SectorPipe_Pos); NSS(SectorPipe_In); //NSS(SubQBuf); NSS(SubQBuf_Safe); NSS(SubQChecksumOK); NSS(HeaderBufValid); NSS(HeaderBuf); NSS(IRQBuffer); NSS(IRQOutTestMask); NSS(CDCReadyReceiveCounter); NSS(FilterFile); NSS(FilterChan); NSS(PendingCommand); NSS(PendingCommandPhase); NSS(PendingCommandCounter); NSS(SPUCounter); NSS(Mode); NSS(DriveStatus); NSS(StatusAfterSeek); NSS(Forward); NSS(Backward); NSS(Muted); NSS(PlayTrackMatch); NSS(PSRCounter); NSS(CurSector); NSS(SectorsRead); NSS(AsyncIRQPending); NSS(AsyncResultsPending); NSS(AsyncResultsPendingCount); NSS(SeekTarget); NSS(SeekRetryCounter); // FIXME: Save TOC stuff? #if 0 CDUtility::TOC toc; bool IsPSXDisc; uint8 DiscID[4]; #endif NSS(CommandLoc); NSS(CommandLoc_Dirty); NSS(xa_previous); NSS(xa_cur_set); NSS(xa_cur_file); NSS(xa_cur_chan); NSS(ReportLastF); //(%= crap about file format recovery in case SectorPipe_Pos changes) } void PS_CDC::ResetTS(void) { lastts = 0; } void PS_CDC::RecalcIRQ(void) { IRQ_Assert(IRQ_CD, (bool)(IRQBuffer & (IRQOutTestMask & 0x1F))); } //static int32 doom_ts; void PS_CDC::WriteIRQ(uint8 V) { assert(CDCReadyReceiveCounter <= 0); assert(!(IRQBuffer & 0xF)); //PSX_WARNING("[CDC] ***IRQTHINGY: 0x%02x -- %u", V, doom_ts); CDCReadyReceiveCounter = 2000; //1024; IRQBuffer = (IRQBuffer & 0x10) | V; RecalcIRQ(); } void PS_CDC::BeginResults(void) { //if(ResultsIn) // { // printf("Cleared %d results. IRQBuffer=0x%02x\n", ResultsIn, IRQBuffer); //} ResultsIn = 0; ResultsWP = 0; ResultsRP = 0; memset(ResultsBuffer, 0x00, sizeof(ResultsBuffer)); } void PS_CDC::WriteResult(uint8 V) { ResultsBuffer[ResultsWP] = V; ResultsWP = (ResultsWP + 1) & 0xF; ResultsIn = (ResultsIn + 1) & 0x1F; if(!ResultsIn) PSX_WARNING("[CDC] Results buffer overflow!"); } uint8 PS_CDC::ReadResult(void) { uint8 ret = ResultsBuffer[ResultsRP]; if(!ResultsIn) PSX_WARNING("[CDC] Results buffer underflow!"); ResultsRP = (ResultsRP + 1) & 0xF; ResultsIn = (ResultsIn - 1) & 0x1F; return ret; } uint8 PS_CDC::MakeStatus(bool cmd_error) { uint8 ret = 0; // Are these bit positions right? if(DriveStatus == DS_PLAYING) ret |= 0x80; // Probably will want to be careful with this HeaderBufValid versus seek/read bit business in the future as it is a bit fragile; // "Gran Turismo 1"'s music(or erroneous lack of) is a good test case. if(DriveStatus == DS_READING) { if(!HeaderBufValid) ret |= 0x40; else ret |= 0x20; } else if(DriveStatus == DS_SEEKING || DriveStatus == DS_SEEKING_LOGICAL) ret |= 0x40; if(Status_TrayOpenBit) ret |= 0x10; if(DriveStatus != DS_STOPPED) ret |= 0x02; if(cmd_error) ret |= 0x01; //DiscChanged = false; // FIXME: Only do it on NOP command execution? //comment added with 0.9.38.5 - code removed by octoshock at some unknown point //maybe a good point for looking at disc swap related bugs return(ret); } bool PS_CDC::DecodeSubQ(uint8 *subpw) { uint8 tmp_q[0xC]; memset(tmp_q, 0, 0xC); for(int i = 0; i < 96; i++) tmp_q[i >> 3] |= ((subpw[i] & 0x40) >> 6) << (7 - (i & 7)); if((tmp_q[0] & 0xF) == 1) { SubQChecksumOK = subq_check_checksum(tmp_q); if(SubQChecksumOK) { memcpy(SubQBuf_Safe, tmp_q, 0xC); return(true); } } return(false); } static const int16 CDADPCMImpulse[7][25] = { { 0, -5, 17, -35, 70, -23, -68, 347, -839, 2062, -4681, 15367, 21472, -5882, 2810, -1352, 635, -235, 26, 43, -35, 16, -8, 2, 0, }, /* 0 */ { 0, -2, 10, -34, 65, -84, 52, 9, -266, 1024, -2680, 9036, 26516, -6016, 3021, -1571, 848, -365, 107, 10, -16, 17, -8, 3, -1, }, /* 1 */ { -2, 0, 3, -19, 60, -75, 162, -227, 306, -67, -615, 3229, 29883, -4532, 2488, -1471, 882, -424, 166, -27, 5, 6, -8, 3, -1, }, /* 2 */ { -1, 3, -2, -5, 31, -74, 179, -402, 689, -926, 1272, -1446, 31033, -1446, 1272, -926, 689, -402, 179, -74, 31, -5, -2, 3, -1, }, /* 3 */ { -1, 3, -8, 6, 5, -27, 166, -424, 882, -1471, 2488, -4532, 29883, 3229, -615, -67, 306, -227, 162, -75, 60, -19, 3, 0, -2, }, /* 4 */ { -1, 3, -8, 17, -16, 10, 107, -365, 848, -1571, 3021, -6016, 26516, 9036, -2680, 1024, -266, 9, 52, -84, 65, -34, 10, -2, 0, }, /* 5 */ { 0, 2, -8, 16, -35, 43, 26, -235, 635, -1352, 2810, -5882, 21472, 15367, -4681, 2062, -839, 347, -68, -23, 70, -35, 17, -5, 0, }, /* 6 */ }; void PS_CDC::ReadAudioBuffer(int32 samples[2]) { samples[0] = AudioBuffer.Samples[0][AudioBuffer.ReadPos]; samples[1] = AudioBuffer.Samples[1][AudioBuffer.ReadPos]; AudioBuffer.ReadPos++; } INLINE void PS_CDC::ApplyVolume(int32 samples[2]) { // // Take care not to alter samples[] before we're done calculating the new output samples! // int32 left_out = ((samples[0] * DecodeVolume[0][0]) >> 7) + ((samples[1] * DecodeVolume[1][0]) >> 7); int32 right_out = ((samples[0] * DecodeVolume[0][1]) >> 7) + ((samples[1] * DecodeVolume[1][1]) >> 7); clamp(&left_out, -32768, 32767); clamp(&right_out, -32768, 32767); if(Muted) { left_out = 0; right_out = 0; } samples[0] = left_out; samples[1] = right_out; } // // This function must always set samples[0] and samples[1], even if just to 0; range of samples[n] shall be restricted to -32768 through 32767. // void PS_CDC::GetCDAudio(int32 samples[2]) { const unsigned freq = (AudioBuffer.ReadPos < AudioBuffer.Size) ? AudioBuffer.Freq : 0; samples[0] = 0; samples[1] = 0; if(!freq) return; if(freq == 7 || freq == 14) { ReadAudioBuffer(samples); if(freq == 14) ReadAudioBuffer(samples); } else { int32 out_tmp[2] = { 0, 0 }; for(unsigned i = 0; i < 2; i++) { const int16* imp = CDADPCMImpulse[ADPCM_ResampCurPhase]; int16* wf = &ADPCM_ResampBuf[i][(ADPCM_ResampCurPos + 32 - 25) & 0x1F]; for(unsigned s = 0; s < 25; s++) { out_tmp[i] += imp[s] * wf[s]; } out_tmp[i] >>= 15; clamp(&out_tmp[i], -32768, 32767); samples[i] = out_tmp[i]; } ADPCM_ResampCurPhase += freq; if(ADPCM_ResampCurPhase >= 7) { int32 raw[2] = { 0, 0 }; ADPCM_ResampCurPhase -= 7; ReadAudioBuffer(raw); for(unsigned i = 0; i < 2; i++) { ADPCM_ResampBuf[i][ADPCM_ResampCurPos + 0] = ADPCM_ResampBuf[i][ADPCM_ResampCurPos + 32] = raw[i]; } ADPCM_ResampCurPos = (ADPCM_ResampCurPos + 1) & 0x1F; } } // // Algorithmically, volume is applied after resampling for CD-XA ADPCM playback, per PS1 tests(though when "mute" is applied wasn't tested). // ApplyVolume(samples); } EW_PACKED( struct XA_Subheader { uint8 file; uint8 channel; uint8 submode; uint8 coding; uint8 file_dup; uint8 channel_dup; uint8 submode_dup; uint8 coding_dup; }); EW_PACKED( struct XA_SoundGroup { uint8 params[16]; uint8 samples[112]; }); #define XA_SUBMODE_EOF 0x80 #define XA_SUBMODE_REALTIME 0x40 #define XA_SUBMODE_FORM 0x20 #define XA_SUBMODE_TRIGGER 0x10 #define XA_SUBMODE_DATA 0x08 #define XA_SUBMODE_AUDIO 0x04 #define XA_SUBMODE_VIDEO 0x02 #define XA_SUBMODE_EOR 0x01 #define XA_CODING_EMPHASIS 0x40 //#define XA_CODING_BPS_MASK 0x30 //#define XA_CODING_BPS_4BIT 0x00 //#define XA_CODING_BPS_8BIT 0x10 //#define XA_CODING_SR_MASK 0x0C //#define XA_CODING_SR_378 0x00 //#define XA_CODING_SR_ #define XA_CODING_8BIT 0x10 #define XA_CODING_189 0x04 #define XA_CODING_STEREO 0x01 // Special regression prevention test cases: // Um Jammer Lammy (start doing poorly) // Yarudora Series Vol.1 - Double Cast (non-FMV speech) bool PS_CDC::XA_Test(const uint8 *sdata) { const XA_Subheader *sh = (const XA_Subheader *)&sdata[12 + 4]; if(!(Mode & MODE_STRSND)) return false; if(!(sh->submode & XA_SUBMODE_AUDIO)) return false; //printf("Test File: 0x%02x 0x%02x - Channel: 0x%02x 0x%02x - Submode: 0x%02x 0x%02x - Coding: 0x%02x 0x%02x - \n", sh->file, sh->file_dup, sh->channel, sh->channel_dup, sh->submode, sh->submode_dup, sh->coding, sh->coding_dup); if((Mode & MODE_SF) && (sh->file != FilterFile || sh->channel != FilterChan)) return false; if(!xa_cur_set || (Mode & MODE_SF)) { xa_cur_set = true; xa_cur_file = sh->file; xa_cur_chan = sh->channel; } else if(sh->file != xa_cur_file || sh->channel != xa_cur_chan) return false; if(sh->submode & XA_SUBMODE_EOF) { //puts("YAY"); xa_cur_set = false; xa_cur_file = 0; xa_cur_chan = 0; } return true; } void PS_CDC::ClearAudioBuffers(void) { memset(&AudioBuffer, 0, sizeof(AudioBuffer)); memset(xa_previous, 0, sizeof(xa_previous)); xa_cur_set = false; xa_cur_file = 0; xa_cur_chan = 0; memset(ADPCM_ResampBuf, 0, sizeof(ADPCM_ResampBuf)); ADPCM_ResampCurPhase = 0; ADPCM_ResampCurPos = 0; } // // output should be readable at -2 and -1 static void DecodeXAADPCM(const uint8 *input, int16 *output, const unsigned shift, const unsigned weight) { // Weights copied over from SPU channel ADPCM playback code, may not be entirely the same for CD-XA ADPCM, we need to run tests. static const int32 Weights[16][2] = { // s-1 s-2 { 0, 0 }, { 60, 0 }, { 115, -52 }, { 98, -55 }, { 122, -60 }, }; for(int i = 0; i < 28; i++) { int32 sample; sample = (int16)(input[i] << 8); sample >>= shift; sample += ((output[i - 1] * Weights[weight][0]) >> 6) + ((output[i - 2] * Weights[weight][1]) >> 6); if(sample < -32768) sample = -32768; if(sample > 32767) sample = 32767; output[i] = sample; } } void PS_CDC::XA_ProcessSector(const uint8 *sdata, CD_Audio_Buffer *ab) { const XA_Subheader *sh = (const XA_Subheader *)&sdata[12 + 4]; const unsigned unit_index_shift = (sh->coding & XA_CODING_8BIT) ? 0 : 1; //printf("File: 0x%02x 0x%02x - Channel: 0x%02x 0x%02x - Submode: 0x%02x 0x%02x - Coding: 0x%02x 0x%02x - \n", sh->file, sh->file_dup, sh->channel, sh->channel_dup, sh->submode, sh->submode_dup, sh->coding, sh->coding_dup); ab->ReadPos = 0; ab->Size = 18 * (4 << unit_index_shift) * 28; if(sh->coding & XA_CODING_STEREO) ab->Size >>= 1; ab->Freq = (sh->coding & XA_CODING_189) ? 3 : 6; //fprintf(stderr, "Coding: %02x %02x\n", sh->coding, sh->coding_dup); for(unsigned group = 0; group < 18; group++) { const XA_SoundGroup *sg = (const XA_SoundGroup *)&sdata[12 + 4 + 8 + group * 128]; for(unsigned unit = 0; unit < (4U << unit_index_shift); unit++) { const uint8 param = sg->params[(unit & 3) | ((unit & 4) << 1)]; const uint8 param_copy = sg->params[4 | (unit & 3) | ((unit & 4) << 1)]; uint8 ibuffer[28]; int16 obuffer[2 + 28]; if(param != param_copy) { PSX_WARNING("[CDC] CD-XA param != param_copy --- %d %02x %02x\n", unit, param, param_copy); } for(unsigned i = 0; i < 28; i++) { uint8 tmp = sg->samples[i * 4 + (unit >> unit_index_shift)]; if(unit_index_shift) { tmp <<= (unit & 1) ? 0 : 4; tmp &= 0xf0; } ibuffer[i] = tmp; } const bool ocn = (bool)(unit & 1) && (sh->coding & XA_CODING_STEREO); obuffer[0] = xa_previous[ocn][0]; obuffer[1] = xa_previous[ocn][1]; DecodeXAADPCM(ibuffer, &obuffer[2], param & 0x0F, param >> 4); xa_previous[ocn][0] = obuffer[28]; xa_previous[ocn][1] = obuffer[29]; if(param != param_copy) memset(obuffer, 0, sizeof(obuffer)); if(sh->coding & XA_CODING_STEREO) { for(unsigned s = 0; s < 28; s++) { ab->Samples[ocn][group * (2 << unit_index_shift) * 28 + (unit >> 1) * 28 + s] = obuffer[2 + s]; } } else { for(unsigned s = 0; s < 28; s++) { ab->Samples[0][group * (4 << unit_index_shift) * 28 + unit * 28 + s] = obuffer[2 + s]; ab->Samples[1][group * (4 << unit_index_shift) * 28 + unit * 28 + s] = obuffer[2 + s]; } } } } #if 0 // Test for(unsigned i = 0; i < ab->Size; i++) { static unsigned counter = 0; ab->Samples[0][i] = (counter & 2) ? -0x6000 : 0x6000; ab->Samples[1][i] = rand(); counter++; } #endif } void PS_CDC::ClearAIP(void) { AsyncResultsPendingCount = 0; AsyncIRQPending = 0; } void PS_CDC::CheckAIP(void) { if(AsyncIRQPending && CDCReadyReceiveCounter <= 0) { BeginResults(); for(unsigned i = 0; i < AsyncResultsPendingCount; i++) WriteResult(AsyncResultsPending[i]); WriteIRQ(AsyncIRQPending); ClearAIP(); } } void PS_CDC::SetAIP(unsigned irq, unsigned result_count, uint8 *r) { if(AsyncIRQPending) { PSX_WARNING("***WARNING*** Previous notification skipped: CurSector=%d, old_notification=0x%02x", CurSector, AsyncIRQPending); } ClearAIP(); AsyncResultsPendingCount = result_count; for(unsigned i = 0; i < result_count; i++) AsyncResultsPending[i] = r[i]; AsyncIRQPending = irq; CheckAIP(); } void PS_CDC::SetAIP(unsigned irq, uint8 result0) { uint8 tr[1] = { result0 }; SetAIP(irq, 1, tr); } void PS_CDC::SetAIP(unsigned irq, uint8 result0, uint8 result1) { uint8 tr[2] = { result0, result1 }; SetAIP(irq, 2, tr); } void PS_CDC::EnbufferizeCDDASector(const uint8 *buf) { CD_Audio_Buffer *ab = &AudioBuffer; ab->Freq = 7 * ((Mode & MODE_SPEED) ? 2 : 1); ab->Size = 588; if(SubQBuf_Safe[0] & 0x40) { for(int i = 0; i < 588; i++) { ab->Samples[0][i] = 0; ab->Samples[1][i] = 0; } } else { for(int i = 0; i < 588; i++) { ab->Samples[0][i] = (int16)MDFN_de16lsb<false>(&buf[i * sizeof(int16) * 2 + 0]); ab->Samples[1][i] = (int16)MDFN_de16lsb<false>(&buf[i * sizeof(int16) * 2 + 2]); } } ab->ReadPos = 0; } // SetAIP(CDCIRQ_DISC_ERROR, MakeStatus() | 0x04, 0x04); void PS_CDC::HandlePlayRead(void) { uint8 read_buf[2352 + 96]; //PSX_WARNING("Read sector: %d", CurSector); if(CurSector >= ((int32)toc.tracks[100].lba + 300) && CurSector >= (75 * 60 * 75 - 150)) { PSX_WARNING("[CDC] Read/Play position waaay too far out(%u), forcing STOP", CurSector); DriveStatus = DS_STOPPED; SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; return; } if(CurSector >= (int32)toc.tracks[100].lba) { PSX_WARNING("[CDC] In leadout area: %u", CurSector); //ZERO TODO - this is the critical point for testing leadout-reading. } Cur_disc->ReadLBA2448(CurSector,read_buf); // FIXME: error out on error. DecodeSubQ(read_buf + 2352); if(SubQBuf_Safe[1] == 0xAA && (DriveStatus == DS_PLAYING || (!(SubQBuf_Safe[0] & 0x40) && (Mode & MODE_CDDA)))) { HeaderBufValid = false; PSX_WARNING("[CDC] CD-DA leadout reached: %u", CurSector); // Status in this end-of-disc context here should be generated after we're in the pause state. DriveStatus = DS_PAUSED; SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; SetAIP(CDCIRQ_DATA_END, MakeStatus()); return; } if(DriveStatus == DS_PLAYING) { // Note: Some game(s) start playing in the pregap of a track(so don't replace this with a simple subq index == 0 check for autopause). if(PlayTrackMatch == -1 && SubQChecksumOK) PlayTrackMatch = SubQBuf_Safe[0x1]; if((Mode & MODE_AUTOPAUSE) && PlayTrackMatch != -1 && SubQBuf_Safe[0x1] != PlayTrackMatch) { // Status needs to be taken before we're paused(IE it should still report playing). SetAIP(CDCIRQ_DATA_END, MakeStatus()); DriveStatus = DS_PAUSED; SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; PSRCounter = 0; return; } if((Mode & MODE_REPORT) && (((SubQBuf_Safe[0x9] >> 4) != ReportLastF) || Forward || Backward) && SubQChecksumOK) { uint8 tr[8]; //zero 14-jun-2016 - useful after all for fixing bugs in "Fantastic Pinball Kyutenkai" #if 1 uint16 abs_lev_max = 0; bool abs_lev_chselect = SubQBuf_Safe[0x8] & 0x01; for(int i = 0; i < 588; i++) abs_lev_max = std::max<uint16>(abs_lev_max, std::min<int>(abs((int16)MDFN_de16lsb(&read_buf[i * 4 + (abs_lev_chselect * 2)])), 32767)); abs_lev_max |= abs_lev_chselect << 15; #endif ReportLastF = SubQBuf_Safe[0x9] >> 4; tr[0] = MakeStatus(); tr[1] = SubQBuf_Safe[0x1]; // Track tr[2] = SubQBuf_Safe[0x2]; // Index if(SubQBuf_Safe[0x9] & 0x10) { tr[3] = SubQBuf_Safe[0x3]; // R M tr[4] = SubQBuf_Safe[0x4] | 0x80; // R S tr[5] = SubQBuf_Safe[0x5]; // R F } else { tr[3] = SubQBuf_Safe[0x7]; // A M tr[4] = SubQBuf_Safe[0x8]; // A S tr[5] = SubQBuf_Safe[0x9]; // A F } //zero 14-jun-2016 - useful after all for fixing bugs in "Fantastic Pinball Kyutenkai" //tr[6] = 0; //abs_lev_max >> 0; //tr[7] = 0; //abs_lev_max >> 8; tr[6] = abs_lev_max >> 0; tr[7] = abs_lev_max >> 8; SetAIP(CDCIRQ_DATA_READY, 8, tr); } } if(SectorPipe_In >= SectorPipe_Count) { uint8* buf = SectorPipe[SectorPipe_Pos]; SectorPipe_In--; if(DriveStatus == DS_READING) { if(SubQBuf_Safe[0] & 0x40) //) || !(Mode & MODE_CDDA)) { memcpy(HeaderBuf, buf + 12, 12); HeaderBufValid = true; if((Mode & MODE_STRSND) && (buf[12 + 3] == 0x2) && ((buf[12 + 6] & 0x64) == 0x64)) { if(XA_Test(buf)) { if(AudioBuffer.ReadPos < AudioBuffer.Size) { PSX_WARNING("[CDC] CD-XA ADPCM sector skipped - readpos=0x%04x, size=0x%04x", AudioBuffer.ReadPos, AudioBuffer.Size); } else { XA_ProcessSector(buf, &AudioBuffer); } } } else { // maybe if(!(Mode & 0x30)) too? if(!(buf[12 + 6] & 0x20)) { #ifdef WANT_LEC_CHECK if (EnableLEC) { if (!edc_lec_check_and_correct(buf, true)) { printf("Bad sector? - %d", CurSector); } } #endif } if(!(Mode & 0x30) && (buf[12 + 6] & 0x20)) PSX_WARNING("[CDC] BORK: %d", CurSector); int32 offs = (Mode & 0x20) ? 0 : 12; int32 size = (Mode & 0x20) ? 2340 : 2048; if(Mode & 0x10) { offs = 12; size = 2328; } memcpy(SB, buf + 12 + offs, size); SB_In = size; SetAIP(CDCIRQ_DATA_READY, MakeStatus()); } } } if(!(SubQBuf_Safe[0] & 0x40) && ((Mode & MODE_CDDA) || DriveStatus == DS_PLAYING)) { if(AudioBuffer.ReadPos < AudioBuffer.Size) { PSX_WARNING("[CDC] BUG CDDA buffer full"); } else { EnbufferizeCDDASector(buf); } } } memcpy(SectorPipe[SectorPipe_Pos], read_buf, 2352); SectorPipe_Pos = (SectorPipe_Pos + 1) % SectorPipe_Count; SectorPipe_In++; PSRCounter += 33868800 / (75 * ((Mode & MODE_SPEED) ? 2 : 1)); if(DriveStatus == DS_PLAYING) { // FIXME: What's the real fast-forward and backward speed? if(Forward) CurSector += 12; else if(Backward) { CurSector -= 12; if(CurSector < 0) // FIXME: How does a real PS handle this condition? CurSector = 0; } else CurSector++; } else CurSector++; SectorsRead++; } pscpu_timestamp_t PS_CDC::Update(const pscpu_timestamp_t timestamp) { int32 clocks = timestamp - lastts; //doom_ts = timestamp; while(clocks > 0) { int32 chunk_clocks = clocks; if(PSRCounter > 0 && chunk_clocks > PSRCounter) chunk_clocks = PSRCounter; if(PendingCommandCounter > 0 && chunk_clocks > PendingCommandCounter) chunk_clocks = PendingCommandCounter; if(chunk_clocks > SPUCounter) chunk_clocks = SPUCounter; if(DiscStartupDelay > 0) { if(chunk_clocks > DiscStartupDelay) chunk_clocks = DiscStartupDelay; DiscStartupDelay -= chunk_clocks; if(DiscStartupDelay <= 0) { DriveStatus = DS_PAUSED; // or is it supposed to be DS_STANDBY? } } //MDFN_DispMessage("%02x %d -- %d %d -- %02x", IRQBuffer, CDCReadyReceiveCounter, PSRCounter, PendingCommandCounter, PendingCommand); if(!(IRQBuffer & 0xF)) { if(CDCReadyReceiveCounter > 0 && chunk_clocks > CDCReadyReceiveCounter) chunk_clocks = CDCReadyReceiveCounter; if(CDCReadyReceiveCounter > 0) CDCReadyReceiveCounter -= chunk_clocks; } CheckAIP(); if(PSRCounter > 0) { uint8 pwbuf[96]; PSRCounter -= chunk_clocks; if(PSRCounter <= 0) { if(DriveStatus == DS_RESETTING) { SetAIP(CDCIRQ_COMPLETE, MakeStatus()); Muted = false; // Does it get reset here? ClearAudioBuffers(); SB_In = 0; SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; Mode = 0x20; // Confirmed(and see "This Is Football 2"). CurSector = 0; CommandLoc = 0; DriveStatus = DS_PAUSED; // or DS_STANDBY? ClearAIP(); } else if(DriveStatus == DS_SEEKING) { CurSector = SeekTarget; // // CurSector + x for "Tomb Raider"'s sake, as it relies on behavior that we can't emulate very well without a more accurate CD drive // emulation model. // for(int x = -1; x >= -16; x--) { //printf("%d\n", CurSector + x); Cur_disc->ReadLBA_PW(pwbuf, CurSector + x, false); if(DecodeSubQ(pwbuf)) break; } DriveStatus = StatusAfterSeek; if(DriveStatus != DS_PAUSED && DriveStatus != DS_STANDBY) { PSRCounter = 33868800 / (75 * ((Mode & MODE_SPEED) ? 2 : 1)); } } else if(DriveStatus == DS_SEEKING_LOGICAL) { CurSector = SeekTarget; Cur_disc->ReadLBA_PW(pwbuf, CurSector, false); DecodeSubQ(pwbuf); if(!(Mode & MODE_CDDA) && !(SubQBuf_Safe[0] & 0x40)) { if(!SeekRetryCounter) { DriveStatus = DS_STANDBY; SetAIP(CDCIRQ_DISC_ERROR, MakeStatus() | 0x04, 0x04); } else { SeekRetryCounter--; PSRCounter = 33868800 / 75; } } else { DriveStatus = StatusAfterSeek; if(DriveStatus != DS_PAUSED && DriveStatus != DS_STANDBY) { PSRCounter = 33868800 / (75 * ((Mode & MODE_SPEED) ? 2 : 1)); } } } else if(DriveStatus == DS_READING || DriveStatus == DS_PLAYING) { HandlePlayRead(); } } } if(PendingCommandCounter > 0) { PendingCommandCounter -= chunk_clocks; if(PendingCommandCounter <= 0 && CDCReadyReceiveCounter > 0) { PendingCommandCounter = CDCReadyReceiveCounter; //256; } //else if(PendingCommandCounter <= 0 && PSRCounter > 0 && PSRCounter < 2000) //{ // PendingCommandCounter = PSRCounter + 1; //} else if(PendingCommandCounter <= 0) { int32 next_time = 0; if(PendingCommandPhase == -1) { if(ArgsRP != ArgsWP) { ArgsReceiveLatch = ArgsBuf[ArgsRP & 0x0F]; ArgsRP = (ArgsRP + 1) & 0x1F; PendingCommandPhase += 1; next_time = 1815; } else { PendingCommandPhase += 2; next_time = 8500; } } else if(PendingCommandPhase == 0) // Command phase 0 { if(ArgsReceiveIn < 32) ArgsReceiveBuf[ArgsReceiveIn++] = ArgsReceiveLatch; if(ArgsRP != ArgsWP) { ArgsReceiveLatch = ArgsBuf[ArgsRP & 0x0F]; ArgsRP = (ArgsRP + 1) & 0x1F; next_time = 1815; } else { PendingCommandPhase++; next_time = 8500; } } else if(PendingCommandPhase >= 2) // Command phase 2+ { BeginResults(); const CDC_CTEntry *command = &Commands[PendingCommand]; next_time = (this->*(command->func2))(); } else // Command phase 1 { if(PendingCommand >= 0x20 || !Commands[PendingCommand].func) { BeginResults(); PSX_WARNING("[CDC] Unknown command: 0x%02x", PendingCommand); WriteResult(MakeStatus(true)); WriteResult(ERRCODE_BAD_COMMAND); WriteIRQ(CDCIRQ_DISC_ERROR); } else if(ArgsReceiveIn < Commands[PendingCommand].args_min || ArgsReceiveIn > Commands[PendingCommand].args_max) { BeginResults(); PSX_DBG(PSX_DBG_WARNING, "[CDC] Bad number(%d) of args(first check) for command 0x%02x", ArgsReceiveIn, PendingCommand); for(unsigned int i = 0; i < ArgsReceiveIn; i++) PSX_DBG(PSX_DBG_WARNING, " 0x%02x", ArgsReceiveBuf[i]); PSX_DBG(PSX_DBG_WARNING, "\n"); WriteResult(MakeStatus(true)); WriteResult(ERRCODE_BAD_NUMARGS); WriteIRQ(CDCIRQ_DISC_ERROR); } else { BeginResults(); const CDC_CTEntry *command = &Commands[PendingCommand]; PSX_DBG(PSX_DBG_SPARSE, "[CDC] Command: %s --- ", command->name); for(unsigned int i = 0; i < ArgsReceiveIn; i++) PSX_DBG(PSX_DBG_SPARSE, " 0x%02x", ArgsReceiveBuf[i]); PSX_DBG(PSX_DBG_SPARSE, "\n"); next_time = (this->*(command->func))(ArgsReceiveIn, ArgsReceiveBuf); PendingCommandPhase = 2; } ArgsReceiveIn = 0; } // end command phase 1 if(!next_time) PendingCommandCounter = 0; else PendingCommandCounter += next_time; } } SPUCounter = SPU->UpdateFromCDC(chunk_clocks); clocks -= chunk_clocks; } // end while(clocks > 0) lastts = timestamp; return(timestamp + CalcNextEvent()); } void PS_CDC::Write(const pscpu_timestamp_t timestamp, uint32 A, uint8 V) { A &= 0x3; //printf("Write: %08x %02x\n", A, V); if(A == 0x00) { RegSelector = V & 0x3; } else { const unsigned reg_index = ((RegSelector & 0x3) * 3) + (A - 1); Update(timestamp); //PSX_WARNING("[CDC] Write to register 0x%02x: 0x%02x @ %d --- 0x%02x 0x%02x\n", reg_index, V, timestamp, DMABuffer.CanRead(), IRQBuffer); switch(reg_index) { default: PSX_WARNING("[CDC] Unknown write to register 0x%02x: 0x%02x\n", reg_index, V); break; case 0x00: if(PendingCommandCounter > 0) { PSX_WARNING("[CDC] WARNING: Interrupting command 0x%02x, phase=%d, timeleft=%d with command=0x%02x", PendingCommand, PendingCommandPhase, PendingCommandCounter, V); } if(IRQBuffer & 0xF) { PSX_WARNING("[CDC] Attempting to start command(0x%02x) while IRQBuffer(0x%02x) is not clear.", V, IRQBuffer); } if(ResultsIn > 0) { PSX_WARNING("[CDC] Attempting to start command(0x%02x) while command results(count=%d) still in buffer.", V, ResultsIn); } PendingCommandCounter = 10500 + PSX_GetRandU32(0, 3000) + 1815; PendingCommand = V; PendingCommandPhase = -1; ArgsReceiveIn = 0; break; case 0x01: ArgsBuf[ArgsWP & 0xF] = V; ArgsWP = (ArgsWP + 1) & 0x1F; if(!((ArgsWP - ArgsRP) & 0x0F)) { PSX_WARNING("[CDC] Argument buffer overflow"); } break; case 0x02: if(V & 0x80) { if(!DMABuffer.CanRead()) { if(!SB_In) { PSX_WARNING("[CDC] Data read begin when no data to read!"); DMABuffer.Write(SB, 2340); while(DMABuffer.CanWrite()) DMABuffer.WriteByte(0x00); } else { DMABuffer.Write(SB, SB_In); SB_In = 0; } } else { //PSX_WARNING("[CDC] Attempt to start data transfer via 0x80->1803 when %d bytes still in buffer", DMABuffer.CanRead()); } } else if(V & 0x40) // Something CD-DA related(along with & 0x20 ???)? { for(unsigned i = 0; i < 4 && DMABuffer.CanRead(); i++) DMABuffer.ReadByte(); } else { DMABuffer.Flush(); } if(V & 0x20) { PSX_WARNING("[CDC] Mystery IRQ trigger bit set."); IRQBuffer |= 0x10; RecalcIRQ(); } break; case 0x04: IRQOutTestMask = V; RecalcIRQ(); break; case 0x05: if((IRQBuffer &~ V) != IRQBuffer && ResultsIn) { // To debug icky race-condition related problems in "Psychic Detective", and to see if any games suffer from the same potential issue // (to know what to test when we emulate CPU more accurately in regards to pipeline stalls and timing, which could throw off our kludge // for this issue) PSX_WARNING("[CDC] Acknowledged IRQ(wrote 0x%02x, before_IRQBuffer=0x%02x) while %u bytes in results buffer.", V, IRQBuffer, ResultsIn); } IRQBuffer &= ~V; RecalcIRQ(); if(V & 0x80) // Forced CD hardware reset of some kind(interface, controller, and drive?) Seems to take a while(relatively speaking) to complete. { PSX_WARNING("[CDC] Soft Reset"); SoftReset(); } if(V & 0x40) // Does it clear more than arguments buffer? Doesn't appear to clear results buffer. { ArgsWP = ArgsRP = 0; } break; case 0x07: Pending_DecodeVolume[0][0] = V; break; case 0x08: Pending_DecodeVolume[0][1] = V; break; case 0x09: Pending_DecodeVolume[1][1] = V; break; case 0x0A: Pending_DecodeVolume[1][0] = V; break; case 0x0B: if(V & 0x20) { memcpy(DecodeVolume, Pending_DecodeVolume, sizeof(DecodeVolume)); for(int i = 0; i < 2; i++) { for(int o = 0; o < 2; o++) { //fprintf(stderr, "Input Channel %d, Output Channel %d -- Volume=%d\n", i, o, DecodeVolume[i][o]); } } } break; } PSX_SetEventNT(PSX_EVENT_CDC, timestamp + CalcNextEvent()); } } uint8 PS_CDC::Read(const pscpu_timestamp_t timestamp, uint32 A) { uint8 ret = 0; A &= 0x03; //printf("Read %08x\n", A); if(A == 0x00) { ret = RegSelector & 0x3; if(ArgsWP == ArgsRP) ret |= 0x08; // Args FIFO empty. if(!((ArgsWP - ArgsRP) & 0x10)) ret |= 0x10; // Args FIFO has room. if(ResultsIn) ret |= 0x20; if(DMABuffer.CanRead()) ret |= 0x40; if(PendingCommandCounter > 0 && PendingCommandPhase <= 1) ret |= 0x80; } else { switch(A & 0x3) { case 0x01: ret = ReadResult(); break; case 0x02: //PSX_WARNING("[CDC] DMA Buffer manual read"); if(DMABuffer.CanRead()) ret = DMABuffer.ReadByte(); else { PSX_WARNING("[CDC] CD data transfer port read, but no data present!"); } break; case 0x03: if(RegSelector & 0x1) { ret = 0xE0 | IRQBuffer; } else { ret = 0xFF; } break; } } return(ret); } bool PS_CDC::DMACanRead(void) { return(DMABuffer.CanRead()); } uint32 PS_CDC::DMARead(void) { uint32 data = 0; for(int i = 0; i < 4; i++) { if(DMABuffer.CanRead()) data |= DMABuffer.ReadByte() << (i * 8); else { //assert(0); } } return(data); } bool PS_CDC::CommandCheckDiscPresent(void) { if(!Cur_disc || DiscStartupDelay > 0) { WriteResult(MakeStatus(true)); WriteResult(ERRCODE_NOT_READY); WriteIRQ(CDCIRQ_DISC_ERROR); return(false); } return(true); } int32 PS_CDC::Command_GetStat(const int arg_count, const uint8 *args) { WriteResult(MakeStatus()); //PSX-SPX: this command ACKs the TrayOpenBit if the shell is no longer open //(mednafen does this differently) if(!TrayOpen) Status_TrayOpenBit = false; WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_Setloc(const int arg_count, const uint8 *args) { uint8 m, s, f; if((args[0] & 0x0F) > 0x09 || args[0] > 0x99 || (args[1] & 0x0F) > 0x09 || args[1] > 0x59 || (args[2] & 0x0F) > 0x09 || args[2] > 0x74) { WriteResult(MakeStatus(true)); WriteResult(ERRCODE_BAD_ARGVAL); WriteIRQ(CDCIRQ_DISC_ERROR); return(0); } m = BCD_to_U8(args[0]); s = BCD_to_U8(args[1]); f = BCD_to_U8(args[2]); CommandLoc = f + 75 * s + 75 * 60 * m - 150; CommandLoc_Dirty = true; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::CalcSeekTime(int32 initial, int32 target, bool motor_on, bool paused) { int32 ret = 0; if(!motor_on) { initial = 0; ret += 33868800; } ret += std::max<int64>((int64)abs(initial - target) * 33868800 * 1000 / (72 * 60 * 75) / 1000, 20000); if(abs(initial - target) >= 2250) ret += (int64)33868800 * 300 / 1000; else if(paused) { // The delay to restart from a Pause state is...very....WEIRD. The time it takes is related to the amount of time that has passed since the pause, and // where on the disc the laser head is, with generally more time passed = longer to resume, except that there's a window of time where it takes a // ridiculous amount of time when not much time has passed. // // What we have here will be EXTREMELY simplified. // // //if(time_passed >= 67737) //{ //} //else { // Take twice as long for 1x mode. ret += 1237952 * ((Mode & MODE_SPEED) ? 1 : 2); } } //else if(target < initial) // ret += 1000000; ret += PSX_GetRandU32(0, 25000); PSX_DBG(PSX_DBG_SPARSE, "[CDC] CalcSeekTime() %d->%d = %d\n", initial, target, ret); return(ret); } #if 0 void PS_CDC::BeginSeek(uint32 target, int after_seek) { SeekTarget = target; StatusAfterSeek = after_seek; PSRCounter = CalcSeekTime(CurSector, SeekTarget, DriveStatus != DS_STOPPED, DriveStatus == DS_PAUSED); } #endif // Remove this function when we have better seek emulation; it's here because the Rockman complete works games(at least 2 and 4) apparently have finicky fubared CD // access code. void PS_CDC::PreSeekHack(int32 target) { uint8 pwbuf[96]; int max_try = 32; CurSector = target; // If removing/changing this, take into account how it will affect ReadN/ReadS/Play/etc command calls that interrupt a seek. SeekRetryCounter = 128; // If removing this SubQ reading bit, think about how it will interact with a Read command of data(or audio :b) sectors when Mode bit0 is 1. do { Cur_disc->ReadLBA_PW(pwbuf, target++, true); } while(!DecodeSubQ(pwbuf) && --max_try > 0); } /* Play command with a track argument that's not a valid BCD quantity causes interesting half-buggy behavior on an actual PS1(unlike some of the other commands, an error doesn't seem to be generated for a bad BCD argument). */ int32 PS_CDC::Command_Play(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); ClearAIP(); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); Forward = Backward = false; if(arg_count && args[0]) { int track = BCD_to_U8(args[0]); if(track < toc.first_track) { PSX_WARNING("[CDC] Attempt to play track before first track."); track = toc.first_track; } else if(track > toc.last_track) { PSX_WARNING("[CDC] Attempt to play track after last track."); track = toc.last_track; } ClearAudioBuffers(); SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; PlayTrackMatch = track; PSX_WARNING("[CDC] Play track: %d", track); SeekTarget = toc.tracks[track].lba; PSRCounter = CalcSeekTime(CurSector, SeekTarget, DriveStatus != DS_STOPPED, DriveStatus == DS_PAUSED); HeaderBufValid = false; PreSeekHack(SeekTarget); ReportLastF = 0xFF; DriveStatus = DS_SEEKING; StatusAfterSeek = DS_PLAYING; } else if(CommandLoc_Dirty || DriveStatus != DS_PLAYING) { ClearAudioBuffers(); SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; if(CommandLoc_Dirty) SeekTarget = CommandLoc; else SeekTarget = CurSector; PlayTrackMatch = -1; PSRCounter = CalcSeekTime(CurSector, SeekTarget, DriveStatus != DS_STOPPED, DriveStatus == DS_PAUSED); HeaderBufValid = false; PreSeekHack(SeekTarget); ReportLastF = 0xFF; DriveStatus = DS_SEEKING; StatusAfterSeek = DS_PLAYING; } CommandLoc_Dirty = false; return(0); } int32 PS_CDC::Command_Forward(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); Backward = false; Forward = true; return(0); } int32 PS_CDC::Command_Backward(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); Backward = true; Forward = false; return(0); } void PS_CDC::ReadBase(void) { if(!CommandCheckDiscPresent()) return; if(!IsPSXDisc) { WriteResult(MakeStatus(true)); WriteResult(ERRCODE_BAD_COMMAND); WriteIRQ(CDCIRQ_DISC_ERROR); return; } WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); if(DriveStatus == DS_SEEKING_LOGICAL && SeekTarget == CommandLoc && StatusAfterSeek == DS_READING) { CommandLoc_Dirty = false; return; } if(CommandLoc_Dirty || DriveStatus != DS_READING) { // Don't flush the DMABuffer here; see CTR course selection screen. ClearAIP(); ClearAudioBuffers(); SB_In = 0; SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; // TODO: separate motor start from seek phase? if(CommandLoc_Dirty) SeekTarget = CommandLoc; else SeekTarget = CurSector; PSRCounter = /*903168 * 1.5 +*/ CalcSeekTime(CurSector, SeekTarget, DriveStatus != DS_STOPPED, DriveStatus == DS_PAUSED); HeaderBufValid = false; PreSeekHack(SeekTarget); DriveStatus = DS_SEEKING_LOGICAL; StatusAfterSeek = DS_READING; } CommandLoc_Dirty = false; } int32 PS_CDC::Command_ReadN(const int arg_count, const uint8 *args) { ReadBase(); return 0; } int32 PS_CDC::Command_ReadS(const int arg_count, const uint8 *args) { ReadBase(); return 0; } int32 PS_CDC::Command_Stop(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); if(DriveStatus == DS_STOPPED) { return(5000); } else { ClearAudioBuffers(); ClearAIP(); SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; DriveStatus = DS_STOPPED; HeaderBufValid = false; return(33868); // FIXME, should be much higher. } } int32 PS_CDC::Command_Stop_Part2(void) { PSRCounter = 0; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_COMPLETE); return(0); } int32 PS_CDC::Command_Standby(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); if(DriveStatus != DS_STOPPED) { WriteResult(MakeStatus(true)); WriteResult(0x20); WriteIRQ(CDCIRQ_DISC_ERROR); return(0); } WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); ClearAudioBuffers(); ClearAIP(); SectorPipe_Pos = SectorPipe_In = 0; SectorsRead = 0; DriveStatus = DS_STANDBY; return((int64)33868800 * 100 / 1000); // No idea, FIXME. } int32 PS_CDC::Command_Standby_Part2(void) { PSRCounter = 0; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_COMPLETE); return(0); } int32 PS_CDC::Command_Pause(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); if(DriveStatus == DS_PAUSED || DriveStatus == DS_STOPPED) { return(5000); } else { CurSector -= std::min<uint32>(4, SectorsRead); // See: Bedlam, Rise 2 SectorsRead = 0; // "Viewpoint" flips out and crashes if reading isn't stopped (almost?) immediately. //ClearAudioBuffers(); SectorPipe_Pos = SectorPipe_In = 0; ClearAIP(); DriveStatus = DS_PAUSED; // An approximation. return((1124584 + ((int64)CurSector * 42596 / (75 * 60))) * ((Mode & MODE_SPEED) ? 1 : 2)); } } int32 PS_CDC::Command_Pause_Part2(void) { PSRCounter = 0; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_COMPLETE); return(0); } int32 PS_CDC::Command_Reset(const int arg_count, const uint8 *args) { WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); if(DriveStatus != DS_RESETTING) { HeaderBufValid = false; DriveStatus = DS_RESETTING; PSRCounter = 1136000; } return(0); } int32 PS_CDC::Command_Mute(const int arg_count, const uint8 *args) { Muted = true; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_Demute(const int arg_count, const uint8 *args) { Muted = false; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_Setfilter(const int arg_count, const uint8 *args) { FilterFile = args[0]; FilterChan = args[1]; //PSX_WARNING("[CDC] Setfilter: %02x %02x", args[0], args[1]); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_Setmode(const int arg_count, const uint8 *args) { Mode = args[0]; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_Getparam(const int arg_count, const uint8 *args) { WriteResult(MakeStatus()); WriteResult(Mode); WriteResult(0x00); WriteResult(FilterFile); WriteResult(FilterChan); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_GetlocL(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); if(!HeaderBufValid) { WriteResult(MakeStatus(true)); WriteResult(0x80); WriteIRQ(CDCIRQ_DISC_ERROR); return(0); } for(unsigned i = 0; i < 8; i++) { //printf("%d %d: %02x\n", DriveStatus, i, HeaderBuf[i]); WriteResult(HeaderBuf[i]); } WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_GetlocP(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); //printf("%2x:%2x %2x:%2x:%2x %2x:%2x:%2x\n", SubQBuf_Safe[0x1], SubQBuf_Safe[0x2], SubQBuf_Safe[0x3], SubQBuf_Safe[0x4], SubQBuf_Safe[0x5], SubQBuf_Safe[0x7], SubQBuf_Safe[0x8], SubQBuf_Safe[0x9]); WriteResult(SubQBuf_Safe[0x1]); // Track WriteResult(SubQBuf_Safe[0x2]); // Index WriteResult(SubQBuf_Safe[0x3]); // R M WriteResult(SubQBuf_Safe[0x4]); // R S WriteResult(SubQBuf_Safe[0x5]); // R F WriteResult(SubQBuf_Safe[0x7]); // A M WriteResult(SubQBuf_Safe[0x8]); // A S WriteResult(SubQBuf_Safe[0x9]); // A F WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_ReadT(const int arg_count, const uint8 *args) { WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(44100 * 768 / 1000); } int32 PS_CDC::Command_ReadT_Part2(void) { WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_COMPLETE); return(0); } int32 PS_CDC::Command_GetTN(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); WriteResult(MakeStatus()); WriteResult(U8_to_BCD(toc.first_track)); WriteResult(U8_to_BCD(toc.last_track)); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_GetTD(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); int track; uint8 m, s, f; if(!args[0]) track = 100; else { track = BCD_to_U8(args[0]); if(!BCD_is_valid(args[0]) || track < toc.first_track || track > toc.last_track) // Error { WriteResult(MakeStatus(true)); WriteResult(ERRCODE_BAD_ARGVAL); WriteIRQ(CDCIRQ_DISC_ERROR); return(0); } } LBA_to_AMSF(toc.tracks[track].lba, &m, &s, &f); WriteResult(MakeStatus()); WriteResult(U8_to_BCD(m)); WriteResult(U8_to_BCD(s)); //WriteResult(U8_to_BCD(f)); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } int32 PS_CDC::Command_SeekL(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); SeekTarget = CommandLoc; PSRCounter = (33868800 / (75 * ((Mode & MODE_SPEED) ? 2 : 1))) + CalcSeekTime(CurSector, SeekTarget, DriveStatus != DS_STOPPED, DriveStatus == DS_PAUSED); HeaderBufValid = false; PreSeekHack(SeekTarget); DriveStatus = DS_SEEKING_LOGICAL; StatusAfterSeek = DS_STANDBY; ClearAIP(); return(PSRCounter); } int32 PS_CDC::Command_SeekP(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); SeekTarget = CommandLoc; PSRCounter = CalcSeekTime(CurSector, SeekTarget, DriveStatus != DS_STOPPED, DriveStatus == DS_PAUSED); HeaderBufValid = false; PreSeekHack(SeekTarget); DriveStatus = DS_SEEKING; StatusAfterSeek = DS_STANDBY; ClearAIP(); return(PSRCounter); } int32 PS_CDC::Command_Seek_PartN(void) { if(DriveStatus == DS_STANDBY) { BeginResults(); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_COMPLETE); return(0); } else { return(std::max<int32>(PSRCounter, 256)); } } int32 PS_CDC::Command_Test(const int arg_count, const uint8 *args) { //PSX_WARNING("[CDC] Test command sub-operation: 0x%02x", args[0]); switch(args[0]) { default: PSX_WARNING("[CDC] Unknown Test command sub-operation: 0x%02x", args[0]); WriteResult(MakeStatus(true)); WriteResult(0x10); WriteIRQ(CDCIRQ_DISC_ERROR); break; case 0x00: case 0x01: case 0x02: case 0x03: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: PSX_WARNING("[CDC] Unknown Test command sub-operation: 0x%02x", args[0]); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); break; #if 0 case 0x50: // *Need to retest this test command, it takes additional arguments??? Or in any case, it generates a different error code(0x20) than most other Test // sub-commands that generate an error code(0x10). break; // Same with 0x60, 0x71-0x76 #endif case 0x51: // *Need to retest this test command PSX_WARNING("[CDC] Unknown Test command sub-operation: 0x%02x", args[0]); WriteResult(0x01); WriteResult(0x00); WriteResult(0x00); break; case 0x75: // *Need to retest this test command PSX_WARNING("[CDC] Unknown Test command sub-operation: 0x%02x", args[0]); WriteResult(0x00); WriteResult(0xC0); WriteResult(0x00); WriteResult(0x00); break; // // SCEx counters not reset by command 0x0A. // case 0x04: // Reset SCEx counters WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); break; case 0x05: // Read SCEx counters WriteResult(0x00); // Number of TOC/leadin reads? (apparently increases by 1 or 2 per ReadTOC, even on non-PSX music CD) WriteResult(0x00); // Number of SCEx strings received? (Stays at zero on music CD) WriteIRQ(CDCIRQ_ACKNOWLEDGE); break; case 0x20: { WriteResult(0x97); WriteResult(0x01); WriteResult(0x10); WriteResult(0xC2); WriteIRQ(CDCIRQ_ACKNOWLEDGE); } break; case 0x21: // *Need to retest this test command. { WriteResult(0x01); WriteIRQ(CDCIRQ_ACKNOWLEDGE); } break; case 0x22: { static const uint8 td[7] = { 0x66, 0x6f, 0x72, 0x20, 0x55, 0x2f, 0x43 }; for(unsigned i = 0; i < 7; i++) WriteResult(td[i]); WriteIRQ(CDCIRQ_ACKNOWLEDGE); } break; case 0x23: case 0x24: { static const uint8 td[8] = { 0x43, 0x58, 0x44, 0x32, 0x35, 0x34, 0x35, 0x51 }; for(unsigned i = 0; i < 8; i++) WriteResult(td[i]); WriteIRQ(CDCIRQ_ACKNOWLEDGE); } break; case 0x25: { static const uint8 td[8] = { 0x43, 0x58, 0x44, 0x31, 0x38, 0x31, 0x35, 0x51 }; for(unsigned i = 0; i < 8; i++) WriteResult(td[i]); WriteIRQ(CDCIRQ_ACKNOWLEDGE); } break; } return(0); } int32 PS_CDC::Command_ID(const int arg_count, const uint8 *args) { if(!CommandCheckDiscPresent()) return(0); WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(33868); } int32 PS_CDC::Command_ID_Part2(void) { if(IsPSXDisc) { WriteResult(MakeStatus()); WriteResult(0x00); WriteResult(0x20); WriteResult(0x00); } else { WriteResult(MakeStatus() | 0x08); WriteResult(0x90); WriteResult(toc.disc_type); WriteResult(0x00); } if(IsPSXDisc) { WriteResult(DiscID[0]); WriteResult(DiscID[1]); WriteResult(DiscID[2]); WriteResult(DiscID[3]); } else { WriteResult(0xff); WriteResult(0); WriteResult(0); WriteResult(0); } if(IsPSXDisc) WriteIRQ(CDCIRQ_COMPLETE); else WriteIRQ(CDCIRQ_DISC_ERROR); return(0); } int32 PS_CDC::Command_Init(const int arg_count, const uint8 *args) { return(0); } int32 PS_CDC::Command_ReadTOC(const int arg_count, const uint8 *args) { int32 ret_time; HeaderBufValid = false; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); // ReadTOC doesn't error out if the tray is open, and it completes rather quickly in that case. // if(!CommandCheckDiscPresent()) return(26000); // A gross approximation. // The penalty for the drive being stopped seems to be rather high(higher than what CalcSeekTime() currently introduces), although // that should be investigated further. // // ...and not to mention the time taken varies from disc to disc even! ret_time = 30000000 + CalcSeekTime(CurSector, 0, DriveStatus != DS_STOPPED, DriveStatus == DS_PAUSED); DriveStatus = DS_PAUSED; // Ends up in a pause state when the command is finished. Maybe we should add DS_READTOC or something... ClearAIP(); return ret_time; } int32 PS_CDC::Command_ReadTOC_Part2(void) { //if(!CommandCheckDiscPresent()) // DriveStatus = DS_PAUSED; WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_COMPLETE); return(0); } int32 PS_CDC::Command_0x1d(const int arg_count, const uint8 *args) { WriteResult(MakeStatus()); WriteIRQ(CDCIRQ_ACKNOWLEDGE); return(0); } PS_CDC::CDC_CTEntry PS_CDC::Commands[0x20] = { { /* 0x00, */ 0, 0, NULL, NULL, NULL }, { /* 0x01, */ 0, 0, "GetStat", &PS_CDC::Command_GetStat, NULL }, { /* 0x02, */ 3, 3, "Setloc", &PS_CDC::Command_Setloc, NULL }, { /* 0x03, */ 0, 1, "Play", &PS_CDC::Command_Play, NULL }, { /* 0x04, */ 0, 0, "Forward", &PS_CDC::Command_Forward, NULL }, { /* 0x05, */ 0, 0, "Backward", &PS_CDC::Command_Backward, NULL }, { /* 0x06, */ 0, 0, "ReadN", &PS_CDC::Command_ReadN, NULL }, { /* 0x07, */ 0, 0, "Standby", &PS_CDC::Command_Standby, &PS_CDC::Command_Standby_Part2 }, { /* 0x08, */ 0, 0, "Stop", &PS_CDC::Command_Stop, &PS_CDC::Command_Stop_Part2 }, { /* 0x09, */ 0, 0, "Pause", &PS_CDC::Command_Pause, &PS_CDC::Command_Pause_Part2 }, { /* 0x0A, */ 0, 0, "Reset", &PS_CDC::Command_Reset, NULL }, { /* 0x0B, */ 0, 0, "Mute", &PS_CDC::Command_Mute, NULL }, { /* 0x0C, */ 0, 0, "Demute", &PS_CDC::Command_Demute, NULL }, { /* 0x0D, */ 2, 2, "Setfilter", &PS_CDC::Command_Setfilter, NULL }, { /* 0x0E, */ 1, 1, "Setmode", &PS_CDC::Command_Setmode, NULL }, { /* 0x0F, */ 0, 0, "Getparam", &PS_CDC::Command_Getparam, NULL }, { /* 0x10, */ 0, 0, "GetlocL", &PS_CDC::Command_GetlocL, NULL }, { /* 0x11, */ 0, 0, "GetlocP", &PS_CDC::Command_GetlocP, NULL }, { /* 0x12, */ 1, 1, "ReadT", &PS_CDC::Command_ReadT, &PS_CDC::Command_ReadT_Part2 }, { /* 0x13, */ 0, 0, "GetTN", &PS_CDC::Command_GetTN, NULL }, { /* 0x14, */ 1, 1, "GetTD", &PS_CDC::Command_GetTD, NULL }, { /* 0x15, */ 0, 0, "SeekL", &PS_CDC::Command_SeekL, &PS_CDC::Command_Seek_PartN }, { /* 0x16, */ 0, 0, "SeekP", &PS_CDC::Command_SeekP, &PS_CDC::Command_Seek_PartN }, { /* 0x17, */ 0, 0, NULL, NULL, NULL }, { /* 0x18, */ 0, 0, NULL, NULL, NULL }, { /* 0x19, */ 1, 1/* ??? */, "Test", &PS_CDC::Command_Test, NULL }, { /* 0x1A, */ 0, 0, "ID", &PS_CDC::Command_ID, &PS_CDC::Command_ID_Part2 }, { /* 0x1B, */ 0, 0, "ReadS", &PS_CDC::Command_ReadS, NULL }, { /* 0x1C, */ 0, 0, "Init", &PS_CDC::Command_Init, NULL }, { /* 0x1D, */ 2, 2, "Unknown 0x1D", &PS_CDC::Command_0x1d, NULL }, { /* 0x1E, */ 0, 0, "ReadTOC", &PS_CDC::Command_ReadTOC, &PS_CDC::Command_ReadTOC_Part2 }, { /* 0x1F, */ 0, 0, NULL, NULL, NULL }, }; }
22.653985
229
0.651829
Moliman
c51319e855c456ae95b4296da2d7deba8b33a7ad
18,161
cpp
C++
src/hssh/global_topological/utils/local_to_global.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/hssh/global_topological/utils/local_to_global.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/hssh/global_topological/utils/local_to_global.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file local_to_global.cpp * \author Collin Johnson * * Definition of utility functions that convert from the local topological representation of an area to a global * topological representation of the area: * * - find_place_exit_transition * - find_relative_place_exit */ #include "hssh/global_topological/utils/local_to_global.h" #include "hssh/global_topological/global_path_segment.h" #include "hssh/global_topological/global_place.h" #include "hssh/global_topological/utils/visit.h" #include "hssh/local_topological/area.h" #include "hssh/local_topological/areas/place.h" #include "hssh/local_topological/gateway.h" #include "hssh/local_topological/local_topo_map.h" #include "utils/cyclic_iterator.h" #include "utils/stub.h" #include <algorithm> // #define DEBUG_PLACE_EXIT namespace vulcan { namespace hssh { // Where did the robot leave the path? enum class PathTransitionType { plus, minus, same, opposite, sequence, none, }; GlobalTransition entry_transition(const LocalPlace& localPlace, const Gateway& entryGateway, const GlobalPlace& globalPlace); GlobalTransition entry_transition(const LocalPathSegment& localSegment, const Gateway& entryGateway, const GlobalPathSegment& globalSegment); boost::optional<GlobalTransition> entry_along_sequence(const std::vector<TransitionAffordance>& localSequence, const Gateway& entryGateway, const GlobalTransitionSequence& globalSequence); int place_exit_index(const LocalArea& area, const Gateway& entry, const Gateway& exit); int absolute_transition_index(const LocalArea& area, const Gateway& transition); PathTransitionType local_path_exit_type(const LocalArea& area, const boost::optional<Gateway>& entry, const Gateway& exit); std::pair<GlobalPlace, GlobalTransition> create_global_place_from_local_place(const GlobalArea& globalArea, boost::optional<Gateway> entryGateway, const LocalArea& localArea) { // Fail to create a place if the pased in area isn't a place if (!is_place_type(localArea.type())) { return std::pair<GlobalPlace, GlobalTransition>(); } const LocalPlace* localPlace = static_cast<const LocalPlace*>(&localArea); GlobalTransitionCycle cycle(globalArea, localPlace->star()); GlobalPlace globalPlace(globalArea.id(), localArea.type(), localArea.id(), cycle); // If there is an entry gateway, then find the corresponding entry transition if (entryGateway) { return std::make_pair(globalPlace, entry_transition(*localPlace, *entryGateway, globalPlace)); } // Otherwise, this is the initial area, so we don't need to do anything. else { return std::make_pair(globalPlace, GlobalTransition()); } } std::pair<GlobalPathSegment, GlobalTransition> create_global_path_segment_from_local_path_segment(const GlobalArea& globalArea, boost::optional<Gateway> entryGateway, const LocalArea& localArea, bool isExplored) { // Fail to create a path segment if the pased in area isn't a path segment if (localArea.type() != AreaType::path_segment) { return std::pair<GlobalPathSegment, GlobalTransition>(); } const LocalPathSegment* localSegment = static_cast<const LocalPathSegment*>(&localArea); Line<float> center(localSegment->minusTransition().gateway().center(), localSegment->plusTransition().gateway().center()); GlobalTransitionSequence left(globalArea, localSegment->leftDestinations(), center); GlobalTransitionSequence right(globalArea, localSegment->rightDestinations(), center); GlobalTransition minus(next_id(), globalArea, GlobalArea(localSegment->minusTransition().type()), NavigationStatus::navigable, ExplorationStatus::frontier); GlobalTransition plus(next_id(), globalArea, GlobalArea(localSegment->plusTransition().type()), NavigationStatus::navigable, ExplorationStatus::frontier); auto lambda = localSegment->lambda(); GlobalPathSegment globalSegment(globalArea.id(), plus, minus, lambda, left, right, isExplored); // If there is an entry gateway, then find the corresponding entry transition if (entryGateway) { return std::make_pair(globalSegment, entry_transition(*localSegment, *entryGateway, globalSegment)); } // Otherwise, this is the initial area, so we don't need to do anything. else { return std::make_pair(globalSegment, GlobalTransition()); } } GlobalTransition find_place_exit_transition(const GlobalTransitionCycle& cycle, const GlobalTransition& entry, const TopologicalVisit& visit) { auto entryIt = std::find(cycle.begin(), cycle.end(), entry); int relativeExit = find_relative_place_exit_index(visit); // If we have a valid entry and the relative exit is possible within the cycle, then find it if ((entryIt != cycle.end()) && (relativeExit >= 0) && (relativeExit < static_cast<int>(cycle.size()))) { auto cycIt = utils::cyclic_iterator<GlobalTransitionCycle::Iter>(entryIt, cycle.begin(), cycle.end()); std::advance(cycIt, relativeExit); return *cycIt; } #ifdef DEBUG_PLACE_EXIT std::cerr << "WARNING: find_place_exit_transition: No relative exit transition was found, so only the absolute index " << "of the exit transition is used. It might be unreliable...Relative exit: " << relativeExit << " cycle: " << cycle.size() << "\n"; #endif // DEBUG_PLACE_EXIT auto exit = visit.exitEvent(); if (exit && exit->transitionGateway()) { int exitIndex = absolute_transition_index(*exit->exitedArea(), *exit->transitionGateway()); // If there's a valid exit, then take it if ((exitIndex >= 0) && (exitIndex < static_cast<int>(cycle.size()))) { return cycle[exitIndex]; } } // Otherwise, the exit transition doesn't exist, so an invalid exit must be returned. Most likely localizing // in an invalid map hypothesis. return GlobalTransition(); } int find_relative_place_exit_index(const TopologicalVisit& visit) { auto entry = visit.entryEvent(); auto exit = visit.exitEvent(); // If no exit event has occurred yet, then there isn't a valid index if (!exit || !entry.transitionGateway() || !exit->transitionGateway()) { return -1; } // Find the relative index for both the entry and exit events to see that they match. They might not. If they don't, // defer to the exit index, as it contains more complete knowledge of the area. int entryIndex = -1; int exitIndex = -1; if (entry.enteredArea()) { entryIndex = place_exit_index(*entry.enteredArea(), *entry.transitionGateway(), *exit->transitionGateway()); } if (exit->exitedArea()) { exitIndex = place_exit_index(*exit->exitedArea(), *entry.transitionGateway(), *exit->transitionGateway()); } #ifdef DEBUG_PLACE_EXIT if (entryIndex != exitIndex) { std::cerr << "WARNING: find_relative_place_exit_index: Didn't find the same relative index: Via entry:" << entryIndex << " Via exit:" << exitIndex << '\n'; } #endif // DEBUG_PLACE_EXIT return (exitIndex != -1) ? exitIndex : entryIndex; } GlobalTransition find_path_exit_transition(const GlobalPathSegment& pathSegment, const GlobalTransition& entry, const TopologicalVisit& visit) { // If there is no exit event, then there can't be an exit transition if (!visit.exitEvent()) { return GlobalTransition(); } auto exitType = local_path_exit_type(*visit.exitEvent()->exitedArea(), visit.entryEvent().transitionGateway(), *visit.exitEvent()->transitionGateway()); switch (exitType) { case PathTransitionType::plus: return pathSegment.plusTransition(); case PathTransitionType::minus: return pathSegment.minusTransition(); case PathTransitionType::opposite: return (pathSegment.plusTransition() == entry) ? pathSegment.minusTransition() : pathSegment.plusTransition(); case PathTransitionType::same: return entry; case PathTransitionType::sequence: std::cerr << "WARNING: Exiting to a sequence not yet supported!\n"; break; case PathTransitionType::none: std::cerr << "ERROR: find_path_exit_transition: Found no exit transition.\n"; break; } return GlobalTransition(); } bool path_endpoints_were_swapped(const GlobalPathSegment& entryPathSegment, const GlobalTransition& entryTransition, const GlobalPathSegment& exitPathSegment, const GlobalTransition& exitTransition, const TopologicalVisit& visit) { return false; // const LocalPathSegment* path = static_cast<const LocalPathSegment*>(visit.localArea()); // // // If no entry gateway, started at a path segment, so need to just assign based on which transition in local // path // // segment matches. This approach is fine because global path segment direction is same as local direction // for // // the initial area. // if(!visit.entryEvent().transitionGateway()) // { // return false; // } // // // If the entry and exit transitions are not the same, but are at the plus/minus ends, then exited through // the // // opposite transition // if((path->plusTransition().gateway().isSimilarTo(*entry) && // path->minusTransition().gateway().isSimilarTo(exit)) // || (path->minusTransition().gateway().isSimilarTo(*entry) && // path->plusTransition().gateway().isSimilarTo(exit))) // { // return PathTransitionType::opposite; // } // // If the entry and exit transitions are the same gateway, then the robot exited through the same transition // else if((path->plusTransition().gateway().isSimilarTo(*entry) && // path->plusTransition().gateway().isSimilarTo(exit)) // || (path->minusTransition().gateway().isSimilarTo(*entry) && // path->minusTransition().gateway().isSimilarTo(exit))) // { // return PathTransitionType::same; // } // // Otherwise, must've exited along the sequence somewhere // else // { // return PathTransitionType::sequence; // } } GlobalTransition entry_transition(const LocalPlace& localPlace, const Gateway& entryGateway, const GlobalPlace& globalPlace) { // Find the gateway fragment in the local place. This index is the offset into the global transition cycle. auto entryFrag = localPlace.findGatewayFragment(entryGateway); // If an entry was found, then the index can be used to get the GlobalTransition if (entryFrag) { auto& cycle = globalPlace.cycle(); return cycle[entryFrag->fragmentId]; } // Otherwise, no transition exists std::cerr << "ERROR: Found no entry transition for a newly created place!\n"; return GlobalTransition(); } GlobalTransition entry_transition(const LocalPathSegment& localSegment, const Gateway& entryGateway, const GlobalPathSegment& globalSegment) { // The entry is either one of the endpoints or along one of the sequences if (localSegment.minusTransition().gateway().isSimilarTo(entryGateway)) { return globalSegment.minusTransition(); } if (localSegment.plusTransition().gateway().isSimilarTo(entryGateway)) { return globalSegment.plusTransition(); } auto leftEntry = entry_along_sequence(localSegment.leftDestinations(), entryGateway, globalSegment.leftSequence()); if (leftEntry) { return *leftEntry; } auto rightEntry = entry_along_sequence(localSegment.rightDestinations(), entryGateway, globalSegment.rightSequence()); if (rightEntry) { return *rightEntry; } std::cerr << "ERROR: Found no entry transition for a newly created path segment! Going with closest end\n"; // Selecting the closest endpoint transition double minusDist = distance_between_points(localSegment.minusTransition().gateway().center(), entryGateway.center()); double plusDist = distance_between_points(localSegment.plusTransition().gateway().center(), entryGateway.center()); return plusDist < minusDist ? globalSegment.plusTransition() : globalSegment.minusTransition(); } boost::optional<GlobalTransition> entry_along_sequence(const std::vector<TransitionAffordance>& localSequence, const Gateway& entryGateway, const GlobalTransitionSequence& globalSequence) { // Iterate through the sequence. If a matching gateway is found, then it matches up with the index of the global // sequence for (std::size_t n = 0; n < localSequence.size(); ++n) { if (localSequence[n].gateway().isSimilarTo(entryGateway)) { // If an entry is found that's safe, take it if (n < globalSequence.size()) { return globalSequence[n]; } } } // Didn't find a transition. So must be some sort of invalid state. return boost::none; } int place_exit_index(const LocalArea& area, const Gateway& entry, const Gateway& exit) { // Must be a place if (!is_place_type(area.type())) { return -1; } const LocalPlace* place = static_cast<const LocalPlace*>(&area); auto entryFrag = place->findGatewayFragment(entry); auto exitFrag = place->findGatewayFragment(exit); if (entryFrag && exitFrag) { int entryIndex = entryFrag->fragmentId; int exitIndex = exitFrag->fragmentId; // Exit is after entry in the arbitrary fragment ordering if (entryIndex <= exitIndex) { return exitIndex - entryIndex; } // Wrap around to the end else { int numFragments = std::distance(place->star().begin(), place->star().end()); return (numFragments - entryIndex) + exitIndex; } } #ifdef DEBUG_PLACE_EXIT else { std::cerr << "place_exit_index: Found entry? " << static_cast<bool>(entryFrag) << " Found exit? " << static_cast<bool>(exitFrag) << " Star: " << place->star() << '\n'; } #endif // One of the fragments couldn't be found, so there isn't an index return -1; } int absolute_transition_index(const LocalArea& area, const Gateway& transition) { if (is_place_type(area.type())) { const LocalPlace* place = static_cast<const LocalPlace*>(&area); auto frag = place->findGatewayFragment(transition); return frag ? frag->fragmentId : -1; } return -1; } PathTransitionType local_path_exit_type(const LocalArea& area, const boost::optional<Gateway>& entry, const Gateway& exit) { if (area.type() != AreaType::path_segment) { return PathTransitionType::none; } const LocalPathSegment* path = static_cast<const LocalPathSegment*>(&area); // If no entry gateway, started at a path segment, so need to just assign based on which transition in local path // segment matches. This approach is fine because global path segment direction is same as local direction for // the initial area. if (!entry) { if (path->plusTransition().gateway().isSimilarTo(exit)) { return PathTransitionType::plus; } else if (path->minusTransition().gateway().isSimilarTo(exit)) { return PathTransitionType::minus; } else // exited along a sequence { return PathTransitionType::sequence; } } // If the entry and exit transitions are not the same, but are at the plus/minus ends, then exited through the // opposite transition if ((path->plusTransition().gateway().isSimilarTo(*entry) && path->minusTransition().gateway().isSimilarTo(exit)) || (path->minusTransition().gateway().isSimilarTo(*entry) && path->plusTransition().gateway().isSimilarTo(exit))) { return PathTransitionType::opposite; } // If the entry and exit transitions are the same gateway, then the robot exited through the same transition else if ((path->plusTransition().gateway().isSimilarTo(*entry) && path->plusTransition().gateway().isSimilarTo(exit)) || (path->minusTransition().gateway().isSimilarTo(*entry) && path->minusTransition().gateway().isSimilarTo(exit))) { return PathTransitionType::same; } // Otherwise, must've exited along the sequence somewhere else { return PathTransitionType::sequence; } } } // namespace hssh } // namespace vulcan
39.914286
120
0.64176
anuranbaka
78a0ae13fae57b12ff7b64b5f29128a3dca3005e
6,085
cpp
C++
examples/common/opengl/OpenGLShim.osx.cpp
cdave1/difont
2c38726cc3b7a6e06b920accef4ce752967fa61d
[ "MIT" ]
3
2015-03-09T05:51:02.000Z
2019-07-29T10:33:32.000Z
examples/common/opengl/OpenGLShim.osx.cpp
cdave1/difont
2c38726cc3b7a6e06b920accef4ce752967fa61d
[ "MIT" ]
null
null
null
examples/common/opengl/OpenGLShim.osx.cpp
cdave1/difont
2c38726cc3b7a6e06b920accef4ce752967fa61d
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 David Petrie david@davidpetrie.com * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from the * use of this software. Permission is granted to anyone to use this software for * any purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim * that you wrote the original software. If you use this software in a product, an * acknowledgment in the product documentation would be appreciated but is not * required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "OpenGLShim.h" #include "CommonMath.h" #include <fstream> #include <string> #include <sstream> void difont::examples::OpenGL::Begin(GLenum prim) { //glBegin(prim); } void difont::examples::OpenGL::Vertex3f(float x, float y, float z) { //glVertex3f(x, y, z); } void difont::examples::OpenGL::Color4f(float r, float g, float b, float a) { //glColor4f(r, g, b, a); } void difont::examples::OpenGL::TexCoord2f(float s, float t) { //glTexCoord2f(s, t); } void difont::examples::OpenGL::End() { //glEnd(); } static std::string m_shaderInfoLog; static std::string m_programInfoLog; GLuint difont::examples::OpenGL::loadFragmentShader(const char *path) { return difont::examples::OpenGL::loadShader(path, GL_FRAGMENT_SHADER); } GLuint difont::examples::OpenGL::loadVertexShader(const char *path) { return difont::examples::OpenGL::loadShader(path, GL_VERTEX_SHADER); } GLuint difont::examples::OpenGL::loadShaderProgram(const char *vertexShaderPath, const char *fragmentShaderPath) { GLint status = 0; GLint linked = 0; GLuint vertexShader = 0; GLuint fragmentShader = 0; GLuint shaderProgram = 0; vertexShader = loadVertexShader(vertexShaderPath); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { m_shaderInfoLog = shaderInfoLog(vertexShader); glDeleteShader(vertexShader); std::ostringstream output; output << "Error compiling GLSL vertex shader: '"; output << vertexShaderPath; output << "'" << std::endl << std::endl; output << "Shader info log:" << std::endl; output << m_shaderInfoLog; m_shaderInfoLog = output.str(); fprintf(stderr, "%s\n", m_shaderInfoLog.c_str()); } else { fragmentShader = loadFragmentShader(fragmentShaderPath); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { m_shaderInfoLog = shaderInfoLog(fragmentShader); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); std::ostringstream output; output << "Error compiling GLSL fragment shader: '"; output << fragmentShaderPath; output << "'" << std::endl << std::endl; output << "Shader info log:" << std::endl; output << m_shaderInfoLog; m_shaderInfoLog = output.str(); fprintf(stderr, "%s\n", m_shaderInfoLog.c_str()); } else { shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &linked); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); if (!linked) { m_programInfoLog = programInfoLog(shaderProgram); glDeleteProgram(shaderProgram); std::ostringstream output; output << "Error linking GLSL shaders into a shader program." << std::endl; output << "GLSL vertex shader: '" << vertexShaderPath; output << "'" << std::endl; output << "GLSL fragment shader: '" << fragmentShaderPath; output << "'" << std::endl << std::endl; output << "Program info log:" << std::endl; output << m_programInfoLog; m_programInfoLog = output.str(); fprintf(stderr, "%s\n", m_programInfoLog.c_str()); } } } return shaderProgram; } GLuint difont::examples::OpenGL::loadShader(const char *filename, GLenum shaderType) { std::string source; std::ifstream file(filename, std::ios::binary); if (file.is_open()) { file.seekg(0, std::ios::end); unsigned int fileSize = static_cast<unsigned int>(file.tellg()); source.resize(fileSize); file.seekg(0, std::ios::beg); file.read(&source[0], fileSize); } GLuint shader = glCreateShader(shaderType); const GLchar *pszSource = reinterpret_cast<const GLchar *>(source.c_str()); glShaderSource(shader, 1, &pszSource, 0); return shader; } std::string difont::examples::OpenGL::programInfoLog(GLuint program) { GLsizei infoLogSize = 0; std::string infoLog; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogSize); infoLog.resize(infoLogSize); glGetProgramInfoLog(program, infoLogSize, &infoLogSize, &infoLog[0]); return infoLog; } std::string difont::examples::OpenGL::shaderInfoLog(GLuint shader) { GLint length; GLint status; std::string infoLog = ""; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); if (length > 0) { char *log = (char *)calloc(1, length); glGetShaderInfoLog(shader, length, &status, log); infoLog = std::string(log); free(log); } return infoLog; }
32.195767
114
0.639277
cdave1
78a351edac2d2c3746f058b415b02b8f7b31bf1e
49,529
hpp
C++
libraries/app/include/deip/app/deip_api_objects.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
1
2021-08-16T12:44:43.000Z
2021-08-16T12:44:43.000Z
libraries/app/include/deip/app/deip_api_objects.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
null
null
null
libraries/app/include/deip/app/deip_api_objects.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
2
2021-08-16T12:44:46.000Z
2021-12-31T17:09:45.000Z
#pragma once #include <deip/chain/schema/account_object.hpp> #include <deip/chain/schema/block_summary_object.hpp> #include <deip/chain/schema/global_property_object.hpp> //#include <deip/chain/history_object.hpp> #include <deip/chain/schema/award_object.hpp> #include <deip/chain/schema/award_recipient_object.hpp> #include <deip/chain/schema/award_withdrawal_request_object.hpp> #include <deip/chain/schema/account_balance_object.hpp> #include <deip/chain/schema/asset_object.hpp> #include <deip/chain/schema/deip_objects.hpp> #include <deip/chain/schema/discipline_object.hpp> #include <deip/chain/schema/discipline_supply_object.hpp> #include <deip/chain/schema/expert_token_object.hpp> #include <deip/chain/schema/expertise_allocation_proposal_object.hpp> #include <deip/chain/schema/expertise_allocation_proposal_vote_object.hpp> #include <deip/chain/schema/nda_contract_object.hpp> #include <deip/chain/schema/nda_contract_file_access_object.hpp> #include <deip/chain/schema/proposal_object.hpp> #include <deip/chain/schema/research_content_object.hpp> #include <deip/chain/schema/research_discipline_relation_object.hpp> #include <deip/chain/schema/research_object.hpp> #include <deip/chain/schema/research_token_sale_object.hpp> #include <deip/chain/schema/review_object.hpp> #include <deip/chain/schema/review_vote_object.hpp> #include <deip/chain/schema/expertise_contribution_object.hpp> #include <deip/chain/schema/transaction_object.hpp> #include <deip/chain/schema/vesting_balance_object.hpp> #include <deip/chain/schema/grant_application_object.hpp> #include <deip/chain/schema/grant_application_review_object.hpp> #include <deip/chain/schema/funding_opportunity_object.hpp> #include <deip/chain/schema/research_license_object.hpp> #include <deip/chain/schema/witness_objects.hpp> #include <deip/chain/schema/contract_agreement_object.hpp> #include <deip/witness/witness_objects.hpp> #include <deip/chain/database/database.hpp> namespace deip { namespace app { using namespace deip::chain; using account_balance_refs_type = std::vector<std::reference_wrapper<const account_balance_object>>; using deip::protocol::percent_type; using deip::protocol::asset_symbol_type; using deip::protocol::external_id_type; typedef chain::change_recovery_account_request_object change_recovery_account_request_api_obj; typedef chain::block_summary_object block_summary_api_obj; typedef chain::withdraw_common_tokens_route_object withdraw_common_tokens_route_api_obj; typedef chain::witness_vote_object witness_vote_api_obj; typedef chain::witness_schedule_object witness_schedule_api_obj; typedef chain::reward_fund_object reward_fund_api_obj; typedef witness::account_bandwidth_object account_bandwidth_api_obj; struct account_api_obj { account_api_obj(const chain::account_object& a, const chain::account_authority_object& auth, const account_balance_refs_type account_balances) : id(a.id) , name(a.name) , memo_key(a.memo_key) , json_metadata(fc::to_string(a.json_metadata)) , proxy(a.proxy) , last_account_update(a.last_account_update) , created(a.created) , mined(a.mined) , recovery_account(a.recovery_account) , last_account_recovery(a.last_account_recovery) , lifetime_vote_count(a.lifetime_vote_count) , can_vote(a.can_vote) , common_tokens_balance(a.common_tokens_balance) , expert_tokens_balance(a.expertise_tokens_balance) , common_tokens_withdraw_rate(a.common_tokens_withdraw_rate) , next_common_tokens_withdrawal(a.next_common_tokens_withdrawal) , withdrawn(a.withdrawn) , to_withdraw(a.to_withdraw) , withdraw_routes(a.withdraw_routes) , witnesses_voted_for(a.witnesses_voted_for) , is_research_group(a.is_research_group) { size_t n = a.proxied_vsf_votes.size(); proxied_vsf_votes.reserve(n); for (size_t i = 0; i < n; i++) { proxied_vsf_votes.push_back(a.proxied_vsf_votes[i]); } owner = authority(auth.owner); active = authority(auth.active); last_owner_update = auth.last_owner_update; for (auto& pair : auth.active_overrides) { active_overrides.insert(std::pair<uint16_t, authority>(pair.first, authority(pair.second))); } for (const account_balance_object& account_balance : account_balances) { balances.push_back(asset(account_balance.amount, account_balance.symbol)); } } account_api_obj() { } account_id_type id; account_name_type name; authority owner; authority active; public_key_type memo_key; std::map<uint16_t, authority> active_overrides; string json_metadata; account_name_type proxy; time_point_sec last_owner_update; time_point_sec last_account_update; time_point_sec created; bool mined = false; account_name_type recovery_account; time_point_sec last_account_recovery; uint32_t lifetime_vote_count = 0; bool can_vote = false; share_type common_tokens_balance; share_type expert_tokens_balance; share_type received_common_tokens; share_type common_tokens_withdraw_rate; time_point_sec next_common_tokens_withdrawal; share_type withdrawn; share_type to_withdraw; uint16_t withdraw_routes = 0; vector<share_type> proxied_vsf_votes; uint16_t witnesses_voted_for; bool is_research_group; share_type average_bandwidth = 0; share_type lifetime_bandwidth = 0; time_point_sec last_bandwidth_update; share_type average_market_bandwidth = 0; share_type lifetime_market_bandwidth = 0; time_point_sec last_market_bandwidth_update; vector<asset> balances; }; struct owner_authority_history_api_obj { owner_authority_history_api_obj(const chain::owner_authority_history_object& o) : id(o.id) , account(o.account) , previous_owner_authority(authority(o.previous_owner_authority)) , last_valid_time(o.last_valid_time) { } owner_authority_history_api_obj() { } owner_authority_history_id_type id; account_name_type account; authority previous_owner_authority; time_point_sec last_valid_time; }; struct account_recovery_request_api_obj { account_recovery_request_api_obj(const chain::account_recovery_request_object& o) : id(o.id) , account_to_recover(o.account_to_recover) , new_owner_authority(authority(o.new_owner_authority)) , expires(o.expires) { } account_recovery_request_api_obj() { } account_recovery_request_id_type id; account_name_type account_to_recover; authority new_owner_authority; time_point_sec expires; }; struct account_history_api_obj { }; struct witness_api_obj { witness_api_obj(const chain::witness_object& w) : id(w.id) , owner(w.owner) , created(w.created) , url(fc::to_string(w.url)) , total_missed(w.total_missed) , last_aslot(w.last_aslot) , last_confirmed_block_num(w.last_confirmed_block_num) , signing_key(w.signing_key) , props(w.props) , sbd_exchange_rate(w.sbd_exchange_rate) , last_sbd_exchange_update(w.last_sbd_exchange_update) , votes(w.votes) , virtual_last_update(w.virtual_last_update) , virtual_position(w.virtual_position) , virtual_scheduled_time(w.virtual_scheduled_time) , last_work(w.last_work) , running_version(w.running_version) , hardfork_version_vote(w.hardfork_version_vote) , hardfork_time_vote(w.hardfork_time_vote) { } witness_api_obj() { } witness_id_type id; account_name_type owner; time_point_sec created; string url; uint32_t total_missed = 0; uint64_t last_aslot = 0; uint64_t last_confirmed_block_num = 0; public_key_type signing_key; chain_properties props; price sbd_exchange_rate; time_point_sec last_sbd_exchange_update; share_type votes; fc::uint128 virtual_last_update; fc::uint128 virtual_position; fc::uint128 virtual_scheduled_time; digest_type last_work; version running_version; hardfork_version hardfork_version_vote; time_point_sec hardfork_time_vote; }; struct signed_block_api_obj : public signed_block { signed_block_api_obj(const signed_block& block) : signed_block(block) { block_id = id(); block_num = block.block_num(); signing_key = signee(); transaction_ids.reserve(transactions.size()); for (const signed_transaction& tx : transactions) transaction_ids.push_back(tx.id()); } signed_block_api_obj() { } block_id_type block_id; uint32_t block_num; public_key_type signing_key; vector<transaction_id_type> transaction_ids; }; struct dynamic_global_property_api_obj : public dynamic_global_property_object { dynamic_global_property_api_obj(const dynamic_global_property_object& gpo, const chain::database& db) : dynamic_global_property_object(gpo) { if (db.has_index<witness::reserve_ratio_index>()) { const auto& r = db.find(witness::reserve_ratio_id_type()); if (BOOST_LIKELY(r != nullptr)) { current_reserve_ratio = r->current_reserve_ratio; average_block_size = r->average_block_size; max_virtual_bandwidth = r->max_virtual_bandwidth; } } } dynamic_global_property_api_obj(const dynamic_global_property_object& gpo) : dynamic_global_property_object(gpo) { } dynamic_global_property_api_obj() { } uint32_t current_reserve_ratio = 0; uint64_t average_block_size = 0; uint128_t max_virtual_bandwidth = 0; }; struct discipline_supply_api_obj { discipline_supply_api_obj(const chain::discipline_supply_object& ds_o) : id(ds_o.id._id) , grantor(ds_o.grantor) , target_discipline(ds_o.target_discipline._id) , created(ds_o.created) , balance(ds_o.balance) , per_block(ds_o.per_block) , start_time(ds_o.start_time) , end_time(ds_o.end_time) , is_extendable(ds_o.is_extendable) , content_hash(fc::to_string(ds_o.content_hash)) { for (auto& pair : ds_o.additional_info) { std::string key = fc::to_string(pair.first); std::string val = fc::to_string(pair.second); additional_info.insert(std::pair<string, string>(key, val)); } } // because fc::variant require for temporary object discipline_supply_api_obj() { } int64_t id; account_name_type grantor; int64_t target_discipline; time_point_sec created; asset balance; share_type per_block; time_point_sec start_time; time_point_sec end_time; bool is_extendable; string content_hash; std::map<std::string, std::string> additional_info; }; struct discipline_api_obj { discipline_api_obj(const chain::discipline_object& d) : id(d.id._id) , external_id(d.external_id) , parent_id(d.parent_id._id) , parent_external_id(d.parent_external_id) , name(fc::to_string(d.name)) {} // because fc::variant require for temporary object discipline_api_obj() { } int64_t id; string external_id; int64_t parent_id; string parent_external_id; std::string name; }; /* [DEPRECATED] */ struct research_group_api_obj { research_group_api_obj(const account_object& acc_o) : external_id(acc_o.name) , is_dao(acc_o.is_research_group) , is_personal(!acc_o.is_research_group) { } // because fc::variant require for temporary object research_group_api_obj() { } external_id_type external_id; bool is_dao; bool is_personal; }; struct research_api_obj { research_api_obj(const chain::research_object& r_o, const vector<discipline_api_obj>& disciplines, const research_group_api_obj& rg_api) : id(r_o.id._id) , external_id(r_o.external_id) , research_group_id(r_o.research_group_id._id) , description(fc::to_string(r_o.description)) , is_finished(r_o.is_finished) , is_private(r_o.is_private) , is_default(r_o.is_default) , created_at(r_o.created_at) , disciplines(disciplines.begin(), disciplines.end()) , number_of_positive_reviews(r_o.number_of_positive_reviews) , number_of_negative_reviews(r_o.number_of_negative_reviews) , number_of_research_contents(r_o.number_of_research_contents) , last_update_time(r_o.last_update_time) , research_group(rg_api) { for (const auto& kvp : r_o.eci_per_discipline) { eci_per_discipline.emplace(std::make_pair(kvp.first._id, kvp.second.value)); } for (const auto& st : r_o.security_tokens) { security_tokens.insert(st); } } // because fc::variant require for temporary object research_api_obj() { } int64_t id; external_id_type external_id; int64_t research_group_id; std::string description; bool is_finished; bool is_private; bool is_default; time_point_sec created_at; vector<discipline_api_obj> disciplines; map<int64_t, int64_t> eci_per_discipline; set<asset> security_tokens; uint16_t number_of_positive_reviews; uint16_t number_of_negative_reviews; uint16_t number_of_research_contents; time_point_sec last_update_time; research_group_api_obj research_group; }; struct research_content_api_obj { research_content_api_obj(const chain::research_content_object& rc_o) : id(rc_o.id._id) , external_id(rc_o.external_id) , research_id(rc_o.research_id._id) , research_external_id(rc_o.research_external_id) , content_type(rc_o.type) , authors(rc_o.authors.begin(), rc_o.authors.end()) , description(fc::to_string(rc_o.description)) , content(fc::to_string(rc_o.content)) , activity_state(rc_o.activity_state) , activity_window_start(rc_o.activity_window_start) , activity_window_end(rc_o.activity_window_end) , created_at(rc_o.created_at) { references.insert(rc_o.references.begin(), rc_o.references.end()); for (const auto& kvp : rc_o.eci_per_discipline) { discipline_id_type discipline_id = kvp.first; share_type weight = kvp.second; eci_per_discipline.emplace(std::make_pair(discipline_id._id, weight.value)); } } // because fc::variant require for temporary object research_content_api_obj() { } int64_t id; external_id_type external_id; int64_t research_id; external_id_type research_external_id; research_content_type content_type; std::set<account_name_type> authors; std::string description; std::string content; research_content_activity_state activity_state; fc::time_point_sec activity_window_start; fc::time_point_sec activity_window_end; fc::time_point_sec created_at; std::set<external_id_type> references; map<int64_t, int64_t> eci_per_discipline; }; struct research_license_api_obj { research_license_api_obj(const chain::research_license_object& rl_o) : id(rl_o.id._id) , external_id(rl_o.external_id) , licenser(rl_o.licenser) , licensee(rl_o.licensee) , terms(fc::to_string(rl_o.terms)) , status(rl_o.status) , expiration_time(rl_o.expiration_time) , created_at(rl_o.created_at) { if (rl_o.fee.valid()) { fee = *rl_o.fee; } } // because fc::variant require for temporary object research_license_api_obj() { } int64_t id; string external_id; external_id_type research_external_id; account_name_type licenser; account_name_type licensee; string terms; uint16_t status; time_point_sec expiration_time; time_point_sec created_at; optional<asset> fee; }; struct expert_token_api_obj { expert_token_api_obj(const chain::expert_token_object& d, const string& discipline_name) : id(d.id._id) , account_name(d.account_name) , discipline_id(d.discipline_id._id) , discipline_external_id(d.discipline_external_id) , discipline_name(discipline_name) , amount(d.amount) {} // because fc::variant require for temporary object expert_token_api_obj() { } int64_t id; string account_name; int64_t discipline_id; string discipline_external_id; string discipline_name; share_type amount; }; struct proposal_api_obj { proposal_api_obj(const chain::proposal_object& p_o) : id(p_o.id._id) , external_id(p_o.external_id) , creator(p_o.proposer) , proposed_transaction(p_o.proposed_transaction) , expiration_time(p_o.expiration_time) , review_period_time(p_o.review_period_time) , fail_reason(fc::to_string(p_o.fail_reason)) , created_at(p_o.created_at) { required_active_approvals.insert(p_o.required_active_approvals.begin(), p_o.required_active_approvals.end()); available_active_approvals.insert(p_o.available_active_approvals.begin(), p_o.available_active_approvals.end()); required_owner_approvals.insert(p_o.required_owner_approvals.begin(), p_o.required_owner_approvals.end()); available_owner_approvals.insert(p_o.available_owner_approvals.begin(), p_o.available_owner_approvals.end()); available_key_approvals.insert(p_o.available_key_approvals.begin(), p_o.available_key_approvals.end()); voted_accounts.insert(p_o.available_active_approvals.begin(), p_o.available_active_approvals.end()); voted_accounts.insert(p_o.available_owner_approvals.begin(), p_o.available_owner_approvals.end()); } // because fc::variant require for temporary object proposal_api_obj() { } int64_t id; string external_id; account_name_type creator; transaction proposed_transaction; time_point_sec expiration_time; optional<time_point_sec> review_period_time; string fail_reason; time_point_sec created_at; set<account_name_type> required_active_approvals; set<account_name_type> available_active_approvals; set<account_name_type> required_owner_approvals; set<account_name_type> available_owner_approvals; set<public_key_type> available_key_approvals; set<account_name_type> voted_accounts; }; struct research_token_sale_api_obj { research_token_sale_api_obj(const chain::research_token_sale_object& rts_o) : id(rts_o.id._id) , external_id(rts_o.external_id) , research_id(rts_o.research_id._id) , research_external_id(rts_o.research_external_id) , start_time(rts_o.start_time) , end_time(rts_o.end_time) , total_amount(rts_o.total_amount) , soft_cap(rts_o.soft_cap) , hard_cap(rts_o.hard_cap) , status(rts_o.status) { for (const auto& security_token_on_sale : rts_o.security_tokens_on_sale) { security_tokens_on_sale.insert(security_token_on_sale); } } // because fc::variant require for temporary object research_token_sale_api_obj() { } int64_t id; string external_id; int64_t research_id; string research_external_id; std::set<asset> security_tokens_on_sale; time_point_sec start_time; time_point_sec end_time; asset total_amount; asset soft_cap; asset hard_cap; uint16_t status; }; struct research_token_sale_contribution_api_obj { research_token_sale_contribution_api_obj(const chain::research_token_sale_contribution_object& co) : id(co.id._id) , research_token_sale(co.research_token_sale) , research_token_sale_id(co.research_token_sale_id._id) , owner(co.owner) , amount(co.amount) , contribution_time(co.contribution_time) {} // because fc::variant require for temporary object research_token_sale_contribution_api_obj() { } int64_t id; string research_token_sale; int64_t research_token_sale_id; account_name_type owner; asset amount; time_point_sec contribution_time; }; struct research_discipline_relation_api_obj { research_discipline_relation_api_obj(const chain::research_discipline_relation_object& re) : id(re.id._id) , research_id(re.research_id._id) , discipline_id(re.discipline_id._id) , votes_count(re.votes_count) , research_eci(re.research_eci) {} // because fc::variant require for temporary object research_discipline_relation_api_obj() { } int64_t id; int64_t research_id; int64_t discipline_id; uint16_t votes_count; share_type research_eci; }; struct expertise_contribution_object_api_obj { expertise_contribution_object_api_obj(const chain::expertise_contribution_object& ec) : id(ec.id._id) , discipline_id(ec.discipline_id._id) , research_id(ec.research_id._id) , research_content_id(ec.research_content_id._id) , eci(ec.eci) {} // because fc::variant require for temporary object expertise_contribution_object_api_obj() { } int64_t id; int64_t discipline_id; int64_t research_id; int64_t research_content_id; share_type eci; }; struct review_api_obj { review_api_obj(const chain::review_object& r, const vector<discipline_api_obj>& disciplines) : id(r.id._id) , external_id(r.external_id) , research_content_id(r.research_content_id._id) , research_content_external_id(r.research_content_external_id) , content(fc::to_string(r.content)) , is_positive(r.is_positive) , author(r.author) , created_at(r.created_at) , assessment_model_v(r.assessment_model_v) , scores(r.assessment_criterias.begin(), r.assessment_criterias.end()) { this->disciplines = disciplines; for (const auto& d : disciplines) { auto& discipline_id = d.id; this->expertise_tokens_amount_by_discipline.emplace(std::make_pair(discipline_id, r.expertise_tokens_amount_by_discipline.at(discipline_id).value)); } } // because fc::variant require for temporary object review_api_obj() { } int64_t id; string external_id; int64_t research_content_id; string research_content_external_id; string content; bool is_positive; account_name_type author; time_point_sec created_at; vector<discipline_api_obj> disciplines; map<int64_t, int64_t> expertise_tokens_amount_by_discipline; int32_t assessment_model_v; map<uint16_t, uint16_t> scores; }; struct review_vote_api_obj { review_vote_api_obj(const chain::review_vote_object& rvo) : id(rvo.id._id) , external_id(rvo.external_id) , discipline_id(rvo.discipline_id._id) , discipline_external_id(rvo.discipline_external_id) , voter(rvo.voter) , review_id(rvo.review_id._id) , review_external_id(rvo.review_external_id) , weight(rvo.weight) , voting_time(rvo.voting_time) {} // because fc::variant require for temporary object review_vote_api_obj() { } int64_t id; string external_id; int64_t discipline_id; string discipline_external_id; account_name_type voter; int64_t review_id; string review_external_id; int64_t weight; time_point_sec voting_time; }; struct expertise_allocation_proposal_api_obj { expertise_allocation_proposal_api_obj(const chain::expertise_allocation_proposal_object& eapo) : id(eapo.id._id) , claimer(eapo.claimer) , discipline_id(eapo.discipline_id._id) , amount(DEIP_EXPERTISE_CLAIM_AMOUNT) , total_voted_expertise(eapo.total_voted_expertise) , quorum_percent(eapo.quorum) , creation_time(eapo.creation_time) , expiration_time(eapo.expiration_time) , description(fc::to_string(eapo.description)) {} // because fc::variant require for temporary object expertise_allocation_proposal_api_obj() { } int64_t id; account_name_type claimer; int64_t discipline_id; share_type amount; int64_t total_voted_expertise; percent_type quorum_percent; time_point_sec creation_time; time_point_sec expiration_time; string description; }; struct expertise_allocation_proposal_vote_api_obj { expertise_allocation_proposal_vote_api_obj(const chain::expertise_allocation_proposal_vote_object& eapvo) : id(eapvo.id._id) , expertise_allocation_proposal_id(eapvo.expertise_allocation_proposal_id._id) , discipline_id(eapvo.discipline_id._id) , voter(eapvo.voter) , weight(eapvo.weight.value) , voting_time(eapvo.voting_time) {} // because fc::variant require for temporary object expertise_allocation_proposal_vote_api_obj() { } int64_t id; int64_t expertise_allocation_proposal_id; int64_t discipline_id; account_name_type voter; int64_t weight; time_point_sec voting_time; }; struct vesting_balance_api_obj { vesting_balance_api_obj(const chain::vesting_balance_object& vbo) : id(vbo.id._id) , owner(vbo.owner) , balance(vbo.balance) , withdrawn(vbo.withdrawn) , vesting_cliff_seconds(vbo.vesting_cliff_seconds) , vesting_duration_seconds(vbo.vesting_duration_seconds) , period_duration_seconds(vbo.period_duration_seconds) , start_timestamp(vbo.start_timestamp) {} // because fc::variant require for temporary object vesting_balance_api_obj() { } int64_t id; account_name_type owner; asset balance; asset withdrawn; uint32_t vesting_cliff_seconds; uint32_t vesting_duration_seconds; uint32_t period_duration_seconds; time_point_sec start_timestamp; }; struct grant_application_api_obj { grant_application_api_obj(const chain::grant_application_object& ga_o) : id(ga_o.id._id) , funding_opportunity_number(ga_o.funding_opportunity_number) , research_id(ga_o.research_id._id) , application_hash(fc::to_string(ga_o.application_hash)) , creator(ga_o.creator) , created_at(ga_o.created_at) , status(ga_o.status) {} // because fc::variant require for temporary object grant_application_api_obj() { } int64_t id; external_id_type funding_opportunity_number; int64_t research_id; std::string application_hash; account_name_type creator; fc::time_point_sec created_at; grant_application_status status; }; struct grant_application_review_api_obj { grant_application_review_api_obj(const chain::grant_application_review_object& r, const vector<discipline_api_obj>& disciplines) : id(r.id._id) , grant_application_id(r.grant_application_id._id) , content(fc::to_string(r.content)) , is_positive(r.is_positive) , author(r.author) , created_at(r.created_at) { this->disciplines = disciplines; } // because fc::variant require for temporary object grant_application_review_api_obj() { } int64_t id; int64_t grant_application_id; string content; bool is_positive; account_name_type author; time_point_sec created_at; vector<discipline_api_obj> disciplines; }; struct funding_opportunity_api_obj { funding_opportunity_api_obj(const chain::funding_opportunity_object& fo_o) : id(fo_o.id._id) , organization_id(fo_o.organization_id._id) , organization_external_id(fo_o.organization_external_id) , review_committee_id(fo_o.review_committee_id._id) , review_committee_external_id(fo_o.review_committee_external_id) , treasury_id(fo_o.treasury_id._id) , treasury_external_id(fo_o.treasury_external_id) , grantor(fo_o.grantor) , funding_opportunity_number(fo_o.funding_opportunity_number) , amount(fo_o.amount) , award_ceiling(fo_o.award_ceiling) , award_floor(fo_o.award_floor) , current_supply(fo_o.current_supply) , expected_number_of_awards(fo_o.expected_number_of_awards) , min_number_of_positive_reviews(fo_o.min_number_of_positive_reviews) , min_number_of_applications(fo_o.min_number_of_applications) , max_number_of_research_to_grant(fo_o.max_number_of_research_to_grant) , posted_date(fo_o.posted_date) , open_date(fo_o.open_date) , close_date(fo_o.close_date) , distribution_type(fo_o.distribution_type) { for (auto& pair : fo_o.additional_info) { std::string key = fc::to_string(pair.first); std::string val = fc::to_string(pair.second); additional_info.insert(std::pair<string, string>(key, val)); } for (auto& discipline_id : fo_o.target_disciplines) { target_disciplines.insert(discipline_id._id); } officers.insert(fo_o.officers.begin(), fo_o.officers.end()); } // because fc::variant require for temporary object funding_opportunity_api_obj() { } int64_t id; account_id_type organization_id; external_id_type organization_external_id; account_id_type review_committee_id; external_id_type review_committee_external_id; account_id_type treasury_id; external_id_type treasury_external_id; account_name_type grantor; external_id_type funding_opportunity_number; asset amount = asset(0, DEIP_SYMBOL); asset award_ceiling = asset(0, DEIP_SYMBOL); asset award_floor = asset(0, DEIP_SYMBOL); asset current_supply = asset(0, DEIP_SYMBOL); uint16_t expected_number_of_awards; uint16_t min_number_of_positive_reviews; uint16_t min_number_of_applications; uint16_t max_number_of_research_to_grant; fc::time_point_sec posted_date; fc::time_point_sec open_date; fc::time_point_sec close_date; std::map<std::string, std::string> additional_info; std::set<int64_t> target_disciplines; std::set<account_name_type> officers; uint16_t distribution_type; }; struct asset_api_obj { asset_api_obj(const chain::asset_object& a_o) : id(a_o.id._id) , symbol(a_o.symbol) , string_symbol(fc::to_string(a_o.string_symbol)) , precision(a_o.precision) , issuer(a_o.issuer) , description(fc::to_string(a_o.description)) , current_supply(a_o.current_supply) , max_supply(a_o.max_supply) , type(a_o.type) { if (a_o.tokenized_research.valid()) { tokenized_research = *a_o.tokenized_research; } if (a_o.license_revenue_holders_share.valid()) { license_revenue_holders_share = *a_o.license_revenue_holders_share; } } // because fc::variant require for temporary object asset_api_obj() { } int64_t id; asset_symbol_type symbol; std::string string_symbol; uint8_t precision; account_name_type issuer; std::string description; share_type current_supply; share_type max_supply; uint8_t type; optional<external_id_type> tokenized_research; optional<percent> license_revenue_holders_share; }; struct account_balance_api_obj { account_balance_api_obj(const chain::account_balance_object& ab_o) : id(ab_o.id._id) , asset_id(ab_o.asset_id._id) , asset_symbol(fc::to_string(ab_o.string_symbol)) , owner(ab_o.owner) , amount(ab_o.to_asset()) { if (ab_o.tokenized_research.valid()) { tokenized_research = *ab_o.tokenized_research; } } // because fc::variant require for temporary object account_balance_api_obj() { } int64_t id; int64_t asset_id; string asset_symbol; account_name_type owner; asset amount; optional<external_id_type> tokenized_research; }; struct award_recipient_api_obj { award_recipient_api_obj(const chain::award_recipient_object& ar_o) : id(ar_o.id._id) , award_number(ar_o.award_number) , subaward_number(ar_o.subaward_number) , funding_opportunity_number(ar_o.funding_opportunity_number) , research_id(ar_o.research_id._id) , research_external_id(ar_o.research_external_id) , awardee(ar_o.awardee) , source(ar_o.source) , total_amount(ar_o.total_amount) , total_expenses(ar_o.total_expenses) , status(ar_o.status) { } award_recipient_api_obj() { } int64_t id; external_id_type award_number; external_id_type subaward_number; external_id_type funding_opportunity_number; int64_t research_id; external_id_type research_external_id; account_name_type awardee; account_name_type source; asset total_amount; asset total_expenses; uint16_t status; }; struct award_api_obj { award_api_obj(const chain::award_object& award, const vector<award_recipient_api_obj>& awardees_list) : id(award.id._id) , funding_opportunity_number(award.funding_opportunity_number) , award_number(award.award_number) , awardee(award.awardee) , creator(award.creator) , status(award.status) , amount(award.amount) , university_id(award.university_id._id) , university_external_id(award.university_external_id) , university_overhead(award.university_overhead) { awardees.insert(awardees.end(), awardees_list.begin(), awardees_list.end()); university_fee = asset(((award.amount.amount * share_type(award.university_overhead.amount))) / DEIP_100_PERCENT, award.amount.symbol); } // because fc::variant require for temporary object award_api_obj() { } int64_t id; external_id_type funding_opportunity_number; external_id_type award_number; string awardee; string creator; uint16_t status; asset amount; int64_t university_id; external_id_type university_external_id; percent university_overhead; asset university_fee; vector<award_recipient_api_obj> awardees; }; struct award_withdrawal_request_api_obj { award_withdrawal_request_api_obj(const chain::award_withdrawal_request_object& awr_o) : id(awr_o.id._id) , award_number(awr_o.award_number) , subaward_number(awr_o.subaward_number) , payment_number(awr_o.payment_number) , requester(awr_o.requester) , amount(awr_o.amount) , description(fc::to_string(awr_o.description)) , status(awr_o.status) , time(awr_o.time) , attachment(fc::to_string(awr_o.attachment)) { } // because fc::variant require for temporary object award_withdrawal_request_api_obj() { } int64_t id; external_id_type award_number; external_id_type subaward_number; external_id_type payment_number; account_name_type requester; asset amount = asset(0, DEIP_SYMBOL); std::string description; uint16_t status; fc::time_point_sec time; std::string attachment; }; struct nda_contract_api_obj { nda_contract_api_obj(const chain::nda_contract_object& c_o) : id(c_o.id._id) , external_id(c_o.external_id) , creator(c_o.creator) , parties(c_o.parties.begin(), c_o.parties.end()) , description(fc::to_string(c_o.description)) , research_external_id(c_o.research_external_id) , created_at(c_o.created_at) , start_time(c_o.start_time) , end_time(c_o.end_time) {} // because fc::variant require for temporary object nda_contract_api_obj() { } int64_t id; external_id_type external_id; account_name_type creator; std::set<account_name_type> parties; std::string description; external_id_type research_external_id; fc::time_point_sec created_at; fc::time_point_sec start_time; fc::time_point_sec end_time; }; struct nda_contract_file_access_api_obj { nda_contract_file_access_api_obj(const chain::nda_contract_file_access_object& cfa_o) : id(cfa_o.id._id) , external_id(cfa_o.external_id) , nda_external_id(cfa_o.nda_external_id) , status(cfa_o.status) , requester(cfa_o.requester) , encrypted_payload_hash(fc::to_string(cfa_o.encrypted_payload_hash)) , encrypted_payload_iv(fc::to_string(cfa_o.encrypted_payload_iv)) , encrypted_payload_encryption_key(fc::to_string(cfa_o.encrypted_payload_encryption_key)) , proof_of_encrypted_payload_encryption_key(fc::to_string(cfa_o.proof_of_encrypted_payload_encryption_key)) {} // because fc::variant require for temporary object nda_contract_file_access_api_obj() { } int64_t id; external_id_type external_id; external_id_type nda_external_id; uint16_t status; account_name_type requester; std::string encrypted_payload_hash; std::string encrypted_payload_iv; std::string encrypted_payload_encryption_key; std::string proof_of_encrypted_payload_encryption_key; }; struct contract_agreement_api_obj { contract_agreement_api_obj(const chain::contract_agreement_object& c_o) : external_id(c_o.external_id) , creator(c_o.creator) , parties(c_o.parties.begin(), c_o.parties.end()) , hash(fc::to_string(c_o.hash)) , created_at(c_o.created_at) , start_time(c_o.start_time) , end_time(c_o.end_time) {} // because fc::variant require for temporary object contract_agreement_api_obj() { } external_id_type external_id; account_name_type creator; flat_map<account_name_type, uint8_t> parties; std::string hash; fc::time_point_sec created_at; fc::time_point_sec start_time; fc::optional<fc::time_point_sec> end_time; }; }; // namespace app } // namespace deip // clang-format off FC_REFLECT( deip::app::account_api_obj, (id) (name) (owner) (active) (memo_key) (active_overrides) (json_metadata) (proxy) (last_owner_update) (last_account_update) (created) (mined) (recovery_account) (last_account_recovery) (lifetime_vote_count) (can_vote) (common_tokens_balance) (expert_tokens_balance) (received_common_tokens) (common_tokens_withdraw_rate) (next_common_tokens_withdrawal) (withdrawn) (to_withdraw) (withdraw_routes) (proxied_vsf_votes) (witnesses_voted_for) (is_research_group) (average_bandwidth) (lifetime_bandwidth) (last_bandwidth_update) (average_market_bandwidth) (lifetime_market_bandwidth) (last_market_bandwidth_update) (balances) ) FC_REFLECT( deip::app::owner_authority_history_api_obj, (id) (account) (previous_owner_authority) (last_valid_time) ) FC_REFLECT( deip::app::account_recovery_request_api_obj, (id) (account_to_recover) (new_owner_authority) (expires) ) FC_REFLECT( deip::app::witness_api_obj, (id) (owner) (created) (url)(votes)(virtual_last_update)(virtual_position)(virtual_scheduled_time)(total_missed) (last_aslot)(last_confirmed_block_num)(signing_key) (props) (sbd_exchange_rate)(last_sbd_exchange_update) (last_work) (running_version) (hardfork_version_vote)(hardfork_time_vote) ) FC_REFLECT_DERIVED( deip::app::signed_block_api_obj, (deip::protocol::signed_block), (block_id) (block_num) (signing_key) (transaction_ids) ) FC_REFLECT_DERIVED( deip::app::dynamic_global_property_api_obj, (deip::chain::dynamic_global_property_object), (current_reserve_ratio) (average_block_size) (max_virtual_bandwidth) ) FC_REFLECT( deip::app::discipline_supply_api_obj, (id) (grantor) (target_discipline) (created) (balance) (per_block) (start_time) (end_time) (is_extendable) (content_hash) (additional_info) ) FC_REFLECT( deip::app::discipline_api_obj, (id) (external_id) (parent_id) (parent_external_id) (name)) FC_REFLECT( deip::app::research_api_obj, (id) (external_id) (research_group_id) (description) (is_finished) (is_private) (is_default) (created_at) (disciplines) (eci_per_discipline) (security_tokens) (number_of_positive_reviews) (number_of_negative_reviews) (number_of_research_contents) (last_update_time) (research_group) ) FC_REFLECT( deip::app::research_content_api_obj, (id) (external_id) (research_id) (research_external_id) (content_type) (description) (content) (authors) (activity_state) (activity_window_start) (activity_window_end) (created_at) (references) (eci_per_discipline) ) FC_REFLECT( deip::app::research_license_api_obj, (id) (external_id) (research_external_id) (licenser) (licensee) (terms) (status) (expiration_time) (created_at) (fee) ) FC_REFLECT( deip::app::expert_token_api_obj, (id) (account_name) (discipline_id) (discipline_external_id) (discipline_name) (amount) ) FC_REFLECT( deip::app::proposal_api_obj, (id) (external_id) (creator) (proposed_transaction) (expiration_time) (review_period_time) (fail_reason) (created_at) (required_active_approvals) (available_active_approvals) (required_owner_approvals) (available_owner_approvals) (available_key_approvals) (voted_accounts) ) FC_REFLECT( deip::app::research_group_api_obj, (external_id) (is_dao) (is_personal) ) FC_REFLECT( deip::app::research_token_sale_api_obj, (id) (external_id) (research_id) (research_external_id) (security_tokens_on_sale) (start_time) (end_time) (total_amount) (soft_cap) (hard_cap) (status) ) FC_REFLECT( deip::app::research_token_sale_contribution_api_obj, (id) (research_token_sale) (research_token_sale_id) (owner) (amount) (contribution_time) ) FC_REFLECT( deip::app::research_discipline_relation_api_obj, (id) (research_id) (discipline_id) (votes_count) (research_eci) ) FC_REFLECT( deip::app::expertise_contribution_object_api_obj, (id) (discipline_id) (research_id) (research_content_id) (eci) ) FC_REFLECT( deip::app::review_api_obj, (id) (external_id) (research_content_id) (research_content_external_id) (content) (is_positive) (author) (created_at) (disciplines) (expertise_tokens_amount_by_discipline) (assessment_model_v) (scores) ) FC_REFLECT( deip::app::review_vote_api_obj, (id) (external_id) (discipline_id) (discipline_external_id) (voter) (review_id) (review_external_id) (weight) (voting_time) ) FC_REFLECT( deip::app::expertise_allocation_proposal_api_obj, (id) (claimer) (discipline_id) (amount) (total_voted_expertise) (quorum_percent) (creation_time) (expiration_time) (description) ) FC_REFLECT( deip::app::expertise_allocation_proposal_vote_api_obj, (id) (expertise_allocation_proposal_id) (discipline_id) (voter) (weight) (voting_time) ) FC_REFLECT( deip::app::vesting_balance_api_obj, (id) (owner) (balance) (withdrawn) (vesting_cliff_seconds) (vesting_duration_seconds) (period_duration_seconds) (start_timestamp) ) FC_REFLECT( deip::app::grant_application_api_obj, (id) (funding_opportunity_number) (research_id) (application_hash) (creator) (created_at) (status) ) FC_REFLECT( deip::app::grant_application_review_api_obj, (id) (grant_application_id) (content) (is_positive) (author) (created_at) (disciplines) ) FC_REFLECT( deip::app::funding_opportunity_api_obj, (id) (organization_id) (organization_external_id) (review_committee_id) (review_committee_external_id) (treasury_id) (treasury_external_id) (grantor) (funding_opportunity_number) (amount) (award_ceiling) (award_floor) (current_supply) (expected_number_of_awards) (min_number_of_positive_reviews) (min_number_of_applications) (max_number_of_research_to_grant) (posted_date) (open_date) (close_date) (additional_info) (target_disciplines) (officers) (distribution_type) ) FC_REFLECT( deip::app::asset_api_obj, (id) (symbol) (string_symbol) (precision) (issuer) (description) (current_supply) (max_supply) (type) (tokenized_research) (license_revenue_holders_share) ) FC_REFLECT( deip::app::account_balance_api_obj, (id) (asset_id) (asset_symbol) (owner) (amount) (tokenized_research) ) FC_REFLECT( deip::app::award_api_obj, (id) (funding_opportunity_number) (award_number) (awardee) (creator) (status) (amount) (university_id) (university_external_id) (university_overhead) (university_fee) (awardees) ) FC_REFLECT( deip::app::award_recipient_api_obj, (id) (award_number) (subaward_number) (funding_opportunity_number) (research_id) (research_external_id) (awardee) (source) (total_amount) (total_expenses) (status) ) FC_REFLECT( deip::app::award_withdrawal_request_api_obj, (id) (award_number) (subaward_number) (payment_number) (requester) (amount) (description) (status) (time) (attachment) ) FC_REFLECT( deip::app::nda_contract_api_obj, (id) (external_id) (creator) (parties) (description) (research_external_id) (created_at) (start_time) (end_time) ) FC_REFLECT( deip::app::nda_contract_file_access_api_obj, (id) (external_id) (nda_external_id) (status) (requester) (encrypted_payload_hash) (encrypted_payload_iv) (encrypted_payload_encryption_key) (proof_of_encrypted_payload_encryption_key) ) FC_REFLECT( deip::app::contract_agreement_api_obj, (external_id) (creator) (parties) (hash) (created_at) (start_time) (end_time) ) // clang-format on
28.563437
160
0.665206
DEIPworld
78a43ef410d600cef07daa678b193fc5481f550a
3,876
hpp
C++
CargoVessel.hpp
danilaferents/Vessels
06d5f3d08d1f059e53946a06240c69bd4b5e9c7f
[ "Apache-2.0" ]
null
null
null
CargoVessel.hpp
danilaferents/Vessels
06d5f3d08d1f059e53946a06240c69bd4b5e9c7f
[ "Apache-2.0" ]
null
null
null
CargoVessel.hpp
danilaferents/Vessels
06d5f3d08d1f059e53946a06240c69bd4b5e9c7f
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef CargoVessel_hpp #define CargoVessel_hpp #include "main.hpp" #include "Vessels.hpp" using namespace destination; namespace cargovessel { class CargoVessel : public Vessel { // Типы груза public: enum CargoType {FOOD, WOOD, GOOD}; private: // максимальная грузоподъемность int maxcargo; // сколько сейчас загружено int curcargo; // массив контейнеров, int container_num; CargoType* containercontent; public: // Конструктор CargoVessel() { maxcargo=0; curcargo=0; container_num=0; containercontent=nullptr; } CargoVessel(int id, Destination* dest, int eta, ShipProperties* props,int maxcargo, int curcargo, int container_num, std::initializer_list<CargoType> values) : Vessel(id,dest,eta,props) { containercontent=new CargoType[container_num]; //va_list Cargo; //va_start(Cargo,cargotype); this->maxcargo=maxcargo; this->curcargo=curcargo; this->container_num=container_num; int i=0; for(auto& value : values) { containercontent[i]=value; i++; } /* for (int i=0;i<container_num;i++) { //CargoType ourcargo=va_arg(Cargo,CargoType); //std::cout<<std::endl<<"WTF. "<<cargotype<<ourcargo<<std::endl; //(containercontent)[i]=ourcargo; containercontent[i]=cargotype; } */ //va_end(Cargo); } //destructor ~CargoVessel() { if (containercontent) delete containercontent; } CargoVessel(CargoVessel& cargoVessel) : Vessel(cargoVessel) { // maxcargo=cargoVessel.GetMaxCargo(); maxcargo=cargoVessel.maxcargo; //curcargo=cargoVessel.GetCurCargo(); curcargo=cargoVessel.curcargo; //container_num=cargoVessel.GetConteinerNum(); container_num=cargoVessel.container_num; //if (cargoVessel.GetConteinerContent()) if (cargoVessel.containercontent) { containercontent=new CargoType[cargoVessel.container_num]; for (int i=0;i<cargoVessel.container_num;i++) { //containercontent[i]=cargoVessel.GetConteinerContent()[i]; containercontent[i]=cargoVessel.containercontent[i]; } } else { containercontent=nullptr; } } int GetMaxCargo() const; int GetCurCargo() const; int GetContainerNum() const; bool CompareContainernumAndRealContainers() const; CargoType *GetContainerContent() const; // Печать грузового судна friend std::ostream& operator<<(std::ostream& os, const CargoVessel& v) { os << (const Vessel &) v; os << "Maxcargo: " <<v.maxcargo<< std::endl; os<<"How much cargo now: "<<v.curcargo<<std::endl; os<<"How many containers: "<<v.container_num<<std::endl; for (int i=0;i<v.container_num;i++) { os<<(v.containercontent)[i]<<" "; } os<<std::endl; return os; } }; } #endif
36.224299
197
0.484262
danilaferents
78a5687aded5e9bdf992a772baac86266a543c71
2,446
cpp
C++
bbs/trashcan_test.cpp
ryanm101/wwiv
e8c094ef9485f42e1c053e2803d095af6c87f969
[ "Apache-2.0" ]
5
2017-01-31T23:12:37.000Z
2021-06-29T19:51:12.000Z
bbs/trashcan_test.cpp
ryanm101/wwiv
e8c094ef9485f42e1c053e2803d095af6c87f969
[ "Apache-2.0" ]
null
null
null
bbs/trashcan_test.cpp
ryanm101/wwiv
e8c094ef9485f42e1c053e2803d095af6c87f969
[ "Apache-2.0" ]
3
2015-07-05T22:42:31.000Z
2015-07-06T03:33:24.000Z
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)2007-2021, WWIV Software Services */ /* */ /* 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 "bbs/trashcan.h" #include "bbs/bbs_helper.h" #include "core/strings.h" #include "sdk/filenames.h" #include "gtest/gtest.h" #include <string> using namespace wwiv::strings; class TrashcanTest : public testing::Test { protected: void SetUp() override { helper.SetUp(); const std::string text = "all\n*end\nstart*\n*sub*\n"; helper.files().CreateTempFile(StrCat("gfiles/", TRASHCAN_TXT), text); } public: BbsHelper helper; }; TEST_F(TrashcanTest, SimpleCase) { Trashcan t(*a()->config()); EXPECT_TRUE(t.IsTrashName("all")); EXPECT_FALSE(t.IsTrashName("al")); EXPECT_FALSE(t.IsTrashName("a")); EXPECT_TRUE(t.IsTrashName("end")); EXPECT_TRUE(t.IsTrashName("send")); EXPECT_FALSE(t.IsTrashName("ends")); EXPECT_TRUE(t.IsTrashName("start")); EXPECT_TRUE(t.IsTrashName("starting")); EXPECT_FALSE(t.IsTrashName("sstart")); EXPECT_TRUE(t.IsTrashName("sub")); EXPECT_TRUE(t.IsTrashName("ssub")); EXPECT_TRUE(t.IsTrashName("subs")); EXPECT_FALSE(t.IsTrashName("dude")); EXPECT_FALSE(t.IsTrashName("a")); }
39.451613
76
0.493459
ryanm101
78a6a2a9628a0070253d04a20897b2c0a782e60b
2,493
cpp
C++
src/qt/controls/progressbarcontrol.cpp
karagog/gutil
43936af9bc4be1945e4f1a3656e91dfbf42cc35b
[ "Apache-2.0" ]
null
null
null
src/qt/controls/progressbarcontrol.cpp
karagog/gutil
43936af9bc4be1945e4f1a3656e91dfbf42cc35b
[ "Apache-2.0" ]
2
2015-01-30T21:47:55.000Z
2015-02-10T00:22:27.000Z
src/qt/controls/progressbarcontrol.cpp
karagog/gutil
43936af9bc4be1945e4f1a3656e91dfbf42cc35b
[ "Apache-2.0" ]
null
null
null
/*Copyright 2010-2015 George Karagoulis 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 "progressbarcontrol.h" #include <gutil/macros.h> #include <QStackedLayout> #include <QVBoxLayout> NAMESPACE_GUTIL1(Qt); ProgressBarControl::ProgressBarControl(bool be, QWidget *parent) :QWidget(parent), _p_AutoShow(true), m_isCancellable(true) { _button.setStyleSheet("background-color: rgba(0,0,0,0);"); _progressBar.setTextVisible(false); setLayout(new QVBoxLayout(this)); layout()->setContentsMargins(0, 0, 0, 0); layout()->addWidget(&_progressBar); _label.setAlignment(::Qt::AlignCenter); QFont f; f.setBold(true); _label.setFont(f); _progressBar.setLayout(new QStackedLayout(&_progressBar)); _progressBar.layout()->setContentsMargins(0, 0, 0, 0); ((QStackedLayout*)_progressBar.layout())->setStackingMode(QStackedLayout::StackAll); _progressBar.layout()->addWidget(&_label); _progressBar.layout()->addWidget(&_button); connect(&_button, SIGNAL(clicked()), this, SIGNAL(Clicked())); setButtonEnabled(be); if(GetAutoShow()) hide(); } void ProgressBarControl::SetIsCancellable(bool c) { m_isCancellable = c; _button.setVisible(c); } void ProgressBarControl::setButtonEnabled(bool which) { if(which) { _button.show(); ((QStackedLayout *)_progressBar.layout())->setCurrentWidget(&_button); } else { _button.hide(); } } void ProgressBarControl::SetProgress(int p, const QString &s) { if(GetAutoShow()) { if(p == _progressBar.maximum() && isVisible()) hide(); else if(p < _progressBar.maximum() && !isVisible()) show(); } _progressBar.setValue(p); if(_button.isVisible()) _label.setText(QString(tr("%1%2")) .arg(s) .arg(m_isCancellable ? tr(" (Click to cancel)") : QString::null)); else _label.setText(s); } END_NAMESPACE_GUTIL1;
26.242105
89
0.671881
karagog
78a907e035c0b51c06aa55f402aa8f68dbdc79b5
7,093
cpp
C++
src/liquid.cpp
Y2Z/liquid
f55fd3c6f8e9cf2f6f024df4499470945b06400f
[ "CC0-1.0" ]
5
2017-02-10T08:37:14.000Z
2022-03-27T23:52:56.000Z
src/liquid.cpp
Y2Z/Liquid
f55fd3c6f8e9cf2f6f024df4499470945b06400f
[ "CC0-1.0" ]
87
2016-01-22T01:39:59.000Z
2022-01-04T01:17:30.000Z
src/liquid.cpp
Y2Z/liquid
f55fd3c6f8e9cf2f6f024df4499470945b06400f
[ "CC0-1.0" ]
1
2017-04-20T20:14:00.000Z
2017-04-20T20:14:00.000Z
#include "lqd.h" #include "liquid.hpp" #include <QApplication> #include <QCoreApplication> #include <QDateTime> #include <QDebug> #include <QProcess> #include <QSettings> #include <QTime> #include <QWebEngineProfile> #if defined(Q_OS_MAC) #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> #endif void Liquid::applyQtStyleSheets(QWidget* widget) { QString styleSheet; // Load built-in base stylesheet { QFile styleSheetFile(":/styles/base.qss"); styleSheetFile.open(QFile::ReadOnly); styleSheet = QLatin1String(styleSheetFile.readAll()); styleSheetFile.close(); } // Load built-in color theme stylesheet { QFile colorThemeStyleSheetFile(QString(":/styles/%1.qss").arg((Liquid::detectDarkMode()) ? "dark" : "light")); colorThemeStyleSheetFile.open(QFile::ReadOnly); styleSheet += QLatin1String(colorThemeStyleSheetFile.readAll()); colorThemeStyleSheetFile.close(); } // Load user-defined stylesheet { QFile customStyleSheetFile(Liquid::getConfigDir().absolutePath() + QDir::separator() + PROG_NAME ".qss"); if (customStyleSheetFile.open(QFile::ReadOnly)) { styleSheet += QLatin1String(customStyleSheetFile.readAll()); customStyleSheetFile.close(); } } widget->setStyleSheet(styleSheet); } void Liquid::createDesktopFile(const QString liquidAppName, const QString liquidAppStartingUrl) { #if defined(Q_OS_LINUX) // Compose content QString context = "#!/usr/bin/env xdg-open\n\n"; context += "[Desktop Entry]\n"; context += "Type=Application\n"; context += "Name=" + liquidAppName + "\n"; context += "Icon=internet-web-browser\n"; context += "Exec=liquid " + liquidAppName + "\n"; context += "Comment=" + liquidAppStartingUrl + "\n"; context += "Categories=Network;WebBrowser;\n"; // Construct directory path // QString desktopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); QString desktopPath = QDir::homePath() + QDir::separator() + "Desktop"; // Check if the desktop path exists QDir dir(desktopPath); if (dir.exists()) { // Create file QFile file(desktopPath + QDir::separator() + liquidAppName + ".desktop"); file.open(QIODevice::WriteOnly); file.write(context.toStdString().c_str()); file.setPermissions(QFileDevice::ReadUser |QFileDevice::WriteUser |QFileDevice::ExeUser |QFileDevice::ReadGroup |QFileDevice::ReadOther); file.flush(); file.close(); } #else Q_UNUSED(liquidAppName); Q_UNUSED(liquidAppStartingUrl); #endif } bool Liquid::detectDarkMode(void) { #if defined(Q_OS_LINUX) QProcess process; process.start("gsettings", QStringList() << "get" << "org.gnome.desktop.interface" << "gtk-theme"); process.waitForFinished(1000); QString output = process.readAllStandardOutput(); if (output.size() > 0) { return output.endsWith("-dark'\n", Qt::CaseInsensitive); } #elif defined(Q_OS_MACOS) static const QString macOsVer = QSysInfo::productVersion(); static const QStringList macOsVerParts = macOsVer.split('.'); if (macOsVerParts.at(0).toInt() > 10 || (macOsVerParts.at(0).toInt() >= 10 && macOsVerParts.at(1).toInt() >= 14)) { bool macOsUserInterfaceIsUsingDarkMode = false; CFStringRef darkStr = CFSTR("Dark"); CFStringRef macOsUserInterfaceStyleStr = CFSTR("AppleInterfaceStyle"); CFStringRef macOsUserInterfaceStyle = (CFStringRef)CFPreferencesCopyAppValue(macOsUserInterfaceStyleStr, kCFPreferencesCurrentApplication); if (macOsUserInterfaceStyle != Q_NULLPTR) { macOsUserInterfaceIsUsingDarkMode = (CFStringCompare(macOsUserInterfaceStyle, darkStr, 0) == kCFCompareEqualTo); CFRelease(macOsUserInterfaceStyle); return macOsUserInterfaceIsUsingDarkMode; } } #elif defined(Q_OS_WIN) return (QSettings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", QSettings::NativeFormat) .value("AppsUseLightTheme", 1) == 0); #endif return QApplication::palette().text().color().lightnessF() > QApplication::palette().window().color().lightnessF(); } QByteArray Liquid::generateRandomByteArray(const int byteLength) { std::vector<quint32> buf; srand(QTime::currentTime().msec()); for (int i = 0; i < byteLength; ++i) { buf.push_back(rand()); } return QByteArray(reinterpret_cast<const char*>(buf.data()), byteLength); } QDir Liquid::getAppsDir(void) { return QDir(getConfigDir().absolutePath() + QDir::separator() + LQD_APPS_DIR_NAME + QDir::separator()); } QDir Liquid::getConfigDir(void) { const QSettings* settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, PROG_NAME, PROG_NAME, Q_NULLPTR); QFileInfo settingsFileInfo(settings->fileName()); return QDir(settingsFileInfo.absolutePath() + QDir::separator()); } QString Liquid::getDefaultUserAgentString(void) { return QWebEngineProfile().httpUserAgent(); } QStringList Liquid::getLiquidAppsList(void) { const QFileInfoList liquidAppsFileList = getAppsDir().entryInfoList(QStringList() << "*.ini", QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); QStringList liquidAppsNames; foreach (QFileInfo liquidAppFileInfo, liquidAppsFileList) { liquidAppsNames << liquidAppFileInfo.completeBaseName(); } return liquidAppsNames; } QString Liquid::getReadableDateTimeString(void) { return QDateTime::currentDateTimeUtc().toString(QLocale().dateTimeFormat()); } void Liquid::removeDesktopFile(const QString liquidAppName) { #if defined(Q_OS_LINUX) // Construct directory path // QString desktopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); const QString desktopPath = QDir::homePath() + QDir::separator() + "Desktop"; // Check if the desktop path exists QDir dir(desktopPath); if (dir.exists()) { // Unlink file QFile file(desktopPath + QDir::separator() + liquidAppName + ".desktop"); file.remove(); } #else Q_UNUSED(liquidAppName); #endif } void Liquid::runLiquidApp(const QString liquidAppName) { QProcess::startDetached(QCoreApplication::applicationFilePath(), QStringList() << QStringLiteral("%1").arg(liquidAppName)); } void Liquid::sleep(const int ms) { const QTime proceedAfter = QTime::currentTime().addMSecs(ms); while (QTime::currentTime() < proceedAfter) { QCoreApplication::processEvents(QEventLoop::AllEvents, ms / 4); } }
34.769608
147
0.653179
Y2Z
78a999c33b83020d3d48d14cef7fbbc23f5945ff
60,975
cpp
C++
Models/ModelsDemo.cpp
kakol20/HFG
055ebd29c12a3830256c8469dc7b1f5de155d810
[ "MIT" ]
null
null
null
Models/ModelsDemo.cpp
kakol20/HFG
055ebd29c12a3830256c8469dc7b1f5de155d810
[ "MIT" ]
null
null
null
Models/ModelsDemo.cpp
kakol20/HFG
055ebd29c12a3830256c8469dc7b1f5de155d810
[ "MIT" ]
null
null
null
/* Beginning DirectX 11 Game Programming By Allen Sherrod and Wendy Jones 3D Models Demo - Demonstrates loading a model from an .OBJ file. */ #include"ModelsDemo.h" #include<xnamath.h> #include<stdio.h> #include"objLoader.h" //char* TERRAIN_TEXTURE_NAME = "GameObjects/Menu_Stuff/Play.jpg"; char* MENU_TEXTURE_NAME = "GameObjects/Menu_Stuff/Play.jpg"; char* SOIL_TEXTURE_NAME = "GameObjects/DomeTexture.png"; struct VertexPos { XMFLOAT3 pos; XMFLOAT2 tex0; XMFLOAT3 norm; }; struct TextVertexPos { XMFLOAT3 pos; XMFLOAT2 tex0; }; ModelsDemo::ModelsDemo() : textureMapVS_(0), textureMapPS_(0), textTextureMapVS_(0), textTextureMapPS_(0), inputLayout_(0), textInputLayout_(0), textVertexBuffer_(0), textColorMapSampler_(0), vertexBuffer1_(0), colorMap1_(0), textColorMap_(0), colorMapSampler_(0), viewCB_(0), projCB_(0), worldCB_(0), camPosCB_(0), totalVerts1_(0), gameState_(PLAY_INTRO), pauseMenuSelection(RETURN), displayFPS(true) { ZeroMemory(&controller1State_, sizeof(XINPUT_STATE)); ZeroMemory(&prevController1State_, sizeof(XINPUT_STATE)); ZeroMemory(&mouseCurrState, sizeof(DIMOUSESTATE)); ZeroMemory(&mousePrevState, sizeof(DIMOUSESTATE)); m_alphaEnableBlendingState = 0; m_alphaDisableBlendingState = 0; m_depthStencilState = 0; m_depthDisabledStencilState = 0; frameTime_ = 0; fps_ = 0; } ModelsDemo::~ModelsDemo() { } bool ModelsDemo::LoadContent() { ID3DBlob* vsBuffer = 0; bool compileResult = CompileD3DShader("TextureMap.fx", "VS_Main", "vs_4_0", &vsBuffer); if (compileResult == false) { DXTRACE_MSG("Error compiling the vertex shader!"); return false; } HRESULT d3dResult; d3dResult = d3dDevice_->CreateVertexShader(vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), 0, &textureMapVS_); if (FAILED(d3dResult)) { DXTRACE_MSG("Error creating the vertex shader!"); if (vsBuffer) vsBuffer->Release(); return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; unsigned int totalLayoutElements = ARRAYSIZE(solidColorLayout); d3dResult = d3dDevice_->CreateInputLayout(solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), &inputLayout_); //vsBuffer->Release( ); if (FAILED(d3dResult)) { DXTRACE_MSG("Error creating the input layout!"); return false; } ID3DBlob* psBuffer = 0; compileResult = CompileD3DShader("TextureMap.fx", "PS_Main", "ps_4_0", &psBuffer); if (compileResult == false) { DXTRACE_MSG("Error compiling pixel shader!"); return false; } d3dResult = d3dDevice_->CreatePixelShader(psBuffer->GetBufferPointer(), psBuffer->GetBufferSize(), 0, &textureMapPS_); //psBuffer->Release( ); if (FAILED(d3dResult)) { DXTRACE_MSG("Error creating pixel shader!"); return false; } ////////////////////////////////////////////text 2d shaders//////////////////////////////////////////////////////////// //ID3DBlob* vsBuffer = 0; vsBuffer = 0; compileResult = CompileD3DShader("TextTextureMap.fx", "VS_Main", "vs_4_0", &vsBuffer); if (compileResult == false) { DXTRACE_MSG("Error compiling the vertex shader!"); return false; } d3dResult = d3dDevice_->CreateVertexShader(vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), 0, &textTextureMapVS_); if (FAILED(d3dResult)) { DXTRACE_MSG("Error creating the vertex shader!"); if (vsBuffer) vsBuffer->Release(); return false; } D3D11_INPUT_ELEMENT_DESC textSolidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; totalLayoutElements = ARRAYSIZE(textSolidColorLayout); d3dResult = d3dDevice_->CreateInputLayout(textSolidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), &textInputLayout_); vsBuffer->Release(); if (FAILED(d3dResult)) { DXTRACE_MSG("Error creating the input layout!"); return false; } //ID3DBlob* psBuffer = 0; psBuffer = 0; compileResult = CompileD3DShader("TextTextureMap.fx", "PS_Main", "ps_4_0", &psBuffer); if (compileResult == false) { DXTRACE_MSG("Error compiling pixel shader!"); return false; } d3dResult = d3dDevice_->CreatePixelShader(psBuffer->GetBufferPointer(), psBuffer->GetBufferSize(), 0, &textTextureMapPS_); psBuffer->Release(); if (FAILED(d3dResult)) { DXTRACE_MSG("Error creating pixel shader!"); return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, "fontEX.png", 0, 0, &textColorMap_, 0); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to load the texture image!"); return false; } D3D11_SAMPLER_DESC textColorMapDesc; ZeroMemory(&textColorMapDesc, sizeof(textColorMapDesc)); textColorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; textColorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; textColorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; textColorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; textColorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; textColorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; d3dResult = d3dDevice_->CreateSamplerState(&textColorMapDesc, &textColorMapSampler_); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to create color map sampler state!"); return false; } D3D11_BUFFER_DESC textVertexDesc; ZeroMemory(&textVertexDesc, sizeof(textVertexDesc)); textVertexDesc.Usage = D3D11_USAGE_DYNAMIC; textVertexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; textVertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; const int sizeOfSprite = sizeof(TextVertexPos) * 6; const int maxLetters = 24; textVertexDesc.ByteWidth = sizeOfSprite * maxLetters; d3dResult = d3dDevice_->CreateBuffer(&textVertexDesc, 0, &textVertexBuffer_); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to create vertex buffer!"); return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ------------------------------ LOADING CHARACTER MODELS ------------------------------ // ---------- LOADING PLAYERS ---------- Player1.setPosition({ -10.0f, 0.0f, 0.0f }); Player2.setPosition({ 10.0f, 0.0f, 0.0f }); camera_.snapPosition(&Player1, &Player2); //============ WOLF ============ if (!Wolf_M.Init("PlayerModels/Antonina_Wolf/Idle/Wolf_IdleF1.obj", d3dResult, d3dDevice_)) return false; if (!Wolf_T.Init("PlayerModels/Antonina_Wolf/Wolf_Diff_Eye.png", d3dResult, d3dDevice_)) return false; if (!WolfIdle.Load("PlayerModels/Antonina_Wolf/Idle/Wolf_IdleF", 8, d3dResult, d3dDevice_)) return false; // working if (!WolfWalk.Load("PlayerModels/Antonina_Wolf/Walk/Wolf_WalkF", 8, d3dResult, d3dDevice_)) return false; // working if (!WolfDamaged.Load("PlayerModels/Antonina_Wolf/Damage/Wolf_HitF", 8, d3dResult, d3dDevice_)) return false; // working if (!WolfDeath.Load("PlayerModels/Antonina_Wolf/Death/Wolf_DyingF", 8, d3dResult, d3dDevice_)) return false; // working - fast if (!WolfAttack.Load("PlayerModels/Antonina_Wolf/Attack/Wolf_AttackF", 8, d3dResult, d3dDevice_)) return false; // working - fast //============ ROBOT ============ if (!Robot_M.Init("PlayerModels/Cameron_Robot/Idle/RobotIdle1.obj", d3dResult, d3dDevice_)) return false; if (!Robot_T.Init("PlayerModels/Cameron_Robot/RobotUVforModel.png", d3dResult, d3dDevice_)) return false; if (!RobotWalk.Load("PlayerModels/Cameron_Robot/Walk/RobotWalk", 8, d3dResult, d3dDevice_)) return false; // working if (!RobotDeath.Load("PlayerModels/Cameron_Robot/Death/RobotDeath", 8, d3dResult, d3dDevice_)) return false; // working if (!RobotAttack.Load("PlayerModels/Cameron_Robot/Attack/RobotAttack", 8, d3dResult, d3dDevice_)) return false; // working if (!RobotDamaged.Load("PlayerModels/Cameron_Robot/Damage/RobotDamage", 8, d3dResult, d3dDevice_)) return false; // working if (!RobotIdle.Load("PlayerModels/Cameron_Robot/Idle/RobotIdle", 8, d3dResult, d3dDevice_)) return false; // working //============ KREMIT ============ if (!Kremit_M.Init("PlayerModels/Matthew_Kremit/Idle/Kremit_idle_1.obj", d3dResult, d3dDevice_)) return false; if (!Kremit_T.Init("PlayerModels/Matthew_Kremit/Kremit_Texture.png", d3dResult, d3dDevice_)) return false; if (!KremitIdle.Load("PlayerModels/Matthew_Kremit/Idle/Kremit_idle_", 8, d3dResult, d3dDevice_)) return false; // working if (!KremitWalk.Load("PlayerModels/Matthew_Kremit/Walk/Kremit_Walking_", 8, d3dResult, d3dDevice_)) return false; // working if (!KremitDeath.Load("PlayerModels/Matthew_Kremit/Death/Kremit_Death_", 8, d3dResult, d3dDevice_)) return false; // working if (!KremitAttack.Load("PlayerModels/Matthew_Kremit/Attack/Kremit_Attack_", 8, d3dResult, d3dDevice_)) return false; // working if (!KremitDamaged.Load("PlayerModels/Matthew_Kremit/Damage/Kremit_Damaged_", 8, d3dResult, d3dDevice_)) return false; // working //============ ZOMBIE ============ if (!Zombie_M.Init("PlayerModels/Nathan_ExoSuit/Idle/Exo_Suit_Idle_01.obj", d3dResult, d3dDevice_)) return false; if (!Zombie_T.Init("PlayerModels/Nathan_ExoSuit/CorpseBodTexture2.png", d3dResult, d3dDevice_)) return false; if (!ZombieIdle.Load("PlayerModels/Nathan_ExoSuit/Idle/Exo_Suit_Idle_0", 8, d3dResult, d3dDevice_)) return false; //working if (!ZombieWalk.Load("PlayerModels/Nathan_ExoSuit/Walk/Exo_Suit_Walk_0", 8, d3dResult, d3dDevice_)) return false; // working if (!ZombieDeath.Load("PlayerModels/Nathan_ExoSuit/Death/Exo_Suit_Death_0", 8, d3dResult, d3dDevice_)) return false; // working if (!ZombieDamaged.Load("PlayerModels/Nathan_ExoSuit/Damage/Exo_suit_Hit_0", 8, d3dResult, d3dDevice_)) return false; // working if (!ZombieAttack.Load("PlayerModels/Nathan_Exosuit/Attack/Exo_Suit_Punching_0", 8, d3dResult, d3dDevice_)) return false; // working //============ ALIEN ============ if (!Alien_M.Init("PlayerModels/Lucy_Alien/Idle/Alien_Idle_1.obj", d3dResult, d3dDevice_)) return false; if (!Alien_T.Init("PlayerModels/Lucy_Alien/CharacterTexture.png", d3dResult, d3dDevice_)) return false; if (!AlienIdle.Load("PlayerModels/Lucy_Alien/Idle/Alien_Idle_", 8, d3dResult, d3dDevice_)) return false; // working if (!AlienWalk.Load("PlayerModels/Lucy_Alien/Walk/Alien_Walk_", 8, d3dResult, d3dDevice_)) return false; // working if (!AlienDeath.Load("PlayerModels/Lucy_Alien/Death/Alien_Dying_", 8, d3dResult, d3dDevice_)) return false; // working if (!AlienAttack.Load("PlayerModels/Lucy_Alien/Attack/Alien_Attack_", 8, d3dResult, d3dDevice_)) return false; // working if (!AlienDamaged.Load("PlayerModels/Lucy_Alien/Damage/Alien_GettingHit_", 8, d3dResult, d3dDevice_)) return false; // working //============ SKINNY ============ if (!Skinny_M.Init("PlayerModels/Valdas_Skinny/Skinny_Idle_1.obj", d3dResult, d3dDevice_)) return false; if (!Skinny_T.Init("PlayerModels/Valdas_Skinny/UV17.png", d3dResult, d3dDevice_)) return false; if (!SkinnyIdle.Load("PlayerModels/Valdas_Skinny/Idle/Skinny_Idle_", 8, d3dResult, d3dDevice_)) return false; // working if (!SkinnyWalk.Load("PlayerModels/Valdas_Skinny/Walk/Skinny_Walking_", 8, d3dResult, d3dDevice_)) return false; // working if (!SkinnyDeath.Load("PlayerModels/Valdas_Skinny/Death/Skinny_Death_", 8, d3dResult, d3dDevice_)) return false; // working if (!SkinnyAttack.Load("PlayerModels/Valdas_Skinny/Attack/Skinny_Punch_", 8, d3dResult, d3dDevice_)) return false; // working if (!SkinnyDamaged.Load("PlayerModels/Valdas_Skinny/Damage/Skinny_Gethit_", 8, d3dResult, d3dDevice_)) return false; // working if (Player1.IsPaused()) { Player1.TogglePause(); } if (Player2.IsPaused()) { Player2.TogglePause(); } // SETTING THE ANIMATIONS!!!! Player1.setIsAnimated(true); Player1.setAnimation("idle"); Player1.setFPS(8 / 1.0f); // number of frames / the length of animation in seconds /*if (!Player1.IsReversed()) { Player1.ToggleReverse(); }*/ Player2.setIsAnimated(true); Player2.setAnimation("idle"); Player2.setFPS(8 / 1.0f); float mult = 140.0f; // ---------- LOADING OBJECTS ---------- if (!SkyBoxMesh.Init("GameObjects/Skybox1.obj", d3dResult, d3dDevice_)) return false; if (!SkyBoxTexture.Init("GameObjects/SkyBoxTextureSpace.png", d3dResult, d3dDevice_)) return false; SkyBox.setMesh(&SkyBoxMesh); SkyBox.setTexture(&SkyBoxTexture); SkyBox.setPosition({ 0.0f, 0.0f, 0.0f }); if (!DomeMesh.Init("GameObjects/Dome/Dome.obj", d3dResult, d3dDevice_)) return false; if (!DomeTexture.Init("GameObjects/Dome/DomeTexture.png", d3dResult, d3dDevice_)) return false; DomeObj.setMesh(&DomeMesh); DomeObj.setTexture(&DomeTexture); DomeObj.setPosition({ 0.0f, 0.1f, 0.0f }); if (!DoorMesh.Init("GameObjects/Door/DoorModel.obj", d3dResult, d3dDevice_)) return false; if (!DoorTexture.Init("GameObjects/Door/DoorUVClean.png", d3dResult, d3dDevice_)) return false; Door.setMesh(&DoorMesh); Door.setTexture(&DoorTexture); XMVECTOR temp = XMVectorSet(100.0f, 0.0f, 100.0f, 0.0f); temp = XMVector3Normalize(temp) * 160.0f; Door.setPosition({ XMVectorGetX(temp), XMVectorGetY(temp), XMVectorGetZ(temp) }); Door.setDirection(temp * -1.0f); if (!CabinetMesh.Init("GameObjects/Props/Cabinet01.obj", d3dResult, d3dDevice_)) return false; if (!CabinetTexture.Init("GameObjects/Props/Cabinet.png", d3dResult, d3dDevice_)) return false; Cabinet.setMesh(&CabinetMesh); Cabinet.setTexture(&CabinetTexture); temp = XMVectorSet(70.0f, 0.0f, 100.0f, 0.0f); temp = XMVector3Normalize(temp) * mult; Cabinet.setPosition({ XMVectorGetX(temp), XMVectorGetY(temp), XMVectorGetZ(temp) }); Cabinet.setDirection(temp * -1.0f); if (!ContainerMesh.Init("GameObjects/Props/Container.obj", d3dResult, d3dDevice_)) return false; if (!ContainerTexture.Init("GameObjects/Props/ContainerUVColour.png", d3dResult, d3dDevice_)) return false; Container.setMesh(&ContainerMesh); Container.setTexture(&ContainerTexture); temp = XMVectorSet(80.0f, 0.0f, 100.0f, 0.0f); temp = XMVector3Normalize(temp) * mult; Container.setPosition({ XMVectorGetX(temp), XMVectorGetY(temp), XMVectorGetZ(temp) }); Container.setDirection(temp * -1.0f); if (!CanisterMesh.Init("GameObjects/Props/Canister_Props.obj", d3dResult, d3dDevice_)) return false; if (!CanisterTexture.Init("GameObjects/Props/Canisters_UV.png", d3dResult, d3dDevice_)) return false; Canister.setMesh(&CanisterMesh); Canister.setTexture(&CanisterTexture); temp = XMVectorSet(130.0f, 0.0f, 100.0f, 0.0f); temp = XMVector3Normalize(temp) * mult; Canister.setPosition({ XMVectorGetX(temp), XMVectorGetY(temp), XMVectorGetZ(temp) }); Canister.setDirection(temp * -1.0f); if (!HangarMesh.Init("GameObjects/Props/Exo_Hanger_Prop.obj", d3dResult, d3dDevice_)) return false; if (!HangarTexture.Init("GameObjects/Props/Hanger_Colours_Flipped.png", d3dResult, d3dDevice_)) return false; Hangar.setMesh(&HangarMesh); Hangar.setTexture(&HangarTexture); temp = XMVectorSet(150.0f, 0.0f, 100.0f, 0.0f); temp = XMVector3Normalize(temp) * mult; Hangar.setPosition({ XMVectorGetX(temp), XMVectorGetY(temp), XMVectorGetZ(temp) }); Hangar.setDirection(temp * -1.0f); /*if (enter pressed on bob) { Player1.setMesh(& Player1Mesh) set texture set animations*/ //Player1.SetCharacter(WOLF); /*}*/ // ------------------------------ END ------------------------------ D3D11_BUFFER_DESC vertexDesc; D3D11_SUBRESOURCE_DATA resourceData; /*VertexPos terrainVertices[] = { { XMFLOAT3(100.0f, 0.0f , 100.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(100.0f, 0.0f , -100.0f), XMFLOAT2(1.0f, 1.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(-100.0f , -0.0f , -100.0f), XMFLOAT2(0.0f, 1.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(-100.0f , -0.0f , -100.0f), XMFLOAT2(0.0f, 1.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(-100.0f , 0.0f, 100.0f), XMFLOAT2(0.0f, 0.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(100.0f, 0.0f, 100.0f), XMFLOAT2(1.0f, 0.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, };*/ TextVertexPos terrainVertices[] = { { XMFLOAT3(-1.0f, 1.0f, 0.5f), XMFLOAT2(0.0f, 0.0f) }, { XMFLOAT3 (1.0f, 1.0f, 0.5f), XMFLOAT2(1.0f, 0.0f) }, { XMFLOAT3(-1.0f, -1.0f, 0.5f), XMFLOAT2(0.0f, 1.0f) }, { XMFLOAT3(1.0f, 1.0f, 0.5f), XMFLOAT2(1.0f, 0.0f) }, { XMFLOAT3(1.0f ,-1.0f, 0.5f), XMFLOAT2(1.0f, 1.0f) }, { XMFLOAT3(-1.0f, -1.0f, 0.5f), XMFLOAT2(0.0f, 1.0f) }, }; //D3D11_BUFFER_DESC vertexDesc; ZeroMemory(&vertexDesc, sizeof(vertexDesc)); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof(VertexPos) * 6; //D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory(&resourceData, sizeof(resourceData)); resourceData.pSysMem = terrainVertices; d3dResult = d3dDevice_->CreateBuffer(&vertexDesc, &resourceData, &vertexBufferTerrain_); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to create vertex buffer!"); return false; } d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, MENU_TEXTURE_NAME, 0, 0, &terrainColorMap_, 0); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to load the texture image!"); return false; } //===================== BLOODY QUAD!!! ================ D3D11_BUFFER_DESC vertexDesc1; D3D11_SUBRESOURCE_DATA resourceData1; VertexPos quadVertices[] = { { XMFLOAT3(10.0f, 0.0f , 10.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(10.0f, 0.0f , -10.0f), XMFLOAT2(1.0f, 1.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(-10.0f,0.0f , -10.0f), XMFLOAT2(0.0f, 1.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(-10.0f ,0.0f , -10.0f), XMFLOAT2(0.0f, 1.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(-10.0f , 0.0f, 10.0f), XMFLOAT2(0.0f, 0.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, { XMFLOAT3(10.0f, 0.0f, 10.0f), XMFLOAT2(1.0f, 0.0f) , XMFLOAT3(0.0f, 1.0f , 0.0f) }, }; //D3D11_BUFFER_DESC vertexDesc; ZeroMemory(&vertexDesc1, sizeof(vertexDesc1)); vertexDesc1.Usage = D3D11_USAGE_DEFAULT; vertexDesc1.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc1.ByteWidth = sizeof(VertexPos) * 6; //D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory(&resourceData1, sizeof(resourceData1)); resourceData1.pSysMem = quadVertices; d3dResult = d3dDevice_->CreateBuffer(&vertexDesc1, &resourceData1, &vertexBufferQuad_); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to create vertex buffer!"); return false; } d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, SOIL_TEXTURE_NAME, 0, 0, &soilColorMap_, 0); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to load the texture image!"); return false; } //===================================================== D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory(&colorMapDesc, sizeof(colorMapDesc)); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; //colorMapDesc.Filter = D3D11_FILTER_ANISOTROPIC; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; d3dResult = d3dDevice_->CreateSamplerState(&colorMapDesc, &colorMapSampler_); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to create color map sampler state!"); return false; } D3D11_BUFFER_DESC constDesc; ZeroMemory(&constDesc, sizeof(constDesc)); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = sizeof(XMMATRIX); constDesc.Usage = D3D11_USAGE_DEFAULT; d3dResult = d3dDevice_->CreateBuffer(&constDesc, 0, &viewCB_); if (FAILED(d3dResult)) { return false; } d3dResult = d3dDevice_->CreateBuffer(&constDesc, 0, &projCB_); if (FAILED(d3dResult)) { return false; } d3dResult = d3dDevice_->CreateBuffer(&constDesc, 0, &worldCB_); if (FAILED(d3dResult)) { return false; } constDesc.ByteWidth = sizeof(XMFLOAT4); d3dResult = d3dDevice_->CreateBuffer(&constDesc, 0, &camPosCB_); if (FAILED(d3dResult)) { return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////// /* D3D11_BLEND_DESC blendDesc2; ZeroMemory( &blendDesc2, sizeof( blendDesc2 ) ); blendDesc2.RenderTarget[0].BlendEnable = TRUE; blendDesc2.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc2.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc2.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDesc2.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc2.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendDesc2.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDesc2.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; d3dDevice_->CreateBlendState( &blendDesc2, &alphaBlendState_ ); //d3dDevice_->CreateBlendState( &BlendState, &alphaBlendState_ ); d3dContext_->OMSetBlendState( alphaBlendState_, blendFactor, 0xFFFFFFFF );*/ ////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11_BLEND_DESC blendStateDescription; // Clear the blend state description. ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC)); // Create an alpha enabled blend state description. blendStateDescription.RenderTarget[0].BlendEnable = TRUE; //blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; //blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f; // Create the blend state using the description. d3dResult = d3dDevice_->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState); if (FAILED(d3dResult)) { return false; } // Modify the description to create an alpha disabled blend state description. blendStateDescription.RenderTarget[0].BlendEnable = FALSE; // Create the blend state using the description. d3dResult = d3dDevice_->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState); if (FAILED(d3dResult)) { return false; } projMatrix_ = XMMatrixPerspectiveFovLH(XM_PIDIV4, 800.0f / 600.0f, 0.01f, 10000.0f); projMatrix_ = XMMatrixTranspose(projMatrix_); camera_.SetDistance(12.0f, 4.0f, 20.0f); return true; } void ModelsDemo::UnloadContent() { if (colorMapSampler_) colorMapSampler_->Release(); if (textColorMapSampler_) textColorMapSampler_->Release(); //QUAD if (soilColorMap_) soilColorMap_->Release(); if (terrainColorMap_) terrainColorMap_->Release(); if (textColorMap_) textColorMap_->Release(); if (textureMapVS_) textureMapVS_->Release(); if (textTextureMapPS_) textTextureMapPS_->Release(); if (textTextureMapVS_) textTextureMapVS_->Release(); if (textureMapPS_) textureMapPS_->Release(); if (inputLayout_) inputLayout_->Release(); if (textInputLayout_) textInputLayout_->Release(); if (textVertexBuffer_) textVertexBuffer_->Release(); if (viewCB_) viewCB_->Release(); if (projCB_) projCB_->Release(); if (worldCB_) worldCB_->Release(); if (camPosCB_) camPosCB_->Release(); if (m_alphaEnableBlendingState) { m_alphaEnableBlendingState->Release(); m_alphaEnableBlendingState = 0; } if (m_alphaDisableBlendingState) { m_alphaDisableBlendingState->Release(); m_alphaDisableBlendingState = 0; } // unloading models Player1Mesh.Unload(); Player1Texture.unloadTexture(); Player2Mesh.Unload(); Player2Texture.unloadTexture(); Zombie_T.unloadTexture(); Zombie_M.Unload(); Wolf_T.unloadTexture(); Wolf_M.Unload(); Kremit_T.unloadTexture(); Kremit_M.Unload(); Robot_T.unloadTexture(); Robot_M.Unload(); Alien_T.unloadTexture(); Alien_M.Unload(); SkyBoxMesh.Unload(); SkyBoxTexture.unloadTexture(); DomeMesh.Unload(); DomeTexture.unloadTexture(); DoorMesh.Unload(); DoorTexture.unloadTexture(); CabinetMesh.Unload(); CabinetTexture.unloadTexture(); ContainerMesh.Unload(); ContainerTexture.unloadTexture(); CanisterMesh.Unload(); CanisterTexture.unloadTexture(); HangarMesh.Unload(); HangarTexture.unloadTexture(); colorMapSampler_ = 0; textColorMapSampler_ = 0; //colorMap1_ = 0; //colorMap2_ = 0; //SOIL soilColorMap_ = 0; terrainColorMap_ = 0; textColorMap_ = 0; textureMapVS_ = 0; textureMapPS_ = 0; textTextureMapVS_ = 0; textTextureMapPS_ = 0; inputLayout_ = 0; textInputLayout_ = 0; textVertexBuffer_ = 0; viewCB_ = 0; projCB_ = 0; worldCB_ = 0; } void ModelsDemo::TurnOnAlphaBlending() { float blendFactor[4]; // Setup the blend factor. blendFactor[0] = 0.0f; blendFactor[1] = 0.0f; blendFactor[2] = 0.0f; blendFactor[3] = 0.0f; // Turn on the alpha blending. d3dContext_->OMSetBlendState(m_alphaEnableBlendingState, blendFactor, 0xffffffff); return; } void ModelsDemo::TurnOffAlphaBlending() { float blendFactor[4]; // Setup the blend factor. blendFactor[0] = 0.0f; blendFactor[1] = 0.0f; blendFactor[2] = 0.0f; blendFactor[3] = 0.0f; // Turn off the alpha blending. d3dContext_->OMSetBlendState(m_alphaDisableBlendingState, blendFactor, 0xffffffff); return; } void ModelsDemo::TurnZBufferOn() { d3dContext_->OMSetDepthStencilState(m_depthStencilState, 1); return; } void ModelsDemo::TurnZBufferOff() { d3dContext_->OMSetDepthStencilState(m_depthDisabledStencilState, 1); return; } void ModelsDemo::SetGameState(GameStates state) { gameState_ = state; } GameStates ModelsDemo::GetGameState() { return gameState_; } void ModelsDemo::Update(float dt) { //camera_.ApplyZoom(.01); //camera_.ApplyRotation(0.001,0.001); if (gameState_ == RUN) { XMVECTOR cameraPosition = XMLoadFloat3(&camera_.GetPosition()); // following each other //models[0].moveForward(2 * dt); Tank3Speed = 2 * dt; // Updating Players Player1.update(dt, Player2.getPosition()); Player2.update(dt, Player1.getPosition()); } else { Tank3Speed = 0; } float moveSpeed = 0.01f; float moveSpeed2 = 20.0f; float zoom = 0.0; float xRotation = 0.0; float yRotation = 0.0; wait -= dt; attack_time1 -= dt; attack_time2 -= dt; //============================= STATES CONTROLS !!! ================== if (gameState_ == START_MENU ) { if ((!(keystate[DIK_S] & 0x80) && (keyPrevState[DIK_S] & 0x80))) { MMSelection++; } else if ((!(keystate[DIK_W] & 0x80) && (keyPrevState[DIK_W] & 0x80))) { MMSelection --; } if ((keystate[DIK_RETURN] & 0x80) && (MMSelection == EXIT) && (wait <= 0)) { gameState_ = START_MENU; wait = 0.1; } if ((keystate[DIK_RETURN] & 0x80) && (MMSelection == CREDITS) && (wait <= 0)) { gameState_ = THANKS; wait = 0.1; } if ((keystate[DIK_RETURN] & 0x80) && (MMSelection == PLAY) && (wait <= 0)) { gameState_ = SELECTION; wait = 0.1; } } if (gameState_ == SELECTION) { Player1.setPosition({ -10.0f, 0.0f, 0.0f }); Player2.setPosition({ 10.0f, 0.0f, 0.0f }); if ((keystate[DIK_RETURN] & 0x80) && (wait <= 0)) { gameState_ = RUN; wait = 0.1f; } //=========== Select Player 1 =================== if ((!(keystate[DIK_S] & 0x80) && (keyPrevState[DIK_S] & 0x80))) { P1charSelection++; } if ((!(keystate[DIK_W] & 0x80) && (keyPrevState[DIK_W] & 0x80))) { P1charSelection--; } //=========== Select Player 2 ================ if ((!(keystate[DIK_DOWN] & 0x80) && (keyPrevState[DIK_DOWN] & 0x80))) { P2charSelection ++; } if ((!(keystate[DIK_UP] & 0x80) && (keyPrevState[DIK_UP] & 0x80))) { P2charSelection --; } } if (gameState_ == PAUSED) { if (!(keystate[DIK_ESCAPE] & 0x80) && (keyPrevState[DIK_ESCAPE] & 0x80) && (wait <= 0)) { //PostQuitMessage(0); gameState_ = RUN; } if ((keystate[DIK_RETURN] & 0x80) && (pauseMenuSelection == RETURN) && (wait <= 0)) { //PostQuitMessage(0); gameState_ = RUN; } if ((keystate[DIK_RETURN] & 0x80) && (pauseMenuSelection == PLAY_MOVIE) && (wait <= 0)) { //PostQuitMessage(0); gameState_ = INTRO_MOVIE_REPLAY; } if ((keystate[DIK_RETURN] & 0x80) && (pauseMenuSelection == QUIT) && (wait <= 0)) { gameState_ = START_MENU; wait = 0.1; } if ((!(keystate[DIK_RETURN] & 0x80) && (keyPrevState[DIK_RETURN] & 0x80) && (wait <= 0)) && (pauseMenuSelection == FPS)) { displayFPS = !displayFPS; } if ((!(keystate[DIK_DOWN] & 0x80) && (keyPrevState[DIK_DOWN] & 0x80)) || (!(keystate[DIK_S] & 0x80) && (keyPrevState[DIK_S] & 0x80))) { pauseMenuSelection++; } if ((!(keystate[DIK_UP] & 0x80) && (keyPrevState[DIK_UP] & 0x80)) || (!(keystate[DIK_W] & 0x80) && (keyPrevState[DIK_W] & 0x80))) { pauseMenuSelection--; } } if (gameState_ == POST_MATCH) { if ((!(keystate[DIK_RETURN] & 0x80) && (keyPrevState[DIK_RETURN] & 0x80) && (wait <= 0))) { gameState_ = START_MENU; } } if (gameState_ == THANKS) { if ((!(keystate[DIK_RETURN] & 0x80) && (keyPrevState[DIK_RETURN] & 0x80) && (wait <= 0))) { gameState_ = START_MENU; } } //========================== GETTING THE INPUTS / COLLISIONS ============================== //moveSpeed=0.001f; float moveLeftRight = 0.0; float moveBackForward = 0.0; float moveUpDown = 0.0; float dist = Player1.getRadius() + Player2.getRadius() ; Player2.SetPlayer(false); if (gameState_ == RUN) { //// =========== MODEL MOVEMENTS 1 ================= if ((keystate[DIK_W] & 0x80)) { AnimatioState = WALK; Player1.SetReverse(false); bool right = false; Player1.moveRight(dt, right); } else if ((keystate[DIK_S] & 0x80)) { AnimatioState = WALK; Player1.SetReverse(true); bool right = true; Player1.moveRight(dt, right); } else if ((keystate[DIK_A] & 0x80)) { AnimatioState = WALK; Player1.SetReverse(true); Player1.moveForward(dt, true); } else if ((keystate[DIK_D] & 0x80)) { AnimatioState = WALK; Player1.SetReverse(false); if (collision.colliding(Player1.getPosition(), Player2.getPosition(), dt, dist) != 1) { //m_z1 += moveSpeed2 * dt; bool forward = false; Player1.moveForward(dt, forward); } } else if ((keystate[DIK_F] & 0x80) && (attack_time1 <= 0)) { Player1.SetReverse(false); AnimatioState = ATTACK; attack_time1 = 1.0f; } else if ((collision.colliding(Player1.getPosition(), Player2.getPosition(), dt, dist) == 1) && (Player1.GetCurremtFrame() == 7) && AnimatioState == 2) { Player2.ApplyDamage(Player1.GetAttack()); if (Player2.GetAlive()) { AnimatioState2 = HITTED; } else { AnimatioState2 = DIE; } } else { //preventing to stop the attack animation, //but stopping the move animation once the button is not pressed anymore if (AnimatioState != ATTACK && AnimatioState != HITTED && AnimatioState != DIE) { AnimatioState = IDLE; } } switch (AnimatioState) { case IDLE: Player1.setAnimation("idle"); Player1.setFPS(8 / 1.0f); if (PrevAnimState != IDLE) { Player1.SetCurrentFrame(0); } break; case WALK: Player1.setAnimation("walk"); Player1.setFPS(8 / 1.0f); if (PrevAnimState != WALK) { Player1.SetCurrentFrame(0); } break; case ATTACK: Player1.setAnimation("attack"); Player1.setFPS(8 / 1.0f); if (PrevAnimState != ATTACK) { Player1.SetCurrentFrame(0); } //here we are actually stopping the attack animation ONCE IS OVER!!! if (Player1.GetCurremtFrame() == 7) { AnimatioState = IDLE; } break; case HITTED: Player1.setAnimation("damaged"); Player1.setFPS(8 / 1.0f); if (PrevAnimState != HITTED) { Player1.SetCurrentFrame(0); } if (Player1.GetCurremtFrame() == 7) { AnimatioState = IDLE; } break; case DIE: Player1.setAnimation("death"); Player1.setFPS(8 / 1.0f); if (PrevAnimState != DIE) { Player1.SetCurrentFrame(0); } if (Player1.GetCurremtFrame() == 7) { AnimatioState = 0; gameState_ = POST_MATCH; } break; } PrevAnimState = AnimatioState; // =========== MODEL MOVEMENTS 2 ================= if ((keystate[DIK_DOWN] & 0x80)) { AnimatioState2 = WALK; Player2.SetReverse(true); bool right = false; Player2.moveRight(dt, right); } else if ((keystate[DIK_UP] & 0x80)) { AnimatioState2 = WALK; Player2.SetReverse(false); bool right = true; Player2.moveRight(dt, right); } else if ((keystate[DIK_RIGHT] & 0x80)) { AnimatioState2 = WALK; Player2.SetReverse(true); Player2.moveForward(dt, true); } else if ((keystate[DIK_LEFT] & 0x80)) { AnimatioState2 = WALK; Player2.SetReverse(false); if (collision.colliding(Player2.getPosition(), Player1.getPosition(), dt, dist) != 1) { bool forward = false; Player2.moveForward(dt, forward); } } else if ((keystate[DIK_NUMPAD4] & 0x80) && (attack_time2 <= 0)) { Player2.SetReverse(false); AnimatioState2 = ATTACK; attack_time2 = 1.0f; } else if ((collision.colliding(Player2.getPosition(), Player1.getPosition(), dt, dist) == 1) && (Player2.GetCurremtFrame() == 7) && AnimatioState2 == 2) { Player1.ApplyDamage(Player2.GetAttack()); if (Player1.GetAlive()) { AnimatioState = HITTED; } else { AnimatioState = DIE; } } else { //preventing to stop the attack animation, //but stopping the move animation once the button is not pressed anymore if (AnimatioState2 != ATTACK && AnimatioState2 != HITTED && AnimatioState2 != DIE) { AnimatioState2 = IDLE; } } switch (AnimatioState2) { case IDLE: Player2.setAnimation("idle"); Player2.setFPS(8 / 1.0f); if (PrevAnimState2 != IDLE) { Player2.SetCurrentFrame(0); } break; case WALK: Player2.setAnimation("walk"); Player2.setFPS(8 / 1.0f); if (PrevAnimState2 != WALK) { Player2.SetCurrentFrame(0); } break; case ATTACK: Player2.setAnimation("attack"); Player2.setFPS(8 / 1.0f); if (PrevAnimState2 != ATTACK) { Player2.SetCurrentFrame(0); } //here we are actually stopping the attack animation ONCE IS OVER!!! if (Player2.GetCurremtFrame() == 7) { AnimatioState2 = IDLE; } break; case HITTED: Player2.setAnimation("damaged"); Player2.setFPS(8 / 1.0f); if (PrevAnimState2 != HITTED) { Player2.SetCurrentFrame(0); } //here we are actually stopping the attack animation ONCE IS OVER!!! if (Player2.GetCurremtFrame() == 7) { AnimatioState2 = IDLE; } break; case DIE: Player2.setAnimation("death"); Player2.setFPS(8 / 1.0f); if (PrevAnimState2 != DIE) { Player2.SetCurrentFrame(0); } //here we are actually stopping the attack animation ONCE IS OVER!!! if (Player2.GetCurremtFrame() == 7) { AnimatioState2 = IDLE; gameState_ = POST_MATCH; } break; } PrevAnimState2 = AnimatioState2; //=================== AM I STILL ALIVE??? ================== //============================== CAMERA ===================================== if (camera_.getControllable()) { if ((keystate[DIK_J] & 0x80)) { //moveLeftRight -= moveSpeed; moveLeftRight -= moveSpeed2 * dt; } if ((keystate[DIK_L] & 0x80)) { //moveLeftRight += moveSpeed; moveLeftRight += moveSpeed2 * dt; } if ((keystate[DIK_K] & 0x80)) { //moveBackForward -= moveSpeed; moveBackForward -= dt * moveSpeed2; } if ((keystate[DIK_I] & 0x80)) { //moveBackForward += moveSpeed; moveBackForward += dt * moveSpeed2; } if ((keystate[DIK_U] & 0x80)) { //moveBackForward -= moveSpeed; moveUpDown -= dt * moveSpeed2; } if ((keystate[DIK_O] & 0x80)) { //moveBackForward += moveSpeed; moveUpDown += dt * moveSpeed2; } } if (keystate[DIK_SUBTRACT] & 0x80) { zoom += moveSpeed * 2; } if (keystate[DIK_ADD] & 0x80) { zoom -= moveSpeed * 2; } if (!(keystate[DIK_ESCAPE] & 0x80) && (keyPrevState[DIK_ESCAPE] & 0x80)) { //PostQuitMessage(0); gameState_ = PAUSED; } if (camera_.getControllable()) { if ((mouseCurrState.lX != mousePrevState.lX) || (mouseCurrState.lY != mousePrevState.lY)) { yRotation += mousePrevState.lX * 0.005f; //yRotation += mousePrevState.lX * dt*2.0f;//mouse movement already based on time xRotation += mouseCurrState.lY * 0.005f; //xRotation += mouseCurrState.lY * dt*2.0f;/mouse movement already based on time if (xRotation>XM_PI / 8) { xRotation = XM_PI / 8; } if (xRotation<-(XM_PI / 8)) { xRotation = -(XM_PI / 8); } mousePrevState = mouseCurrState; } camera_.Move(moveLeftRight, moveBackForward, moveUpDown); //camera_.setControllable(false); camera_.ApplyRotation(xRotation, yRotation); } camera_.ApplyZoom(zoom); camera_.update(dt, &Player1, &Player2); } memcpy(&prevController1State_, &controller1State_, sizeof(XINPUT_STATE)); } bool ModelsDemo::DrawString(char* message, float startX, float startY) { //float clearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; //d3dContext_->ClearRenderTargetView( backBufferTarget_, clearColor ); // Size in bytes for a single sprite. const int sizeOfSprite = sizeof(TextVertexPos) * 6; // Demo's dynamic buffer setup for max of 24 letters. const int maxLetters = 24; int length = strlen(message); // Clamp for strings too long. if (length > maxLetters) length = maxLetters; // Char's width on screen. float charWidth = 32.0f / 800.0f; // Char's height on screen. float charHeight = 32.0f / 640.0f; // Char's texel width. //float texelWidth = 32.0f / 864.0f; float texelWidth = 32.0f / 3072.0f; // verts per-triangle (3) * total triangles (2) = 6. const int verticesPerLetter = 6; D3D11_MAPPED_SUBRESOURCE mapResource; HRESULT d3dResult = d3dContext_->Map(textVertexBuffer_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapResource); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to map resource!"); return false; } // Point to our vertex buffer's internal data. TextVertexPos *spritePtr = (TextVertexPos*)mapResource.pData; const int indexSpace = static_cast<char>(' '); const int indexA = static_cast<char>('A'); const int indexZ = static_cast<char>('Z'); const int indexSquare = static_cast<char>(127); for (int i = 0; i < length; ++i) { float thisStartX = startX + (charWidth * static_cast<float>(i)); float thisEndX = thisStartX + charWidth; float thisEndY = startY + charHeight; spritePtr[0].pos = XMFLOAT3(thisEndX, thisEndY, 1.0f); spritePtr[1].pos = XMFLOAT3(thisEndX, startY, 1.0f); spritePtr[2].pos = XMFLOAT3(thisStartX, startY, 1.0f); spritePtr[3].pos = XMFLOAT3(thisStartX, startY, 1.0f); spritePtr[4].pos = XMFLOAT3(thisStartX, thisEndY, 1.0f); spritePtr[5].pos = XMFLOAT3(thisEndX, thisEndY, 1.0f); int texLookup = 0; int letter = static_cast<char>(message[i]); //if( letter < indexA || letter > indexZ ) if (letter < indexSpace || letter > indexSquare) { // Grab one index past Z, which is a blank space in the texture. // texLookup = ( indexZ - indexA ) + 1; texLookup = indexSquare; } else { // A = 0, B = 1, Z = 25, etc. //texLookup = ( letter - indexA ); texLookup = (letter - indexSpace); } float tuStart = 0.0f + (texelWidth * static_cast<float>(texLookup)); float tuEnd = tuStart + texelWidth; spritePtr[0].tex0 = XMFLOAT2(tuEnd, 0.0f); spritePtr[1].tex0 = XMFLOAT2(tuEnd, 1.0f); spritePtr[2].tex0 = XMFLOAT2(tuStart, 1.0f); spritePtr[3].tex0 = XMFLOAT2(tuStart, 1.0f); spritePtr[4].tex0 = XMFLOAT2(tuStart, 0.0f); spritePtr[5].tex0 = XMFLOAT2(tuEnd, 0.0f); spritePtr += 6; } d3dContext_->Unmap(textVertexBuffer_, 0); d3dContext_->Draw(6 * length, 0); return true; } void ModelsDemo::Render() { if (d3dContext_ == 0) return; float clearColor[4] = { 0.7f, 0.8f, 1.0f, 1.0f }; d3dContext_->ClearRenderTargetView(backBufferTarget_, clearColor); d3dContext_->ClearDepthStencilView(depthStencilView_, D3D11_CLEAR_DEPTH, 1.0f, 0); unsigned int stride = sizeof(VertexPos); unsigned int offset = 0; //======================= MENU !!! ======================= if (gameState_ == START_MENU) { /////////////////////////////////////////////TEXT////////////////////////////////////////////// TurnZBufferOff(); TurnOnAlphaBlending(); stride = sizeof(TextVertexPos); offset = 0; d3dContext_->IASetInputLayout(textInputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &vertexBufferTerrain_, &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textTextureMapVS_, 0, 0); d3dContext_->PSSetShader(textTextureMapPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &terrainColorMap_); d3dContext_->PSSetSamplers(0, 1, &colorMapSampler_); d3dContext_->Draw(6, 0); TurnOffAlphaBlending(); TurnZBufferOn(); //////////////////////////////////////////////////////////////////////////////////////////////// if (MMSelection == PLAY) { MENU_TEXTURE_NAME = "GameObjects/Menu_Stuff/Play.jpg"; HRESULT d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, MENU_TEXTURE_NAME, 0, 0, &terrainColorMap_, 0); } if (MMSelection == OPTIONS) { MENU_TEXTURE_NAME = "GameObjects/Menu_Stuff/Options.jpg"; HRESULT d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, MENU_TEXTURE_NAME, 0, 0, &terrainColorMap_, 0); } if (MMSelection == CREDITS) { MENU_TEXTURE_NAME = "GameObjects/Menu_Stuff/Credits.jpg"; HRESULT d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, MENU_TEXTURE_NAME, 0, 0, &terrainColorMap_, 0); } if (MMSelection == EXIT) { MENU_TEXTURE_NAME = "GameObjects/Menu_Stuff/Quit.jpg"; HRESULT d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, MENU_TEXTURE_NAME, 0, 0, &terrainColorMap_, 0); } } //============= Character Selection ============= if (gameState_ == SELECTION) { TurnZBufferOff(); TurnOnAlphaBlending(); // Sending THE FONT to the SHADER stride = sizeof(TextVertexPos); offset = 0; d3dContext_->IASetInputLayout(textInputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &vertexBufferTerrain_, &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textTextureMapVS_, 0, 0); d3dContext_->PSSetShader(textTextureMapPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &terrainColorMap_); d3dContext_->PSSetSamplers(0, 1, &colorMapSampler_); d3dContext_->Draw(6, 0); // Sending THE TEXTURE to the SHADER MENU_TEXTURE_NAME = "GameObjects/Menu_Stuff/Selection.jpg"; HRESULT d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, MENU_TEXTURE_NAME, 0, 0, &terrainColorMap_, 0); stride = sizeof(TextVertexPos); offset = 0; d3dContext_->IASetInputLayout(textInputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &textVertexBuffer_, &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textTextureMapVS_, 0, 0); d3dContext_->PSSetShader(textTextureMapPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &textColorMap_); d3dContext_->PSSetSamplers(0, 1, &textColorMapSampler_); Player1.SetAlive(true); Player2.SetAlive(true); DrawString("PRESS ENTER TO SELECT", -0.4f, 0.0f); DrawString("CHARACTER", -0.2f, -0.1f); //=============== Player 1 ============== if (P1charSelection == WOLF) { DrawString("->WOLF<-", -0.63f, -0.1f); Player1.SetCharacter(WOLF); Player1.setMesh(&Wolf_M); Player1.setTexture(&Wolf_T); Player1.setIdleMesh(&WolfIdle); Player1.setWalkMesh(&WolfWalk); Player1.setDeathMesh(&WolfDeath); Player1.setAttackMesh(&WolfAttack); Player1.setDamagedMesh(&WolfDamaged); } else { DrawString("WOLF", -0.55f, -0.1f); } if (P1charSelection == ROBOT) { DrawString("->ROBOT<-", -0.63f, -0.2f); Player1.SetCharacter(ROBOT); Player1.setMesh(&Robot_M); Player1.setTexture(&Robot_T); Player1.setDamagedMesh(&RobotDamaged); Player1.setIdleMesh(&RobotIdle); Player1.setWalkMesh(&RobotWalk); Player1.setDeathMesh(&RobotDeath); Player1.setAttackMesh(&RobotAttack); Player1.setDamagedMesh(&RobotDamaged); } else { DrawString("ROBOT", -0.55f, -0.2f); } if (P1charSelection == KREMIT) { DrawString("->KREMIT<-", -0.63f, -0.3f); Player1.SetCharacter(KREMIT); Player1.setMesh(&Kremit_M); Player1.setTexture(&Kremit_T); Player1.setIdleMesh(&KremitIdle); Player1.setWalkMesh(&KremitWalk); Player1.setDeathMesh(&KremitDeath); Player1.setAttackMesh(&KremitAttack); Player1.setDamagedMesh(&KremitDamaged); } else { DrawString("KREMIT", -0.55f, -0.3f); } if (P1charSelection == ZOMBIE) { Player1.SetCharacter(ZOMBIE); DrawString("->ZOMBIE<-", -0.63f, -0.4f); Player1.setMesh(&Zombie_M); Player1.setTexture(&Zombie_T); Player1.setIdleMesh(&ZombieIdle); Player1.setWalkMesh(&ZombieWalk); Player1.setDeathMesh(&ZombieDeath); Player1.setAttackMesh(&ZombieAttack); Player1.setDamagedMesh(&ZombieDamaged); } else { DrawString("ZOMBIE", -0.55f, -0.4f); } if (P1charSelection == ALIEN) { DrawString("->ALIEN<-", -0.63f, -0.5f); Player1.SetCharacter(ALIEN); Player1.setMesh(&Alien_M); Player1.setTexture(&Alien_T); Player1.setIdleMesh(&AlienIdle); Player1.setWalkMesh(&AlienWalk); Player1.setDeathMesh(&AlienDeath); Player1.setAttackMesh(&AlienAttack); Player1.setDamagedMesh(&AlienDamaged); } else { DrawString("ALIEN", -0.55f, -0.5f); } if (P1charSelection == SKINNY) { DrawString("->SKINNY<-", -0.63f, -0.6f); Player1.SetCharacter(SKINNY); Player1.setMesh(&Skinny_M); Player1.setTexture(&Skinny_T); Player1.setIdleMesh(&SkinnyIdle); Player1.setWalkMesh(&SkinnyWalk); Player1.setDeathMesh(&SkinnyDeath); Player1.setAttackMesh(&SkinnyAttack); Player1.setDamagedMesh(&SkinnyDamaged); } else { DrawString("SKINNY", -0.55f, -0.6f); } //=============== Player 2 ============== if (P2charSelection == WOLF) { DrawString("->WOLF<-", 0.33f, -0.1f); Player2.SetCharacter(WOLF); Player2.setMesh(&Wolf_M); Player2.setTexture(&Wolf_T); Player2.setIdleMesh(&WolfIdle); Player2.setWalkMesh(&WolfWalk); Player2.setDeathMesh(&WolfDeath); Player2.setAttackMesh(&WolfAttack); Player2.setDamagedMesh(&WolfDamaged); } else { DrawString("WOLF", 0.41f, -0.1f); } if (P2charSelection == ROBOT) { DrawString("->ROBOT<-", 0.33f, -0.2f); Player2.SetCharacter(ROBOT); Player2.setMesh(&Robot_M); Player2.setTexture(&Robot_T); Player2.setIdleMesh(&RobotIdle); Player2.setWalkMesh(&RobotWalk); Player2.setDeathMesh(&RobotDeath); Player2.setAttackMesh(&RobotAttack); Player2.setDamagedMesh(&RobotDamaged); } else { DrawString("ROBOT", 0.41f, -0.2f); } if (P2charSelection == KREMIT) { DrawString("->KREMIT<-", 0.33f, -0.3f); Player2.SetCharacter(KREMIT); Player2.setMesh(&Kremit_M); Player2.setTexture(&Kremit_T); Player2.setIdleMesh(&KremitIdle); Player2.setWalkMesh(&KremitWalk); Player2.setDeathMesh(&KremitDeath); Player2.setAttackMesh(&KremitAttack); Player2.setDamagedMesh(&KremitDamaged); } else { DrawString("KREMIT", 0.41f, -0.3f); } if (P2charSelection == ZOMBIE) { DrawString("->ZOMBIE<-", 0.33f, -0.4f); Player2.SetCharacter(ZOMBIE); Player2.setMesh(&Zombie_M); Player2.setTexture(&Zombie_T); Player2.setIdleMesh(&ZombieIdle); Player2.setWalkMesh(&ZombieWalk); Player2.setDeathMesh(&ZombieDeath); Player2.setAttackMesh(&ZombieAttack); Player2.setDamagedMesh(&ZombieDamaged); } else { DrawString("ZOMBIE", 0.41f, -0.4f); } if (P2charSelection == ALIEN) { DrawString("->ALIEN<-", 0.33f, -0.5f); Player2.SetCharacter(ALIEN); Player2.setMesh(&Alien_M); Player2.setTexture(&Alien_T); Player2.setIdleMesh(&AlienIdle); Player2.setWalkMesh(&AlienWalk); Player2.setDeathMesh(&AlienDeath); Player2.setAttackMesh(&AlienAttack); Player2.setDamagedMesh(&AlienDamaged); } else { DrawString("ALIEN", 0.41f, -0.5f); } if (P2charSelection == SKINNY) { DrawString("->SKINNY<-", 0.33f, -0.6f); Player2.SetCharacter(SKINNY); Player2.setMesh(&Skinny_M); Player2.setTexture(&Skinny_T); Player2.setIdleMesh(&SkinnyIdle); Player2.setWalkMesh(&SkinnyWalk); Player2.setDeathMesh(&SkinnyDeath); Player2.setAttackMesh(&SkinnyAttack); Player2.setDamagedMesh(&SkinnyDamaged); } else { DrawString("SKINNY", 0.41f, -0.6f); } TurnOffAlphaBlending(); TurnZBufferOn(); } if ((gameState_ == RUN) || (gameState_ == PAUSED) || (gameState_ == POST_MATCH)) { /////////////////////////////////////////geometry settings////////////////////////////// d3dContext_->IASetInputLayout(inputLayout_); //d3dContext_->IASetVertexBuffers(0, 1, model2Mesh.getVertexBuffer(), &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textureMapVS_, 0, 0); d3dContext_->PSSetShader(textureMapPS_, 0, 0); d3dContext_->PSSetSamplers(0, 1, &colorMapSampler_); //TurnZBufferOff(); // 1st objects //d3dContext_->PSSetShaderResources(0, 1, model2Texture.getColorMap()); XMMATRIX worldMat = XMMatrixIdentity(); worldMat = XMMatrixTranspose(worldMat); XMMATRIX viewMat = camera_.GetViewMatrix(); viewMat = XMMatrixTranspose(viewMat); XMFLOAT3 cameraPos = camera_.GetPosition(); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &worldMat, 0, 0); d3dContext_->UpdateSubresource(viewCB_, 0, 0, &viewMat, 0, 0); d3dContext_->UpdateSubresource(projCB_, 0, 0, &projMatrix_, 0, 0); d3dContext_->UpdateSubresource(camPosCB_, 0, 0, &cameraPos, 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->VSSetConstantBuffers(1, 1, &viewCB_); d3dContext_->VSSetConstantBuffers(2, 1, &projCB_); d3dContext_->VSSetConstantBuffers(3, 1, &camPosCB_); XMVECTOR cameraPosition = XMLoadFloat3(&camera_.GetPosition()); ////////////////////terrain//////////////////////////////// //================ SOIL ========================= d3dContext_->PSSetShaderResources(0, 1, &soilColorMap_); worldMat = XMMatrixIdentity(); worldMat = XMMatrixTranspose(worldMat); XMMATRIX scale = XMMatrixIdentity(); scale = XMMatrixScaling(250.0f, 250.0f, 250.0f); worldMat = scale; d3dContext_->UpdateSubresource(worldCB_, 0, 0, &worldMat, 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->IASetVertexBuffers(0, 1, &vertexBufferQuad_, &stride, &offset); d3dContext_->Draw(6, 0); // ---------- DRAWING GAME OBJECTS ---------- // Skybox d3dContext_->IASetVertexBuffers(0, 1, SkyBox.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, SkyBox.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &SkyBox.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(SkyBox.getMesh()->getTotalVerts(), 0); // Door d3dContext_->IASetVertexBuffers(0, 1, Door.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, Door.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &Door.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(Door.getMesh()->getTotalVerts(), 0); # // Cabinet d3dContext_->IASetVertexBuffers(0, 1, Cabinet.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, Cabinet.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &Cabinet.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(Cabinet.getMesh()->getTotalVerts(), 0); //Container d3dContext_->IASetVertexBuffers(0, 1, Container.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, Container.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &Container.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(Container.getMesh()->getTotalVerts(), 0); // Canister d3dContext_->IASetVertexBuffers(0, 1, Canister.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, Canister.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &Canister.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(Canister.getMesh()->getTotalVerts(), 0); // Dome d3dContext_->IASetVertexBuffers(0, 1, DomeObj.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, DomeObj.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &DomeObj.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(DomeObj.getMesh()->getTotalVerts(), 0); // Hangar d3dContext_->IASetVertexBuffers(0, 1, Hangar.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, Hangar.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &Hangar.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(Hangar.getMesh()->getTotalVerts(), 0); // ---------- DRAWING PLAYERS ---------- d3dContext_->IASetVertexBuffers(0, 1, Player1.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, Player1.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &Player1.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(Player1.getMesh()->getTotalVerts(), 0); d3dContext_->IASetVertexBuffers(0, 1, Player2.getMesh()->getVertexBuffer(), &stride, &offset); d3dContext_->PSSetShaderResources(0, 1, Player2.getTexture()->getColorMap()); d3dContext_->UpdateSubresource(worldCB_, 0, 0, &Player2.getWorldMat(), 0, 0); d3dContext_->VSSetConstantBuffers(0, 1, &worldCB_); d3dContext_->Draw(Player2.getMesh()->getTotalVerts(), 0); } if ((gameState_ == RUN) && (displayFPS == true)) { /////////////////////////////////////////////TEXT////////////////////////////////////////////// TurnZBufferOff(); TurnOnAlphaBlending(); stride = sizeof(TextVertexPos); offset = 0; d3dContext_->IASetInputLayout(textInputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &textVertexBuffer_, &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textTextureMapVS_, 0, 0); d3dContext_->PSSetShader(textTextureMapPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &textColorMap_); d3dContext_->PSSetSamplers(0, 1, &textColorMapSampler_); char output[64]; //sprintf_s(output, "FPS:%d", fps_); //DrawString(output, -0.9f, 0.83f); //sprintf_s(output, "Frame Time:%.6f", frameTime_); //DrawString(output, -0.9f, 0.6f); sprintf_s(output, "Player1 HP:%.1f", Player1.GetHealth()); DrawString(output, -1.0f, 0.7f); sprintf_s(output, "Player2 HP:%.1f", Player2.GetHealth()); DrawString(output, 0.4f, 0.7f); TurnOffAlphaBlending(); TurnZBufferOn(); //////////////////////////////////////////////////////////////////////////////////////////////// } if (gameState_ == PAUSED) { /////////////////////////////////////////////TEXT////////////////////////////////////////////// TurnZBufferOff(); TurnOnAlphaBlending(); stride = sizeof(TextVertexPos); offset = 0; d3dContext_->IASetInputLayout(textInputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &textVertexBuffer_, &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textTextureMapVS_, 0, 0); d3dContext_->PSSetShader(textTextureMapPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &textColorMap_); d3dContext_->PSSetSamplers(0, 1, &textColorMapSampler_); DrawString("GAME PAUSED", -0.2f, 0.0f); if (pauseMenuSelection == RETURN) { DrawString("->Return to Game<-", -0.33f, -0.1f); } else { DrawString("Return to Game", -0.25f, -0.1f); } if (pauseMenuSelection == FPS) { if (displayFPS == true) { DrawString("->Display FPS: ON<-", -0.35f, -0.2f); } else { DrawString("->Display FPS:OFF<-", -0.35f, -0.2f); } } else { if (displayFPS == true) { DrawString("Display FPS: ON", -0.27f, -0.2f); } else { DrawString("Display FPS:OFF", -0.27f, -0.2f); } } if (pauseMenuSelection == PLAY_MOVIE) { DrawString("->Play the Movie<-", -0.33f, -0.3f); } else { DrawString("Play the Movie", -0.25f, -0.3f); } if (pauseMenuSelection == QUIT) { DrawString("->Quit the Game<-", -0.33f, -0.4f); } else { DrawString("Quit the Game", -0.25f, -0.4f); } TurnOffAlphaBlending(); TurnZBufferOn(); //////////////////////////////////////////////////////////////////////////////////////////////// } if (gameState_ == POST_MATCH) { TurnZBufferOff(); TurnOnAlphaBlending(); stride = sizeof(TextVertexPos); offset = 0; d3dContext_->IASetInputLayout(textInputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &textVertexBuffer_, &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textTextureMapVS_, 0, 0); d3dContext_->PSSetShader(textTextureMapPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &textColorMap_); d3dContext_->PSSetSamplers(0, 1, &textColorMapSampler_); DrawString("PRESS ENTER TO GET TO ", -0.5f, 0.8f); DrawString("THE MAIN MENU ", -0.3f, 0.7f); if (Player1.GetAlive()) { DrawString("CONGRATULATIONS PLAYER 1 ", -0.5f, 0.1f); DrawString("YOU WON THE MATCH!!!", -0.4f, 0.0f); } else if (Player2.GetAlive()) { DrawString("CONGRATULATIONS PLAYER 2 YOU WON THE MATCH!!!", -0.5f, 0.1f); DrawString("YOU WON THE MATCH!!!", -0.4f, 0); } TurnOffAlphaBlending(); TurnZBufferOn(); } if (gameState_ == THANKS) { TurnZBufferOff(); TurnOnAlphaBlending(); // Sending THE FONT to the SHADER stride = sizeof(TextVertexPos); offset = 0; d3dContext_->IASetInputLayout(textInputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &vertexBufferTerrain_, &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textTextureMapVS_, 0, 0); d3dContext_->PSSetShader(textTextureMapPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &terrainColorMap_); d3dContext_->PSSetSamplers(0, 1, &colorMapSampler_); d3dContext_->Draw(6, 0); // Sending THE TEXTURE to the SHADER MENU_TEXTURE_NAME = "GameObjects/Menu_Stuff/Selection.jpg"; HRESULT d3dResult = D3DX11CreateShaderResourceViewFromFile(d3dDevice_, MENU_TEXTURE_NAME, 0, 0, &terrainColorMap_, 0); stride = sizeof(TextVertexPos); offset = 0; d3dContext_->IASetInputLayout(textInputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &textVertexBuffer_, &stride, &offset); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(textTextureMapVS_, 0, 0); d3dContext_->PSSetShader(textTextureMapPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &textColorMap_); d3dContext_->PSSetSamplers(0, 1, &textColorMapSampler_); DrawString("PRESS ENTER TO GET TO ", -0.5f, 0.4f); DrawString("THE MAIN MENU ", -0.3f, 0.3f); DrawString("PROGRAMMERS: ", -0.3f, 0.1f); DrawString("Adrian Lee Aquino-Neary,", -0.5f, 0.0f); DrawString("Alessandro Cinque.", -0.4f, -0.1f); DrawString("ARTISTS: ", -0.2f, -0.3f); DrawString("Charles Flint,", -0.35f, -0.4f); DrawString("Valdas Biveinis,", -0.35f, -0.5f); DrawString("Matthew Williams,", -0.4f, -0.6f); DrawString("Antonina Robevska,", -0.4f, -0.7f); DrawString("Cameron Savvidou-Jones,", -0.5f, -0.8f); DrawString("Andreea Luciana Smedoiu.", -0.5f, -0.9f); TurnOffAlphaBlending(); TurnZBufferOn(); } swapChain_->Present(0, 0); }
29.105012
153
0.679311
kakol20
78aa655e0ad6618c65361a0f2bb57862690880f9
26,923
cpp
C++
src/game/shared/tf/tf_weapon_grapplinghook.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/shared/tf/tf_weapon_grapplinghook.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/shared/tf/tf_weapon_grapplinghook.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // TF Grappling Hook // //============================================================================= #include "cbase.h" #include "in_buttons.h" #include "tf_weapon_grapplinghook.h" // Client specific. #ifdef CLIENT_DLL #include "c_tf_player.h" #include "gc_clientsystem.h" #include "prediction.h" #include "soundenvelope.h" // Server specific. #else #include "tf_player.h" #include "entity_rune.h" #include "effect_dispatch_data.h" #include "tf_fx.h" #include "func_respawnroom.h" #endif //============================================================================= // // Grappling hook tables. // IMPLEMENT_NETWORKCLASS_ALIASED( TFGrapplingHook, DT_GrapplingHook ) BEGIN_NETWORK_TABLE( CTFGrapplingHook, DT_GrapplingHook ) #ifdef GAME_DLL SendPropEHandle( SENDINFO( m_hProjectile ) ), #else // GAME_DLL RecvPropEHandle( RECVINFO( m_hProjectile ) ), #endif // CLIENT_DLL END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CTFGrapplingHook ) END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS( tf_weapon_grapplinghook, CTFGrapplingHook ); PRECACHE_WEAPON_REGISTER( tf_weapon_grapplinghook ); // Server specific. #ifndef CLIENT_DLL BEGIN_DATADESC( CTFGrapplingHook ) END_DATADESC() #endif // CLIENT_DLL // This is basically a copy of s_acttableMeleeAllclass table except primary fire to use grappling hook specific acttable_t s_grapplinghook_normal_acttable[] = { { ACT_MP_STAND_IDLE, ACT_MP_STAND_MELEE_ALLCLASS, false }, { ACT_MP_CROUCH_IDLE, ACT_MP_CROUCH_MELEE_ALLCLASS, false }, { ACT_MP_RUN, ACT_MP_RUN_MELEE_ALLCLASS, false }, { ACT_MP_WALK, ACT_MP_WALK_MELEE_ALLCLASS, false }, { ACT_MP_AIRWALK, ACT_GRAPPLE_PULL_IDLE, false }, { ACT_MP_CROUCHWALK, ACT_MP_CROUCHWALK_MELEE_ALLCLASS, false }, { ACT_MP_JUMP, ACT_MP_JUMP_MELEE_ALLCLASS, false }, { ACT_MP_JUMP_START, ACT_MP_JUMP_START_MELEE_ALLCLASS, false }, { ACT_MP_JUMP_FLOAT, ACT_MP_JUMP_FLOAT_MELEE_ALLCLASS, false }, { ACT_MP_JUMP_LAND, ACT_MP_JUMP_LAND_MELEE_ALLCLASS, false }, { ACT_MP_SWIM, ACT_MP_SWIM_MELEE_ALLCLASS, false }, { ACT_MP_DOUBLEJUMP_CROUCH, ACT_MP_DOUBLEJUMP_CROUCH_MELEE, false }, { ACT_MP_ATTACK_STAND_PRIMARYFIRE, ACT_GRAPPLE_FIRE_START, false }, { ACT_MP_ATTACK_CROUCH_PRIMARYFIRE, ACT_GRAPPLE_FIRE_START, false }, { ACT_MP_ATTACK_SWIM_PRIMARYFIRE, ACT_GRAPPLE_FIRE_START, false }, { ACT_MP_ATTACK_AIRWALK_PRIMARYFIRE, ACT_GRAPPLE_FIRE_START, false }, { ACT_MP_ATTACK_STAND_SECONDARYFIRE, ACT_MP_ATTACK_STAND_MELEE_SECONDARY, false }, { ACT_MP_ATTACK_CROUCH_SECONDARYFIRE, ACT_MP_ATTACK_CROUCH_MELEE_SECONDARY,false }, { ACT_MP_ATTACK_SWIM_SECONDARYFIRE, ACT_MP_ATTACK_SWIM_MELEE_ALLCLASS, false }, { ACT_MP_ATTACK_AIRWALK_SECONDARYFIRE, ACT_MP_ATTACK_AIRWALK_MELEE_ALLCLASS, false }, { ACT_MP_GESTURE_FLINCH, ACT_MP_GESTURE_FLINCH_MELEE, false }, { ACT_MP_GRENADE1_DRAW, ACT_MP_MELEE_GRENADE1_DRAW, false }, { ACT_MP_GRENADE1_IDLE, ACT_MP_MELEE_GRENADE1_IDLE, false }, { ACT_MP_GRENADE1_ATTACK, ACT_MP_MELEE_GRENADE1_ATTACK, false }, { ACT_MP_GRENADE2_DRAW, ACT_MP_MELEE_GRENADE2_DRAW, false }, { ACT_MP_GRENADE2_IDLE, ACT_MP_MELEE_GRENADE2_IDLE, false }, { ACT_MP_GRENADE2_ATTACK, ACT_MP_MELEE_GRENADE2_ATTACK, false }, { ACT_MP_GESTURE_VC_HANDMOUTH, ACT_MP_GESTURE_VC_HANDMOUTH_MELEE, false }, { ACT_MP_GESTURE_VC_FINGERPOINT, ACT_MP_GESTURE_VC_FINGERPOINT_MELEE, false }, { ACT_MP_GESTURE_VC_FISTPUMP, ACT_MP_GESTURE_VC_FISTPUMP_MELEE, false }, { ACT_MP_GESTURE_VC_THUMBSUP, ACT_MP_GESTURE_VC_THUMBSUP_MELEE, false }, { ACT_MP_GESTURE_VC_NODYES, ACT_MP_GESTURE_VC_NODYES_MELEE, false }, { ACT_MP_GESTURE_VC_NODNO, ACT_MP_GESTURE_VC_NODNO_MELEE, false }, }; // This is basically a copy of s_acttableSecondary table except primary fire to use grappling hook specific acttable_t s_grapplinghook_engineer_acttable[] = { { ACT_MP_STAND_IDLE, ACT_MP_STAND_SECONDARY, false }, { ACT_MP_CROUCH_IDLE, ACT_MP_CROUCH_SECONDARY, false }, { ACT_MP_RUN, ACT_MP_RUN_SECONDARY, false }, { ACT_MP_WALK, ACT_MP_WALK_SECONDARY, false }, { ACT_MP_AIRWALK, ACT_MP_AIRWALK_SECONDARY, false }, { ACT_MP_CROUCHWALK, ACT_MP_CROUCHWALK_SECONDARY, false }, { ACT_MP_JUMP, ACT_MP_JUMP_SECONDARY, false }, { ACT_MP_JUMP_START, ACT_MP_JUMP_START_SECONDARY, false }, { ACT_MP_JUMP_FLOAT, ACT_MP_JUMP_FLOAT_SECONDARY, false }, { ACT_MP_JUMP_LAND, ACT_MP_JUMP_LAND_SECONDARY, false }, { ACT_MP_SWIM, ACT_MP_SWIM_SECONDARY, false }, { ACT_MP_DOUBLEJUMP_CROUCH, ACT_MP_DOUBLEJUMP_CROUCH_SECONDARY, false }, { ACT_MP_ATTACK_STAND_PRIMARYFIRE, ACT_GRAPPLE_FIRE_START, false }, { ACT_MP_ATTACK_CROUCH_PRIMARYFIRE, ACT_GRAPPLE_FIRE_START, false }, { ACT_MP_ATTACK_SWIM_PRIMARYFIRE, ACT_GRAPPLE_FIRE_START, false }, { ACT_MP_ATTACK_AIRWALK_PRIMARYFIRE, ACT_GRAPPLE_FIRE_START, false }, { ACT_MP_RELOAD_STAND, ACT_MP_RELOAD_STAND_SECONDARY, false }, { ACT_MP_RELOAD_STAND_LOOP, ACT_MP_RELOAD_STAND_SECONDARY_LOOP, false }, { ACT_MP_RELOAD_STAND_END, ACT_MP_RELOAD_STAND_SECONDARY_END, false }, { ACT_MP_RELOAD_CROUCH, ACT_MP_RELOAD_CROUCH_SECONDARY, false }, { ACT_MP_RELOAD_CROUCH_LOOP,ACT_MP_RELOAD_CROUCH_SECONDARY_LOOP,false }, { ACT_MP_RELOAD_CROUCH_END, ACT_MP_RELOAD_CROUCH_SECONDARY_END, false }, { ACT_MP_RELOAD_SWIM, ACT_MP_RELOAD_SWIM_SECONDARY, false }, { ACT_MP_RELOAD_SWIM_LOOP, ACT_MP_RELOAD_SWIM_SECONDARY_LOOP, false }, { ACT_MP_RELOAD_SWIM_END, ACT_MP_RELOAD_SWIM_SECONDARY_END, false }, { ACT_MP_RELOAD_AIRWALK, ACT_MP_RELOAD_AIRWALK_SECONDARY, false }, { ACT_MP_RELOAD_AIRWALK_LOOP, ACT_MP_RELOAD_AIRWALK_SECONDARY_LOOP, false }, { ACT_MP_RELOAD_AIRWALK_END,ACT_MP_RELOAD_AIRWALK_SECONDARY_END,false }, { ACT_MP_GESTURE_FLINCH, ACT_MP_GESTURE_FLINCH_SECONDARY, false }, { ACT_MP_GRENADE1_DRAW, ACT_MP_SECONDARY_GRENADE1_DRAW, false }, { ACT_MP_GRENADE1_IDLE, ACT_MP_SECONDARY_GRENADE1_IDLE, false }, { ACT_MP_GRENADE1_ATTACK, ACT_MP_SECONDARY_GRENADE1_ATTACK, false }, { ACT_MP_GRENADE2_DRAW, ACT_MP_SECONDARY_GRENADE2_DRAW, false }, { ACT_MP_GRENADE2_IDLE, ACT_MP_SECONDARY_GRENADE2_IDLE, false }, { ACT_MP_GRENADE2_ATTACK, ACT_MP_SECONDARY_GRENADE2_ATTACK, false }, { ACT_MP_ATTACK_STAND_GRENADE, ACT_MP_ATTACK_STAND_GRENADE, false }, { ACT_MP_ATTACK_CROUCH_GRENADE, ACT_MP_ATTACK_STAND_GRENADE, false }, { ACT_MP_ATTACK_SWIM_GRENADE, ACT_MP_ATTACK_STAND_GRENADE, false }, { ACT_MP_ATTACK_AIRWALK_GRENADE, ACT_MP_ATTACK_STAND_GRENADE, false }, { ACT_MP_GESTURE_VC_HANDMOUTH, ACT_MP_GESTURE_VC_HANDMOUTH_SECONDARY, false }, { ACT_MP_GESTURE_VC_FINGERPOINT, ACT_MP_GESTURE_VC_FINGERPOINT_SECONDARY, false }, { ACT_MP_GESTURE_VC_FISTPUMP, ACT_MP_GESTURE_VC_FISTPUMP_SECONDARY, false }, { ACT_MP_GESTURE_VC_THUMBSUP, ACT_MP_GESTURE_VC_THUMBSUP_SECONDARY, false }, { ACT_MP_GESTURE_VC_NODYES, ACT_MP_GESTURE_VC_NODYES_SECONDARY, false }, { ACT_MP_GESTURE_VC_NODNO, ACT_MP_GESTURE_VC_NODNO_SECONDARY, false }, }; acttable_t *CTFGrapplingHook::ActivityList( int &iActivityCount ) { CTFPlayer *pOwner = GetTFPlayerOwner(); if ( pOwner ) { if ( pOwner->IsPlayerClass( TF_CLASS_ENGINEER ) ) { iActivityCount = ARRAYSIZE( s_grapplinghook_engineer_acttable ); return s_grapplinghook_engineer_acttable; } else { iActivityCount = ARRAYSIZE( s_grapplinghook_normal_acttable ); return s_grapplinghook_normal_acttable; } } return BaseClass::ActivityList( iActivityCount ); } poseparamtable_t s_grapplinghook_normal_poseparamtable[] = { { "R_hand_grip", 14 }, { "R_arm", 2 }, }; poseparamtable_t s_grapplinghook_engineer_poseparamtable[] = { { "r_handposes_engineer", 1 }, }; poseparamtable_t *CTFGrapplingHook::PoseParamList( int &iPoseParamCount ) { CTFPlayer *pOwner = GetTFPlayerOwner(); if ( pOwner ) { if ( pOwner->IsPlayerClass( TF_CLASS_ENGINEER ) ) { iPoseParamCount = ARRAYSIZE( s_grapplinghook_engineer_poseparamtable ); return s_grapplinghook_engineer_poseparamtable; } else { iPoseParamCount = ARRAYSIZE( s_grapplinghook_normal_poseparamtable ); return s_grapplinghook_normal_poseparamtable; } } return BaseClass::PoseParamList( iPoseParamCount ); } ConVar tf_grapplinghook_projectile_speed( "tf_grapplinghook_projectile_speed", "1500", FCVAR_REPLICATED | FCVAR_CHEAT, "How fast does the grappliing hook projectile travel" ); ConVar tf_grapplinghook_max_distance( "tf_grapplinghook_max_distance", "2000", FCVAR_REPLICATED | FCVAR_CHEAT, "Valid distance for grappling hook to travel" ); ConVar tf_grapplinghook_fire_delay( "tf_grapplinghook_fire_delay", "0.5", FCVAR_REPLICATED | FCVAR_CHEAT ); float m_flNextSupernovaDenyWarning = 0.f; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFGrapplingHook::CTFGrapplingHook() { #ifdef GAME_DLL m_bReleasedAfterLatched = false; #endif // GAME_DLL #ifdef CLIENT_DLL m_pHookSound = NULL; m_bLatched = false; #endif // CLIENT_DLL } void CTFGrapplingHook::Precache() { BaseClass::Precache(); #ifdef GAME_DLL PrecacheScriptSound( "WeaponGrapplingHook.Shoot" ); #endif // GAME_DLL } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CBaseEntity *CTFGrapplingHook::FireProjectile( CTFPlayer *pPlayer ) { #ifdef GAME_DLL Assert( m_hProjectile == NULL ); m_hProjectile = BaseClass::FireProjectile( pPlayer ); return m_hProjectile; #else return BaseClass::FireProjectile( pPlayer ); #endif // GAME_DLL } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::ItemPostFrame( void ) { CTFPlayer *pOwner = GetTFPlayerOwner(); if (!pOwner) return; #ifdef CLIENT_DLL static bool bFired = false; #endif // CLIENT_DLL CBaseEntity *pHookTarget = pOwner->GetGrapplingHookTarget(); bool bJump = ( pOwner->m_nButtons & IN_JUMP ) > 0; bool bForceReleaseHook = pHookTarget != NULL && bJump; if ( !bForceReleaseHook && ( pOwner->m_nButtons & IN_ATTACK || pOwner->IsUsingActionSlot() ) ) { #ifdef CLIENT_DLL if ( !bFired ) { PrimaryAttack(); bFired = true; } #else PrimaryAttack(); #endif // CLIENT_DLL if ( pOwner->GetGrapplingHookTarget() ) { SendWeaponAnim( ACT_GRAPPLE_PULL_START ); } else if ( m_hProjectile ) { SendWeaponAnim( ACT_VM_PRIMARYATTACK ); } else { SendWeaponAnim( ACT_GRAPPLE_IDLE ); } } else { #ifdef CLIENT_DLL bFired = false; #endif // CLIENT_DLL OnHookReleased( bForceReleaseHook ); } if ( pOwner->GetViewModel(0) ) { pOwner->GetViewModel(0)->SetPlaybackRate( 1.f ); } if ( pOwner->GetViewModel(1) ) { pOwner->GetViewModel(1)->SetPlaybackRate( 1.f ); } BaseClass::ItemPostFrame(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFGrapplingHook::CanAttack( void ) { CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( pPlayer->m_Shared.IsFeignDeathReady() ) return false; return BaseClass::CanAttack(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::PrimaryAttack( void ) { CTFPlayer *pOwner = GetTFPlayerOwner(); #ifdef GAME_DLL // make sure to unlatch from the current target and remove the old projectile before we fire a new one if ( m_bReleasedAfterLatched ) { RemoveHookProjectile( true ); } #endif // GAME_DLL if ( m_hProjectile ) return; if ( m_flNextPrimaryAttack > gpGlobals->curtime ) return; if ( pOwner && pOwner->m_Shared.IsControlStunned() ) return; Vector vecSrc; QAngle angForward; Vector vecOffset( 23.5f, -8.0f, -3.0f ); // copied from CTFWeaponBaseGun::FireArrow GetProjectileFireSetup( pOwner, vecOffset, &vecSrc, &angForward, false ); Vector vecForward; AngleVectors( angForward, &vecForward ); // check if aiming at skybox trace_t tr; UTIL_TraceLine( vecSrc, vecSrc + tf_grapplinghook_max_distance.GetFloat() * vecForward, MASK_SOLID, pOwner, COLLISION_GROUP_DEBRIS, &tr ); if ( !tr.DidHit() || ( tr.fraction < 1.0 && tr.surface.flags & SURF_SKY ) ) { #ifdef CLIENT_DLL // play fail sound on client here if ( pOwner && prediction->IsFirstTimePredicted() ) { pOwner->EmitSound( "Player.DenyWeaponSelection" ); } #endif // CLIENT_DLL return; } BaseClass::PrimaryAttack(); m_flNextPrimaryAttack = gpGlobals->curtime + tf_grapplinghook_fire_delay.GetFloat(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFGrapplingHook::Deploy( void ) { #ifdef GAME_DLL RemoveHookProjectile( true ); m_bReleasedAfterLatched = IsLatchedToTargetPlayer(); #endif // GAME_DLL return BaseClass::Deploy(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFGrapplingHook::Holster( CBaseCombatWeapon *pSwitchingTo ) { #ifdef GAME_DLL RemoveHookProjectile(); m_bReleasedAfterLatched = IsLatchedToTargetPlayer(); #endif // GAME_DLL return BaseClass::Holster( pSwitchingTo ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::GetProjectileFireSetup( CTFPlayer *pPlayer, Vector vecOffset, Vector *vecSrc, QAngle *angForward, bool bHitTeammates /*= true*/, float flEndDist /*= 2000.f*/ ) { BaseClass::GetProjectileFireSetup( pPlayer, vecOffset, vecSrc, angForward, bHitTeammates, flEndDist ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CTFGrapplingHook::GetProjectileSpeed() { CTFPlayer *pOwner = GetTFPlayerOwner(); if ( pOwner && pOwner->m_Shared.GetCarryingRuneType() == RUNE_AGILITY ) { switch ( pOwner->GetPlayerClass()->GetClassIndex() ) { case TF_CLASS_SOLDIER: case TF_CLASS_HEAVYWEAPONS: return 2600.f; default: return 3000.f; } } return tf_grapplinghook_projectile_speed.GetFloat(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFGrapplingHook::SendWeaponAnim( int actBase ) { CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( !pPlayer ) return BaseClass::SendWeaponAnim( actBase ); if ( actBase == ACT_VM_DRAW ) { actBase = ACT_GRAPPLE_DRAW; } else if ( pPlayer->GetGrapplingHookTarget() ) { if ( GetActivity() != ACT_GRAPPLE_PULL_START && GetActivity() != ACT_GRAPPLE_PULL_IDLE ) { bool bResult = BaseClass::SendWeaponAnim( ACT_GRAPPLE_PULL_START ); //DevMsg("pull start %f\n", gpGlobals->curtime ); m_startPullingTimer.Start( SequenceDuration() ); return bResult; } else { if ( GetActivity() == ACT_GRAPPLE_PULL_IDLE ) return true; if ( GetActivity() == ACT_GRAPPLE_PULL_START && m_startPullingTimer.HasStarted() && !m_startPullingTimer.IsElapsed() ) return true; actBase = ACT_GRAPPLE_PULL_IDLE; //DevMsg("pull idle %f\n", gpGlobals->curtime ); m_startPullingTimer.Invalidate(); } } else if ( actBase == ACT_VM_PRIMARYATTACK ) { if ( GetActivity() != ACT_GRAPPLE_FIRE_START && GetActivity() != ACT_GRAPPLE_FIRE_IDLE ) { bool bResult = BaseClass::SendWeaponAnim( ACT_GRAPPLE_FIRE_START ); //DevMsg("fire start %f\n", gpGlobals->curtime ); m_startFiringTimer.Start( SequenceDuration() ); return bResult; } else { if ( GetActivity() == ACT_GRAPPLE_FIRE_IDLE ) return true; if ( GetActivity() == ACT_GRAPPLE_FIRE_START && m_startFiringTimer.HasStarted() && !m_startFiringTimer.IsElapsed() ) return true; actBase = ACT_GRAPPLE_FIRE_IDLE; //DevMsg("fire idle %f\n", gpGlobals->curtime ); m_startFiringTimer.Invalidate(); } } else { if ( GetActivity() == ACT_GRAPPLE_PULL_IDLE ) { actBase = ACT_GRAPPLE_PULL_END; //DevMsg("pull end %f\n", gpGlobals->curtime ); } else { if ( GetActivity() == ACT_GRAPPLE_IDLE ) return true; actBase = ACT_GRAPPLE_IDLE; //DevMsg("grapple idle %f\n", gpGlobals->curtime ); } } return BaseClass::SendWeaponAnim( actBase ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::PlayWeaponShootSound( void ) { #ifdef GAME_DLL EmitSound( "WeaponGrapplingHook.Shoot" ); #endif // GAME_DLL } #ifdef GAME_DLL //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::ActivateRune() { CTFPlayer *pOwner = GetTFPlayerOwner(); if ( pOwner && pOwner->m_Shared.IsRuneCharged() ) { RuneTypes_t type = pOwner->m_Shared.GetCarryingRuneType(); if ( type == RUNE_SUPERNOVA ) { // don't allow stealthed player to activate the power if ( pOwner->m_Shared.IsStealthed() ) return; int nEnemyTeam = GetEnemyTeam( pOwner->GetTeamNumber() ); // apply super nova effect to all enemies bool bHitAnyTarget = false; CUtlVector< CTFPlayer* > vecPlayers; CUtlVector< CTFPlayer* > vecVictims; CollectPlayers( &vecPlayers, nEnemyTeam, COLLECT_ONLY_LIVING_PLAYERS ); const float flEffectRadiusSqr = Sqr( 1500.f ); const float flMinPushForce = 200.f; const float flMaxPushForce = 500.f; const float flMinStunDuration = 2.f; const float flMaxStunDuration = 4.f; for ( int i = 0; i < vecPlayers.Count(); ++i ) { CTFPlayer *pOther = vecPlayers[i]; Vector toPlayer = pOther->WorldSpaceCenter() - pOwner->WorldSpaceCenter(); float flDistSqr = toPlayer.LengthSqr(); // Collect valid enemies if ( flDistSqr <= flEffectRadiusSqr && pOwner->IsLineOfSightClear( pOther, CBaseCombatCharacter::IGNORE_ACTORS ) && !PointInRespawnRoom( pOther, pOther->WorldSpaceCenter() ) ) { vecVictims.AddToTail( pOther ); } } // if there is more than one victim, the stun duration increases float flStunDuration = MIN( flMinStunDuration + ( ( vecVictims.Count() - 1 ) * 0.5 ), flMaxStunDuration ); for ( int i = 0; i < vecVictims.Count(); ++i ) { // force enemy to drop rune, stun, and push them CTFPlayer *pOther = vecVictims[i]; const char *pszEffect = pOwner->GetTeamNumber() == TF_TEAM_RED ? "powerup_supernova_strike_red" : "powerup_supernova_strike_blue"; CPVSFilter filter( WorldSpaceCenter() ); Vector vStart = pOwner->WorldSpaceCenter(); Vector vEnd = pOther->GetAbsOrigin() + Vector( 0, 0, 56 ); te_tf_particle_effects_control_point_t controlPoint = { PATTACH_ABSORIGIN, vEnd }; TE_TFParticleEffectComplex( filter, 0.f, pszEffect, vStart, QAngle( 0.f, 0.f, 0.f ), NULL, &controlPoint, pOther, PATTACH_CUSTOMORIGIN ); pOther->DropRune( false, pOwner->GetTeamNumber() ); pOther->DropFlag(); pOther->m_Shared.StunPlayer( flStunDuration, 1.f, TF_STUN_MOVEMENT | TF_STUN_CONTROLS, pOwner ); // send the player flying // make sure we push players up and away Vector toPlayer = pOther->WorldSpaceCenter() - pOwner->WorldSpaceCenter(); toPlayer.z = 0.0f; toPlayer.NormalizeInPlace(); toPlayer.z = 1.0f; // scale push force based on distance from the supernova origin float flDistSqr = toPlayer.LengthSqr(); float flPushForce = RemapValClamped( flDistSqr, 0.f, flEffectRadiusSqr, flMaxPushForce, flMinPushForce ); Vector vPush = flPushForce * toPlayer; pOther->ApplyAbsVelocityImpulse( vPush ); bHitAnyTarget = true; } // don't deploy with no target if ( bHitAnyTarget ) { // play effect const char *pszEffect = pOwner->GetTeamNumber() == TF_TEAM_RED ? "powerup_supernova_explode_red" : "powerup_supernova_explode_blue"; CEffectData data; data.m_nHitBox = GetParticleSystemIndex( pszEffect ); data.m_vOrigin = pOwner->GetAbsOrigin(); data.m_vAngles = vec3_angle; CPASFilter filter( data.m_vOrigin ); filter.SetIgnorePredictionCull( true ); te->DispatchEffect( filter, 0.0, data.m_vOrigin, "ParticleEffect", data ); pOwner->EmitSound( "Powerup.PickUpSupernovaActivate" ); // remove the power and reposition instantly pOwner->m_Shared.SetCarryingRuneType( RUNE_NONE ); CTFRune::RepositionRune( type, TEAM_ANY ); } else { if ( gpGlobals->curtime > m_flNextSupernovaDenyWarning ) { m_flNextSupernovaDenyWarning = gpGlobals->curtime + 0.5f; CSingleUserRecipientFilter singleFilter( pOwner ); EmitSound( singleFilter, pOwner->entindex(), "Player.UseDeny" ); ClientPrint( pOwner, HUD_PRINTCENTER, "#TF_Powerup_Supernova_Deny" ); } } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::RemoveHookProjectile( bool bForce /*= false*/ ) { if ( !bForce && IsLatchedToTargetPlayer() ) { // don't remove the projectile until we unlatched from the target (by hooking again) return; } if ( m_hProjectile ) { UTIL_Remove( m_hProjectile ); m_hProjectile = NULL; } } bool CTFGrapplingHook::IsLatchedToTargetPlayer() const { CTFPlayer *pOwner = GetTFPlayerOwner(); return pOwner && pOwner->GetGrapplingHookTarget() && pOwner->GetGrapplingHookTarget()->IsPlayer(); } #endif // GAME_DLL void CTFGrapplingHook::OnHookReleased( bool bForce ) { #ifdef GAME_DLL RemoveHookProjectile( bForce ); m_bReleasedAfterLatched = IsLatchedToTargetPlayer(); #endif // GAME_DLL if ( GetActivity() != ACT_GRAPPLE_DRAW && GetActivity() != ACT_GRAPPLE_IDLE && GetActivity() != ACT_GRAPPLE_PULL_END ) SendWeaponAnim( ACT_GRAPPLE_PULL_END ); if ( bForce ) m_flNextPrimaryAttack = gpGlobals->curtime + tf_grapplinghook_fire_delay.GetFloat(); } #ifdef CLIENT_DLL //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::UpdateOnRemove() { StopHookSound(); BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::OnDataChanged( DataUpdateType_t type ) { BaseClass::OnDataChanged( type ); UpdateHookSound(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::StartHookSound() { StopHookSound(); CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController(); CLocalPlayerFilter filter; m_pHookSound = controller.SoundCreate( filter, entindex(), "WeaponGrapplingHook.ReelStart" ); controller.Play( m_pHookSound, 1.0, 100 ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::StopHookSound() { if ( m_pHookSound ) { CSoundEnvelopeController::GetController().SoundDestroy( m_pHookSound ); m_pHookSound = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFGrapplingHook::UpdateHookSound() { CTFPlayer *pOwner = GetTFPlayerOwner(); if ( pOwner ) { bool bLatched = pOwner->GetGrapplingHookTarget() != NULL && m_hProjectile != NULL; if ( m_bLatched != bLatched ) { if ( !m_bLatched ) { StartHookSound(); } else { StopHookSound(); CLocalPlayerFilter filter; EmitSound( filter, entindex(), "WeaponGrapplingHook.ReelStop" ); } m_bLatched = bLatched; } } } //----------------------------------------------------------------------------- // CEquipGrapplingHookNotification //----------------------------------------------------------------------------- void CEquipGrapplingHookNotification::Accept() { m_bHasTriggered = true; CPlayerInventory *pLocalInv = TFInventoryManager()->GetLocalInventory(); if ( !pLocalInv ) { MarkForDeletion(); return; } C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( !pLocalPlayer ) { MarkForDeletion(); return; } // try to equip non-stock-grapplinghook first /*static CSchemaItemDefHandle pItemDef_GrapplingHook( "TF_WEAPON_GRAPPLINGHOOK" ); Assert( pItemDef_GrapplingHook ); CEconItemView *pGrapplingHook = NULL; if ( pItemDef_GrapplingHook ) { for ( int i = 0 ; i < pLocalInv->GetItemCount() ; ++i ) { CEconItemView *pItem = pLocalInv->GetItem( i ); Assert( pItem ); if ( pItem->GetItemDefinition() == pItemDef_GrapplingHook ) { pGrapplingHook = pItem; break; } } }*/ // Default item becomes a grappling hook in this mode itemid_t iItemId = INVALID_ITEM_ID; /*if ( pGrapplingHook ) { iItemId = pGrapplingHook->GetItemID(); }*/ if ( iItemId == INVALID_ITEM_ID ) { iItemId = 0; static CSchemaItemDefHandle pItemDef_Grapple( "TF_WEAPON_GRAPPLINGHOOK" ); CEconItemView *pDefaultGrapple = TFInventoryManager()->GetBaseItemForClass( pLocalPlayer->GetPlayerClass()->GetClassIndex(), LOADOUT_POSITION_ACTION ); if ( pDefaultGrapple ) { if ( pDefaultGrapple->GetItemDefinition() == pItemDef_Grapple ) { iItemId = pDefaultGrapple->GetItemID(); } } } TFInventoryManager()->EquipItemInLoadout( pLocalPlayer->GetPlayerClass()->GetClassIndex(), LOADOUT_POSITION_ACTION, iItemId ); // Tell the GC to tell server that we should respawn if we're in a respawn room GCSDK::CGCMsg< GCSDK::MsgGCEmpty_t > msg( k_EMsgGCRespawnPostLoadoutChange ); GCClientSystem()->BSendMessage( msg ); MarkForDeletion(); } //=========================================================================================== void CEquipGrapplingHookNotification::UpdateTick() { C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( pLocalPlayer ) { CTFGrapplingHook *pGrapplingHook = dynamic_cast<CTFGrapplingHook*>( pLocalPlayer->Weapon_OwnsThisID( TF_WEAPON_GRAPPLINGHOOK ) ); if ( pGrapplingHook ) { MarkForDeletion(); } } } #endif // CLIENT_DLL
31.342258
182
0.652045
cstom4994
78ad13da77add9623166e1403465e0b18366af01
2,709
hpp
C++
include/algorithms/public/Standardization.hpp
jamesb93/flucoma-core
3e964dd569f6fff15bd5249a705dc0da8f7b2ad8
[ "BSD-3-Clause" ]
null
null
null
include/algorithms/public/Standardization.hpp
jamesb93/flucoma-core
3e964dd569f6fff15bd5249a705dc0da8f7b2ad8
[ "BSD-3-Clause" ]
null
null
null
include/algorithms/public/Standardization.hpp
jamesb93/flucoma-core
3e964dd569f6fff15bd5249a705dc0da8f7b2ad8
[ "BSD-3-Clause" ]
null
null
null
/* Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/) Copyright 2017-2019 University of Huddersfield. Licensed under the BSD-3 License. See license.md file in the project root for full license information. This project has received funding from the European Research Council (ERC) under the European Union’s Horizon 2020 research and innovation programme (grant agreement No 725899). */ #pragma once #include "../util/ScalerUtils.hpp" #include "../util/FluidEigenMappings.hpp" #include "../../data/TensorTypes.hpp" #include <Eigen/Core> #include <cassert> #include <cmath> namespace fluid { namespace algorithm { class Standardization { public: using ArrayXd = Eigen::ArrayXd; using ArrayXXd = Eigen::ArrayXXd; void init(RealMatrixView in) { using namespace Eigen; using namespace _impl; ArrayXXd input = asEigen<Array>(in); mMean = input.colwise().mean(); mStd = ((input.rowwise() - mMean.transpose()).square().colwise().mean()) .sqrt(); handleZerosInScale(mStd); mInitialized = true; } void init(const RealVectorView mean, const RealVectorView std) { using namespace Eigen; using namespace _impl; mMean = asEigen<Array>(mean); mStd = asEigen<Array>(std); handleZerosInScale(mStd); mInitialized = true; } void processFrame(const RealVectorView in, RealVectorView out, bool inverse = false) const { using namespace Eigen; using namespace _impl; ArrayXd input = asEigen<Array>(in); ArrayXd result; if (!inverse) { result = (input - mMean) / mStd; } else { result = (input * mStd) + mMean; } out <<= asFluid(result); } void process(const RealMatrixView in, RealMatrixView out, bool inverse = false) const { using namespace Eigen; using namespace _impl; ArrayXXd input = asEigen<Array>(in); ArrayXXd result; if (!inverse) { result = (input.rowwise() - mMean.transpose()); result = result.rowwise() / mStd.transpose(); } else { result = (input.rowwise() * mStd.transpose()); result = (result.rowwise() + mMean.transpose()); } out <<= asFluid(result); } bool initialized() const { return mInitialized; } void getMean(RealVectorView out) const { out <<= _impl::asFluid(mMean); } void getStd(RealVectorView out) const { out <<= _impl::asFluid(mStd); } index dims() const { return mMean.size(); } index size() const { return 1; } void clear() { mMean.setZero(); mStd.setZero(); mInitialized = false; } ArrayXd mMean; ArrayXd mStd; bool mInitialized{false}; }; }// namespace algorithm }// namespace fluid
24.853211
76
0.657807
jamesb93
78aedd5065fd9df1ab0a5d0b1f0250c098aa5ded
13,441
cpp
C++
nampower/main.cpp
hellokvn/nampower
5b75ebdbb8430a556211e0a8967338d914055359
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
nampower/main.cpp
hellokvn/nampower
5b75ebdbb8430a556211e0a8967338d914055359
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
nampower/main.cpp
hellokvn/nampower
5b75ebdbb8430a556211e0a8967338d914055359
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* Copyright (c) 2017-2018, namreeb (legal@namreeb.org) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ // 1.2 #include <vector> #include <Windows.h> #include <boost/filesystem.hpp> #include "misc.hpp" #include "offsets.hpp" #include "game.hpp" #include <hadesmem/process.hpp> #include <hadesmem/patcher.hpp> #include <Windows.h> #include <cstdint> #include <memory> #include <atomic> #ifdef _DEBUG #include <sstream> #endif BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID); namespace { static DWORD gCooldown; #ifdef _DEBUG static DWORD gLastCast; #endif // true when we are simulating a server-based spell cancel to reset the cast bar static std::atomic<bool> gCancelling; // true when the current spell cancellation requires that we notify the server // (a client side cancellation of a non-instant cast spell) static std::atomic<bool> gNotifyServer; // true when we are in the middle of an attempt to cast a spell static std::atomic<bool> gCasting; static game::SpellFailedReason gCancelReason; using CastSpellT = bool(__fastcall *)(void *, int, void *, std::uint64_t); using SendCastT = void(__fastcall *)(game::SpellCast *); using CancelSpellT = int(__fastcall *)(bool, bool, game::SpellFailedReason); using SignalEventT = void(__fastcall *)(game::Events); using PacketHandlerT = int(__stdcall *)(int, game::CDataStore *); std::unique_ptr<hadesmem::PatchDetour<CastSpellT>> gCastDetour; std::unique_ptr<hadesmem::PatchDetour<SendCastT>> gSendCastDetour; std::unique_ptr<hadesmem::PatchDetour<CancelSpellT>> gCancelSpellDetour; std::unique_ptr<hadesmem::PatchDetour<SignalEventT>> gSignalEventDetour; std::unique_ptr<hadesmem::PatchDetour<PacketHandlerT>> gSpellDelayedDetour; std::unique_ptr<hadesmem::PatchRaw> gCastbarPatch; void BeginCast(DWORD currentTime, std::uint32_t castTime, int spellId) { gCooldown = castTime ? currentTime + castTime : 0; #ifdef _DEBUG // don't bother building the string if nobody will see it if (::IsDebuggerPresent()) { std::stringstream str; str << "Casting " << game::GetSpellName(spellId) << " with cast time " << castTime << " at time " << currentTime; if (gLastCast) str << " elapsed: " << (currentTime - gLastCast); ::OutputDebugStringA(str.str().c_str()); } gLastCast = currentTime; #endif if (castTime) { void(*signalEvent)(std::uint32_t, const char *, ...) = reinterpret_cast<decltype(signalEvent)>(Offsets::SignalEventParam); signalEvent(game::Events::SPELLCAST_START, "%s%d", game::GetSpellName(spellId), castTime); } } bool CastSpellHook(hadesmem::PatchDetourBase *detour, void *unit, int spellId, void *item, std::uint64_t guid) { auto const currentTime = ::GetTickCount(); // is there a cooldown? if (gCooldown) { // is it still active? if (gCooldown > currentTime) return false; gCooldown = 0; } gCasting = true; auto const spell = game::GetSpellInfo(spellId); auto const castSpell = detour->GetTrampolineT<CastSpellT>(); auto ret = castSpell(unit, spellId, item, guid); auto const castTime = game::GetCastTime(unit, spellId); // if this is a trade skill or item enchant, do nothing further if (spell->Effect[0] == game::SpellEffects::SPELL_EFFECT_TRADE_SKILL || spell->Effect[0] == game::SpellEffects::SPELL_EFFECT_ENCHANT_ITEM || spell->Effect[0] == game::SpellEffects::SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) return ret; // haven't gotten spell result from the previous cast yet, probably due to latency. // simulate a cancel to clear the cast bar but only when there should be a cast time if (!ret && castTime) { gCancelling = true; auto const cancelSpell = reinterpret_cast<CancelSpellT>(Offsets::CancelSpell); cancelSpell(false, false, game::SpellFailedReason::SPELL_FAILED_ERROR); gCancelling = false; // try again... ret = castSpell(unit, spellId, item, guid); } auto const cursorMode = *reinterpret_cast<int *>(Offsets::CursorMode); if (ret && !!spell && !(spell->Attributes & game::SPELL_ATTR_RANGED) && cursorMode != 2) BeginCast(currentTime, castTime, spellId); gCasting = false; return ret; } int CancelSpellHook(hadesmem::PatchDetourBase *detour, bool failed, bool notifyServer, game::SpellFailedReason reason) { gNotifyServer = notifyServer; gCancelReason = reason; #ifdef _DEBUG if (::IsDebuggerPresent()) { std::stringstream str; str << "Cancel spell. " << " failed: " << failed << " notifyServer: " << notifyServer << " reason: " << reason << " cancelling: " << gCancelling << "\n" << std::endl; ::OutputDebugStringA(str.str().c_str()); } #endif auto const cancelSpell = detour->GetTrampolineT<CancelSpellT>(); auto const ret = cancelSpell(failed, notifyServer, reason); return ret; } void SendCastHook(hadesmem::PatchDetourBase *detour, game::SpellCast *cast) { auto const cursorMode = *reinterpret_cast<int *>(Offsets::CursorMode); // if we were waiting for a target, it means there is no cast bar yet. make one \o/ if (cursorMode == 2) { auto const unit = game::GetObjectPtr(cast->caster); auto const castTime = game::GetCastTime(unit, cast->spellId); BeginCast(::GetTickCount(), castTime, cast->spellId); } auto const sendCast = detour->GetTrampolineT<SendCastT>(); sendCast(cast); } void SignalEventHook(hadesmem::PatchDetourBase *detour, game::Events eventId) { auto const currentTime = ::GetTickCount(); if (!gCasting && (eventId == game::Events::SPELLCAST_STOP || eventId == game::Events::SPELLCAST_FAILED)) { #ifdef _DEBUG if (::IsDebuggerPresent()) { std::stringstream str; str << "Event " << (eventId == game::Events::SPELLCAST_STOP ? "SPELLCAST_STOP" : "SPELLCAST_FAILED") << " at time " << currentTime << " gLastCast = " << gLastCast << " gCooldown = " << gCooldown << std::endl; ::OutputDebugStringA(str.str().c_str()); } #endif } // SPELLCAST_STOP means the cast started and then stopped. it may or may not have completed. // this can happen by one of two conditions: // 1) it is caused by us in CastSpellHook() because the player is spamming // casts and we have not yet received result of the last one (or by the // client through some other means) // 2) the player is casting slowly enough (or possibly not at all) such that // the result of the last cast arrives before our next attempt to cast // for scenario #1 we want to allow the event as it will reset the cast bar // on the last attempt. // for scenario #2, we have already reset the cast bar, and we do not want to // do it again because we may already be casting the next spell. if (eventId == game::Events::SPELLCAST_STOP) { // if this is from the client, we don't care about anything else. immediately stop // the cast bar and reset our internal cooldown. if (gNotifyServer) gCooldown = 0; // if this is from the server but it is happening too early, it is for one of two reasons. // 1) it is for the last cast, in which case we can ignore it // 2) it is for our current cast and the server decided to cast sooner than we expected // this can happen from mage 8/8 t2 proc or presence of mind else if (!gCasting && !gCancelling && currentTime <= gCooldown) return; } // SPELLCAST_FAILED means the attempt was rejected by either the client or the server, // depending on the value of gNotifyServer. if it was rejected by the server, this // could mean that our latency has decreased since the previous cast. when that happens // the server perceives too little time as having passed to allow another cast. i dont // think there is anything we can do about this except to honor the servers request to // abort the cast. reset our cooldown and allow else if (eventId == game::Events::SPELLCAST_FAILED && !gNotifyServer) gCooldown = 0; auto const signalEvent = detour->GetTrampolineT<SignalEventT>(); signalEvent(eventId); } int SpellDelayedHook(hadesmem::PatchDetourBase *detour, int opCode, game::CDataStore *packet) { auto const spellDelayed = detour->GetTrampolineT<PacketHandlerT>(); auto const rpos = packet->m_read; auto const guid = packet->Get<std::uint64_t>(); auto const delay = packet->Get<std::uint32_t>(); packet->m_read = rpos; auto const activePlayer = game::ClntObjMgrGetActivePlayer(); if (guid == activePlayer) { auto const currentTime = ::GetTickCount(); // if we are casting a spell and it was delayed, update our own state so we do not allow a cast too soon if (currentTime < gCooldown) { gCooldown += delay; #ifdef _DEBUG gLastCast += delay; #endif } } return spellDelayed(opCode, packet); } } extern "C" __declspec(dllexport) DWORD Load() { gCooldown = 0; #ifdef _DEBUG gLastCast = 0; #endif gCancelling = false; gNotifyServer = false; gCasting = false; const hadesmem::Process process(::GetCurrentProcessId()); // 1.2 auto const luaLoadScriptsOrig = hadesmem::detail::AliasCast<LuaLoadScriptsT>(Offsets::FrameScript__LoadWorldScripts); auto registerHook = new hadesmem::PatchDetour<LuaLoadScriptsT>(process, luaLoadScriptsOrig, &LuaLoadScripts); registerHook->Apply(); LuaToNumber = hadesmem::detail::AliasCast<decltype(LuaToNumber)>(Offsets::Lua__ToNumber); // are we in a game? unsigned __int64(__stdcall *getPlayerGuid)() = (decltype(getPlayerGuid))(Offsets::GetPlayerGuid); if ((*getPlayerGuid)()) RegisterLuaFunctions(); // 1.2 end // activate spellbar and our own internal cooldown on a successful cast attempt (result from server not available yet) auto const castSpellOrig = hadesmem::detail::AliasCast<CastSpellT>(Offsets::CastSpell); gCastDetour = std::make_unique<hadesmem::PatchDetour<CastSpellT>>(process, castSpellOrig, &CastSpellHook); gCastDetour->Apply(); // monitor for client-based spell interruptions to stop the castbar auto const cancelSpellOrig = hadesmem::detail::AliasCast<CancelSpellT>(Offsets::CancelSpell); gCancelSpellDetour = std::make_unique<hadesmem::PatchDetour<CancelSpellT>>(process, cancelSpellOrig, &CancelSpellHook); gCancelSpellDetour->Apply(); // monitor for spell cast triggered after target (terrain, item, etc.) is selected auto const sendCastOrig = hadesmem::detail::AliasCast<SendCastT>(Offsets::SendCast); gSendCastDetour = std::make_unique<hadesmem::PatchDetour<SendCastT>>(process, sendCastOrig, &SendCastHook); gSendCastDetour->Apply(); // this hook will alter cast bar behavior based on events from the game auto const signalEventOrig = hadesmem::detail::AliasCast<SignalEventT>(Offsets::SignalEvent); gSignalEventDetour = std::make_unique<hadesmem::PatchDetour<SignalEventT>>(process, signalEventOrig, &SignalEventHook); gSignalEventDetour->Apply(); // watch for pushback notifications from the server auto const spellDelayedOrig = hadesmem::detail::AliasCast<PacketHandlerT>(Offsets::SpellDelayed); gSpellDelayedDetour = std::make_unique<hadesmem::PatchDetour<PacketHandlerT>>(process, spellDelayedOrig, &SpellDelayedHook); gSpellDelayedDetour->Apply(); // prevent spellbar re-activation upon successful cast notification from server const std::vector<std::uint8_t> patch(5, 0x90); gCastbarPatch = std::make_unique<hadesmem::PatchRaw>(process, reinterpret_cast<void *>(Offsets::CreateCastbar), patch); gCastbarPatch->Apply(); return EXIT_SUCCESS; }
38.076487
130
0.699055
hellokvn
78aeefb249308d5b46b82e2962ceb1c7d561065d
723
cpp
C++
Resources/TextureLoaderSOIL.cpp
rexapex/OSE-V2-STD-Modules
2d504e1293e22b4d1eb124656b730980c18b18f4
[ "Zlib" ]
null
null
null
Resources/TextureLoaderSOIL.cpp
rexapex/OSE-V2-STD-Modules
2d504e1293e22b4d1eb124656b730980c18b18f4
[ "Zlib" ]
null
null
null
Resources/TextureLoaderSOIL.cpp
rexapex/OSE-V2-STD-Modules
2d504e1293e22b4d1eb124656b730980c18b18f4
[ "Zlib" ]
null
null
null
#include "stdafx.h" #include "TextureLoaderSOIL.h" namespace ose::resources { TextureLoaderSOIL::TextureLoaderSOIL(const std::string & project_path) : TextureLoader(project_path) {} TextureLoaderSOIL::~TextureLoaderSOIL() {} // loads the texture and sets the values of img_data, width and height // path is absolute and is guaranteed to exist void TextureLoaderSOIL::LoadTexture(const std::string & path, IMGDATA * img_data, int32_t * width, int32_t * height) { *img_data = SOIL_load_image(path.c_str(), width, height, 0, SOIL_LOAD_AUTO); } // free resources used by the texture (img_data) void TextureLoaderSOIL::FreeTexture(IMGDATA img_data) { SOIL_free_image_data(img_data); } }
31.434783
118
0.733057
rexapex
78aeffc51d6ff9d838b0d38adbbe0ef5fb3bc74f
3,188
cpp
C++
more-examples/02-spectrum/src/02-spectrum.cpp
rickkas7/ADCDMAGen3_RK
64a52a8b485f3bec93ebedd5b1337594cc0443d8
[ "MIT" ]
1
2019-11-22T06:57:24.000Z
2019-11-22T06:57:24.000Z
more-examples/02-spectrum/src/02-spectrum.cpp
rickkas7/ADCDMAGen3_RK
64a52a8b485f3bec93ebedd5b1337594cc0443d8
[ "MIT" ]
null
null
null
more-examples/02-spectrum/src/02-spectrum.cpp
rickkas7/ADCDMAGen3_RK
64a52a8b485f3bec93ebedd5b1337594cc0443d8
[ "MIT" ]
2
2019-12-30T07:19:47.000Z
2020-09-03T17:59:48.000Z
#include "Particle.h" #include "ADCDMAGen3_RK.h" #include "FftComplex.h" // https://www.nayuki.io/page/free-small-fft-in-multiple-languages #include <cmath> // std::abs #include "Adafruit_SSD1306_RK.h" // The Adafruit library defines abs as a macro. Undo that so std::abs works right. #undef abs SYSTEM_THREAD(ENABLED); SerialLogHandler logHandler; const unsigned long UPDATE_PERIOD_MS = 20; const size_t SAMPLE_FREQ = 32000; // Hz const size_t SAMPLES_IN_BUFFER = 512; static nrf_saadc_value_t buffer[SAMPLES_IN_BUFFER * 2]; static nrf_saadc_value_t *bufferReady = 0; std::vector< std::complex<double> > complexSamples; const unsigned long UPDATE_PERIOD = 20; unsigned long lastUpdate; ADCDMAGen3 adc; // SSD1306 SPI Display Settings #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels #define OLED_DC A4 #define OLED_CS A3 #define OLED_RESET A5 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &SPI, OLED_DC, OLED_RESET, OLED_CS); void setup() { // Optional, just for testing so I can see the logs below // waitFor(Serial.isConnected, 10000); // Pre-allocate an array of complex<double> samples in a vector. We reuse this for FFT. complexSamples.resize(SAMPLES_IN_BUFFER); adc.withBufferCallback([](nrf_saadc_value_t *buf, size_t size) { // This gets executed after each sample buffer has been read. // Note: This is executed in interrupt context, so beware of what you do here! // We just remember the buffer and handle it from loop bufferReady = buf; }); ret_code_t err = adc .withSampleFreqHz(SAMPLE_FREQ) .withDoubleBufferSplit(SAMPLES_IN_BUFFER * 2, buffer) .withResolution(NRF_SAADC_RESOLUTION_12BIT) .withAcqTime(NRF_SAADC_ACQTIME_3US) .withSamplePin(A0) .init(); Log.info("adc.init %lu", err); adc.start(); display.begin(SSD1306_SWITCHCAPVCC); display.clearDisplay(); display.display(); } void loop() { if (millis() - lastUpdate >= UPDATE_PERIOD) { lastUpdate = millis(); if (bufferReady) { int16_t *src = (int16_t *)bufferReady; bufferReady = 0; for(size_t ii = 0; ii < SAMPLES_IN_BUFFER; ii++) { // We are using 12-bit sampling so values are 0-4095 (inclusive). // Create real part from -1.0 to +1.0 instead complexSamples[ii] = (double)(src[ii] - 2048) / 2048; } // Run the FFT on the samples Fft::transformRadix2(complexSamples); display.clearDisplay(); // Results in the frequency domain are from index 0 to index (SAMPLES_IN_BUFFER / 2) // where index 0 is the DC component and the maximum indexex is the highest // frequency, which is 1/2 the sampling frequency of 8kHz // (The top half of the buffer is the negative frequencies, which we ignore.) // Start at 1 to ignore the DC component for(size_t ii = 1; ii < 128; ii++) { // int freq = ii * SAMPLE_FREQ / SAMPLES_IN_BUFFER; double value = std::abs(complexSamples[ii].real()); int height = (int)value * 64 / 5; if (height > 64) { height = 64; } if (height > 1) { display.drawLine(ii, 64, ii, 64 - height, 1); } } display.display(); } } }
23.791045
90
0.69793
rickkas7
78b055cb897fa2c35449af16c55f21c5a451e63d
747
hpp
C++
library/ATF/_BSP_MAT_GROUP.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/_BSP_MAT_GROUP.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/_BSP_MAT_GROUP.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE #pragma pack(push, 2) struct _BSP_MAT_GROUP { unsigned __int16 Type; unsigned __int16 TriNum; __int16 MtlId; __int16 LgtId; float BBMin[3]; float BBMax[3]; float Origin[3]; unsigned int VBMinIndex; unsigned int IBMinIndex; unsigned int VertexBufferId; unsigned int VCnt; unsigned int CFaceStartVId; void *MultiSourceUV; void *MultiSourceST; unsigned __int16 ObjectId; float CoronaAlpha; }; #pragma pack(pop) END_ATF_NAMESPACE
24.9
108
0.637216
lemkova
78b58c7afb2eabca7c46a2a2ac8bcb8026cdab5d
2,656
cpp
C++
Circuit5A/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
Circuit5A/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
Circuit5A/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
#include <Arduino.h> //PIN VARIABLES //the motor will be controlled by the motor A pins on the motor driver const int AIN1 = 13; //control pin 1 on the motor driver for the right motor const int AIN2 = 12; //control pin 2 on the motor driver for the right motor const int PWMA = 11; //speed control pin on the motor driver for the right motor int switchPin = 7; //switch to turn the robot on and off //VARIABLES int motorSpeed = 0; //starting speed for the motor int val = 0; void spinMotor(int); void setup() { pinMode(switchPin, INPUT_PULLUP); //set this as a pullup to sense whether the switch is flipped //set the motor control pins as outputs pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT); pinMode(PWMA, OUTPUT); Serial.begin(9600); //begin serial communication with the computer Serial.println("Enter motor speed (-255 to 255)... "); //Prompt to get input in the serial monitor. } void loop() { if (Serial.available() > 0) { //if the user has entered something in the serial monitor val = Serial.parseInt(); //set the motor speed equal to the number in the serial message if(val == 0) return; motorSpeed = val; Serial.print("Motor Speed: "); //print the speed that the motor is set to run at Serial.println(motorSpeed); } if (digitalRead(7) == LOW) { //if the switch is on... spinMotor(motorSpeed); } else { //if the switch is off... spinMotor(0); //turn the motor off } } /********************************************************************************/ void spinMotor(int motorSpeed) //function for driving the right motor { if (motorSpeed > 0) //if the motor should drive forward (positive speed) { digitalWrite(AIN1, HIGH); //set pin 1 to high digitalWrite(AIN2, LOW); //set pin 2 to low } else if (motorSpeed < 0) //if the motor should drive backward (negative speed) { digitalWrite(AIN1, LOW); //set pin 1 to low digitalWrite(AIN2, HIGH); //set pin 2 to high } else //if the motor should stop { digitalWrite(AIN1, LOW); //set pin 1 to low digitalWrite(AIN2, LOW); //set pin 2 to low } analogWrite(PWMA, abs(motorSpeed)); //now that the motor direction is set, drive it at the entered speed }
39.058824
122
0.551581
padlewski
78b79ac1b055f49968313e4c5f68b596866664c0
11,605
cpp
C++
Wizard/datainspectiondialog.cpp
johnsonjonaris/CoNECt
ca0e0f5672026fcb78431a6fc29f4ccd69ad0b74
[ "Apache-2.0" ]
null
null
null
Wizard/datainspectiondialog.cpp
johnsonjonaris/CoNECt
ca0e0f5672026fcb78431a6fc29f4ccd69ad0b74
[ "Apache-2.0" ]
null
null
null
Wizard/datainspectiondialog.cpp
johnsonjonaris/CoNECt
ca0e0f5672026fcb78431a6fc29f4ccd69ad0b74
[ "Apache-2.0" ]
null
null
null
#include "datainspectiondialog.h" DataInspectionDialog::DataInspectionDialog(QWidget *parent) : QDialog(parent) { setupUi(this); CoronalLabel->installEventFilter(this); SagittalLabel->installEventFilter(this); AxialLabel->installEventFilter(this); // connect signals and slots connect(ImagesBox,SIGNAL(activated(int)),this,SLOT(onImageBoxChange(int))); connect(PreviousButton,SIGNAL(clicked()),this,SLOT(onPreviousButtonClick())); connect(NextButton,SIGNAL(clicked()),this,SLOT(onNextButtonClick())); connect(SubjectsTree,SIGNAL(itemPressed(QTreeWidgetItem*,int)), this,SLOT(onTreeItemPressed(QTreeWidgetItem*,int))); connect(ButtonBox, SIGNAL(accepted()), this, SLOT(checkBeforeExit())); } void DataInspectionDialog::init(bool isInd,const QString &src, const QString &bn, ImageFileType ft,int nImgs) { // note that fileType should never be allowed to be RAW individual = isInd; path = src; baseName = bn; fileType = ft; expectedNImages = nImgs; PreviousButton->setEnabled(false); if (individual) { // if individual, disable all control buttons, no need for tree NextButton->setEnabled(false); Subject_ID_Text->setEnabled(false); SubjectsTree->setEnabled(false); } else { QStringList subjects = QDir(path).entryList(QDir::NoDotAndDotDot | QDir::AllDirs); nSubjects = subjects.size(); NextButton->setEnabled(nSubjects > 1); // identify first subject Subject_ID_Text->setText("Subject ID: "+subjects.first()); SubjectsTree->clear(); // prepare tree for (int i =0; i<subjects.size();i++) { QTreeWidgetItem *item = new QTreeWidgetItem(); item->setData(0,Qt::CheckStateRole,true); item->setText(1,subjects.at(i)); item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable|Qt::ItemIsUserCheckable); SubjectsTree->insertTopLevelItem(i,item); } SubjectsTree->setColumnWidth(0,36); SubjectsTree->setColumnWidth(1,64); SubjectsTree->setCurrentItem(SubjectsTree->invisibleRootItem()->child(0)); } subjectIndex = 0; imageIndex = 0; // prepare color table for (int i = 0;i<256;i++) cTable.append(qRgb( i, i, i )); // load image clearDisplay(); data.clear(); updateSubject(); } bool DataInspectionDialog::eventFilter(QObject *t, QEvent *e) { if (e->type() == QEvent::Wheel) { QWheelEvent *we = static_cast<QWheelEvent *>(e); int s = we->delta()/120; if (t == CoronalLabel) { int slice = qMin(qMax(imgRow+s,0),nRows-1); if (slice != imgRow) { imgRow = slice; plotCoronal(imgRow); } } else if (t == SagittalLabel) { int slice = qMin(qMax(imgCol+s,0),nCols-1); if (slice != imgCol) { imgCol = slice; plotSagittal(imgCol); } } else if (t == AxialLabel) { int slice = qMin(qMax(imgSlice+s,0),nSlices-1); if (slice != imgSlice) { imgSlice = slice; plotAxial(imgSlice); } } } // this is a must otherwise keys are not handled return QDialog::eventFilter(t,e); } void DataInspectionDialog::onImageBoxChange(int index) { if (index != imageIndex) { imageIndex = index; displayImage(); } } void DataInspectionDialog::onPreviousButtonClick() { subjectIndex--; PreviousButton->setDisabled(subjectIndex == 0); NextButton->setEnabled(subjectIndex < nSubjects); SubjectsTree->setCurrentItem(SubjectsTree->invisibleRootItem()->child(subjectIndex)); updateSubject(); } void DataInspectionDialog::onNextButtonClick() { subjectIndex++; NextButton->setDisabled(subjectIndex == nSubjects-1); PreviousButton->setEnabled(subjectIndex > 0); SubjectsTree->setCurrentItem(SubjectsTree->invisibleRootItem()->child(subjectIndex)); updateSubject(); } void DataInspectionDialog::onTreeItemPressed(QTreeWidgetItem *item, int col) { if ( (item == NULL) || SubjectsTree->selectedItems().isEmpty() || col == -1) return; uint index = SubjectsTree->invisibleRootItem()->indexOfChild(item); qDebug()<<"tree ind "<<index<<" current: "<<subjectIndex; if (index == subjectIndex) return; subjectIndex = index; PreviousButton->setDisabled(subjectIndex == 0); NextButton->setDisabled(subjectIndex == nSubjects-1); updateSubject(); } void DataInspectionDialog::updateSubject() { QString sb = ""; if (!individual) { sb = SubjectsTree->currentItem()->text(1); Subject_ID_Text->setText("Subject ID: "+sb); } if (openImage()) displayImage(); else { if (individual) QMessageBox::critical(this,"Error opening data", "Could not open data for subject "+baseName+"."); else QMessageBox::critical(this,"Error opening data", "Could not open data for subject "+sb+"."); } } void DataInspectionDialog::checkBeforeExit() { if (individual) accept(); QTreeWidgetItem *root = SubjectsTree->invisibleRootItem(); if (root == NULL) accept(); subjectsStatus = ucolvec(root->childCount()); for (int i = 0; i < root->childCount();++i) subjectsStatus(i) = root->child(i)->checkState(0); accept(); } // Handle Image Control bool DataInspectionDialog::openImage() { if (fileType == RAW) return false; QString fileName; if (individual) fileName = path+"/"+baseName; else fileName = path+"/"+SubjectsTree->currentItem()->text(1)+"/"+baseName; if (fileName.isEmpty()) return false; // read analyze AnalyzeHeader header; MyProgressDialog *progress = new MyProgressDialog(this); progress->disableMain(); progress->disableCancel(); // start by reading header data QString fn = QFileInfo(fileName).absolutePath()+"/"+QFileInfo(fileName).baseName(); QString imgFileName = (fileType == ANALYZE)?(fn+".img"):(fn+".nii"); QString headerFileName = (fileType == ANALYZE)?(fn+".hdr"):(fn+".nii"); if (!readHeader(headerFileName, header, fileType)) return false; // Acquire information from the header uint dt = header.dime.datatype; data.clear(); // read data according to its type, diffusion data can not be float or double if (dt == DT_UNSIGNED_CHAR) { if (readImage(imgFileName,fileType,false,progress,header,data)) { } else return false; } else if (dt == DT_SIGNED_SHORT) { QList< Cube<short> > out = QList< Cube<short> >(); if (readImage(imgFileName,fileType,false,progress,header,out)) { fcube tmp; for (int i =0;i<out.size();i++) { tmp = conv_to<fcube>::from(out.at(i)); tmp = 255.0*(tmp - tmp.min())/(tmp.max()-tmp.min()); data.append(conv_to<uchar_cube>::from(tmp)); tmp.clear(); } out.clear(); } else return false; } else if (dt == DT_SIGNED_INT) { QList< Cube<s32> > out = QList< Cube<s32> >(); if(readImage(imgFileName,fileType,false,progress,header,out)) { fcube tmp; for (int i =0;i<out.size();i++) { tmp = conv_to<fcube>::from(out.at(i)); tmp = 255.0*(tmp - tmp.min())/(tmp.max()-tmp.min()); data.append(conv_to<uchar_cube>::from(tmp)); tmp.clear(); } out.clear(); } else return false; } else { QMessageBox::critical(this,"Faulty data","Non integer data can not be used for diffusion."); delete progress; return false; } // store volumes info nRows = data.first().n_rows; nCols = data.first().n_cols; nSlices = data.first().n_slices; // update images box ImagesBox->clear(); // below is a workaround due to an internal compiler error // adding item by item causes that error QStringList list; for (int i = 0;i < data.size();i++) list.append(QString("Image %1").arg(i)); ImagesBox->addItems(list); ImagesBox->setCurrentIndex(0); imageIndex = 0; progress->setValue(progress->maximum()); QApplication::restoreOverrideCursor(); delete progress; if (expectedNImages != data.size()) QMessageBox::critical(this,"Image mismatch","Number of loaded images does not match " "the gradient table ("+QString::number(expectedNImages)+")."); return true; } void DataInspectionDialog::clearDisplay() { CoronalLabel->clear(); SagittalLabel->clear(); AxialLabel->clear(); } void DataInspectionDialog::displayImage() { clearDisplay(); imgRow = nRows/2; imgCol = nCols/2; imgSlice = nSlices/2; plotCoronal(imgRow); plotSagittal(imgCol); plotAxial(imgSlice); } void DataInspectionDialog::plotCoronal(int slice) { if (data.isEmpty() || imageIndex == -1) return; // mirror vertically uchar_mat t = data.at(imageIndex)(span(slice),span::all,span::all); QImage img = QImage(t.memptr(),nCols,nSlices,nCols,QImage::Format_Indexed8); img.setColorTable(cTable); img = img.scaled(QSize(250,250)); CoronalLabel->setPixmap(QPixmap::fromImage( img.transformed(QTransform(1,0,0,0,-1,0,0,0,1)) )); } void DataInspectionDialog::plotSagittal(int slice) { if (data.isEmpty() || imageIndex == -1 || imageIndex > data.size()-1) return; // mirror vertically uchar_mat t = data.at(imageIndex)(span::all,span(slice),span::all); QImage img = QImage(t.memptr(),nRows,nSlices,nRows,QImage::Format_Indexed8); img.setColorTable(cTable); img = img.scaled(QSize(250,250)); SagittalLabel->setPixmap(QPixmap::fromImage( img.transformed(QTransform(1,0,0,0,-1,0,0,0,1)) )); } void DataInspectionDialog::plotAxial(int slice) { if (data.isEmpty() || imageIndex == -1 || imageIndex > data.size()-1) return; // transpose then mirror vertically uchar_mat t = data.at(imageIndex)(span::all,span::all,span(slice)); QImage img = QImage(t.memptr(),nRows,nCols,nRows,QImage::Format_Indexed8); img.setColorTable(cTable); img = img.scaled(QSize(250,250)); AxialLabel->setPixmap(QPixmap::fromImage( img.transformed(QTransform(0,-1,0,1,0,0,0,0,1)) )); } void DataInspectionDialog::keyPressEvent(QKeyEvent *e) { int key = e->key(); if (key == Qt::Key_4) { if (!PreviousButton->isEnabled()) return; PreviousButton->click(); } else if (key == Qt::Key_6) { if (!NextButton->isEnabled()) return; NextButton->click(); } else if (key == Qt::Key_8) { if (imageIndex == 0) return; ImagesBox->setCurrentIndex(--imageIndex); displayImage(); return; } else if (key == Qt::Key_2) { if (imageIndex == ImagesBox->count()-1) return; ImagesBox->setCurrentIndex(++imageIndex); displayImage(); return; } else if (key == Qt::Key_S) { Qt::CheckState state = SubjectsTree->currentItem()->checkState(0); state = (state == Qt::Checked)?Qt::Unchecked:Qt::Checked; SubjectsTree->currentItem()->setCheckState(0,state); return; } else QDialog::keyPressEvent(e); }
33.637681
100
0.609737
johnsonjonaris
78b8c3aa494a26f179fcc1be113bbba4655fd5f3
17,570
cpp
C++
lamg/main/mex/aggregationsweep.cpp
zzhao76/Generalized-Eigensolver
9dbbc6aff30a7407f04209b56ab926b4080aef10
[ "BSD-3-Clause" ]
94
2020-02-07T00:18:56.000Z
2022-03-07T23:46:44.000Z
lamg/main/mex/aggregationsweep.cpp
zzhao76/Generalized-Eigensolver
9dbbc6aff30a7407f04209b56ab926b4080aef10
[ "BSD-3-Clause" ]
14
2020-03-09T12:05:41.000Z
2022-02-10T01:10:28.000Z
lamg/main/mex/aggregationsweep.cpp
zzhao76/Generalized-Eigensolver
9dbbc6aff30a7407f04209b56ab926b4080aef10
[ "BSD-3-Clause" ]
15
2020-03-03T14:41:29.000Z
2021-12-22T01:58:28.000Z
/*================================================================= * aggregationsweep.c * * Sweep over graph nodes and aggregate them. * * MATLAB calling syntax: * [x, x2, stat, aggregateSize, numAggregates] = aggregationSweep * (bins, x, x2, stat, aggregateSize, numAggregates, C, D, W, * ratioMax, maxCoarseningRatio) *=================================================================*/ #include "mex.h" #include <math.h> /* * stat array coding schema: -1: undecided 0: seed >0: index of seed */ /* Input arguments */ #define BINS_IN prhs[0] #define X_IN prhs[1] #define X2_IN prhs[2] #define STAT_IN prhs[3] #define AGGREGATESIZE_IN prhs[4] #define NUMAGGREGATES_IN prhs[5] #define C_IN prhs[6] #define D_IN prhs[7] #define W_IN prhs[8] #define RATIOMAX_IN prhs[9] #define MAXCOARSENINGRATIO_IN prhs[10] /* Output arguments */ #define X_OUT plhs[0] #define X2_OUT plhs[1] #define STAT_OUT plhs[2] #define AGGREGATESIZE_OUT plhs[3] #define NUMAGGREGATES_OUT plhs[4] /* Function declarations */ static unsigned int get_as_uint32(const mxArray *x); static double get_as_double(const mxArray *x); static void checkArguments(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]); static void processBin(double *bin, mwSize binSize, double *x, double *x2, double *stat, double *aggregateSize, unsigned int *numAggregates, const mxArray *prhs[]); /* * Main gateway function called by MATLAB. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { unsigned int *numAggregates, *numAggregatesData; mwSize n, numBins, binSize; mwIndex i; mxArray *cellBin; double *x, *x2, *stat, *aggregateSize, maxCoarseningRatio, *bin; /* Read and validate input, output arguments */ checkArguments(nlhs, plhs, nrhs, prhs); n = mxGetM(X_IN); maxCoarseningRatio = get_as_double(MAXCOARSENINGRATIO_IN); numAggregates = (unsigned int*)mxCalloc(1, sizeof(unsigned int)); *numAggregates = get_as_uint32(NUMAGGREGATES_IN); /* Duplicate input arrays into an output arrays, to be changed in-place */ X_OUT = mxDuplicateArray(X_IN); X2_OUT = mxDuplicateArray(X2_IN); STAT_OUT = mxDuplicateArray(STAT_IN); AGGREGATESIZE_OUT = mxDuplicateArray(AGGREGATESIZE_IN); // NUMAGGREGATES_OUT = mxDuplicateArray(NUMAGGREGATES_IN); x = mxGetPr(X_OUT); x2 = mxGetPr(X2_OUT); stat = mxGetPr(STAT_OUT); aggregateSize = mxGetPr(AGGREGATESIZE_OUT); // numAggregates = mxGetPr(NUMAGGREGATES_OUT); /* Main loop over bins of undecided nodes in descending connection strength order */ // mexPrintf("original numAggregates = %d\n", *numAggregates); numBins = mxGetNumberOfElements(BINS_IN); for (i = numBins-1; (int)i >= 0; i--) { cellBin = mxGetCell(BINS_IN, i); bin = mxGetPr(cellBin); binSize = mxGetN(cellBin); processBin(bin, binSize, x, x2, stat, aggregateSize, numAggregates, prhs); // mexPrintf("after bin %d numAggregates = %d\n", i, *numAggregates); /* Stop if reached target coarsening ratio. Checking only * after an entire bin for easier future parallelization. * Also less expensive. */ if (*numAggregates <= n*maxCoarseningRatio) { break; } } // for bin in bins NUMAGGREGATES_OUT = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL); numAggregatesData = (unsigned int*)mxGetPr(NUMAGGREGATES_OUT); *numAggregatesData = *numAggregates; mxFree(numAggregates); } /* Perform an aggregation sweep on a bin of undecided nodes. */ static void processBin(double *bin, mwSize binSize, double *x, double *x2, double *stat, double *aggregateSize, unsigned int *numAggregates, const mxArray *prhs[]) { // *_index refer to indices into a sparse matrix's non-zero array, e.g., j_index. // i, j correspond to nodes, i.e., indices in the X array mwIndex *C_jcol, *C_irow, *C_colIndex, *W_jcol, *W_irow; mwSize n, K; mwIndex b, i, j, j_index, x_index, xi_index, xs_index, p, k, C_colStart, C_colEnd, W_colStart, W_colEnd, W_colSize; double ratioMax, ratioMax2, newAggregateSize; int s; // Seed for current node. If -1, indicates no seed was found. UINT32_T *Ci; // index array into C(i,:) of potential seeds for node i double *r, *q, *E; // Hold fine nodal energy terms double *C, *C_colData, *D, *W, d, d2, y, Cij, Cij_max, xj, Ec, mu, maxMu, mu2; double rr, qq; // Double-letter variables are temporary placeholder of single values in the corresponding single-letter array. unsigned int Ci_size, C_colSize, smallRatio; // mexPrintf("processBin(size=%d)\n", binSize); n = mxGetM(X_IN); K = mxGetN(X_IN); C_irow = mxGetIr(C_IN); C_jcol = mxGetJc(C_IN); // Points to start of col N(:,j) C = mxGetPr(C_IN); W_irow = mxGetIr(W_IN); W_jcol = mxGetJc(W_IN); // Points to start of col N(:,j) W = mxGetPr(W_IN); D = mxGetPr(D_IN); ratioMax = get_as_double(RATIOMAX_IN); ratioMax2 = K*ratioMax*ratioMax; /* Main loop over undecided nodes */ for (b = 0; b < binSize; b++, bin++) { i = (int)(*bin)-1; // Convert to 0-based index // Check that i was not made a seed during previous node visitation if (stat[i] >= 0) { continue; } // mexPrintf("##############################################\n"); // mexPrintf("%d/%d i=%d \n", b, binSize, i); // Find i's undecided & seed delta-affinitive neighbor set Ci // Equivalent MATLAB calls: // [Ci, ~, Ni] = find(C(:,i)); // smallAgg = stat(Ci) <= 0; % Only undecided & seed neighbors // Ci = Ci(smallAgg); // Ni = Ni(smallAgg); C_colStart = C_jcol[i]; C_colEnd = C_jcol[i+1]; Ci_size = 0; C_colSize = C_colEnd-C_colStart; Ci = (UINT32_T*)mxCalloc(C_colSize, sizeof(UINT32_T)); // initialized to 0. We will mark relevant neighbors of each i as 1. C_colIndex = C_irow + C_colStart; // Points to beginning of C(:,i) - irow index C_colData = C + C_colStart; // Points to beginning of C(:,i) - data for (p = 0; p < C_colSize; p++) { j = C_colIndex[p]; if (stat[j] <= 0) { Ci[Ci_size++] = p; } } if (Ci_size == 0) { // No delta-neighbors mxFree(Ci); continue; } /* // // mexPrintf("Ci [alloc=%d, size=%d]\n", C_colSize, Ci_size); for (p = 0; p < Ci_size; p++) { // // mexPrintf(" p=%d Ci[p]=%d j=%d affinity=%f\n", p, Ci[p], C_colIndex[Ci[p]], C_colData[Ci[p]]); } */ // Allocate arrays for energy terms that involve i and its W-neighbors // Equivalent MATLAB calls: // [k, ~, w] = find(W(:,i)); // w = w'; W_colStart = W_jcol[i]; W_colEnd = W_jcol[i+1]; W_colSize = W_colEnd-W_colStart; d = D[i]; d2 = 0.5*D[i]; // Compute fine nodal energy min_y Ei(x;y) : depends on i and TV r = (double*)mxCalloc(K, sizeof(double)); q = (double*)mxCalloc(K, sizeof(double)); E = (double*)mxCalloc(K, sizeof(double)); for (k = 0; k < K; k++) { // Equivalent MATLAB calls: // r = w*x(k,:); // q = w*x2(k,:); rr = 0.0; qq = 0.0; // mexPrintf("Energy terms, TV k=%d\n", k); for (j_index = W_colStart, p = 0; j_index < W_colEnd; j_index++, p++) { j = W_irow[j_index]; // W-neighbor of i x_index = j+n*k; // Index of x(j,k) // // mexPrintf(" j=%d W=%f x[%d]=%f\n", j, W[j_index], x_index, x[x_index]); rr += W[j_index] * x[x_index]; qq += W[j_index] * x2[x_index]; } // Equivalent MATLAB calls: // y = r/d; // E = (d2*y - r).*y + q; r[k] = rr; q[k] = qq; y = rr/d; // Minimizer of E(x;y) E[k] = (d2*y - rr)*y + qq; // min_y E(x;y), evaluated using Horner's rule } /* // mexPrintf("Nodal energy terms:\n"); for (k = 0; k < K; k++) { // mexPrintf(" k=%d r=%+f q=%+f y=%+f E=%+f\n", k, r[k], q[k], r[k]/d, E[k]); } */ // - Compute Ei(x;xj), the prospective coarse nodal energy upon // aggregating i with each j in Ci, assuming that y=xj is then a good- // enough approximation to the minimizer of Ei(x;y). Depends on i,j and TV. // - Compute the energy ratio mu = Ec/E for all W-neighbors and TVs. // - Find the best seed s to aggregate i with: // s = argmax_S [C_{ij}], S = {j: delta-nbhr of i s.t. Ec/E <= mu} // mexPrintf("Look for seed\n"); // Loop over potential seeds s = -1; // Best admissible seed encountered so far. -1 indicates not found. Cij_max = -1.0; for (p = 0; p < Ci_size; p++) { j_index = Ci[p]; // index of neighbor j of i in C_colData=C(i,:) j = C_colIndex[j_index]; // Neighbor of i x_index = j; // Beginning index of x(j,:) // mexPrintf(" Ci-neighbor p=%d j_index=%d j=%d\n", p, j_index, j); // Loop over TVs and compute mu=Ec/E. If it exceeds maxRatio // for a TV, no need to compute it for subsequent TVs. maxMu = -1.0; smallRatio = 1; // mu2 = 0.0; for (k = 0; k < K; k++) { // Equivalent MATLAB calls: // rows = ones(numel(Ci),1); // r = r(rows,:); // q = q(rows,:); // E = E(rows,:); // xj = x(Ci,:); // xJoint = xj; // Ec = (d2*xJoint - r).*xJoint + q; xj = x[x_index]; // Index of x(j,k) Ec = (d2*xj - r[k])*xj + q[k]; // E(x;xj), evaluated using Horner's rule // Equivalent MATLAB calls: // mu = max(Ec./E, [], 2); // smallRatio = find(mu <= ratioMax); mu = Ec/(E[k]+1e-15); // mexPrintf(" Ec=%.2f E=%.2f mu=%.2f\n", Ec, E, mu); // mu2 += mu*mu; if (mu > maxMu) { maxMu = mu; } if (maxMu > ratioMax) { smallRatio = 0; break; } // Go to next TV column x_index += n; } // for k in TVs /* // mexPrintf(" avgMu=%.2f\n", sqrt(mu2/K)); if (mu2 > ratioMax2) { smallRatio = 0; } */ // Update best seed // Equivalent MATLAB calls: // Ni = Ni(smallRatio); // Find relevant neighbors // Ci = Ci(smallRatio); // [~, k] = max(Ni); // Maximize affinity // k = k(1); // s = Ci(k); // Remember to convert to 1-based!!! Cij = C_colData[j_index]; // mexPrintf(" smallRatio=%d Cij=%f current max=%f\n", smallRatio, Cij, Cij_max); if (smallRatio && (Cij > Cij_max)) { Cij_max = Cij; s = j; // mexPrintf(" Set s to %d, current max=%f\n", s, Cij_max); } } // mexPrintf("seed s = %d\n", s); // Clean work arrays of node i mxFree(Ci); mxFree(r); mxFree(q); mxFree(E); if (s < 0) { // No seed found, don't aggregate i continue; } //------------------------ // Aggregate i with s //------------------------ // Update TV values of new aggregate // Equivalent MATLAB calls: // x(i,:) = xJoint(k,:); // x2(i,:) = xAggregate.^2; xi_index = i; // Beginning index of x(i,:) xs_index = s; // Beginning index of x(s,:) for (k = 0; k < K; k++) { x [xi_index] = x [xs_index]; x2[xi_index] = x2[xs_index]; // mexPrintf("Copied x[%d] to x[%d], new value = %f\n", xs_index, xi_index, x[xi_index]); // Go to next TV column xi_index += n; xs_index += n; } // Update node status arrays // mexPrintf("Updating stat arrays: i = %d, s = %d\n", i, s); stat[s] = 0; stat[i] = (double)(s+1); newAggregateSize = aggregateSize[s]+1; aggregateSize[i] = newAggregateSize; aggregateSize[s] = newAggregateSize; *numAggregates = (*numAggregates)-1; } // mexPrintf("end processBin() numAggregates = %d\n", *numAggregates); } /* * Check that A is a sparse n-by-n matrix. * Check that CANDIDATE is m-by-1. */ static void checkArguments(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwSize n, K; /* Check for proper number of input and output arguments */ if (nrhs != 11) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidNumInputs", "11 input arguments required."); } if (nlhs > 5) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidNumOutputs", "Too many output arguments."); } /* Check for proper types of input and output arguments */ if (!mxIsCell(BINS_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "BINS must be a cell array."); } if (!mxIsDouble(X_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "X must be a double-precision floating-point array."); } if (!mxIsDouble(X2_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "X2 must be a double-precision floating-point array."); } if (!mxIsDouble(AGGREGATESIZE_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "AGGREGATESIZE must be a double-precision floating-point array."); } //if (!mxIsDouble(NUMAGGREGATES_IN)) { // mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", // "NUMAGGREGATES must be a double-precision floating-point number."); // } if (mxGetClassID(NUMAGGREGATES_IN) != mxUINT32_CLASS) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "NUMAGGREGATES must be a uint32 unsigned integer."); } if (!mxIsSparse(C_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "C must be a sparse matrix."); } if (!mxIsDouble(D_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "D must be a double-precision floating-point array."); } if (!mxIsSparse(W_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "W must be a sparse matrix."); } if (!mxIsDouble(RATIOMAX_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "RATIOMAX must be a double-precision floating-point number."); } if (!mxIsDouble(MAXCOARSENINGRATIO_IN)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "MAXCOARSENINGRATIO must be a double-precision floating-point number."); } /* Check for proper sizes of input and output arguments -- * omitting full implementation, doing a simple example only */ n = mxGetM(X_IN); K = mxGetN(X_IN); if ((mxGetM(X2_IN) != n) || (mxGetN(X2_IN) != K)) { mexErrMsgIdAndTxt( "MATLAB:aggregationsweep:invalidInput", "X2 and X must have the same size."); } } /* Convert input argument to unsigned int. */ static unsigned int get_as_uint32(const mxArray *x) { unsigned int *pr; pr = (unsigned int *)mxGetData(x); return pr[0]; } /* Convert input argument to double. */ static double get_as_double(const mxArray *x) { double *pr; pr = (double *)mxGetData(x); return pr[0]; }
40.298165
151
0.503301
zzhao76
78c0a20cf5f0d3ce4dfce2cd78de6b3c351e7b90
1,841
cpp
C++
src/FalconEngine/Platform/OpenGL/OpenGLCullState.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
6
2017-04-17T12:34:57.000Z
2019-10-19T23:29:59.000Z
src/FalconEngine/Platform/OpenGL/OpenGLCullState.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
null
null
null
src/FalconEngine/Platform/OpenGL/OpenGLCullState.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
2
2019-12-30T08:28:04.000Z
2020-08-05T09:58:53.000Z
#include <FalconEngine/Platform/OpenGL/OpenGLCullState.h> #if defined(FALCON_ENGINE_API_OPENGL) #include <FalconEngine/Graphics/Renderer/State/CullState.h> namespace FalconEngine { /************************************************************************/ /* Constructors and Destructor */ /************************************************************************/ PlatformCullState::PlatformCullState(): mCullEnabled(false), mCullCounterClockwise(false) { } /************************************************************************/ /* Public Members */ /************************************************************************/ void PlatformCullState::Initialize(const CullState *cullState) { mCullEnabled = cullState->mEnabled; mCullCounterClockwise = cullState->mCounterClockwise; mCullEnabled ? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(mCullCounterClockwise ? GL_FRONT : GL_BACK); } void PlatformCullState::Set(const CullState *cullState) { if (cullState->mEnabled) { if (!mCullEnabled) { mCullEnabled = true; glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); } bool cullCounterClockwise = cullState->mCounterClockwise; if (cullCounterClockwise != mCullCounterClockwise) { mCullCounterClockwise = cullCounterClockwise; if (mCullCounterClockwise) { glCullFace(GL_FRONT); } else { glCullFace(GL_BACK); } } } else if (mCullEnabled) { mCullEnabled = false; glDisable(GL_CULL_FACE); } } } #endif
27.073529
74
0.500272
Lywx
78c308a775ac466de133399636821f3eb191a9a3
24,826
cpp
C++
src/test_cycles_basic.cpp
geraldc-unm/Comb
790d054f9722e6752a27a1c2e08c135f9d5b8e75
[ "MIT" ]
21
2018-10-03T18:15:04.000Z
2022-02-16T08:07:50.000Z
src/test_cycles_basic.cpp
geraldc-unm/Comb
790d054f9722e6752a27a1c2e08c135f9d5b8e75
[ "MIT" ]
5
2019-10-07T23:06:57.000Z
2021-08-16T16:10:58.000Z
src/test_cycles_basic.cpp
geraldc-unm/Comb
790d054f9722e6752a27a1c2e08c135f9d5b8e75
[ "MIT" ]
6
2019-09-13T16:47:33.000Z
2022-03-03T16:17:32.000Z
////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2018-2021, Lawrence Livermore National Security, LLC. // // Produced at the Lawrence Livermore National Laboratory // // LLNL-CODE-758885 // // All rights reserved. // // This file is part of Comb. // // For details, see https://github.com/LLNL/Comb // Please also see the LICENSE file for MIT license. ////////////////////////////////////////////////////////////////////////////// #include "comb.hpp" #include "comm_pol_mock.hpp" #include "comm_pol_mpi.hpp" #include "CommFactory.hpp" namespace COMB { template < typename pol_comm, typename pol_mesh, typename pol_many, typename pol_few > void do_cycles_basic(CommContext<pol_comm>& con_comm_in, CommInfo& comm_info, MeshInfo& info, IdxT num_vars, IdxT ncycles, ExecContext<pol_mesh>& con_mesh, COMB::Allocator& aloc_mesh, ExecContext<pol_many>& con_many, COMB::Allocator& aloc_many, ExecContext<pol_few>& con_few, COMB::Allocator& aloc_few, Timer& tm, Timer& tm_total) { static_assert(std::is_same<pol_many, pol_few>::value, "do_cycles_basic expects pol_many and pol_few to be the same"); static_assert(std::is_same<pol_many, seq_pol>::value #ifdef COMB_ENABLE_CUDA || std::is_same<pol_many, cuda_pol>::value #endif ,"do_cycles_basic expects pol_many to be seq_pol or cuda_pol"); CPUContext tm_con; tm_total.clear(); tm.clear(); char test_name[1024] = ""; snprintf(test_name, 1024, "Basic\nComm %s Mesh %s %s Buffers %s %s %s %s", pol_comm::get_name(), pol_mesh::get_name(), aloc_mesh.name(), pol_many::get_name(), aloc_many.name(), pol_few::get_name(), aloc_few.name()); fgprintf(FileGroup::all, "Starting test %s\n", test_name); { Range r0(test_name, Range::orange); // make a copy of comminfo to duplicate the MPI communicator CommInfo comminfo(comm_info); using comm_type = Comm<pol_many, pol_few, pol_comm>; using policy_comm = typename comm_type::policy_comm; using recv_message_type = typename comm_type::recv_message_type; using send_message_type = typename comm_type::send_message_type; #ifdef COMB_ENABLE_MPI // set name of communicator // include name of memory space if using mpi datatypes for pack/unpack char comm_name[MPI_MAX_OBJECT_NAME] = ""; snprintf(comm_name, MPI_MAX_OBJECT_NAME, "COMB_MPI_CART_COMM%s%s", (comm_type::use_mpi_type) ? "_" : "", (comm_type::use_mpi_type) ? aloc_mesh.name() : ""); comminfo.set_name(comm_name); #endif CommContext<pol_comm> con_comm(con_comm_in #ifdef COMB_ENABLE_MPI ,comminfo.cart.comm #endif ); // sometimes set cutoff to 0 (always use pol_many) to simplify algorithms if (std::is_same<pol_many, pol_few>::value) { // check comm send (packing) method switch (comminfo.post_send_method) { case CommInfo::method::waitsome: case CommInfo::method::testsome: // don't change cutoff to see if breaking messages into // sized groups matters break; default: // already packing individually or all together // might aw well use simpler algorithm comminfo.cutoff = 0; break; } } // make communicator object comm_type comm(con_comm, comminfo, aloc_mesh, aloc_many, aloc_few); comm.barrier(); tm_total.start(tm_con, "start-up"); std::vector<MeshData> vars; vars.reserve(num_vars); { CommFactory factory(comminfo); for (IdxT i = 0; i < num_vars; ++i) { vars.emplace_back(info, aloc_mesh); MeshData& var = vars.back(); // allocate variable var.allocate(); // initialize variable DataT* data = var.data(); IdxT totallen = info.totallen; con_mesh.for_all(totallen, detail::set_n1(data)); con_mesh.synchronize(); // add variable to comm factory.add_var(var); } factory.populate(comm, con_many, con_few); } // do_cycles_basic expects that all sends and receives have_many (use pol_many) assert(comm.m_recvs.message_group_few.messages.size() == 0); assert(comm.m_sends.message_group_few.messages.size() == 0); tm_total.stop(tm_con); /************************************************************************** ************************************************************************** * * Perform test communication steps to ensure communication gives * the right answer * ************************************************************************** **************************************************************************/ comm.barrier(); Range r1("test comm", Range::indigo); tm_total.start(tm_con, "test-comm"); IdxT ntestcycles = std::max(IdxT{1}, ncycles/IdxT{10}); for (IdxT test_cycle = 0; test_cycle < ntestcycles; ++test_cycle) { // test comm Range r2("cycle", Range::cyan); bool mock_communication = comm.mock_communication(); IdxT imin = info.min[0]; IdxT jmin = info.min[1]; IdxT kmin = info.min[2]; IdxT imax = info.max[0]; IdxT jmax = info.max[1]; IdxT kmax = info.max[2]; IdxT ilen = info.len[0]; IdxT jlen = info.len[1]; IdxT klen = info.len[2]; IdxT iglobal_offset = info.global_offset[0]; IdxT jglobal_offset = info.global_offset[1]; IdxT kglobal_offset = info.global_offset[2]; IdxT ilen_global = info.global.sizes[0]; IdxT jlen_global = info.global.sizes[1]; IdxT klen_global = info.global.sizes[2]; IdxT iperiodic = info.global.periodic[0]; IdxT jperiodic = info.global.periodic[1]; IdxT kperiodic = info.global.periodic[2]; IdxT ighost_width = info.ghost_widths[0]; IdxT jghost_width = info.ghost_widths[1]; IdxT kghost_width = info.ghost_widths[2]; IdxT ijlen = info.stride[2]; IdxT ijlen_global = ilen_global * jlen_global; Range r3("pre-comm", Range::red); // tm.start(tm_con, "pre-comm"); for (IdxT i = 0; i < num_vars; ++i) { DataT* data = vars[i].data(); IdxT var_i = i + 1; con_mesh.for_all_3d(klen, jlen, ilen, [=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i) { IdxT zone = i + j * ilen + k * ijlen; IdxT iglobal = i + iglobal_offset; if (iperiodic) { iglobal = iglobal % ilen_global; if (iglobal < 0) iglobal += ilen_global; } IdxT jglobal = j + jglobal_offset; if (jperiodic) { jglobal = jglobal % jlen_global; if (jglobal < 0) jglobal += jlen_global; } IdxT kglobal = k + kglobal_offset; if (kperiodic) { kglobal = kglobal % klen_global; if (kglobal < 0) kglobal += klen_global; } IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global; DataT expected, found, next; int branchid = -1; if (k >= kmin+kghost_width && k < kmax-kghost_width && j >= jmin+jghost_width && j < jmax-jghost_width && i >= imin+ighost_width && i < imax-ighost_width) { // interior non-communicated zones expected = -1.0; found = data[zone]; next =-(zone_global+var_i); branchid = 0; } else if (k >= kmin && k < kmax && j >= jmin && j < jmax && i >= imin && i < imax) { // interior communicated zones expected = -1.0; found = data[zone]; next = zone_global + var_i; branchid = 1; } else if (iglobal < 0 || iglobal >= ilen_global || jglobal < 0 || jglobal >= jlen_global || kglobal < 0 || kglobal >= klen_global) { // out of global bounds exterior zones, some may be owned others not // some may be communicated if at least one dimension is periodic // and another is non-periodic expected = -1.0; found = data[zone]; next = zone_global + var_i; branchid = 2; } else { // in global bounds exterior zones expected = -1.0; found = data[zone]; next =-(zone_global+var_i); branchid = 3; } if (!mock_communication) { if (found != expected) { FGPRINTF(FileGroup::proc, "%p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next); } // LOGPRINTF("%p[%i] = %f\n", data, zone, 1.0); assert(found == expected); } data[zone] = next; }); } con_mesh.synchronize(); // tm.stop(tm_con); r3.restart("post-recv", Range::pink); // tm.start(tm_con, "post-recv"); /************************************************************************ * * Allocate receive buffers and post receives * ************************************************************************/ comm.postRecv(con_many, con_few); // tm.stop(tm_con); r3.restart("post-send", Range::pink); // tm.start(tm_con, "post-send"); /************************************************************************ * * Allocate send buffers, pack, and post sends * ************************************************************************/ comm.postSend(con_many, con_few); // tm.stop(tm_con); r3.stop(); // for (IdxT i = 0; i < num_vars; ++i) { // DataT* data = vars[i].data(); // IdxT var_i = i + 1; // con_mesh.for_all_3d(klen, // jlen, // ilen, // [=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i) { // IdxT zone = i + j * ilen + k * ijlen; // IdxT iglobal = i + iglobal_offset; // if (iperiodic) { // iglobal = iglobal % ilen_global; // if (iglobal < 0) iglobal += ilen_global; // } // IdxT jglobal = j + jglobal_offset; // if (jperiodic) { // jglobal = jglobal % jlen_global; // if (jglobal < 0) jglobal += jlen_global; // } // IdxT kglobal = k + kglobal_offset; // if (kperiodic) { // kglobal = kglobal % klen_global; // if (kglobal < 0) kglobal += klen_global; // } // IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global; // DataT expected, found, next; // int branchid = -1; // if (k >= kmin+kghost_width && k < kmax-kghost_width && // j >= jmin+jghost_width && j < jmax-jghost_width && // i >= imin+ighost_width && i < imax-ighost_width) { // // interior non-communicated zones should not have changed value // expected =-(zone_global+var_i); found = data[zone]; next = -1.0; // branchid = 0; // if (!mock_communication) { // if (found != expected) { // FGPRINTF(FileGroup::proc, "%p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next); // } // // LOGPRINTF("%p[%i] = %f\n", data, zone, 1.0); // assert(found == expected); // } // data[zone] = next; // } // // other zones may be participating in communication, do not access // }); // } // con_mesh.synchronize(); r3.start("wait-recv", Range::pink); // tm.start(tm_con, "wait-recv"); /************************************************************************ * * Wait on receives, unpack, and deallocate receive buffers * ************************************************************************/ comm.waitRecv(con_many, con_few); // tm.stop(tm_con); r3.restart("wait-send", Range::pink); // tm.start(tm_con, "wait-send"); /************************************************************************ * * Wait on sends and deallocate send buffers * ************************************************************************/ comm.waitSend(con_many, con_few); // tm.stop(tm_con); r3.restart("post-comm", Range::red); // tm.start(tm_con, "post-comm"); for (IdxT i = 0; i < num_vars; ++i) { DataT* data = vars[i].data(); IdxT var_i = i + 1; con_mesh.for_all_3d(klen, jlen, ilen, [=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i) { IdxT zone = i + j * ilen + k * ijlen; IdxT iglobal = i + iglobal_offset; if (iperiodic) { iglobal = iglobal % ilen_global; if (iglobal < 0) iglobal += ilen_global; } IdxT jglobal = j + jglobal_offset; if (jperiodic) { jglobal = jglobal % jlen_global; if (jglobal < 0) jglobal += jlen_global; } IdxT kglobal = k + kglobal_offset; if (kperiodic) { kglobal = kglobal % klen_global; if (kglobal < 0) kglobal += klen_global; } IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global; DataT expected, found, next; int branchid = -1; if (k >= kmin+kghost_width && k < kmax-kghost_width && j >= jmin+jghost_width && j < jmax-jghost_width && i >= imin+ighost_width && i < imax-ighost_width) { // interior non-communicated zones should not have changed value expected =-(zone_global+var_i); found = data[zone]; next = -1.0; branchid = 0; } else if (k >= kmin && k < kmax && j >= jmin && j < jmax && i >= imin && i < imax) { // interior communicated zones should not have changed value expected = zone_global + var_i; found = data[zone]; next = -1.0; branchid = 1; } else if (iglobal < 0 || iglobal >= ilen_global || jglobal < 0 || jglobal >= jlen_global || kglobal < 0 || kglobal >= klen_global) { // out of global bounds exterior zones should not have changed value // some may have been communicated, but values should be the same expected = zone_global + var_i; found = data[zone]; next = -1.0; branchid = 2; } else { // in global bounds exterior zones should have changed value // should now be populated with data from another rank expected = zone_global + var_i; found = data[zone]; next = -1.0; branchid = 3; } if (!mock_communication) { if (found != expected) { FGPRINTF(FileGroup::proc, "%p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next); } // LOGPRINTF("%p[%i] = %f\n", data, zone, 1.0); assert(found == expected); } data[zone] = next; }); } con_mesh.synchronize(); // tm.stop(tm_con); r3.stop(); r2.stop(); } comm.barrier(); tm_total.stop(tm_con); tm.clear(); /************************************************************************** ************************************************************************** * * Perform "real" communication steps to benchmark performance * ************************************************************************** **************************************************************************/ r1.restart("bench comm", Range::magenta); tm_total.start(tm_con, "bench-comm"); for(IdxT cycle = 0; cycle < ncycles; cycle++) { Range r2("cycle", Range::yellow); IdxT imin = info.min[0]; IdxT jmin = info.min[1]; IdxT kmin = info.min[2]; IdxT imax = info.max[0]; IdxT jmax = info.max[1]; IdxT kmax = info.max[2]; IdxT ilen = info.len[0]; IdxT jlen = info.len[1]; IdxT klen = info.len[2]; IdxT ijlen = info.stride[2]; Range r3("pre-comm", Range::red); tm.start(tm_con, "pre-comm"); for (IdxT i = 0; i < num_vars; ++i) { DataT* data = vars[i].data(); // set internal zones to 1 con_mesh.for_all_3d(kmax - kmin, jmax - jmin, imax - imin, detail::set_1(ilen, ijlen, data, imin, jmin, kmin)); } con_mesh.synchronize(); tm.stop(tm_con); r3.restart("post-recv", Range::pink); tm.start(tm_con, "post-recv"); /************************************************************************ * * Allocate receive buffers and post receives * ************************************************************************/ // comm.postRecv(con_many, con_few); { // LOGPRINTF("posting receives\n"); IdxT num_recvs = comm.m_recvs.message_group_many.messages.size(); comm.m_recvs.requests.resize(num_recvs, comm.con_comm.recv_request_null()); for (IdxT i = 0; i < num_recvs; ++i) { recv_message_type* message = &comm.m_recvs.message_group_many.messages[i]; comm.m_recvs.message_group_many.allocate(con_many, comm.con_comm, &message, 1, ::detail::Async::no); comm.m_recvs.message_group_many.Irecv(con_many, comm.con_comm, &message, 1, ::detail::Async::no, &comm.m_recvs.requests[i]); } } tm.stop(tm_con); r3.restart("post-send", Range::pink); tm.start(tm_con, "post-send"); /************************************************************************ * * Allocate send buffers, pack, and post sends * ************************************************************************/ // comm.postSend(con_many, con_few); { // LOGPRINTF("posting sends\n"); const IdxT num_sends = comm.m_sends.message_group_many.messages.size(); comm.m_sends.requests.resize(num_sends, comm.con_comm.send_request_null()); for (IdxT i = 0; i < num_sends; ++i) { send_message_type* message = &comm.m_sends.message_group_many.messages[i]; comm.m_sends.message_group_many.allocate(con_many, comm.con_comm, &message, 1, ::detail::Async::no); comm.m_sends.message_group_many.pack(con_many, comm.con_comm, &message, 1, ::detail::Async::no); comm.m_sends.message_group_many.wait_pack_complete(con_many, comm.con_comm, &message, 1, ::detail::Async::no); comm.m_sends.message_group_many.Isend(con_many, comm.con_comm, &message, 1, ::detail::Async::no, &comm.m_sends.requests[i]); } } tm.stop(tm_con); r3.stop(); /* for (IdxT i = 0; i < num_vars; ++i) { DataT* data = vars[i].data(); con_mesh.for_all_3d(klen, jlen, ilen, [=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i) { IdxT zone = i + j * ilen + k * ijlen; DataT expected, found, next; if (k >= kmin && k < kmax && j >= jmin && j < jmax && i >= imin && i < imax) { expected = 1.0; found = data[zone]; next = 1.0; } else { expected = -1.0; found = data[zone]; next = -1.0; } // if (found != expected) { // FGPRINTF(FileGroup::proc, "zone %i(%i %i %i) = %f expected %f\n", zone, i, j, k, found, expected); // } //LOGPRINTF("%p[%i] = %f\n", data, zone, 1.0); data[zone] = next; }); } */ r3.start("wait-recv", Range::pink); tm.start(tm_con, "wait-recv"); /************************************************************************ * * Wait on receives, unpack, and deallocate receive buffers * ************************************************************************/ // comm.waitRecv(con_many, con_few); { // LOGPRINTF("waiting receives\n"); IdxT num_recvs = comm.m_recvs.message_group_many.messages.size(); typename policy_comm::recv_status_type status = comm.con_comm.recv_status_null(); IdxT num_done = 0; while (num_done < num_recvs) { IdxT idx = recv_message_type::wait_recv_any(comm.con_comm, num_recvs, &comm.m_recvs.requests[0], &status); recv_message_type* message = &comm.m_recvs.message_group_many.messages[idx]; comm.m_recvs.message_group_many.unpack(con_many, comm.con_comm, &message, 1, ::detail::Async::no); comm.m_recvs.message_group_many.deallocate(con_many, comm.con_comm, &message, 1, ::detail::Async::no); num_done += 1; } comm.m_recvs.requests.clear(); con_many.synchronize(); } tm.stop(tm_con); r3.restart("wait-send", Range::pink); tm.start(tm_con, "wait-send"); /************************************************************************ * * Wait on sends and deallocate send buffers * ************************************************************************/ // comm.waitSend(con_many, con_few); { // LOGPRINTF("posting sends\n"); IdxT num_sends = comm.m_sends.message_group_many.messages.size(); typename policy_comm::send_status_type status = comm.con_comm.send_status_null(); IdxT num_done = 0; while (num_done < num_sends) { IdxT idx = send_message_type::wait_send_any(comm.con_comm, num_sends, &comm.m_sends.requests[0], &status); send_message_type* message = &comm.m_sends.message_group_many.messages[idx]; comm.m_sends.message_group_many.deallocate(con_many, comm.con_comm, &message, 1, ::detail::Async::no); num_done += 1; } comm.m_sends.requests.clear(); } tm.stop(tm_con); r3.restart("post-comm", Range::red); tm.start(tm_con, "post-comm"); for (IdxT i = 0; i < num_vars; ++i) { DataT* data = vars[i].data(); // set all zones to 1 con_mesh.for_all_3d(klen, jlen, ilen, detail::set_1(ilen, ijlen, data, 0, 0, 0)); } con_mesh.synchronize(); tm.stop(tm_con); r3.stop(); r2.stop(); } comm.barrier(); tm_total.stop(tm_con); r1.stop(); print_timer(comminfo, tm); print_timer(comminfo, tm_total); } tm.clear(); tm_total.clear(); // print_proc_memory_stats(comminfo); } void test_cycles_basic(CommInfo& comminfo, MeshInfo& info, COMB::Executors& exec, COMB::Allocators& alloc, IdxT num_vars, IdxT ncycles, Timer& tm, Timer& tm_total) { #ifdef COMB_ENABLE_MPI CommContext<mpi_pol> con_comm{exec.base_mpi.get()}; #else CommContext<mock_pol> con_comm{exec.base_cpu.get()}; #endif { // mpi/mock sequential exec host memory test do_cycles_basic(con_comm, comminfo, info, num_vars, ncycles, exec.seq.get(), alloc.host.allocator(), exec.seq.get(), alloc.host.allocator(), exec.seq.get(), alloc.host.allocator(), tm, tm_total); } #ifdef COMB_ENABLE_CUDA { // mpi cuda exec cuda memory test do_cycles_basic(con_comm, comminfo, info, num_vars, ncycles, exec.cuda.get(), alloc.cuda_managed.allocator(), exec.cuda.get(), alloc.cuda_hostpinned.allocator(), exec.cuda.get(), alloc.cuda_hostpinned.allocator(), tm, tm_total); } #endif } } // namespace COMB
35.164306
207
0.502377
geraldc-unm
78c3cc49a436ae04b0224394809a04f6587df9db
2,920
cpp
C++
src/Modules/DevGraphics/Shibboleth_NVENCHelpers.cpp
Connway/Shibboleth
23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35
[ "MIT" ]
1
2020-04-06T17:35:47.000Z
2020-04-06T17:35:47.000Z
src/Modules/DevGraphics/Shibboleth_NVENCHelpers.cpp
Connway/Shibboleth
23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35
[ "MIT" ]
null
null
null
src/Modules/DevGraphics/Shibboleth_NVENCHelpers.cpp
Connway/Shibboleth
23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35
[ "MIT" ]
null
null
null
/************************************************************************************ Copyright (C) 2021 by Nicholas LaCroix 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 "Shibboleth_NVENCHelpers.h" #include <Shibboleth_DynamicLoader.h> #include <Shibboleth_Utilities.h> #include <Shibboleth_IApp.h> NS_SHIBBOLETH static NV_ENCODE_API_FUNCTION_LIST g_nvenc_funcs = { NV_ENCODE_API_FUNCTION_LIST_VER }; const NV_ENCODE_API_FUNCTION_LIST& GetNVENCFuncs(void) { return g_nvenc_funcs; } bool InitNVENC(void) { DynamicLoader::ModulePtr nvenc_module = GetApp().getDynamicLoader().loadModule("nvEncodeAPI" DYNAMIC_EXTENSION, "nvenc"); if (!nvenc_module) { nvenc_module = GetApp().getDynamicLoader().loadModule("nvEncodeAPI64" DYNAMIC_EXTENSION, "nvenc"); if (!nvenc_module) { return false; } } using NvEncodeAPIGetMaxSupportedVersionFunc = NVENCSTATUS (NVENCAPI*)(uint32_t*); const NvEncodeAPIGetMaxSupportedVersionFunc get_max_supported_version = nvenc_module->getFunc<NvEncodeAPIGetMaxSupportedVersionFunc>("NvEncodeAPIGetMaxSupportedVersion"); if (!get_max_supported_version) { // $TODO: Log error. return false; } uint32_t max_supported_version = 0; NVENCSTATUS status = get_max_supported_version(&max_supported_version); if (status != NV_ENC_SUCCESS) { // $TODO: Log error. return false; } if (max_supported_version < NVENCAPI_VERSION) { // $TODO: Log error. return false; } using NvEncodeAPICreateInstanceFunc = NVENCSTATUS (NVENCAPI *)(NV_ENCODE_API_FUNCTION_LIST*); const NvEncodeAPICreateInstanceFunc load_api = nvenc_module->getFunc<NvEncodeAPICreateInstanceFunc>("NvEncodeAPICreateInstance"); if (!load_api) { // $TODO: Log error. return false; } status = load_api(&g_nvenc_funcs); if (status != NV_ENC_SUCCESS) { // $TODO: Log error. return false; } return true; } NS_END
32.444444
171
0.737671
Connway
78c8c5e43193b4eb6faeca35bb1f67346a185a6d
13,178
cpp
C++
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/TCBInfoVrifierUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/TCBInfoVrifierUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/TCBInfoVrifierUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2011-2020 Intel Corporation. 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <SgxEcdsaAttestation/QuoteVerification.h> #include <SgxEcdsaAttestation/AttestationParsers.h> #include <Verifiers/TCBInfoVerifier.h> #include <Verifiers/TCBSigningChain.h> #include <Mocks/CertCrlStoresMocks.h> #include <Mocks/TcbSigningChainMock.h> #include <Mocks/CommonVerifierMock.h> #include <Mocks/PckCrlVerifierMock.h> #include <TcbInfoGenerator.h> #include <CertVerification/X509Constants.h> #include <PckParser/PckParser.h> #include "KeyHelpers.h" using namespace testing; using namespace intel::sgx::qvl; struct TCBInfoVerifierUT : public Test { std::vector<pckparser::Extension> extensions; pckparser::Signature signature; intel::sgx::dcap::parser::json::TcbInfo tcbInfo = intel::sgx::dcap::parser::json::TcbInfo::parse(generateTcbInfo()); std::vector<uint8_t> pubKey = {}; const time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); }; TEST_F(TCBInfoVerifierUT, shouldReturnStatusOkWhenVerifyPassPositive) { // GIVEN auto commonVerifierMock = std::make_unique<StrictMock<test::CommonVerifierMock>>(); auto pckCrlVerifierMock = std::make_unique<StrictMock<test::PckCrlVerifierMock>>(); auto tcbSigningChainMock = std::make_unique<StrictMock<test::TcbSigningChainMock>>(); StrictMock<test::CertificateChainMock> certificateChainMock; StrictMock<test::PckCertificateMock> certStoreMock; StrictMock<test::CrlStoreMock> crlStoreMock; StrictMock<test::ValidityMock> validityMock; auto certStoreMockPtr = std::make_shared<StrictMock<test::PckCertificateMock>>(); EXPECT_CALL(*commonVerifierMock, checkSha256EcdsaSignature(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(*tcbSigningChainMock, verify(_, _, _)).WillOnce(Return(STATUS_OK)); EXPECT_CALL(certificateChainMock, getRootCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(certificateChainMock, getTopmostCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(*certStoreMockPtr, getPubKey()).WillOnce(ReturnRef(pubKey)); EXPECT_CALL(*certStoreMockPtr, getValidity()).WillRepeatedly(ReturnRef(validityMock)); EXPECT_CALL(validityMock, getNotAfterTime()).WillRepeatedly(Return(currentTime)); EXPECT_CALL(crlStoreMock, expired(_)).WillOnce(Return(false)); TCBInfoVerifier tcbInfoVerifier(std::move(commonVerifierMock), std::move(tcbSigningChainMock)); // WHEN auto result = tcbInfoVerifier.verify(tcbInfo, certificateChainMock, crlStoreMock, certStoreMock, 1529580962); // THEN EXPECT_EQ(STATUS_OK, result); } TEST_F(TCBInfoVerifierUT, shouldReturnRootCaMissingWhenTcbSigningChainVerifyFail) { // GIVEN auto commonVerifierMock = std::make_unique<StrictMock<test::CommonVerifierMock>>(); auto pckCrlVerifierMock = std::make_unique<StrictMock<test::PckCrlVerifierMock>>(); auto tcbSigningChainMock = std::make_unique<StrictMock<test::TcbSigningChainMock>>(); StrictMock<test::CertificateChainMock> certificateChainMock; StrictMock<test::PckCertificateMock> certStoreMock; StrictMock<test::CrlStoreMock> crlStoreMock; auto certStoreMockPtr = std::make_shared<StrictMock<test::PckCertificateMock>>(); EXPECT_CALL(*tcbSigningChainMock, verify(_, _, _)).WillOnce(Return(STATUS_SGX_ROOT_CA_MISSING)); TCBInfoVerifier tcbInfoVerifier(std::move(commonVerifierMock), std::move(tcbSigningChainMock)); // WHEN auto result = tcbInfoVerifier.verify(tcbInfo, certificateChainMock, crlStoreMock, certStoreMock, currentTime); // THEN EXPECT_EQ(STATUS_SGX_ROOT_CA_MISSING, result); } TEST_F(TCBInfoVerifierUT, shouldReturnInfoInvalidSignatureWhenCheckSha256EcdsaSignatureFail) { // GIVEN auto commonVerifierMock = std::make_unique<StrictMock<test::CommonVerifierMock>>(); auto pckCrlVerifierMock = std::make_unique<StrictMock<test::PckCrlVerifierMock>>(); auto tcbSigningChainMock = std::make_unique<StrictMock<test::TcbSigningChainMock>>(); StrictMock<test::CertificateChainMock> certificateChainMock; StrictMock<test::PckCertificateMock> certStoreMock; StrictMock<test::CrlStoreMock> crlStoreMock; auto certStoreMockPtr = std::make_shared<StrictMock<test::PckCertificateMock>>(); EXPECT_CALL(*commonVerifierMock, checkSha256EcdsaSignature(_, _, _)).WillOnce(Return(false)); EXPECT_CALL(*tcbSigningChainMock, verify(_, _, _)).WillOnce(Return(STATUS_OK)); EXPECT_CALL(certificateChainMock, getRootCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(certificateChainMock, getTopmostCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(*certStoreMockPtr, getPubKey()).WillOnce(ReturnRef(pubKey)); TCBInfoVerifier tcbInfoVerifier(std::move(commonVerifierMock), std::move(tcbSigningChainMock)); // WHEN auto result = tcbInfoVerifier.verify(tcbInfo, certificateChainMock, crlStoreMock, certStoreMock, currentTime); // THEN EXPECT_EQ(STATUS_TCB_INFO_INVALID_SIGNATURE, result); } TEST_F(TCBInfoVerifierUT, shouldReturnStatusSigningCertChainExpiredWhenRootCaExpired) { // GIVEN auto commonVerifierMock = std::make_unique<StrictMock<test::CommonVerifierMock>>(); auto pckCrlVerifierMock = std::make_unique<StrictMock<test::PckCrlVerifierMock>>(); auto tcbSigningChainMock = std::make_unique<StrictMock<test::TcbSigningChainMock>>(); StrictMock<test::CertificateChainMock> certificateChainMock; StrictMock<test::PckCertificateMock> certStoreMock; StrictMock<test::CrlStoreMock> crlStoreMock; StrictMock<test::ValidityMock> validityMock; auto certStoreMockPtr = std::make_shared<StrictMock<test::PckCertificateMock>>(); EXPECT_CALL(*commonVerifierMock, checkSha256EcdsaSignature(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(*tcbSigningChainMock, verify(_, _, _)).WillOnce(Return(STATUS_OK)); EXPECT_CALL(certificateChainMock, getRootCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(certificateChainMock, getTopmostCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(*certStoreMockPtr, getPubKey()).WillOnce(ReturnRef(pubKey)); EXPECT_CALL(*certStoreMockPtr, getValidity()).WillRepeatedly(ReturnRef(validityMock)); EXPECT_CALL(validityMock, getNotAfterTime()).WillOnce(Return(currentTime - 1)); TCBInfoVerifier tcbInfoVerifier(std::move(commonVerifierMock), std::move(tcbSigningChainMock)); // WHEN auto result = tcbInfoVerifier.verify(tcbInfo, certificateChainMock, crlStoreMock, certStoreMock, currentTime); // THEN EXPECT_EQ(STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED, result); } TEST_F(TCBInfoVerifierUT, shouldReturnStatusSigningCertChainExpiredWhenSigningCertExpired) { // GIVEN auto commonVerifierMock = std::make_unique<StrictMock<test::CommonVerifierMock>>(); auto pckCrlVerifierMock = std::make_unique<StrictMock<test::PckCrlVerifierMock>>(); auto tcbSigningChainMock = std::make_unique<StrictMock<test::TcbSigningChainMock>>(); StrictMock<test::CertificateChainMock> certificateChainMock; StrictMock<test::PckCertificateMock> certStoreMock; StrictMock<test::CrlStoreMock> crlStoreMock; StrictMock<test::ValidityMock> validityMock; auto certStoreMockPtr = std::make_shared<StrictMock<test::PckCertificateMock>>(); EXPECT_CALL(*commonVerifierMock, checkSha256EcdsaSignature(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(*tcbSigningChainMock, verify(_, _, _)).WillOnce(Return(STATUS_OK)); EXPECT_CALL(certificateChainMock, getRootCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(certificateChainMock, getTopmostCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(*certStoreMockPtr, getPubKey()).WillOnce(ReturnRef(pubKey)); EXPECT_CALL(*certStoreMockPtr, getValidity()).WillRepeatedly(ReturnRef(validityMock)); EXPECT_CALL(validityMock, getNotAfterTime()).WillOnce(Return(currentTime)).WillOnce(Return(currentTime - 1)); TCBInfoVerifier tcbInfoVerifier(std::move(commonVerifierMock), std::move(tcbSigningChainMock)); // WHEN auto result = tcbInfoVerifier.verify(tcbInfo, certificateChainMock, crlStoreMock, certStoreMock, currentTime); // THEN EXPECT_EQ(STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED, result); } TEST_F(TCBInfoVerifierUT, shouldReturnStatusCrlExpiredWhenRootCaCrlExpired) { // GIVEN auto commonVerifierMock = std::make_unique<StrictMock<test::CommonVerifierMock>>(); auto pckCrlVerifierMock = std::make_unique<StrictMock<test::PckCrlVerifierMock>>(); auto tcbSigningChainMock = std::make_unique<StrictMock<test::TcbSigningChainMock>>(); StrictMock<test::CertificateChainMock> certificateChainMock; StrictMock<test::PckCertificateMock> certStoreMock; StrictMock<test::CrlStoreMock> crlStoreMock; StrictMock<test::ValidityMock> validityMock; auto certStoreMockPtr = std::make_shared<StrictMock<test::PckCertificateMock>>(); EXPECT_CALL(*commonVerifierMock, checkSha256EcdsaSignature(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(*tcbSigningChainMock, verify(_, _, _)).WillOnce(Return(STATUS_OK)); EXPECT_CALL(certificateChainMock, getRootCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(certificateChainMock, getTopmostCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(*certStoreMockPtr, getPubKey()).WillOnce(ReturnRef(pubKey)); EXPECT_CALL(*certStoreMockPtr, getValidity()).WillRepeatedly(ReturnRef(validityMock)); EXPECT_CALL(validityMock, getNotAfterTime()).WillRepeatedly(Return(currentTime)); EXPECT_CALL(crlStoreMock, expired(_)).WillOnce(Return(true)); TCBInfoVerifier tcbInfoVerifier(std::move(commonVerifierMock), std::move(tcbSigningChainMock)); // WHEN auto result = tcbInfoVerifier.verify(tcbInfo, certificateChainMock, crlStoreMock, certStoreMock, currentTime); // THEN EXPECT_EQ(STATUS_SGX_CRL_EXPIRED, result); } TEST_F(TCBInfoVerifierUT, shouldReturnStatusTcbInfoExpiredWhenTcbInfoExpired) { // GIVEN auto commonVerifierMock = std::make_unique<StrictMock<test::CommonVerifierMock>>(); auto pckCrlVerifierMock = std::make_unique<StrictMock<test::PckCrlVerifierMock>>(); auto tcbSigningChainMock = std::make_unique<StrictMock<test::TcbSigningChainMock>>(); StrictMock<test::CertificateChainMock> certificateChainMock; StrictMock<test::PckCertificateMock> certStoreMock; StrictMock<test::CrlStoreMock> crlStoreMock; StrictMock<test::ValidityMock> validityMock; auto certStoreMockPtr = std::make_shared<StrictMock<test::PckCertificateMock>>(); EXPECT_CALL(*commonVerifierMock, checkSha256EcdsaSignature(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(*tcbSigningChainMock, verify(_, _, _)).WillOnce(Return(STATUS_OK)); EXPECT_CALL(certificateChainMock, getRootCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(certificateChainMock, getTopmostCert()).WillRepeatedly(Return(certStoreMockPtr)); EXPECT_CALL(*certStoreMockPtr, getPubKey()).WillOnce(ReturnRef(pubKey)); EXPECT_CALL(*certStoreMockPtr, getValidity()).WillRepeatedly(ReturnRef(validityMock)); EXPECT_CALL(validityMock, getNotAfterTime()).WillRepeatedly(Return(currentTime)); EXPECT_CALL(crlStoreMock, expired(_)).WillOnce(Return(false)); TCBInfoVerifier tcbInfoVerifier(std::move(commonVerifierMock), std::move(tcbSigningChainMock)); // WHEN auto result = tcbInfoVerifier.verify(tcbInfo, certificateChainMock, crlStoreMock, certStoreMock, 1529580963); // THEN EXPECT_EQ(STATUS_SGX_TCB_INFO_EXPIRED, result); }
47.574007
120
0.77766
fqiu1